diff --git a/plugins/stewards/reconcile.test.ts b/plugins/stewards/reconcile.test.ts index 0b46db16..d5354587 100644 --- a/plugins/stewards/reconcile.test.ts +++ b/plugins/stewards/reconcile.test.ts @@ -109,7 +109,7 @@ describe("what changed", () => { describe("waits nobody hears", () => { const status = (blockedOn: string | null) => ({ phase: "Todo", summary: "s", nextAction: "n", actor: "other" as const, blockedOn, requeueAfterMs: null, conditions: [], resources: { workers: [], pullRequests: [], children: [] }, at: 1 }); - const open = [{ id: "esc_1", bindingId: "b", kind: "decision" as const, question: "q", meanwhile: "m", route: "project" as const, recommendation: null, status: "open" as const, resolution: null, createdAt: 1, resolvedAt: null }]; + const open = [{ id: "esc_1", bindingId: "b", kind: "decision" as const, question: "q", meanwhile: "m", route: "project" as const, recommendation: null, status: "open" as const, resolution: null, createdAt: 1, resolvedAt: null, deliveredAt: null }]; it("flags a status blocked on the project steward or the user with no escalation open", () => { expect(unheardWait(status("project steward's approval of the new spec"), [])).toMatch(/project steward/u); diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 15ac3d05..50f02827 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -1,9 +1,11 @@ +import Database from "better-sqlite3"; import { createFakePluginHost, makePluginAgentConfigurationContext, makeThreadResponse } from "@get-bb/plugin-sdk/testing"; import { describe, expect, it } from "vitest"; import { PROJECT_FILE, playbookPath } from "./config.js"; import { comment, issue, pull } from "./fixtures.js"; import { createStewardsPlugin, testHooks } from "./server.js"; import { SOURCE_PLUGIN_IDS, type EntitySnapshot } from "./source-contract.js"; +import { MIGRATIONS } from "./store.js"; import { GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, projectFileTemplate } from "./templates.js"; type Call = { pluginId: string; method: string; input: Record }; @@ -620,6 +622,119 @@ describe("a Linear ticket steward", () => { }); }); +// HUB-195/196: two escalations seconds apart, and the second prompt listed +// the first as if new. HUB-183: a retried steward_update recorded its answer +// twice, and the escalation kept "The binding ended." instead. +describe("escalations delivered once, updates safe to retry", () => { + /** Two tickets with their stewards, and a way for each to escalate. */ + async function two() { + const t = await setup(); + t.entities.set("uuid-12", issue()); + t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", url: "https://linear.app/acme/issue/ENG-13", title: "Fix logout" })); + await t.ring("linear", "uuid-12"); + await t.ring("linear", "uuid-13"); + const project = t.hooks.store.project("p1").threadId!; + const escalate = async (key: string, question: string) => { + await t.tool("steward_report", { phase: "Todo", summary: "Spec drafted.", nextAction: "Wait", actor: "other", escalate: { kind: "decision", question, meanwhile: "Wait." } }, t.hooks.store.find(key)!.threadId!); + return t.hooks.store.openEscalations(t.hooks.store.find(key)!.id).at(-1)!.id; + }; + const toProject = () => t.sends.filter((s) => s.threadId === project).map((s) => s.text); + /** The escalation lines under one heading of a project steward prompt. */ + const under = (text: string, heading: string) => (text.split(`## ${heading}`)[1]?.split("\n## ")[0] ?? "").split("\n").filter((l) => l.startsWith("- esc_")); + return { ...t, project, escalate, toProject, under }; + } + + it("lists an escalation as new once, then as still open, and leaves out one resolved before the send", async () => { + const t = await two(); + const first = await t.escalate("ENG-12", "Include SSO?"); + expect(t.toProject()).toHaveLength(1); + expect(t.under(t.toProject()[0]!, "New escalations routed to you")).toEqual([expect.stringContaining(`${first} from ENG-12 (decision): Include SSO?`)]); + expect(t.toProject()[0]).not.toContain("## Escalations still open with you"); + + const second = await t.escalate("ENG-13", "Keep the old logout route?"); + expect(t.toProject()).toHaveLength(2); + const wake = t.toProject()[1]!; + expect(wake).toMatch(/# Project steward: escalation from ENG-13/u); + expect(t.under(wake, "New escalations routed to you")).toEqual([expect.stringContaining(`${second} from ENG-13`)]); + expect(t.under(wake, "Escalations still open with you")).toEqual([expect.stringContaining(`${first} from ENG-12`)]); + expect(t.hooks.store.escalation(first)!.deliveredAt).not.toBeNull(); + + // The first is decided while the third prompt is on its way (here, while + // the project steward is brought back from the archive): the prompt leaves it out. + t.threads.get(t.project)!.archivedAt = 1; + t.harness.sdk.stub("threads.unarchive", async (args: { threadId: string }) => { + t.hooks.store.resolve(first, "Yes, include SSO."); + return t.sdk.threads.unarchive(args); + }); + const third = await t.escalate("ENG-12", "Which SSO provider?"); + const last = t.toProject().at(-1)!; + expect(t.under(last, "New escalations routed to you")).toEqual([expect.stringContaining(`${third} from ENG-12`)]); + expect(t.under(last, "Escalations still open with you")).toEqual([expect.stringContaining(`${second} from ENG-13`)]); + expect(last).not.toContain(first); + }); + + it("counts escalations open before delivery was recorded as delivered", () => { + const db = new Database(":memory:"); + const added = MIGRATIONS.findIndex((m) => m.includes("ADD COLUMN delivered_at")); + for (const m of MIGRATIONS.slice(0, added)) db.exec(m); + const insert = db.prepare("INSERT INTO escalations (id, binding_id, kind, question, meanwhile, route, status, created_at) VALUES (?, 'b', 'decision', 'q', 'm', 'project', ?, 5)"); + insert.run("esc_open", "open"); + insert.run("esc_done", "resolved"); + for (const m of MIGRATIONS.slice(added)) db.exec(m); + expect(db.prepare("SELECT id, delivered_at FROM escalations ORDER BY id").all()).toEqual([ + { id: "esc_done", delivered_at: null }, + { id: "esc_open", delivered_at: 5 }, + ]); + }); + + it("writes nothing when a forward, resolve or approve target is bad", async () => { + const t = await two(); + const steward = t.hooks.store.find("ENG-12")!.threadId!; + const bad = [ + [{ binding: "ENG-12", guidance: "Use SAML.", resolve: "esc_nope", priority: "high" }, t.project], + [{ binding: "ENG-12", guidance: "Use SAML.", forward: "esc_nope", priority: "high" }, t.project], + [{ guidance: "Use SAML.", approve: true }, steward], + ] as const; + for (const [args, thread] of bad) expect((await t.tool("steward_update", args, thread)).error).toBe(true); + const b = t.hooks.store.find("ENG-12")!; + expect(b.guidance).toEqual([]); + expect(b.priority).toBeNull(); + expect(b.ready.approval).toBeNull(); + }); + + it("saves guidance repeated within five minutes once, and again after", async () => { + const t = await two(); + const update = () => t.tool("steward_update", { binding: "ENG-12", guidance: "Keep SSO out of this ticket." }, t.project); + expect((await update()).text).toBe("ENG-12: guidance saved."); + t.advance(60_000); + expect(await update()).toEqual({ error: false, text: "ENG-12: guidance already saved." }); + expect(t.hooks.store.find("ENG-12")!.guidance).toHaveLength(1); + t.advance(5 * 60_000); + expect((await update()).text).toBe("ENG-12: guidance saved."); + expect(t.hooks.store.find("ENG-12")!.guidance).toHaveLength(2); + // The same text from someone else is theirs to say, not a retry. + expect(t.hooks.store.addGuidance(t.hooks.store.find("ENG-12")!.id, "Keep SSO out of this ticket.", "thr_someone_else")).toBe(true); + expect(t.hooks.store.find("ENG-12")!.guidance).toHaveLength(3); + }); + + it("accepts guidance resolving an approval request that approve: true already closed", async () => { + const t = await two(); + const steward = t.hooks.store.find("ENG-12")!.threadId!; + const met = { checklist: [1, 2, 3, 4].map((item) => ({ item, met: true })), substantial: true }; + await t.tool("steward_report", { phase: "Todo", summary: "Spec posted.", nextAction: "Wait for approval", actor: "other", ready: met }, steward); + const id = /(esc_[\w-]+) from ENG-12 \(approval\)/u.exec(t.toProject().at(-1)!)![1]!; + + expect((await t.tool("steward_update", { binding: "ENG-12", approve: true }, t.project)).error).toBe(false); + const answered = await t.tool("steward_update", { binding: "ENG-12", guidance: "Approved; keep the migration reversible.", resolve: id }, t.project); + expect(answered).toMatchObject({ error: false, text: expect.stringMatching(/guidance saved; recorded the answer on esc_[\w-]+, which was already resolved \(Approved by the project steward\.\)/u) }); + expect(t.hooks.store.escalation(id)!.resolution).toBe("Approved by the project steward.\nApproved; keep the migration reversible."); + // Answering an approval already granted is no decline. + const b = t.hooks.store.find("ENG-12")!; + expect(b.ready.approval).not.toBeNull(); + expect(b.ready.declinedSpecHash).toBeNull(); + }); +}); + describe("terminal states and follow-through", () => { /** A ticket in progress with its steward and one worker at work. */ async function working() { @@ -712,6 +827,43 @@ describe("terminal states and follow-through", () => { expect((await t.list())[0]).toMatchObject({ ended: true }); }); + it("takes an answer to an escalation the ending resolved, once, keeping what the ending said", async () => { + const t = await working(); + await t.tool("steward_report", { phase: "In Progress", summary: "Building.", nextAction: "Wait", actor: "other", escalate: { kind: "decision", question: "Include SSO?", meanwhile: "Building the rest." } }, t.steward); + const id = /(esc_[\w-]+) from ENG-12/u.exec(t.sends.filter((x) => x.threadId === t.project).at(-1)!.text)![1]!; + await t.done(); + await t.report(); + await t.idle(t.steward); + expect((await t.list())[0]).toMatchObject({ ended: true }); + expect(t.hooks.store.escalation(id)).toMatchObject({ status: "resolved", resolution: "The binding ended." }); + + const answer = { binding: "ENG-12", guidance: "Yes, include SSO.", resolve: id }; + const first = await t.tool("steward_update", answer, t.project); + expect(first).toMatchObject({ error: false, text: expect.stringMatching(/guidance saved; recorded the answer on esc_[\w-]+, which was already resolved \(The binding ended\.\)/u) }); + // A retry changes nothing and is no error. + expect(await t.tool("steward_update", answer, t.project)).toMatchObject({ error: false, text: expect.stringMatching(/guidance already saved; esc_[\w-]+ already has this answer/u) }); + expect(t.hooks.store.escalation(id)!.resolution).toBe("The binding ended.\nYes, include SSO."); + expect(t.hooks.store.find("ENG-12")!.guidance.map((g) => g.text)).toEqual(["Yes, include SSO."]); + }); + + it("takes an answer to a forwarded question the ending closed, on the question and its escalation alike", async () => { + const t = await working(); + await t.tool("steward_report", { phase: "In Progress", summary: "Building.", nextAction: "Wait", actor: "other", escalate: { kind: "decision", question: "Include SSO?", meanwhile: "Building the rest." } }, t.steward); + const id = /(esc_[\w-]+) from ENG-12/u.exec(t.sends.filter((x) => x.threadId === t.project).at(-1)!.text)![1]!; + const qst = /(qst_[\w-]+)/u.exec((await t.tool("steward_update", { binding: "ENG-12", forward: id }, t.project)).text)![1]!; + await t.done(); + await t.report(); + await t.idle(t.steward); + expect((await t.list())[0]).toMatchObject({ ended: true }); + expect(t.hooks.store.question(qst)).toMatchObject({ status: "answered", answer: "The binding ended." }); + + const answer = { resolve: qst, answer: "Yes, include SSO." }; + expect(await t.tool("steward_update", answer, t.project)).toMatchObject({ error: false, text: expect.stringMatching(/ENG-12: guidance saved; recorded the answer on esc_[\w-]+, which was already resolved/u) }); + expect(await t.tool("steward_update", answer, t.project)).toMatchObject({ error: false, text: expect.stringMatching(/ENG-12: guidance already saved; esc_[\w-]+ already has this answer/u) }); + expect(t.hooks.store.escalation(id)!.resolution).toBe("The binding ended.\nYes, include SSO."); + expect(t.hooks.store.question(qst)).toMatchObject({ status: "answered", answer: "The binding ended.\nYes, include SSO." }); + }); + it("takes back the ending when the ticket is moved back before the binding ends", async () => { const t = await working(); await t.done(); @@ -1103,6 +1255,8 @@ describe("questions to the user", () => { const closed = await t.tool("steward_update", { resolve: t.qid(unbound.text), answer: "Yes, file it in BB." }, t.project); expect(closed).toMatchObject({ error: false, text: `closed ${t.qid(unbound.text)}.` }); + // A retry of the same close is no error and changes nothing. + expect(await t.tool("steward_update", { resolve: t.qid(unbound.text), answer: "Yes, file it in BB." }, t.project)).toMatchObject({ error: false, text: `${t.qid(unbound.text)} already closed with this answer.` }); expect((await t.tool("steward_update", { resolve: t.qid(unbound.text), answer: "Again." }, t.project)).text).toMatch(/already closed/u); // Guidance on a question about the whole project has no binding to land on: the question closes all the same. const project = await t.tool("steward_update", { ask: { question: "Adopt the new lint rules?" } }, t.project); @@ -1148,6 +1302,15 @@ describe("questions to the user", () => { expect(t.sends.filter((s) => s.threadId === t.steward).at(-1)!.text).toMatch(/decided: No SSO for now\./u); const list = (await t.harness.behavior.runCli(["show", "ENG-12", "--project", "p1"])).stdout; expect(list).toMatch(/\(resolved, me\): Include SSO\? → No SSO for now\./u); + + // A retry is no error, records nothing twice, and does not tell the steward again. + const told = t.sends.filter((s) => s.threadId === t.steward).length; + expect(await t.tool("steward_update", { resolve: qst, answer: "No SSO for now." }, t.project)).toMatchObject({ error: false, text: `ENG-12: guidance already saved; ${esc} already has this answer.` }); + await t.flush(); + expect(t.sends.filter((s) => s.threadId === t.steward)).toHaveLength(told); + expect(t.hooks.store.question(qst)).toMatchObject({ status: "answered", answer: "No SSO for now." }); + expect(t.hooks.store.escalation(esc)!.resolution).toBe("No SSO for now."); + expect(t.hooks.store.find("ENG-12")!.guidance.map((g) => g.text)).toEqual(["No SSO for now."]); }); it("is closed by the user from the page, which resolves a forwarded escalation and tells its steward", async () => { diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 30b4744d..da094c56 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -545,12 +545,16 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } } - /** Message a thread, bringing it back first if it was archived while it waited. */ - async function sendTo(threadId: string, text: string): Promise<"sent" | "gone" | "failed"> { + /** + * Message a thread, bringing it back first if it was archived while it + * waited. A function for the text is called just before the send, after + * those awaits, so it reads the store as of the send. + */ + async function sendTo(threadId: string, text: string | (() => string)): Promise<"sent" | "gone" | "failed"> { const info = await threadInfo(threadId).catch(() => null); if (info === null || info.deletedAt !== null) return "gone"; if (info.archivedAt !== null) await quietly(`unarchive ${threadId}`, () => bb.sdk.threads.unarchive({ threadId })); - return send(threadId, text); + return send(threadId, typeof text === "string" ? text : text()); } async function quietly(what: string, fn: () => Promise): Promise { @@ -1221,17 +1225,25 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (config === null) return; const threadId = await ensureProjectSteward(config); if (threadId === null) return; - const open = store.open(projectId); - const routed = open.flatMap((b) => store.openEscalations(b.id).filter((x) => x.route === "project").map((escalation) => ({ escalation, from: b }))); - const withUser = open.flatMap((b) => store.openEscalations(b.id).filter((x) => x.route === "me" && x.kind !== "approval").map((escalation) => ({ escalation, from: b }))); - const bindings = open.map((binding) => ({ binding, openEscalations: store.openEscalations(binding.id) })); - const questions = store.openQuestions(projectId).map((question) => ({ question, about: question.bindingId === null ? null : store.binding(question.bindingId) })); const records = opts.digestDue ? digestRecords(projectId) : undefined; if (opts.digestDue) store.patchProject(projectId, { digestPending: true }); - await sendTo( - threadId, - formatProjectWake({ reason, bindings, routed, withUser, problems: config.problems, digestDue: opts.digestDue, notes: opts.notes ?? [], bigDecisions: config.file.bigDecisions, questions, timeZone: config.file.nightly.timezone, ...(records === undefined ? {} : { records }) }), - ); + // Read as of the send, so an escalation resolved meanwhile is left out, + // and marked delivered in the same step, so a prompt sent right after + // lists it as still open rather than new. The text is built before the + // mark, so a throw while building it leaves nothing marked. + const delivered = { ids: [] as string[], at: 0 }; + const sent = await sendTo(threadId, () => { + const open = store.open(projectId); + const routed = open.flatMap((b) => store.openEscalations(b.id).filter((x) => x.route === "project").map((escalation) => ({ escalation, from: b }))); + const withUser = open.flatMap((b) => store.openEscalations(b.id).filter((x) => x.route === "me" && x.kind !== "approval").map((escalation) => ({ escalation, from: b }))); + const bindings = open.map((binding) => ({ binding, openEscalations: store.openEscalations(binding.id) })); + const questions = store.openQuestions(projectId).map((question) => ({ question, about: question.bindingId === null ? null : store.binding(question.bindingId) })); + const text = formatProjectWake({ reason, bindings, routed, withUser, problems: config.problems, digestDue: opts.digestDue, notes: opts.notes ?? [], bigDecisions: config.file.bigDecisions, questions, timeZone: config.file.nightly.timezone, ...(records === undefined ? {} : { records }) }); + delivered.ids = routed.filter((r) => r.escalation.deliveredAt === null).map((r) => r.escalation.id); + delivered.at = store.markDelivered(delivered.ids); + return text; + }); + if (sent !== "sent") store.undeliver(delivered.ids, delivered.at); } /** What the digest is written from, since the last one (or a day back): read from the tables, never from the project steward's memory. */ @@ -1913,10 +1925,27 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P try { const done: string[] = []; const notes: string[] = []; + /** Close the question and record the one asked, once every check has passed. */ + const questionWrites = (closing: { question: Question; answer: string; guidanceDropped: boolean } | null, target: Binding | null): string[] => { + const out: string[] = []; + if (closing !== null) { + const closed = store.answer(closing.question.id, closing.answer, threadId); + const dropped = closing.guidanceDropped ? " (guidance not saved: it is kept per binding, so name one with binding to give it)" : ""; + out.push(`${closed ? `closed ${closing.question.id}` : `${closing.question.id} already closed with this answer`}${dropped}`); + } + if (input.ask !== undefined) { + const q = store.ask({ projectId: projectOf!, bindingId: target?.id ?? null, escalationId: null, question: input.ask.question, context: input.ask.context ?? null }); + out.push(`question ${q.id} recorded${target === null ? "" : ` about ${target.entityKey}`}: ask the user in your reply, and close it with steward_update { resolve: "${q.id}", answer } once they answer`); + } + return out; + }; let resolve = input.resolve; let guidance = input.guidance; let bindingRef = input.binding; + // Every check comes before the first write, so a call that fails + // changes nothing and a model can retry it as it was. + // Questions to the user are the project steward's, and kept until answered. const projectOf = store.projectByThread(threadId)?.projectId ?? null; let closing: { question: Question; answer: string; guidanceDropped: boolean } | null = null; @@ -1927,16 +1956,18 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (projectOf !== null && resolve?.startsWith("qst_") === true) { const q = store.question(resolve); if (q === null || q.projectId !== projectOf) return toolError(new Error(`No question ${resolve} in this project.`)); - if (q.status !== "open") return toolError(new Error(`Question ${q.id} is already closed.`)); const answer = input.answer ?? guidance; if (answer === undefined) return toolError(new Error("Give the user's answer (answer) when closing a question.")); const x = q.escalationId === null ? null : store.escalation(q.escalationId); if (x !== null) { // A forwarded escalation: decided as one, which closes the question with it. + // Closed already (the binding ended, a retry) is answered the same way. resolve = x.id; guidance ??= answer; bindingRef ??= x.bindingId; } else { + // A retry of the close that already happened changes nothing. + if (q.status !== "open" && q.answer !== answer) return toolError(new Error(`Question ${q.id} is already closed.`)); closing = { question: q, answer, guidanceDropped: false }; resolve = undefined; if (input.guidance !== undefined && (input.answer !== undefined || q.bindingId !== null)) bindingRef ??= q.bindingId ?? undefined; @@ -1954,30 +1985,67 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (target === null) { const forBinding = [guidance, resolve, input.forward, input.recommendation, input.priority, input.hold, input.stewardModel, input.workerModel, input.approve, input.quote]; if (forBinding.some((v) => v !== undefined)) return toolError(new Error("Name the binding (binding: ENG-12 or owner/repo#3) for that.")); + if (closing === null && input.ask === undefined) return toolError(new Error("Nothing to update: name a binding, ask a question, or close one.")); + return `${questionWrites(closing, null).join("; ")}.`; } - if (input.ask !== undefined && target !== null && target.projectId !== projectOf) return toolError(new Error(`${target.entityKey} is not in this project.`)); - if (closing !== null) { - store.answer(closing.question.id, closing.answer, threadId); - done.push(`closed ${closing.question.id}${closing.guidanceDropped ? " (guidance not saved: it is kept per binding, so name one with binding to give it)" : ""}`); - } - if (input.ask !== undefined) { - const q = store.ask({ projectId: projectOf!, bindingId: target?.id ?? null, escalationId: null, question: input.ask.question, context: input.ask.context ?? null }); - done.push(`question ${q.id} recorded${target === null ? "" : ` about ${target.entityKey}`}: ask the user in your reply, and close it with steward_update { resolve: "${q.id}", answer } once they answer`); - } - if (target === null) { - if (done.length === 0) return toolError(new Error("Nothing to update: name a binding, ask a question, or close one.")); - return `${done.join("; ")}.`; - } + if (input.ask !== undefined && target.projectId !== projectOf) return toolError(new Error(`${target.entityKey} is not in this project.`)); const self = target.threadId === threadId; + const forwarding = input.forward === undefined ? null : store.escalation(input.forward); if (input.forward !== undefined) { - const x = store.escalation(input.forward); - if (x === null || x.status !== "open" || x.bindingId !== target.id) return toolError(new Error(`No open escalation ${input.forward} on ${target.entityKey}.`)); - const holder = x.route === "parent" ? store.binding(target.parentBindingId ?? "")?.threadId : x.route === "project" ? store.project(target.projectId).threadId : null; - if (holder !== threadId) return toolError(new Error(`Escalation ${x.id} is not with this thread, so it cannot forward it.`)); - const route = nextRoute(target, x.route); - const recommendation = input.recommendation ?? x.recommendation; - store.reroute(x.id, route, recommendation); + if (forwarding === null || forwarding.status !== "open" || forwarding.bindingId !== target.id) return toolError(new Error(`No open escalation ${input.forward} on ${target.entityKey}.`)); + const holder = forwarding.route === "parent" ? store.binding(target.parentBindingId ?? "")?.threadId : forwarding.route === "project" ? store.project(target.projectId).threadId : null; + if (holder !== threadId) return toolError(new Error(`Escalation ${forwarding.id} is not with this thread, so it cannot forward it.`)); + } + + const directs = mayDirect(threadId, target); + if (!directs && forwarding === null) return toolError(new Error(`This thread does not steer ${target.entityKey}: only its own steward, a steward above it, or the project steward does.`)); + let approval: { entity: EntitySnapshot; byUser: boolean } | null = null; + let resolving: Escalation | null = null; + if (directs) { + if (self && (input.priority !== undefined || input.hold !== undefined || input.stewardModel !== undefined)) { + return toolError(new Error("A steward does not set its own priority, hold or model; its parent or the project steward does.")); + } + if (input.approve === true) { + const config = await loadConfig(target.projectId); + const playbook = config === null ? null : playbookFor(config, target.kind); + const mode = playbook?.ready?.approval ?? null; + if (mode === null) return toolError(new Error(`${target.entityKey}'s playbook has no ready gate to approve.`)); + if (typeof mode === "object") return toolError(new Error(`${target.entityKey} is approved by moving it to ${mode["linear-state"]} in Linear.`)); + if (target.lastSnapshot === null) return toolError(new Error("Nothing has been observed for this binding yet.")); + const byProject = mode === "project" && isProjectSteward(threadId, target); + const byUser = input.quote !== undefined && (await userSaid(threadId, input.quote)); + if (!byProject && !byUser) { + return toolError( + new Error( + mode === "me" + ? "This spec is approved by the user: quote their words from a message they sent in this thread." + : "This spec is approved by the project steward (or by the user, quoting their words from this thread). Escalate a decision instead.", + ), + ); + } + // Pinned to the spec as it is now, not as last observed: a spec + // comment posted since the last ring is part of what was read. + approval = { entity: (await snapshot(target.source, target.entityId).catch(() => null)) ?? target.lastSnapshot.entity, byUser }; + } + if (resolve !== undefined) { + if (guidance === undefined) return toolError(new Error("Give the answer as guidance when resolving.")); + resolving = store.escalation(resolve); + if (resolving === null || resolving.bindingId !== target.id) return toolError(new Error(`No escalation ${resolve} on ${target.entityKey}.`)); + } + if (input.stewardModel !== undefined && target.threadId !== null) { + 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.stewardModel, input.workerModel, input.approve === true ? true : undefined, input.ask, closing ?? undefined]; + if (asked.every((v) => v === undefined)) return toolError(new Error("Nothing to update: give guidance, resolve, forward, priority, hold, a model, approve, or ask.")); + } + + done.push(...questionWrites(closing, target)); + if (forwarding !== null) { + const route = nextRoute(target, forwarding.route); + const recommendation = input.recommendation ?? forwarding.recommendation; + store.reroute(forwarding.id, route, recommendation); // Kept as a question to the user too, which closes when the escalation is resolved. Made // before the await below, so the escalation cannot be resolved in between and leave it open. const q = @@ -1986,68 +2054,42 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P : store.ask({ projectId: target.projectId, bindingId: target.id, - escalationId: x.id, - question: x.question, - context: [`A ${x.kind} escalation from ${target.entityKey}${target.title === null ? "" : ` (${target.title})`}.`, `Meanwhile: ${x.meanwhile}`, recommendation === null ? null : `Recommendation: ${recommendation}`].filter((c) => c !== null).join(" "), + escalationId: forwarding.id, + question: forwarding.question, + context: [`A ${forwarding.kind} escalation from ${target.entityKey}${target.title === null ? "" : ` (${target.title})`}.`, `Meanwhile: ${forwarding.meanwhile}`, recommendation === null ? null : `Recommendation: ${recommendation}`].filter((c) => c !== null).join(" "), }); - await deliver(target, store.escalation(x.id)!); - if (q !== null) done.push(`forwarded ${x.id} to the user as question ${q.id}: ask them in your reply, then record their answer with guidance + resolve`); - else done.push(`forwarded ${x.id} to the project steward`); - } - - if (!mayDirect(threadId, target)) { - if (done.length > 0) return `${target.entityKey}: ${done.join("; ")}.`; - return toolError(new Error(`This thread does not steer ${target.entityKey}: only its own steward, a steward above it, or the project steward does.`)); - } - if (self && (input.priority !== undefined || input.hold !== undefined || input.stewardModel !== undefined)) { - return toolError(new Error("A steward does not set its own priority, hold or model; its parent or the project steward does.")); + await deliver(target, store.escalation(forwarding.id)!); + if (q !== null) done.push(`forwarded ${forwarding.id} to the user as question ${q.id}: ask them in your reply, then record their answer with guidance + resolve`); + else done.push(`forwarded ${forwarding.id} to the project steward`); } + if (!directs) return `${target.entityKey}: ${done.join("; ")}.`; - if (input.approve === true) { - const config = await loadConfig(target.projectId); - const playbook = config === null ? null : playbookFor(config, target.kind); - const mode = playbook?.ready?.approval ?? null; - if (mode === null) return toolError(new Error(`${target.entityKey}'s playbook has no ready gate to approve.`)); - if (typeof mode === "object") return toolError(new Error(`${target.entityKey} is approved by moving it to ${mode["linear-state"]} in Linear.`)); - if (target.lastSnapshot === null) return toolError(new Error("Nothing has been observed for this binding yet.")); - const byProject = mode === "project" && isProjectSteward(threadId, target); - const byUser = input.quote !== undefined && (await userSaid(threadId, input.quote)); - if (!byProject && !byUser) { - return toolError( - new Error( - mode === "me" - ? "This spec is approved by the user: quote their words from a message they sent in this thread." - : "This spec is approved by the project steward (or by the user, quoting their words from this thread). Escalate a decision instead.", - ), - ); - } - // Pinned to the spec as it is now, not as last observed: a spec - // comment posted since the last ring is part of what was read. - const entity = (await snapshot(target.source, target.entityId).catch(() => null)) ?? target.lastSnapshot.entity; - store.patch(target.id, { ready: { ...target.ready, approval: { at: now(), specHash: specHash(entity, target.threadId), by: threadId }, voidedAt: null, declinedSpecHash: null } }); - for (const x of store.openEscalations(target.id).filter((e) => e.kind === "approval")) store.resolve(x.id, `Approved${byUser ? ` by the user: "${input.quote}"` : " by the project steward"}.`); + if (approval !== null) { + const by = approval.byUser ? ` by the user: "${input.quote}"` : " by the project steward"; + store.patch(target.id, { ready: { ...target.ready, approval: { at: now(), specHash: specHash(approval.entity, target.threadId), by: threadId }, voidedAt: null, declinedSpecHash: null } }); + for (const x of store.openEscalations(target.id).filter((e) => e.kind === "approval")) store.resolve(x.id, `Approved${by}.`); const others = store.openEscalations(target.id).filter((x) => x.id !== resolve); done.push(others.length === 0 ? "spec approved" : `spec approved; still open on it: ${others.map((x) => `${x.id} (${x.kind}, with ${x.route}): ${x.question}`).join(" | ")} — resolve any this approval answers`); - notes.push(`The spec was approved${byUser ? ` by the user: "${input.quote}"` : " by the project steward"}.`); + notes.push(`The spec was approved${by}.`); } if (guidance !== undefined) { - store.addGuidance(target.id, guidance, threadId); - done.push("guidance saved"); - if (resolve === undefined) notes.push(`New guidance: ${guidance}`); + // The same guidance again within minutes is a retry: saved once. + const saved = store.addGuidance(target.id, guidance, threadId); + done.push(saved ? "guidance saved" : "guidance already saved"); + if (saved && resolve === undefined) notes.push(`New guidance: ${guidance}`); } - if (resolve !== undefined) { - if (guidance === undefined) return toolError(new Error("Give the answer as guidance when resolving.")); - const x = store.escalation(resolve); - if (x === null || x.bindingId !== target.id) return toolError(new Error(`No escalation ${resolve} on ${target.entityKey}.`)); - // Approving closes its own request, so naming it in resolve too is no error. - if (!store.resolve(x.id, guidance, threadId) && !(x.kind === "approval" && input.approve === true)) return toolError(new Error(`Escalation ${resolve} is already resolved.`)); - if (x.kind === "approval" && input.approve !== true && target.lastSnapshot !== null) { + if (resolving !== null) { + // Already resolved (the binding ended, a retry) is no error: the answer is added to the record. + const outcome = store.answerEscalation(resolving.id, guidance!, threadId); + if (resolving.kind === "approval" && resolving.status === "open" && input.approve !== true && target.lastSnapshot !== null) { const fresh = store.binding(target.id)!; store.patch(target.id, { ready: { ...fresh.ready, declinedSpecHash: specHash(fresh.lastSnapshot!.entity, fresh.threadId) } }); } - done.push(`resolved ${x.id}`); - notes.push(`Escalation ${x.id} decided: ${guidance}`); + if (resolving.status === "open") done.push(`resolved ${resolving.id}`); + else if (outcome === "appended") done.push(`recorded the answer on ${resolving.id}, which was already resolved (${resolving.resolution ?? "no answer"})`); + else done.push(`${resolving.id} already has this answer`); + if (outcome !== "unchanged") notes.push(`Escalation ${resolving.id} decided: ${guidance}`); } if (input.priority !== undefined || input.hold !== undefined) { store.patch(target.id, { ...(input.priority === undefined ? {} : { priority: input.priority }), ...(input.hold === undefined ? {} : { hold: input.hold === "" ? null : input.hold }) }); @@ -2056,15 +2098,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P notes.push(`Set by your ${isProjectSteward(threadId, target) ? "project" : "parent"} steward: ${what}`); } if (input.stewardModel !== undefined && target.threadId !== null) { - 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.`)); await bb.sdk.threads.update({ threadId: target.threadId, ...(input.stewardModel.model === null ? {} : { model: input.stewardModel.model }), ...(input.stewardModel.reasoningLevel === null ? {} : { reasoningLevel: input.stewardModel.reasoningLevel }) }); } if (input.stewardModel !== undefined || input.workerModel !== undefined) { store.patch(target.id, { ...(input.stewardModel === undefined ? {} : { modelSteward: input.stewardModel.text }), ...(input.workerModel === undefined ? {} : { modelWorker: input.workerModel.text }) }); done.push(`models: steward ${input.stewardModel?.text ?? "unchanged"}, workers ${input.workerModel?.text ?? "unchanged"}`); } - if (done.length === 0) return toolError(new Error("Nothing to update: give guidance, resolve, forward, priority, hold, a model, approve, or ask.")); for (const n of notes) tell(threadId, target, n); return `${target.entityKey}: ${done.join("; ")}.`; } catch (error) { diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index 22294e90..9cd686fa 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -116,6 +116,10 @@ export const MIGRATIONS = [ created_at INTEGER NOT NULL, resolved_at INTEGER )`, + // When an escalation was first put to the project steward as new; later prompts list it as still open. + `ALTER TABLE escalations ADD COLUMN delivered_at INTEGER`, + // Escalations open before delivery was recorded were all delivered already. + `UPDATE escalations SET delivered_at = created_at WHERE status = 'open' AND delivered_at IS NULL`, ]; // ---- values kept as JSON ------------------------------------------------------------ @@ -341,6 +345,8 @@ export type Escalation = { resolution: string | null; createdAt: number; resolvedAt: number | null; + /** When the project steward was first sent it as new. */ + deliveredAt: number | null; }; /** @@ -369,6 +375,9 @@ export type Worker = { threadId: string; bindingId: string; title: string; statu export type ProjectStewardRow = { projectId: string; threadId: string | null; digest: string | null; digestAt: number | null; nightlyDate: string | null; digestPending: boolean; title: string | null; sectionId: string | null }; +/** Guidance repeated within this window is a retry, not new guidance. */ +export const GUIDANCE_DEDUPE_MS = 5 * 60_000; + export const newId = (prefix: string) => `${prefix}_${randomBytes(9).toString("base64url")}`; export function createStore(db: Database.Database, now: () => number) { @@ -396,7 +405,10 @@ export function createStore(db: Database.Database, now: () => number) { const openEscalations = db.prepare<[string], Record>("SELECT * FROM escalations WHERE binding_id = ? AND status = 'open' ORDER BY created_at"); const escalationsFor = db.prepare<[string, number], Record>("SELECT * FROM escalations WHERE binding_id = ? ORDER BY created_at DESC LIMIT ?"); const resolveEscalation = db.prepare("UPDATE escalations SET status = 'resolved', resolution = ?, resolved_at = ? WHERE id = ? AND status = 'open'"); - const rerouteEscalation = db.prepare("UPDATE escalations SET route = ?, recommendation = ? WHERE id = ? AND status = 'open'"); + const appendResolution = db.prepare("UPDATE escalations SET resolution = ? WHERE id = ? AND status = 'resolved'"); + const rerouteEscalation = db.prepare("UPDATE escalations SET route = ?, recommendation = ?, delivered_at = NULL WHERE id = ? AND status = 'open'"); + const markDelivered = db.prepare("UPDATE escalations SET delivered_at = ? WHERE id = ? AND delivered_at IS NULL"); + const clearDelivered = db.prepare("UPDATE escalations SET delivered_at = NULL WHERE id = ? AND delivered_at = ?"); const lastResolvedOfKind = db.prepare<[string, string], { resolved_at: number }>("SELECT resolved_at FROM escalations WHERE binding_id = ? AND kind = ? AND status = 'resolved' ORDER BY resolved_at DESC LIMIT 1"); const insertQuestion = db.prepare( @@ -407,6 +419,7 @@ export function createStore(db: Database.Database, now: () => number) { const answeredSince = db.prepare<[string, number], Record>("SELECT * FROM questions WHERE project_id = ? AND status = 'answered' AND resolved_at >= ? ORDER BY resolved_at"); const answerQuestion = db.prepare("UPDATE questions SET status = 'answered', answer = ?, answered_by = ?, resolved_at = ? WHERE id = ? AND status = 'open'"); const answerForEscalation = db.prepare("UPDATE questions SET status = 'answered', answer = ?, answered_by = ?, resolved_at = ? WHERE escalation_id = ? AND status = 'open'"); + const appendAnswerForEscalation = db.prepare("UPDATE questions SET answer = ? WHERE escalation_id = ? AND status = 'answered'"); const insertWorker = db.prepare("INSERT INTO workers (thread_id, binding_id, title, status, started_at) VALUES (?, ?, ?, 'running', ?)"); const getWorker = db.prepare<[string], Record>("SELECT * FROM workers WHERE thread_id = ?"); @@ -430,6 +443,7 @@ export function createStore(db: Database.Database, now: () => number) { resolution: r.resolution === null ? null : String(r.resolution), createdAt: Number(r.created_at), resolvedAt: r.resolved_at === null ? null : Number(r.resolved_at), + deliveredAt: r.delivered_at === null || r.delivered_at === undefined ? null : Number(r.delivered_at), }); const toQuestion = (r: Record): Question => ({ id: String(r.id), @@ -464,6 +478,16 @@ export function createStore(db: Database.Database, now: () => number) { sectionId: r.section_id === null || r.section_id === undefined ? null : String(r.section_id), }); + /** Resolve an open escalation, and close the question forwarding it made, if any. `by` is who answered it. */ + function resolve(id: string, resolution: string, by = "plugin"): boolean { + return db.transaction(() => { + const at = now(); + if (resolveEscalation.run(resolution, at, id).changes === 0) return false; + answerForEscalation.run(resolution, by, at, id); + return true; + })(); + } + function patch(id: string, fields: BindingPatch): Binding { const entries = Object.entries(fields).filter(([, v]) => v !== undefined) as Array<[keyof typeof COLUMNS, unknown]>; if (entries.length > 0) { @@ -539,9 +563,13 @@ export function createStore(db: Database.Database, now: () => number) { } return patch(id, { pending }); }, - addGuidance(id: string, text: string, by: string): Binding { + /** Save guidance; false when it repeats the binding's last guidance by the same author within five minutes (a retry), which saves nothing. */ + addGuidance(id: string, text: string, by: string): boolean { const b = rowToBinding(getBinding.get(id)!); - return patch(id, { guidance: [...b.guidance, { at: now(), text, by }].slice(-50) }); + const last = b.guidance.at(-1); + if (last !== undefined && last.text === text && last.by === by && now() - last.at < GUIDANCE_DEDUPE_MS) return false; + patch(id, { guidance: [...b.guidance, { at: now(), text, by }].slice(-50) }); + return true; }, // escalations @@ -560,15 +588,34 @@ export function createStore(db: Database.Database, now: () => number) { escalations(bindingId: string, limit = 20): Escalation[] { return escalationsFor.all(bindingId, limit).map(toEscalation); }, - /** Resolve an open escalation, and close the question forwarding it made, if any. `by` is who answered it. */ - resolve(id: string, resolution: string, by = "plugin"): boolean { + resolve, + /** + * Record an answer: resolve the escalation if it is open; if it is + * already resolved (the binding ended, a retry), append the answer to + * what it says, and to the question forwarding it made, unless it + * already says it. + */ + answerEscalation(id: string, text: string, by: string): "resolved" | "appended" | "unchanged" { return db.transaction(() => { - const at = now(); - if (resolveEscalation.run(resolution, at, id).changes === 0) return false; - answerForEscalation.run(resolution, by, at, id); - return true; + if (resolve(id, text, by)) return "resolved" as const; + const x = getEscalation.get(id); + const resolution = x === undefined || x.resolution === null ? "" : String(x.resolution); + if (x === undefined || resolution === text || resolution.endsWith(`\n${text}`)) return "unchanged" as const; + const appended = resolution === "" ? text : `${resolution}\n${text}`; + appendResolution.run(appended, id); + appendAnswerForEscalation.run(appended, id); + return "appended" as const; })(); }, + /** Mark escalations delivered to the project steward; returns the time, to undo with undeliver if the send fails. */ + markDelivered(ids: string[]): number { + const at = now(); + for (const id of ids) markDelivered.run(at, id); + return at; + }, + undeliver(ids: string[], at: number): void { + for (const id of ids) clearDelivered.run(id, at); + }, reroute(id: string, route: EscalationRoute, recommendation: string | null): boolean { return rerouteEscalation.run(route, recommendation, id).changes > 0; }, diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 02630f5c..40b2f2ef 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -261,12 +261,14 @@ export function formatProjectWake(input: { if (input.notes.length > 0) out.push(...input.notes.map((n) => `- ${n}`), ""); if (input.problems.length > 0) out.push("## Configuration problems", "", ...input.problems.map((p) => `- ${p}`), ""); if (input.routed.length > 0) { - out.push("## Escalations routed to you", ""); - for (const { escalation: x, from } of input.routed) { - out.push(`- ${x.id} from ${from.entityKey} (${x.kind}): ${x.question} Meanwhile: ${x.meanwhile}${x.recommendation === null ? "" : ` Recommendation: ${x.recommendation}`}`); - } + // New: not in an earlier prompt. Still open: sent before and not yet decided. + const fresh = input.routed.filter((r) => r.escalation.deliveredAt === null); + const before = input.routed.filter((r) => r.escalation.deliveredAt !== null); + const line = ({ escalation: x, from }: { escalation: Escalation; from: Binding }) => + `- ${x.id} from ${from.entityKey} (${x.kind}): ${x.question} Meanwhile: ${x.meanwhile}${x.recommendation === null ? "" : ` Recommendation: ${x.recommendation}`}`; + if (fresh.length > 0) out.push("## New escalations routed to you", "", ...fresh.map(line), ""); + if (before.length > 0) out.push("## Escalations still open with you", "", "Sent in an earlier prompt and not decided when this one was sent. One you have answered since needs nothing more.", "", ...before.map(line), ""); out.push( - "", "Decide each from the project's guidance (AGENTS.md, architecture and design docs) with steward_update { binding, guidance, resolve }. Forward one to the user (steward_update { binding, forward, recommendation }) only when it is one of these big decisions:", "", ...input.bigDecisions.map((d) => `- ${d}`),