diff --git a/plugins/stewards/migrations.snapshot.json b/plugins/stewards/migrations.snapshot.json index 4cb20389..62ff0092 100644 --- a/plugins/stewards/migrations.snapshot.json +++ b/plugins/stewards/migrations.snapshot.json @@ -157,5 +157,8 @@ "8503121de463ec77e923cbf67bead9d573c0d28343bbc147e14a4284e50d88cb", "b2b3d782a63c5bb74d8ffc09274a0a816c247ff1786bed261f484241d38ed003", "5f7f3062ec065532a809197f70ab75aac9150503518c8c28b2be94640cd8c942", - "64d043c0410e462351414e5acd8557d077ee1ca059ccf0e97ea50ef503f4e666" + "64d043c0410e462351414e5acd8557d077ee1ca059ccf0e97ea50ef503f4e666", + "00a95665ae9de85807efa76a7a72b7567c664b0295c90ebd5a544ab82ce643ea", + "4ef374ea156dddb2cddbfe2eebefb69eb194e22fb19e3cd33e0d368b740e2f5c", + "719d996e69cf67362f4969245bf0eed33d9239d671b80f4ba6b763782404028c" ] diff --git a/plugins/stewards/read-counts.test.ts b/plugins/stewards/read-counts.test.ts index 96d22deb..991b6104 100644 --- a/plugins/stewards/read-counts.test.ts +++ b/plugins/stewards/read-counts.test.ts @@ -180,7 +180,11 @@ describe("a reconcile pass over a fixed binding set (BB-297)", () => { // 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 }); + // BB-386 raised them 193 → 197: `pullBelongsToTicket` reads the pull + // request's handoff row (cached after the first read) so a moved pull + // request belongs to its new binding — three own pull requests — and + // `reconcileOnce` reads the handed-off pull list once for the pass. + expect(reconcile).toEqual({ storeReads: 197, 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 40e57af8..66a9fd73 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -11,7 +11,7 @@ import { guidanceUnitId } from "./guidance.js"; import { parseDotenvValue, refreshPrompt, secretVariable, STEWARDS_SKILLS } from "./server.js"; import { SOURCE_PLUGIN_IDS, type EntitySnapshot } from "./source-contract.js"; import { MIGRATIONS, ESCALATED_NEED_KINDS, NEEDS_KINDS, STEWARD_NEED_KINDS, needChoices, type Binding } from "./store.js"; -import { GITHUB_ISSUES, GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, OPS_WATCH, DEPS_ALERTS, DEPS_PRS, PLAYBOOK_TEMPLATES, projectFileTemplate, stampedTemplate } from "./templates.js"; +import { GITHUB_ISSUES, GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, LOCAL_TICKETS, OPS_WATCH, DEPS_ALERTS, DEPS_PRS, PLAYBOOK_TEMPLATES, projectFileTemplate, stampedTemplate } from "./templates.js"; import { parseTemplateStamp, templateHash } from "./template-stamp.js"; import { STANDING_RULES } from "./wake.js"; import { setup, SHIPPED_SKILLS } from "./test-world.js"; @@ -2463,6 +2463,9 @@ describe("terminal states and follow-through", () => { it("ends without a wrap-up wake when the steward's own last report already said Done", async () => { const t = await working(); await t.report({ phase: "Done" }); + // BB-386: a running worker is open work and takes the wrap-up wake; let it + // finish first, so this is the no-open-work case rule 4 covers. + await t.idle("thr_w1", "Implemented and merged."); const before = t.sends.length; await t.done(); expect(t.sends).toHaveLength(before); @@ -2501,6 +2504,287 @@ describe("terminal states and follow-through", () => { }); }); +// BB-386: a binding ends only when it holds no open work, or when every open +// item is affirmatively finished, handed off or closed. The tracker's terminal +// state starts the wrap-up; it does not finish it. +describe("a binding never ends with open work (BB-386)", () => { + /** A ticket with a steward and a worker that opened two linked pull requests. */ + async function twoPulls() { + const t = await setup(); + const linked = [ + { key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }, + { key: "acme/web#8", url: "https://github.com/acme/web/pull/8" }, + ]; + t.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7" })); + t.entities.set("acme/web#8", pull({ id: "acme/web#8", key: "acme/web#8", url: "https://github.com/acme/web/pull/8" }, { head: "bb/eng-12-retry-2" })); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", linkedPulls: linked })); + await t.ring("linear", "uuid-12"); + const steward = t.hooks.store.find("ENG-12")!.threadId!; + await t.created("thr_w1", steward, "ENG-12: two pull requests"); + return { ...t, steward, linked }; + } + + it("does not end while a second opened pull request is still open", async () => { + const t = await twoPulls(); + // The worker's own last message says it merged #7 and set the ticket Done. + await t.idle("thr_w1", "Merged acme/web#7 and opened acme/web#8; set ENG-12 to Done."); + t.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7", state: "merged" }, { merged: true })); + t.entities.set("uuid-12", issue({ state: "Done", stateType: "completed", linkedPulls: t.linked })); + const before = t.sends.length; + await t.ring("linear", "uuid-12"); + const b = t.hooks.store.find("ENG-12")!; + expect(b.endedAt).toBeNull(); + expect(b.ending).toBe("terminal"); + expect(b.followThrough).not.toBeNull(); + expect(b.followThrough).toMatch(/acme\/web#8/); + const wake = t.sends.slice(before).map((s) => s.text).join("\n"); + expect(wake).toMatch(/acme\/web#8/); + expect(wake).toMatch(/Open work/); + }); + + it("still ends immediately when it holds no open work (BB-52 rule 4)", 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.hooks.store.find("ENG-12")!.threadId!; + await t.tool("steward_report", { phase: "Done", summary: "Merged.", nextAction: "Nothing", actor: "steward" }, steward); + t.entities.set("uuid-12", issue({ state: "Done", stateType: "completed" })); + const before = t.sends.length; + await t.ring("linear", "uuid-12"); + expect(t.sends).toHaveLength(before); + expect(t.hooks.store.find("ENG-12")!.endedAt).not.toBeNull(); + }); + + /** A: ENG-12 owns acme/web#7 by its worker branch; B: ENG-13 is an open binding. */ + async function handoffWorld() { + const t = await setup(); + const linked = { linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] }; + // Only ENG-12 links #7: the target binding must find the handed-off pull + // request through the handoff, not the ticket's timeline. + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", ...linked })); + t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", title: "Add SSO", state: "In Progress", stateType: "started" })); + // A non-default base keeps the plugin from auto-merging, so the Merge item + // it files is visible. + t.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7", title: "Fix login", author: "jane", comments: [comment({ id: "r1", author: "jane", body: "", signedBy: "thr_reviewer", createdAt: "2026-10-14T16:00:00Z" })] }, { head: "bb/eng-12-retry", base: "release", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + await t.ring("linear", "uuid-13"); + const a = t.hooks.store.find("ENG-12")!; + const b = t.hooks.store.find("ENG-13")!; + const url = "https://github.com/acme/web/pull/7"; + const aMerge = t.hooks.store.openNeeds(a.id).find((n) => n.kind === "merge" && n.url === url)!; + return { ...t, a, b, aMerge, url, project: t.spawns[0]!.id }; + } + + it("moves a pull request from one binding to another with steward_report handOff", async () => { + const t = await handoffWorld(); + const handed = await t.tool("steward_report", { phase: "In Progress", summary: "Handing off.", nextAction: "Wait", actor: "steward", handOff: { pull: "acme/web#7", to: "ENG-13" } }, t.a.threadId!); + expect(handed.error).toBe(false); + expect(t.hooks.store.pullHandoff("acme/web#7")).toMatchObject({ toBindingId: t.b.id, fromBindingId: t.a.id }); + await t.ring("linear", "uuid-12"); + await t.ring("linear", "uuid-13"); + // A no longer owns it: its merge need is closed as foreign. + expect(t.hooks.store.need(t.aMerge.id)!.resolution).toBe("The pull request belongs to another ticket."); + // B owns it: it observes the handed-off pull request and files its own + // Merge item, not a foreign close. + expect(t.hooks.store.openNeeds(t.b.id).some((n) => n.kind === "merge" && n.url === t.url)).toBe(true); + }); + + it("adopts a pull request into a binding with the project steward's adoptPull", async () => { + const t = await handoffWorld(); + const adopted = await t.tool("steward_update", { binding: "ENG-13", adoptPull: "acme/web#7" }, t.project); + expect(adopted.error).toBe(false); + expect(adopted.text).toMatch(/adopted acme\/web#7/); + expect(t.hooks.store.pullHandoff("acme/web#7")).toMatchObject({ toBindingId: t.b.id }); + await t.ring("linear", "uuid-12"); + await t.ring("linear", "uuid-13"); + expect(t.hooks.store.need(t.aMerge.id)!.resolution).toBe("The pull request belongs to another ticket."); + expect(t.hooks.store.openNeeds(t.b.id).some((n) => n.kind === "merge" && n.url === t.url)).toBe(true); + }); + + it("does not move a project-steward approval with the pull request, so the target asks again", async () => { + const t = await handoffWorld(); + const sha = "aaaaaaa1"; + t.hooks.store.recordProjectApproval({ bindingId: t.a.id, headSha: sha, entry: null, byThread: t.project }); + const handed = await t.tool("steward_report", { phase: "In Progress", summary: "Handing off.", nextAction: "Wait", actor: "steward", handOff: { pull: "acme/web#7", to: "ENG-13" } }, t.a.threadId!); + expect(handed.error).toBe(false); + expect(handed.text).toMatch(/approval does not move/); + // The record stays with the binding that held it; the target has none, so + // its gate is unmet until the project steward approves it there. + expect(t.hooks.store.projectApproval(t.a.id, sha)).not.toBeNull(); + expect(t.hooks.store.projectApproval(t.b.id, sha)).toBeNull(); + }); + + it("refuses adoptPull for a pull request this server did not open", async () => { + const t = await handoffWorld(); + t.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7", author: "sam" }, { head: "feature/other" })); + const adopted = await t.tool("steward_update", { binding: "ENG-13", adoptPull: "acme/web#7" }, t.project); + expect(adopted.error).toBe(true); + expect(adopted.text).toMatch(/not opened by this server's GitHub login/u); + }); + + it("does not re-home a teammate's pull request that merely names the ticket", async () => { + const t = await setup(); + const linked = { linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] }; + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", ...linked })); + t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", title: "Add SSO", state: "In Progress", stateType: "started" })); + // A teammate opened it; its title names ENG-12 and its body fixes ENG-13. + t.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7", title: "Fix login (ENG-12)", author: "sam", description: "Fixes ENG-13." }, { head: "feature/other", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + await t.ring("linear", "uuid-13"); + const a = t.hooks.store.find("ENG-12")!; + const b = t.hooks.store.find("ENG-13")!; + t.hooks.store.patch(a.id, { endedAt: t.now(), endReason: "terminal" }); + await t.hooks.sweep(); + await t.flush(); + expect(t.hooks.store.pullHandoff("acme/web#7")).toBeNull(); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge" && n.url === "https://github.com/acme/web/pull/7")).toBe(false); + }); + + it("does not re-read a teammate's or a closed orphan pull request on a later sweep", async () => { + const snapshots = (t: Awaited>, id: string) => t.rpcCalls.filter((c) => c.method === "sourceSnapshot" && c.pluginId === SOURCE_PLUGIN_IDS.github && (c.input as { id?: string }).id === id).length; + // A teammate's pull request that names the ticket is never fetched by + // re-homing, so two sweeps cost the same reads. + const teammate = await setup(); + teammate.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + teammate.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7", title: "Fix login (ENG-12)", author: "sam" }, { head: "feature/other", checks: { state: "success", failing: [] } })); + await teammate.ring("linear", "uuid-12"); + // Unconfigure the ticket and pause stewards, so adoption leaves the ended + // binding alone and only re-homing could read the pull request. + teammate.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", labels: [], linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + await (teammate.hooks.settings as unknown as { experimental_set(v: Record): Promise }).experimental_set({ paused: true }); + teammate.hooks.store.patch(teammate.hooks.store.find("ENG-12")!.id, { endedAt: teammate.now(), endReason: "terminal" }); + await teammate.hooks.sweep(); + await teammate.flush(); + const teammateReads = snapshots(teammate, "acme/web#7"); + await teammate.hooks.sweep(); + await teammate.flush(); + expect(snapshots(teammate, "acme/web#7")).toBe(teammateReads); + + // A server-opened pull request that has since closed is read once and then + // recorded as handled. + const closed = await setup(); + closed.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + closed.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7", title: "Fix login", author: "jane" }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] } })); + await closed.ring("linear", "uuid-12"); + closed.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", labels: [], linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + await (closed.hooks.settings as unknown as { experimental_set(v: Record): Promise }).experimental_set({ paused: true }); + closed.hooks.store.patch(closed.hooks.store.find("ENG-12")!.id, { endedAt: closed.now(), endReason: "terminal" }); + closed.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7", title: "Fix login", author: "jane", state: "closed" }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] } })); + await closed.hooks.sweep(); + await closed.flush(); + const closedReads = snapshots(closed, "acme/web#7"); + await closed.hooks.sweep(); + await closed.flush(); + expect(snapshots(closed, "acme/web#7")).toBe(closedReads); + }); + + it("re-homes a handed-off pull request whose new owner also ended, and names it", async () => { + const t = await handoffWorld(); + const handed = await t.tool("steward_report", { phase: "In Progress", summary: "Handing off.", nextAction: "Wait", actor: "steward", handOff: { pull: "acme/web#7", to: "ENG-13" } }, t.a.threadId!); + expect(handed.error).toBe(false); + // The target observes the handed-off pull request before it ends. + await t.ring("linear", "uuid-13"); + // Both bindings end, and no open binding fixes #7. + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", labels: [], linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", title: "Add SSO", state: "In Progress", stateType: "started", labels: [] })); + await (t.hooks.settings as unknown as { experimental_set(v: Record): Promise }).experimental_set({ paused: true }); + t.hooks.store.patch(t.a.id, { endedAt: t.now(), endReason: "terminal" }); + t.hooks.store.patch(t.b.id, { endedAt: t.now(), endReason: "terminal" }); + await t.hooks.sweep(); + await t.flush(); + const need = t.hooks.store.openNeeds(t.b.id).find((n) => n.kind === "decide" && /has no steward/u.test(n.what) && /acme\/web#7/u.test(n.what)); + expect(need).toBeDefined(); + }); + + it("does not mark a re-homing read that failed, so the orphan is named on a later sweep", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + t.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7", title: "Fix login", author: "jane" }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + const a = t.hooks.store.find("ENG-12")!; + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", labels: [] })); + await (t.hooks.settings as unknown as { experimental_set(v: Record): Promise }).experimental_set({ paused: true }); + t.hooks.store.patch(a.id, { endedAt: t.now(), endReason: "terminal" }); + // A failed read is not a handled orphan. + t.setSnapshotError("acme/web#7", true); + await t.hooks.sweep(); + await t.flush(); + expect(t.hooks.store.pullRehomeMarked("acme/web#7", a.id)).toBe(false); + expect(t.hooks.store.openNeeds(a.id).some((n) => n.kind === "decide" && /has no steward/u.test(n.what))).toBe(false); + // Once the read succeeds, the orphan is named. + t.setSnapshotError("acme/web#7", false); + await t.hooks.sweep(); + await t.flush(); + expect(t.hooks.store.openNeeds(a.id).some((n) => n.kind === "decide" && /has no steward/u.test(n.what))).toBe(true); + }); + + it("keeps follow-through on through a wrap-up report that does not settle the open pull request, and names the orphan on the overdue path", async () => { + const t = await setup(); + const linked = { linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] }; + t.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }, { head: "bb/eng-12-retry", checks: { state: "pending", failing: [] } })); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", ...linked })); + await t.ring("linear", "uuid-12"); + const steward = t.hooks.store.find("ENG-12")!.threadId!; + // The steward's own last report names Done, but the open pull request + // blocks the silent end: the binding takes its wrap-up turn. + await t.tool("steward_report", { phase: "Done", summary: "Merged the first.", nextAction: "Nothing", actor: "steward" }, steward); + t.entities.set("uuid-12", issue({ state: "Done", stateType: "completed", ...linked })); + await t.ring("linear", "uuid-12"); + const b = t.hooks.store.find("ENG-12")!; + expect(b.ending).toBe("terminal"); + expect(b.followThrough).toMatch(/acme\/web#7/); + // A wrap-up report that says nothing about #7 keeps follow-through on. + await t.tool("steward_report", { phase: "Done", summary: "Wrapping up.", nextAction: "Nothing", actor: "steward" }, steward); + expect(t.hooks.store.find("ENG-12")!.followThrough).toMatch(/acme\/web#7/); + await t.idle(steward); + expect(t.hooks.store.find("ENG-12")!.endedAt).toBeNull(); + // The deadline is not a quiet end: it names the orphan in a need. + t.advance(6 * 3_600_000 + 60_000); + await t.hooks.sweep(); + await t.flush(); + const need = t.hooks.store.openNeeds(b.id).find((n) => n.kind === "decide" && /acme\/web#7/.test(`${n.what} ${n.how ?? ""}`)); + expect(need).toBeDefined(); + }); + + it("re-homes an open pull request whose owning binding ended, to a binding whose ticket it fixes", async () => { + const t = await setup(); + const linked = { linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] }; + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", ...linked })); + t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", title: "Add SSO", state: "In Progress", stateType: "started", ...linked })); + t.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7", title: "Fix login", author: "jane", description: "Fixes ENG-13." }, { head: "bb/eng-12-retry", checks: { state: "pending", failing: [] } })); + await t.ring("linear", "uuid-12"); + await t.ring("linear", "uuid-13"); + const a = t.hooks.store.find("ENG-12")!; + const b = t.hooks.store.find("ENG-13")!; + t.hooks.store.patch(a.id, { endedAt: t.now(), endReason: "terminal" }); + await t.hooks.sweep(); + await t.flush(); + expect(t.hooks.store.pullHandoff("acme/web#7")).toMatchObject({ toBindingId: b.id, fromBindingId: a.id }); + }); + + it("names a project-steward need for an orphan no open binding fixes", async () => { + const t = await setup(); + const linked = { linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] }; + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", ...linked })); + t.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7", title: "Fix login", author: "jane", description: "No ticket." }, { head: "bb/eng-12-retry", checks: { state: "pending", failing: [] } })); + await t.ring("linear", "uuid-12"); + const a = t.hooks.store.find("ENG-12")!; + t.hooks.store.patch(a.id, { endedAt: t.now(), endReason: "terminal" }); + await t.hooks.sweep(); + await t.flush(); + const need = t.hooks.store.openNeeds(a.id).find((n) => n.kind === "decide" && /has no steward/u.test(n.what)); + expect(need).toBeDefined(); + expect(need!.what).toMatch(/adopt it under a ticket, or close it/u); + }); + + it("states the wrap-up rule in the ticket playbook templates", () => { + for (const text of [LINEAR_TICKETS, LOCAL_TICKETS, GITHUB_ISSUES]) { + expect(text).toMatch(/Reaching a terminal state starts the wrap-up/u); + expect(text).toMatch(/Never leave an open pull request/u); + } + }); +}); + // BB-325: an ended binding (BCP-154) takes no new question, forward, hold or // priority change; a late report or escalation is carried to the project // steward instead of being stored on the binding, and a question left on an diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 91c6a387..d5805124 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -3925,13 +3925,15 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P function leasedPulls(b: Pick): string[] { if (b.kind !== "ticket" || b.lastSnapshot === null) return []; const pulls = b.lastSnapshot.pulls; - return b.lastSnapshot.entity.linkedPulls - .map((l) => l.key) - .filter((k): k is string => k !== null) - .filter((k) => { - const seen = pulls.find((p) => lc(p.key) === lc(k)); - return seen === undefined || !["closed", "merged"].includes(lc(seen.state)); - }); + // A pull request handed to this binding is in the stored snapshot even + // when the ticket's timeline does not link it, so enumerating the + // snapshot as well as the links keeps it leased (BB-386). + const keys = new Set(pulls.map((p) => p.key)); + for (const l of b.lastSnapshot.entity.linkedPulls) if (l.key !== null) keys.add(l.key); + return [...keys].filter((k) => { + const seen = pulls.find((p) => lc(p.key) === lc(k)); + return seen === undefined || !["closed", "merged"].includes(lc(seen.state)); + }); } /** @@ -5542,7 +5544,21 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } // An unread relation keeps the last known parent and children (BB-244). entity = keepRelations(b.lastSnapshot?.entity ?? null, entity); - const observed: Observed = { entity, pulls: b.kind === "ticket" ? await linkedPulls(entity, b.lastSnapshot) : [], at: now() }; + const linked = b.kind === "ticket" ? await linkedPulls(entity, b.lastSnapshot) : []; + // BB-386: a pull request handed to this binding is observed even when the + // ticket's timeline does not link it, so the binding gates and merges it. + if (b.kind === "ticket") { + for (const h of store.pullHandoffsTo(b.id)) { + if (linked.some((p) => lc(p.key) === lc(h.pullKey))) continue; + try { + const pull = await snapshot("github", h.pullKey); + if (pull !== null && pull.kind === "pull") linked.push(pull); + } catch (error) { + bb.log.warn(`stewards: could not read ${h.pullKey}, handed to ${b.entityKey}: ${errorMessage(error)}`); + } + } + } + const observed: Observed = { entity, pulls: linked, at: now() }; const prev = b.lastSnapshot; // BB-53: a merged pull request whose playbook names a deployment target @@ -7407,6 +7423,71 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P */ const TERMINAL_WORKER_REPORT_MS = 15 * 60_000; + /** + * BB-386: re-homing is for orphans this version can prevent. A binding + * that ended before the feature first ran is not scanned: its pull requests + * are the pre-fix backlog the ticket's out-of-scope note covers. The cutoff + * is kept in bb's kv, so a restart does not re-scan or forget it. + */ + let rehomeSinceCache: number | null = null; + async function rehomeSince(): Promise { + if (rehomeSinceCache !== null) return rehomeSinceCache; + const stored = await bb.storage.kv.get("stewards/rehome-since"); + if (typeof stored === "number") { + rehomeSinceCache = stored; + return stored; + } + const at = now(); + await bb.storage.kv.set("stewards/rehome-since", at); + rehomeSinceCache = at; + return at; + } + + /** + * BB-386: the open work a binding still holds, by the mechanical + * definition: pull requests it opened that are still open, running + * workers, open escalations, open needs and a typed wait. Stacked and + * held bindings are not here: they are listed by the wrap-up wake but + * never keep a binding from ending. `pulls` is the open pull-request + * subset, for the follow-through default and the re-homing path. + */ + async function openWorkFor(b: Binding, observed: Observed, opts: { includeWorkers?: boolean } = {}): Promise<{ items: string[]; pulls: string[] }> { + const items: string[] = []; + const pulls: string[] = []; + const ownPulls = await ownPullKeys(b, store.workers(b.id), observed); + for (const p of observedPulls(b, observed)) { + if (p.pull === null) continue; + if (p.pull.merged === true || lc(p.state) === "closed" || lc(p.state) === "merged") continue; + if (!pullBelongsToTicket(b, p, ownPulls)) continue; + pulls.push(p.key); + items.push(`pull request ${p.key} is still open`); + } + if (opts.includeWorkers !== false) { + for (const w of store.workers(b.id)) { + if (w.status === "running") items.push(`worker "${w.title}" (thread ${w.threadId}) is still running`); + } + } + for (const x of store.openEscalations(b.id)) items.push(`escalation ${x.id} (${x.kind}) is still open: ${x.question}`); + for (const n of store.openNeeds(b.id)) items.push(`need ${n.id} (${n.kind}) is still open: ${n.what}`); + if (b.wait !== null) items.push(`a typed wait is still open: ${b.wait.kind} ${b.wait.ref}`); + return { items, pulls }; + } + + /** + * BB-386: the bindings stacked on or held behind `b`, for the wrap-up + * wake's context. These never keep the binding from ending: a behind hold + * lifts when the binding ends, and a stacked binding waits for it. + */ + function stackedOrHeld(b: Binding): string[] { + const out: string[] = []; + for (const h of store.open(b.projectId)) { + if (h.id === b.id) continue; + if (h.mergeBehind.some((k) => lc(k) === lc(b.entityKey) || lc(k) === lc(b.id))) out.push(`${h.entityKey} (held behind this binding)`); + if (b.stackedPulls.length > 0 && h.mergeBehind.some((k) => b.stackedPulls.some((p) => lc(p) === lc(k)))) out.push(`${h.entityKey} (stacked on this binding's pull request)`); + } + return [...new Set(out)]; + } + /** * The one wrap-up (terminal) or stop (detach, disabled, reassigned, * moved) turn before the binding ends. A detach stops the workers now: @@ -7428,9 +7509,20 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const workerDone = kind === "terminal" && store.workers(b.id).some((w) => w.result !== null && (w.endedAt === null || now() - w.endedAt <= TERMINAL_WORKER_REPORT_MS) && workerReportedTerminal(w.result, observed.entity.key, playbook)); - const ownDone = kind === "terminal" && (stewardDone || workerDone); + // BB-386: the ownDone shortcut must not fire while the binding holds open + // work. A binding does not end silently over a pull request it opened, a + // running worker, an open escalation, need or typed wait; it takes its + // wrap-up wake, which names each item. + const work = kind === "terminal" ? await openWorkFor(b, observed) : { items: [] as string[], pulls: [] as string[] }; + const ownDone = kind === "terminal" && (stewardDone || workerDone) && work.items.length === 0; signalNeedActionability(b, observed); - b = store.patch(b.id, { ending: kind, endingAt: now(), followThrough: null, followThroughUntil: null, lastSnapshot: observed, clearedToStart: false }); + // BB-386: follow-through is the default for a still-open pull request the + // binding opened, so the ending waits until the wrap-up settles every + // item rather than ending quietly. A report without followThrough keeps + // it on while any item remains (the report path enforces that too). + const followThrough = work.items.length === 0 ? null : `Open work: ${work.items.join("; ")}`; + const followThroughUntil = followThrough === null ? null : now() + (playbook.followThroughMs ?? DEFAULT_FOLLOW_THROUGH_MS); + b = store.patch(b.id, { ending: kind, endingAt: now(), followThrough, followThroughUntil, lastSnapshot: observed, clearedToStart: false }); // Whatever its work was holding back can go now: landed, canceled or no longer managed, it is not merging later. await releaseBehind(b, kind === "terminal" ? `reached ${observed.entity.state}` : kind === "disabled" ? "the project was switched off" : kind === "reassigned" ? "was reassigned away from this server" : kind === "moved" ? `moved to the ${observed.entity.unit} team, which this project does not watch` : "was detached"); if (kind !== "terminal") await stopWorkers(b); @@ -7449,7 +7541,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P await finishEnding(b, "terminal"); return; } - await wake(b, config, playbook, observed, [kind === "terminal" ? `Terminal: ${observed.entity.state}` : kind === "disabled" ? "Stewards for this project were switched off on this server" : kind === "reassigned" ? `Reassigned: ${observed.entity.assignees.join(", ") || "no assignee"}` : kind === "moved" ? `Moved: ${observed.entity.unit} is not a team this project watches` : `The ${config.file.label} label was removed`], kind); + await wake(b, config, playbook, observed, [ + kind === "terminal" ? `Terminal: ${observed.entity.state}` : kind === "disabled" ? "Stewards for this project were switched off on this server" : kind === "reassigned" ? `Reassigned: ${observed.entity.assignees.join(", ") || "no assignee"}` : kind === "moved" ? `Moved: ${observed.entity.unit} is not a team this project watches` : `The ${config.file.label} label was removed`, + ...work.items.map((i) => `Open work, finish, transfer or close it: ${i}`), + ...(kind === "terminal" ? stackedOrHeld(b).map((i) => `Stacked on or held behind this binding (it never keeps it from ending): ${i}`) : []), + ], kind); } /** @@ -7573,6 +7669,98 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P for (const { b, closed } of byBinding.values()) noteEndingReport(b, `closed ${closed.join("; ")}.`); } + /** BB-386: the entity keys a pull request body says it fixes or closes. */ + function pullFixesKeys(pull: EntitySnapshot): string[] { + const body = pull.description ?? ""; + const out: string[] = []; + for (const m of body.matchAll(/\b(?:fix(?:e[sd])?|close[sd]?|resolve[sd]?)\b:?\s+#(\d+)/giu)) out.push(`${pull.unit}#${m[1]}`); + for (const m of body.matchAll(/\b(?:fix(?:e[sd])?|close[sd]?|resolve[sd]?)\b:?\s+([A-Za-z][A-Za-z0-9]*-\d+)/giu)) out.push(m[1]!); + return [...new Set(out)]; + } + + /** + * BB-386: an open pull request whose owning binding ended is re-homed, + * never dropped. It goes to an open binding whose ticket the pull request + * body says it fixes or closes, or to the project steward as a need naming + * it. Only a pull request a binding on this server opened is moved: a + * teammate's, with no ended binding of ours behind it, is left alone. + * + * An ended binding's snapshot is never refreshed, so each candidate is read + * fresh; a handled one (a handoff row, or a filed need, open or resolved) is + * not looked at again, and the scan is bounded to bindings that ended after + * this shipped. + */ + async function rehomeOrphanedPulls(config: ProjectConfig): Promise { + const projectId = config.projectId; + const login = config.githubLogin; + const since = await rehomeSince(); + const seen = new Set(); + for (const b of store.all(projectId)) { + if (b.endedAt === null || b.endedAt < since || b.lastSnapshot === null) continue; + const observed = b.lastSnapshot; + let ownPulls: ReadonlySet | null = null; + for (const p of observedPulls(b, observed)) { + if (p.pull === null || p.pull.merged === true || lc(p.state) === "closed" || lc(p.state) === "merged") continue; + const key = lc(p.key); + if (seen.has(key)) continue; + // BB-386: a pull request handed away is not this binding's to handle. + // Do not add it to `seen` (a later ended binding is its owner now) + // and do not mark it, so the owner's own iteration still runs. + const handoff = store.pullHandoff(p.key); + if (handoff !== null && handoff.toBindingId !== b.id) continue; + seen.add(key); + // A handled pull request is not looked at again. The mark is the + // primary record; a filed (or resolved) need covers rows that predate + // the mark table. + if (store.pullRehomeMarked(p.key, b.id)) continue; + const what = `${p.key} has no steward: adopt it under a ticket, or close it`; + if (store.needs(b.id, true).some((n) => n.kind === "decide" && n.url === (p.url ?? "") && n.what === what)) { + store.markPullRehome(p.key, b.id); + continue; + } + // The author and the own set do not change, so a teammate's pull + // request is refused from the stored snapshot, before any read. + ownPulls ??= await ownPullKeys(b, store.workers(b.id), observed); + if (!serverOpenedPull(p, ownPulls, login)) { + store.markPullRehome(p.key, b.id); + continue; + } + // Re-read fresh: a merge or close after the binding ended would + // otherwise read as open in the frozen snapshot. A read that fails is + // left unmarked, so the orphan is looked at again rather than + // dropped; a merged or closed result is marked so it is not fetched + // again. + const fresh = await snapshot("github", p.key).catch(() => null); + if (fresh === null) continue; + if (fresh.pull === null || fresh.pull.merged === true || lc(fresh.state) === "closed" || lc(fresh.state) === "merged") { + store.markPullRehome(p.key, b.id); + continue; + } + const target = pullFixesKeys(fresh) + .map((k) => store.find(k, projectId)) + .find((t): t is Binding => t !== null && t.endedAt === null && t.id !== b.id) ?? null; + if (target !== null) { + store.handOffPull(p.key, target.id, b.id); + scheduleReconcile(target.id); + store.markPullRehome(p.key, b.id); + bb.log.info(`stewards: re-homed ${p.key} from ended ${b.entityKey} to ${target.entityKey}`); + continue; + } + store.fileNeed({ + bindingId: b.id, + kind: "decide", + url: p.url ?? "", + what, + how: `The binding that opened it (${b.entityKey}) ended while it was still open.`, + why: "Re-homing found no open binding whose ticket this pull request fixes or closes.", + filedBy: "plugin", + }); + store.markPullRehome(p.key, b.id); + await wakeProject(projectId, `${p.key} has no steward`, { digestDue: false, notes: [what] }); + } + } + } + async function finishEnding(b: Binding, reason: string): Promise { b = store.patch(b.id, { ending: null, endingAt: null, followThrough: null, followThroughUntil: null, endedAt: now(), endReason: reason, awaitingReport: false, requeueAt: null }); // Mechanical cleanup, not a decision: the origin binding has ended, so @@ -7639,12 +7827,29 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P async function followThroughRanOut(b: Binding): Promise { const what = b.followThrough ?? "(not said)"; const stopped = store.workers(b.id).filter((w) => w.status === "running").map((w) => w.title); + // BB-386: the deadline is not a quiet end. Any open work still held is + // named in a `decide` need for the owner, so the orphaned items are + // visible rather than dropped; the re-homing pass then gives an open + // pull request a new owner. + const work = b.lastSnapshot === null ? { items: [] as string[], pulls: [] as string[] } : await openWorkFor(b, b.lastSnapshot); + if (work.items.length > 0) { + store.fileNeed({ + bindingId: b.id, + kind: "decide", + url: "", + what: `Finish the work ${b.entityKey} left open`, + how: `The binding reached a terminal state and kept following through, but its deadline passed with these still open:\n${work.items.map((i) => `- ${i}`).join("\n")}`, + why: "The binding's follow-through ran out before every open item was finished, transferred or closed.", + filedBy: "plugin", + }); + } bb.log.warn(`stewards: ${b.entityKey}'s follow-through ran out (${what})`); await finishEnding(b, "terminal"); await wakeProject(b.projectId, `follow-through ran out on ${b.entityKey}`, { digestDue: false, notes: [ `${b.entityKey} reached a terminal state and its steward kept it open to follow through: ${JSON.stringify(what)}. That ran out before the steward said it was done, so the binding ended${stopped.length > 0 ? ` and these workers were stopped: ${stopped.join("; ")}` : ""}.`, + ...(work.items.length > 0 ? [`Open work it left behind: ${work.items.join("; ")}. The owner has a decide item naming it; an open pull request is re-homed on the next reconcile.`] : []), "Decide from the project's guidance whether the work needs finishing. Reopening the entity resumes its steward; do not do a steward's work yourself.", ], }); @@ -9125,6 +9330,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * naming branch or title is not recognized in this first cut (BB-239 spec). */ function pullBelongsToTicket(b: Binding, pull: EntitySnapshot, ownPulls: ReadonlySet): boolean { + // BB-386: a handoff is authoritative. A pull request moved to another + // binding belongs to the row's target and to no one else, whatever the + // opening worker's branch or the title says. + const handoff = store.pullHandoff(pull.key); + if (handoff !== null) return handoff.toBindingId === b.id; const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&"); if (ownPulls.has(lc(pull.key)) || (pull.url !== null && ownPulls.has(lc(pull.url)))) return true; const key = b.entityKey.trim(); @@ -9144,6 +9354,19 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return new RegExp(`(?:^|[^a-z0-9])${escape(lc(key))}(?:[^a-z0-9]|$)`, "u").test(lc(title)); } + /** + * BB-386: whether a pull request was opened by this server, so a handoff, + * adoption or re-homing may move it. A worker of the binding opened or + * reported it (`ownPulls`), or its author is this server's GitHub login. A + * teammate's pull request that merely names a ticket in its title or head + * branch is never moved; a login that cannot be read does not open the door + * either. + */ + function serverOpenedPull(pull: EntitySnapshot, ownPulls: ReadonlySet, login: string | null): boolean { + if (ownPulls.has(lc(pull.key)) || (pull.url !== null && ownPulls.has(lc(pull.url)))) return true; + return login !== null && pull.author !== null && lc(pull.author) === lc(login); + } + /** * The schedule wake's pull request facts (BB-89): how many of a binding's * linked pull requests are open and how many merged, and whether its @@ -13155,6 +13378,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P .max(20) .optional() .describe('A merge hold: entity keys of open bindings in this project whose work must finish before this binding\'s pull request is merged, like steward_update\'s behind. While it stands the plugin files no Merge item (so the page does not read as "needs you"), the binding shows as held, and it is a live wake source. Report it when a spec says "do not merge before X is Done"; the hold lifts itself, and you are woken, once every named binding has merged its pull requests or ended. Each report replaces the set; `mergeBehind: []` clears it.'), + handOff: z + .object({ + pull: z.string().trim().min(1).max(500).describe("The pull request to transfer: its key (owner/repo#N) or URL. It must be one this binding opened."), + to: z.string().trim().min(1).max(200).describe("The binding that takes it: another open binding's entity key (or id) in this project."), + }) + .optional() + .describe("BB-386: transfer one of this binding's open pull requests to another binding, so that binding merges it. The store records the move and the target files the Merge item; it changes which binding merges, never the lane or the gate. A project-steward approval is bound to the binding and head, so it does not move: the target asks for one again. Use it in the wrap-up turn instead of leaving a pull request behind."), needs: z .array( z.object({ @@ -13299,6 +13529,29 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (missing.length > 0) return toolError(new Error(`Not an open binding or pull request in this project to hold the merge behind: ${missing.join(", ")}.`)); mergeBehind = [...named.map((x) => x.entityKey), ...prKeys]; } + // BB-386: a handoff moves one of this binding's open pull requests to + // another open binding, so the target merges it. The store records the + // move; `pullBelongsToTicket` reads it first, so the opener no longer + // owns the pull and the target's merge item is not foreign. Only a + // pull this binding opened can be moved, and only to a binding on this + // server. + let handOffNote = ""; + if (input.handOff !== undefined) { + const ref = parsePullRef(input.handOff.pull); + if (ref === null) return toolError(new Error(`handOff.pull must be a pull request key (owner/repo#N) or its URL; ${JSON.stringify(input.handOff.pull)} is not.`)); + const pullKey = `${ref.repo}#${ref.number}`; + const target = store.find(input.handOff.to, b.projectId); + if (target === null || target.endedAt !== null) return toolError(new Error(`handOff.to must name an open binding in this project; ${JSON.stringify(input.handOff.to)} is not one.`)); + if (target.id === b.id) return toolError(new Error("handOff.to is this binding; name the binding that takes the pull request.")); + const observed = b.lastSnapshot; + const ownPulls = observed === null ? new Set() : await ownPullKeys(b, store.workers(b.id), observed); + const pull = observed === null ? null : (observedPulls(b, observed).find((p) => lc(p.key) === lc(pullKey)) ?? null); + const login = (await loadConfig(b.projectId))?.githubLogin ?? null; + if (pull === null || !serverOpenedPull(pull, ownPulls, login)) return toolError(new Error(`${pullKey} is not an open pull request this server opened, so it cannot be handed off. A teammate's pull request, or one opened by another binding, is not this binding's to move.`)); + store.handOffPull(pullKey, target.id, b.id); + scheduleReconcile(target.id); + handOffNote = ` ${pullKey} is now ${target.entityKey}'s to merge; it files the Merge item on its next look, and a project-steward approval does not move with it.`; + } // BB-231: a free-form escalation must say how it differs from every // open user-facing item on the binding, or it can duplicate the // plugin's gate item. The pairwise judgement is forced here; no @@ -13332,7 +13585,16 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // unanswered (BB-60). const openBeforeReport = b.ending === "terminal" ? store.openEscalations(b.id) : []; const escalationFollowThrough = b.ending !== "terminal" ? null : (input.escalate?.question ?? openBeforeReport[0]?.question ?? null); - const followThrough = input.followThrough ?? escalationFollowThrough; + // BB-386: while the binding still holds open work (a pull request it + // opened, an open escalation, need or typed wait), follow-through + // stays on even when the report does not name it, so the wrap-up turn + // cannot end the binding over an unfinished item; the overdue path + // raises a need naming the orphans. A running worker is deliberately + // not counted here: the wrap-up report is the steward's affirmative + // decision, and ending the binding stops the worker (the mechanical + // tier's ownDone gate does count it, so no end is silent). + const openWork = b.ending === "terminal" && input.followThrough === undefined && b.lastSnapshot !== null ? await openWorkFor(b, b.lastSnapshot, { includeWorkers: false }) : { items: [] as string[], pulls: [] as string[] }; + const followThrough = input.followThrough ?? escalationFollowThrough ?? (openWork.items.length === 0 ? null : `Open work: ${openWork.items.join("; ")}`); // Follow-through has one deadline from when it was first declared; a // requeue past it is a requeue at it. const followThroughUntil = b.ending !== "terminal" ? null : (b.followThroughUntil ?? (followThrough === null ? null : now() + (playbook?.followThroughMs ?? DEFAULT_FOLLOW_THROUGH_MS))); @@ -13858,20 +14120,20 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // that would contradict it. const requeueOnly = `Until you name one, this wait is delivered only by requeue, ${requeuePhrase}.`; if (b.ending === "terminal") { - if (b.followThrough === null) return `Reported.${untilNote}${waitNote}${replacedNote}${filingNote}${escalated}${deploymentNote}${citesNote} The binding ends when this turn does: running workers are stopped and the thread is archived. End the turn now.`; + if (b.followThrough === null) return `Reported.${untilNote}${waitNote}${replacedNote}${handOffNote}${filingNote}${escalated}${deploymentNote}${citesNote} The binding ends when this turn does: running workers are stopped and the thread is archived. End the turn now.`; const followWake = noWakeSource ? `${noWakeSourceReportSentence(waitingOn, namedOpenKeys)} ${requeueOnly}` : `You will be woken when a worker finishes or something actionable changes, or ${requeuePhrase}. End the turn now.`; - return `Reported.${untilNote}${waitNote}${replacedNote}${filingNote}${escalated}${deploymentNote}${citesNote} The binding stays open to follow through until ${iso(followThroughUntil!)}; running workers keep going. ${followWake}`; + return `Reported.${untilNote}${waitNote}${replacedNote}${handOffNote}${filingNote}${escalated}${deploymentNote}${citesNote} The binding stays open to follow through until ${iso(followThroughUntil!)}; running workers keep going. ${followWake}`; } const recorded = opsTickets.length === 0 ? "" : ` Recorded ${opsTickets.map((t) => `${t.ticket} (${t.did})`).join(", ")} against ${opsTickets.length === 1 ? "its fingerprint" : "their fingerprints"}.`; if (gateJustPassed && nothingPending) { - return `Reported.${untilNote}${waitNote}${replacedNote}${recorded}${filingNote}${escalated}${citesNote} Ready gate: passed and nothing schedules you. Move the ticket to In Progress and start the worker now, in this turn, with the task in the In Progress instructions; do not end the turn first.`; + return `Reported.${untilNote}${waitNote}${replacedNote}${handOffNote}${recorded}${filingNote}${escalated}${citesNote} Ready gate: passed and nothing schedules you. Move the ticket to In Progress and start the worker now, in this turn, with the task in the In Progress instructions; do not end the turn first.`; } const wakeNote = noWakeSource ? `${noWakeSourceReportSentence(waitingOn, namedOpenKeys)} ${requeueOnly}` : `You will be woken when something actionable changes, or ${requeuePhrase}. End the turn now.`; - return `Reported.${untilNote}${waitNote}${replacedNote}${recorded}${filingNote}${gateNote}${escalated}${citesNote} ${wakeNote}`; + return `Reported.${untilNote}${waitNote}${replacedNote}${handOffNote}${recorded}${filingNote}${gateNote}${escalated}${citesNote} ${wakeNote}`; } catch (error) { return toolError(error); } @@ -13953,6 +14215,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P .max(10) .optional() .describe("With hold: the open bindings (entity keys) whose open pull request this stack-wait waits for. It lifts itself, and the steward is woken with that pull request's head branch, as soon as every one has opened a pull request; use it to start a ticket stacked on work still being built."), + adoptPull: z + .string() + .trim() + .min(1) + .max(500) + .optional() + .describe("Project steward only, with binding: take a pull request this server opened (its key owner/repo#N or URL) into that binding, so it merges it. It moves which binding merges, never the lane or the gate; a project-steward approval does not move, so the target asks for one again. Refused for a pull request this server did not open (a teammate's)."), stewardModel: modelSpecSchema.optional().describe("The steward thread's model, provider/model/level."), workerModel: modelSpecSchema.optional().describe("The model for workers it starts from now."), reviewerModel: modelSpecSchema.optional().describe("The model for reviewers its workers start from now."), @@ -14149,6 +14418,38 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } const self = target.threadId === threadId; + // BB-386: the project steward adopts a pull request this server + // opened into a named binding, so the binding that should merge it + // owns it. A teammate's pull request is never adopted; the move + // changes only which binding merges, never the lane, gate or an + // approval. + if (input.adoptPull !== undefined) { + if (projectOf === null) return toolError(new Error("adoptPull is the project steward's: a steward hands a pull request off with steward_report { handOff }.")); + if (target.endedAt !== null) return toolError(new Error(endedBindingRefusal(target))); + const ref = parsePullRef(input.adoptPull); + if (ref === null) return toolError(new Error(`adoptPull must be a pull request key (owner/repo#N) or its URL; ${JSON.stringify(input.adoptPull)} is not.`)); + const pullKey = `${ref.repo}#${ref.number}`; + const pull = await snapshot("github", pullKey).catch(() => null); + if (pull === null || pull.kind !== "pull") return toolError(new Error(`No pull request ${pullKey} to adopt.`)); + const config = await loadConfig(target.projectId); + const login = config?.githubLogin ?? null; + // BB-386 limit 2: a teammate's pull request is never adopted, and a + // login that cannot be read refuses rather than failing open. + if (login === null || pull.author === null || lc(pull.author) !== lc(login)) { + return toolError(new Error(login === null ? `This server's GitHub login could not be read, so ${pullKey} cannot be confirmed as this server's to adopt.` : `${pullKey} was not opened by this server's GitHub login, so it is not this server's to adopt.`)); + } + const handoff = store.pullHandoff(pullKey); + const current = handoff === null ? null : store.binding(handoff.toBindingId); + if (current !== null && current.id === target.id) { + done.push(`${pullKey} is already ${target.entityKey}'s`); + } else { + store.handOffPull(pullKey, target.id, current?.id ?? handoff?.fromBindingId ?? null); + scheduleReconcile(target.id); + done.push(`adopted ${pullKey}; ${target.entityKey} files the Merge item on its next look`); + notes.push(`${pullKey} adopted by ${target.entityKey}; it files the Merge item on its next look. A project-steward approval does not move with it, so the target asks again.`); + } + } + const forwarding = input.forward === undefined ? null : store.escalation(input.forward); if (input.forward !== undefined) { if (forwarding === null || forwarding.status !== "open" || forwarding.bindingId !== target.id) return toolError(new Error(`No open escalation ${input.forward} on ${target.entityKey}.`)); @@ -14277,7 +14578,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const info = await threadInfo(target.threadId); if (info !== null && info.providerId !== "" && info.providerId !== input.stewardModel.providerId) return toolError(new Error(`${target.entityKey}'s steward runs on ${info.providerId}; a model can be changed, the provider cannot.`)); } - const asked = [guidance, resolve, input.forward, input.priority, input.hold, input.behind, input.stack, input.stewardModel, input.workerModel, input.reviewerModel, input.approve === true ? true : undefined, input.ask, input.lesson, closing ?? undefined]; + const asked = [guidance, resolve, input.forward, input.priority, input.hold, input.behind, input.stack, input.stewardModel, input.workerModel, input.reviewerModel, input.approve === true ? true : undefined, input.ask, input.lesson, input.adoptPull, closing ?? undefined]; if (asked.every((v) => v === undefined)) return toolError(new Error("Nothing to update: give guidance, resolve, forward, priority, hold, a model, approve, ask, or record a lesson.")); } const behind: Binding[] = []; @@ -15005,6 +15306,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P applyRationaleClustering(config); // BB-325: close any open item left on an ended binding, once. closeItemsOnEndedBindings(config.projectId); + // BB-386: an open pull request whose owning binding ended is re-homed or + // named in a project-steward need, never dropped. + await rehomeOrphanedPulls(config); for (const b of store.open(config.projectId)) { if (b.threadId !== null) await keepSteward(config.projectId, b.threadId); const deadline = endingDeadline(b, timing.endingTimeoutMs); diff --git a/plugins/stewards/store.test.ts b/plugins/stewards/store.test.ts index a36837de..169c811e 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, BACKLOG_LOOK_MIGRATIONS, BACKLOG_SNAPSHOT_MIGRATIONS, BACKLOG_WRITE_MIGRATIONS, CHECK_FINDING_MIGRATIONS, ESCALATION_REWAKE_MIGRATIONS, HUDDLE_MIGRATIONS, LEARNED_SLACK_MIGRATIONS, LOCAL_TICKET_MIGRATIONS, NON_ACTION_MIGRATIONS, PLAYBOOK_REFRESH_MIGRATIONS, TYPED_WAIT_MIGRATIONS, WAIT_BUDGET_MIGRATIONS, WAIT_SLACK_MIGRATIONS, WAIT_DIVERGENCE_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"; +import { ACTOR_MIGRATIONS, ALERTMANAGER_LOOK_MIGRATIONS, BACKLOG_LOOK_MIGRATIONS, BACKLOG_SNAPSHOT_MIGRATIONS, BACKLOG_WRITE_MIGRATIONS, CHECK_FINDING_MIGRATIONS, ESCALATION_REWAKE_MIGRATIONS, HUDDLE_MIGRATIONS, LEARNED_SLACK_MIGRATIONS, LOCAL_TICKET_MIGRATIONS, NON_ACTION_MIGRATIONS, PLAYBOOK_REFRESH_MIGRATIONS, TYPED_WAIT_MIGRATIONS, WAIT_BUDGET_MIGRATIONS, WAIT_SLACK_MIGRATIONS, WAIT_DIVERGENCE_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, HANDOFF_MIGRATIONS, REHOME_MARK_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]!)); @@ -750,7 +750,7 @@ describe("the actor rename migration (BB-97)", () => { // BB-341's backlog-writes ledger after that, and BB-351's wait-budget // columns after that. BB-354's wait-slacked column followed, and BB-358's // learned-Slack tables are the newest. - const groups = [ESCALATION_REWAKE_MIGRATIONS, LOCAL_TICKET_MIGRATIONS, LEARNED_SLACK_MIGRATIONS, WAIT_SLACK_MIGRATIONS, WAIT_BUDGET_MIGRATIONS, BACKLOG_WRITE_MIGRATIONS, PLAYBOOK_REFRESH_MIGRATIONS, WAIT_DIVERGENCE_MIGRATIONS, NON_ACTION_MIGRATIONS, TYPED_WAIT_MIGRATIONS, BACKLOG_SNAPSHOT_MIGRATIONS, CHECK_FINDING_MIGRATIONS, BACKLOG_LOOK_MIGRATIONS, 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]; + const groups = [REHOME_MARK_MIGRATIONS, HANDOFF_MIGRATIONS, ESCALATION_REWAKE_MIGRATIONS, LOCAL_TICKET_MIGRATIONS, LEARNED_SLACK_MIGRATIONS, WAIT_SLACK_MIGRATIONS, WAIT_BUDGET_MIGRATIONS, BACKLOG_WRITE_MIGRATIONS, PLAYBOOK_REFRESH_MIGRATIONS, WAIT_DIVERGENCE_MIGRATIONS, NON_ACTION_MIGRATIONS, TYPED_WAIT_MIGRATIONS, BACKLOG_SNAPSHOT_MIGRATIONS, CHECK_FINDING_MIGRATIONS, BACKLOG_LOOK_MIGRATIONS, 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]); @@ -850,8 +850,12 @@ describe("the escalation route rename migration (BB-209)", () => { // BB-328's check-findings table after that, BB-334's backlog snapshot // column after that, and BB-333's typed wait column after that. BB-335's // non-action column is last but for BB-333 PR 2's wait-divergence table. - const withoutEscalationRewake = MIGRATIONS.slice(0, -ESCALATION_REWAKE_MIGRATIONS.length); - expect(MIGRATIONS.slice(-ESCALATION_REWAKE_MIGRATIONS.length)).toEqual([...ESCALATION_REWAKE_MIGRATIONS]); + const withoutRehomeMark = MIGRATIONS.slice(0, -REHOME_MARK_MIGRATIONS.length); + expect(MIGRATIONS.slice(-REHOME_MARK_MIGRATIONS.length)).toEqual([...REHOME_MARK_MIGRATIONS]); + const withoutHandoff = withoutRehomeMark.slice(0, -HANDOFF_MIGRATIONS.length); + expect(withoutRehomeMark.slice(-HANDOFF_MIGRATIONS.length)).toEqual([...HANDOFF_MIGRATIONS]); + const withoutEscalationRewake = withoutHandoff.slice(0, -ESCALATION_REWAKE_MIGRATIONS.length); + expect(withoutHandoff.slice(-ESCALATION_REWAKE_MIGRATIONS.length)).toEqual([...ESCALATION_REWAKE_MIGRATIONS]); const withoutLocal = withoutEscalationRewake.slice(0, -LOCAL_TICKET_MIGRATIONS.length); const withoutLearnedSlack = withoutLocal.slice(0, -LEARNED_SLACK_MIGRATIONS.length); expect(withoutLocal.slice(-LEARNED_SLACK_MIGRATIONS.length)).toEqual([...LEARNED_SLACK_MIGRATIONS]); diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 311d74ae..5ac9e9a3 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -925,7 +925,36 @@ export const ESCALATION_REWAKE_MIGRATIONS = [ `ALTER TABLE bindings ADD COLUMN escalation_rewake_at INTEGER`, ]; -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, ...BACKLOG_LOOK_MIGRATIONS, ...CHECK_FINDING_MIGRATIONS, ...BACKLOG_SNAPSHOT_MIGRATIONS, ...TYPED_WAIT_MIGRATIONS, ...NON_ACTION_MIGRATIONS, ...WAIT_DIVERGENCE_MIGRATIONS, ...PLAYBOOK_REFRESH_MIGRATIONS, ...BACKLOG_WRITE_MIGRATIONS, ...WAIT_BUDGET_MIGRATIONS, ...WAIT_SLACK_MIGRATIONS, ...LEARNED_SLACK_MIGRATIONS, ...LOCAL_TICKET_MIGRATIONS, ...ESCALATION_REWAKE_MIGRATIONS]; +// BB-386: a pull request handed from the binding that opened it to another +// binding (a `steward_report { handOff }`, or the project steward's +// `steward_update { adoptPull }`). One row per pull request key, so a handoff +// is a move, not a history; `from_binding_id` is the binding it left, for the +// record and for re-homing. `pullBelongsToTicket` reads it first, so ownership +// follows the row rather than the opening worker's branch. +export const HANDOFF_MIGRATIONS = [ + `CREATE TABLE IF NOT EXISTS pull_handoffs ( + pull_key TEXT PRIMARY KEY, + from_binding_id TEXT, + to_binding_id TEXT NOT NULL, + created_at INTEGER NOT NULL + )`, + `CREATE INDEX IF NOT EXISTS pull_handoffs_to ON pull_handoffs (to_binding_id)`, +]; + +// BB-386: an ended binding's pull request that re-homing has already looked at +// (re-homed, named in a need, or found merged/closed, or a teammate's). One row +// per (pull key, binding), so a later sweep does not re-read it; the same pull +// request under a different ended binding is still considered. +export const REHOME_MARK_MIGRATIONS = [ + `CREATE TABLE IF NOT EXISTS pull_rehome_marks ( + pull_key TEXT NOT NULL, + binding_id TEXT NOT NULL, + at INTEGER NOT NULL, + PRIMARY KEY (pull_key, binding_id) + )`, +]; + +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, ...BACKLOG_LOOK_MIGRATIONS, ...CHECK_FINDING_MIGRATIONS, ...BACKLOG_SNAPSHOT_MIGRATIONS, ...TYPED_WAIT_MIGRATIONS, ...NON_ACTION_MIGRATIONS, ...WAIT_DIVERGENCE_MIGRATIONS, ...PLAYBOOK_REFRESH_MIGRATIONS, ...BACKLOG_WRITE_MIGRATIONS, ...WAIT_BUDGET_MIGRATIONS, ...WAIT_SLACK_MIGRATIONS, ...LEARNED_SLACK_MIGRATIONS, ...LOCAL_TICKET_MIGRATIONS, ...ESCALATION_REWAKE_MIGRATIONS, ...HANDOFF_MIGRATIONS, ...REHOME_MARK_MIGRATIONS]; // ---- values kept as JSON ------------------------------------------------------------ @@ -1838,6 +1867,9 @@ export type WorkerStatus = "running" | "finished" | "failed" | "stopped"; 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; /** 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 }; +/** BB-386: a pull request moved from one binding to another; one row per lowercased pull key. */ +export type PullHandoff = { pullKey: string; fromBindingId: string | null; toBindingId: string; createdAt: number }; + /** 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; nonActions: NonActions }; @@ -2921,6 +2953,46 @@ export function createStore(db: Database.Database, now: () => number, options: S return confirmed; } + // BB-386: a pull request moved from one binding to another. One row per + // lowercased pull key; a move overwrites the previous owner. The table may + // be absent on a store the migration tests built from an earlier list, so the + // statements are prepared only when it exists and the methods no-op without + // it (the same shape as the non-actions probe above). + const hasHandoffs = db.prepare("SELECT 1 AS one FROM sqlite_master WHERE type = 'table' AND name = 'pull_handoffs'").get() !== undefined; + const handoffStmts = hasHandoffs + ? { + upsert: db.prepare( + "INSERT INTO pull_handoffs (pull_key, from_binding_id, to_binding_id, created_at) VALUES (?, ?, ?, ?) ON CONFLICT(pull_key) DO UPDATE SET from_binding_id = excluded.from_binding_id, to_binding_id = excluded.to_binding_id, created_at = excluded.created_at", + ), + get: db.prepare<[string], Record>("SELECT * FROM pull_handoffs WHERE pull_key = ?"), + all: db.prepare<[], Record>("SELECT * FROM pull_handoffs"), + } + : null; + const toHandoff = (r: Record): PullHandoff => ({ + pullKey: String(r.pull_key), + fromBindingId: r.from_binding_id === null || r.from_binding_id === undefined ? null : String(r.from_binding_id), + toBindingId: String(r.to_binding_id), + createdAt: Number(r.created_at), + }); + // The handoff rows are read on every `pullBelongsToTicket` for a linked pull + // request, so they are cached in memory and the cache is kept in step by the + // two writers. One plugin process owns the table, so a cache entry cannot go + // stale behind it. + const handoffCache = new Map(); + // The whole table, read once and kept in step by `handOffPull`, so a binding + // can ask for the pull requests handed to it on every reconcile without a + // query each time. + let handoffToList: Map | null = null; + + // BB-386: the re-homing marks. Absent on a legacy store, like the handoffs. + const hasRehomeMarks = db.prepare("SELECT 1 AS one FROM sqlite_master WHERE type = 'table' AND name = 'pull_rehome_marks'").get() !== undefined; + const rehomeMarkStmts = hasRehomeMarks + ? { + has: db.prepare<[string, string], { n: number }>("SELECT COUNT(*) AS n FROM pull_rehome_marks WHERE pull_key = ? AND binding_id = ?"), + mark: db.prepare("INSERT INTO pull_rehome_marks (pull_key, binding_id, at) VALUES (?, ?, ?) ON CONFLICT(pull_key, binding_id) DO NOTHING"), + } + : null; + // BB-358: the learned Slack mappings and the DM log. The mapping is keyed by // the GitHub login or Linear user id; the value is a Slack user id or the // `not_on_slack` flag. No email is written. The DM log is the per-person, @@ -2937,6 +3009,57 @@ export function createStore(db: Database.Database, now: () => number, options: S const countSlackDm = hasLearnedSlack ? db.prepare<[string, string, number], { n: number }>("SELECT COUNT(*) AS n FROM slack_dms WHERE binding_id = ? AND person_key = ? AND sent_at >= ?") : null; return { + /** + * BB-386: move a pull request to another binding. `pullKey` is normalised + * to lower case; `fromBindingId` is the binding it leaves, when known. + */ + handOffPull(pullKey: string, toBindingId: string, fromBindingId: string | null): void { + if (handoffStmts === null) return; + const key = pullKey.toLowerCase(); + handoffStmts.upsert.run(key, fromBindingId, toBindingId, now()); + handoffCache.set(key, { pullKey: key, fromBindingId, toBindingId, createdAt: now() }); + handoffToList = null; + projectChanged(projectIdForBinding(toBindingId)); + if (fromBindingId !== null) projectChanged(projectIdForBinding(fromBindingId)); + }, + /** BB-386: the current owner of a handed-off pull request, or null when it was never moved. */ + pullHandoff(pullKey: string): PullHandoff | null { + if (handoffStmts === null) return null; + const key = pullKey.toLowerCase(); + const cached = handoffCache.get(key); + if (cached !== undefined) return cached; + const r = handoffStmts.get.get(key); + const result = r === undefined ? null : toHandoff(r); + handoffCache.set(key, result); + return result; + }, + + /** BB-386: the pull requests handed to a binding. */ + pullHandoffsTo(bindingId: string): PullHandoff[] { + if (handoffStmts === null) return []; + if (handoffToList === null) { + handoffToList = new Map(); + for (const r of handoffStmts.all.all()) { + const h = toHandoff(r); + const list = handoffToList.get(h.toBindingId); + if (list === undefined) handoffToList.set(h.toBindingId, [h]); + else list.push(h); + } + } + return handoffToList.get(bindingId) ?? []; + }, + + /** BB-386: whether re-homing already handled this pull request for this binding. */ + pullRehomeMarked(pullKey: string, bindingId: string): boolean { + if (rehomeMarkStmts === null) return false; + return (rehomeMarkStmts.has.get(pullKey.toLowerCase(), bindingId)?.n ?? 0) > 0; + }, + /** BB-386: record that re-homing handled this pull request for this binding. */ + markPullRehome(pullKey: string, bindingId: string): void { + if (rehomeMarkStmts === null) return; + rehomeMarkStmts.mark.run(pullKey.toLowerCase(), bindingId, now()); + }, + /** Run a synchronous handler as one operation, publishing at most one signal per project (BB-90). */ coalescing, /** Run an async handler as one turn, publishing at most one signal per project (BB-95). */ diff --git a/plugins/stewards/templates.ts b/plugins/stewards/templates.ts index 43ec8e6f..accc74c4 100644 --- a/plugins/stewards/templates.ts +++ b/plugins/stewards/templates.ts @@ -185,6 +185,8 @@ budget passes it files the owner's **Review it yourself / Reassign / Keep waiting** decide item, and Keep waiting resets the budget once. ${WAIT_SLACK_GUIDANCE} When every linked pull request is merged, move the ticket to Done. +Reaching a terminal state starts the wrap-up; it does not finish it. A binding never ends while it holds open work: finish every item (merge or close each pull request you opened, let each worker end, settle every escalation, need and wait), hand it off with \`steward_report { handOff: { pull, to } }\` (or ask the project steward to adopt it), or close it with a comment. Never leave an open pull request for someone else to find. + ${buildBlocker("the ticket")} `; @@ -286,6 +288,8 @@ it files the owner's **Review it yourself / Reassign / Keep waiting** decide item, and Keep waiting resets the budget once. ${WAIT_SLACK_GUIDANCE} When every linked pull request is merged, move the ticket to Done. +Reaching a terminal state starts the wrap-up; it does not finish it. A binding never ends while it holds open work: finish every item (merge or close each pull request you opened, let each worker end, settle every escalation, need and wait), hand it off with \`steward_report { handOff: { pull, to } }\` (or ask the project steward to adopt it), or close it with a comment. Never leave an open pull request for someone else to find. + ${buildBlocker("the ticket")} `; @@ -418,6 +422,8 @@ deployment source confirms the merge is live, close the issue with and where it is live, and end with steward_report. Until the deployment confirms it, the work is merged, not done: do not close the issue early. +Reaching a terminal state starts the wrap-up; it does not finish it. A binding never ends while it holds open work: finish every item (merge or close each pull request you opened, let each worker end, settle every escalation, need and wait), hand it off with \`steward_report { handOff: { pull, to } }\` (or ask the project steward to adopt it), or close it with a comment. Never leave an open pull request for someone else to find. + ${buildBlocker("the issue")} `;