diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index ed069740..ae6b408c 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -2423,6 +2423,115 @@ describe("terminal states and follow-through", () => { }); }); +// 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 +// ended binding is closed once and reported once. +describe("an ended binding takes no new writes (BB-325)", () => { + /** A bound ticket with its steward thread, ended mechanically. */ + async function ended() { + const t = await setup(); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); + await t.ring("linear", "uuid-12"); + const [project, steward] = t.spawns.map((x) => x.id) as [string, string]; + const b = t.hooks.store.find("ENG-12")!; + t.hooks.store.patch(b.id, { endedAt: t.now(), endReason: "terminal" }); + return { ...t, project, steward, b: t.hooks.store.find("ENG-12")! }; + } + + it("refuses ask and forward on an ended binding, naming the end and the alternatives, and stores nothing", async () => { + const t = await ended(); + const ask = await t.tool("steward_update", { binding: "ENG-12", ask: { question: "Why did you skip the delivery lookup?" } }, t.project); + expect(ask.error).toBe(true); + expect(ask.text).toMatch(/ENG-12 ended \(terminal\) on \d{4}-\d{2}-\d{2}T[\d:]+Z: an ended binding takes no new question, forward, hold or priority change\./u); + expect(ask.text).toMatch(/Ask at project scope by omitting binding, or reopen the entity first so its steward resumes\./u); + expect(t.hooks.store.openQuestions("p1")).toEqual([]); + + // An escalation left open on the ended binding (a race) is not forwarded either. + const x = t.hooks.store.escalate({ bindingId: t.b.id, kind: "decision", question: "Include SSO?", meanwhile: "Wait.", route: "user", recommendation: null, projectId: "p1", origin: { threadId: null, bindingId: t.b.id, chain: [] } }); + const fwd = await t.tool("steward_update", { binding: "ENG-12", forward: x.id, resolution: "text" }, t.project); + expect(fwd.error).toBe(true); + expect(fwd.text).toMatch(/ENG-12 ended \(terminal\)/u); + expect(t.hooks.store.escalation(x.id)!.status).toBe("open"); + + // A hold or priority change is refused with the same error; resolving an existing question still works. + expect((await t.tool("steward_update", { binding: "ENG-12", hold: "stop" }, t.project)).error).toBe(true); + expect((await t.tool("steward_update", { binding: "ENG-12", priority: "high" }, t.project)).error).toBe(true); + const q = t.hooks.store.ask({ projectId: "p1", bindingId: t.b.id, escalationId: null, question: "Keep the old page?", context: null }); + const resolved = await t.tool("steward_update", { binding: "ENG-12", resolve: q.id, answer: "No." }, t.project); + expect(resolved.error).toBe(false); + expect(t.hooks.store.question(q.id)).toMatchObject({ status: "answered", answer: "No." }); + }); + + it("carries a steward_report from an ended binding to the project steward and writes nothing to the binding", async () => { + const t = await ended(); + const before = t.hooks.store.find("ENG-12")!; + const sends = t.sends.length; + const reported = await t.tool("steward_report", { phase: "In Progress", summary: "Still building.", nextAction: "Wait", actor: "steward", waitingOn: "the review", escalate: { kind: "decision", question: "Include SSO?", meanwhile: "Waiting." } }, t.steward); + expect(reported.error).toBe(false); + expect(reported.text).toMatch(/Reported after ENG-12 ended \(terminal,/u); + const after = t.hooks.store.find("ENG-12")!; + expect(after.status).toEqual(before.status); + expect(after.requeueAt).toEqual(before.requeueAt); + expect(t.hooks.store.openEscalations(after.id)).toEqual([]); + const notes = () => t.hooks.store.peekProjectNotes("p1").filter((n) => n.startsWith("late report from ended binding ENG-12 (terminal,")); + expect(notes()).toHaveLength(1); + expect(notes()[0]).toMatch(/Still building\. Next: Wait \(steward\)/u); + expect(notes()[0]).toMatch(/waiting on the review/u); + expect(notes()[0]).toMatch(/escalation \(decision\): Include SSO\?/u); + // A second late report folds into the one note; it starts no turn. + await t.tool("steward_report", { phase: "Done", summary: "Finished anyway.", nextAction: "Nothing", actor: "steward" }, t.steward); + expect(notes()).toHaveLength(1); + expect(notes()[0]).toMatch(/Finished anyway\./u); + expect(t.sends).toHaveLength(sends); + }); + + it("carries a worker's bb stewards escalate from an ended binding and files nothing", async () => { + const t = await ended(); + t.hooks.store.addWorker("thr_w1", t.b.id, "ENG-12: Implement"); + const out = await t.harness.behavior.runCli(["escalate", "Which API version?", "--context", "v1 is still used.", "--meanwhile", "continue"], { threadId: "thr_w1", projectId: "p1" }); + expect(out.exitCode).toBe(0); + expect(out.stdout).toMatch(/Not filed: ENG-12 ended \(terminal,/u); + expect(t.hooks.store.openEscalations(t.b.id)).toEqual([]); + const note = t.hooks.store.peekProjectNotes("p1").find((n) => n.startsWith("late report from ended binding ENG-12 (terminal,")); + expect(note).toMatch(/escalation: Which API version\? — v1 is still used\. \(meanwhile: continue\)/u); + }); + + it("closes a pre-existing question on an ended binding once and reports it once", async () => { + const t = await ended(); + const q = t.hooks.store.ask({ projectId: "p1", bindingId: t.b.id, escalationId: null, question: "Why did you skip the delivery lookup?", context: null }); + expect(t.hooks.store.openQuestions("p1")).toEqual([]); + // The production path: the sweep's one-time close, not a test-only hook. + await t.hooks.sweep(); + expect(t.hooks.store.question(q.id)).toMatchObject({ status: "answered", answer: "The binding ended." }); + const notes = () => t.hooks.store.peekProjectNotes("p1").filter((n) => n.startsWith("late report from ended binding ENG-12 (terminal,")); + expect(notes()).toHaveLength(1); + expect(notes()[0]).toMatch(/question qst_\S+ \("Why did you skip the delivery lookup\?"\)/u); + // Once: a second sweep closes nothing and adds no note. + t.hooks.store.clearProjectNotes("p1"); + await t.hooks.sweep(); + expect(notes()).toHaveLength(0); + }); + + it("lists each route-user escalation and question finishEnding closes in the project steward's next digest", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); + await t.ring("linear", "uuid-12"); + const b = t.hooks.store.find("ENG-12")!; + const x = t.hooks.store.escalate({ bindingId: b.id, kind: "decision", question: "Include SSO?", meanwhile: "Wait.", route: "user", recommendation: null, projectId: "p1", origin: { threadId: null, bindingId: b.id, chain: [] } }); + const q = t.hooks.store.ask({ projectId: "p1", bindingId: b.id, escalationId: x.id, question: "Include SSO?", context: null }); + // A terminal ending whose follow-through ran out: finishEnding runs. + t.hooks.store.patch(b.id, { ending: "terminal", endingAt: 0, followThrough: "watch", followThroughUntil: 0 }); + await t.hooks.sweep(); + expect(t.hooks.store.find("ENG-12")!.endedAt).not.toBeNull(); + expect(t.hooks.store.escalation(x.id)).toMatchObject({ status: "resolved", resolution: "The binding ended." }); + expect(t.hooks.store.question(q.id)).toMatchObject({ status: "answered", answer: "The binding ended." }); + const note = t.hooks.store.peekProjectNotes("p1").find((n) => n.startsWith("late report from ended binding ENG-12 (terminal,")); + expect(note).toMatch(new RegExp(`decision escalation ${x.id}`, "u")); + expect(note).toMatch(new RegExp(`question ${q.id}`, "u")); + }); +}); + describe("the project steward", () => { it("is renamed to its project and tagged for thread-briefs when it predates both", async () => { const t = await setup(); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 1330ec31..0b9b8cbd 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -6421,12 +6421,76 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * is still open. A thread still running (an ending that timed out) is left * in the sidebar rather than archived mid-turn. */ + /** BB-325: one line naming an escalation or question an ending closed. */ + function closedItemLine(x: Escalation): string { + return `${x.isQuestion ? "question" : `${x.kind} escalation`} ${x.id} (${JSON.stringify(x.question)})`; + } + + /** + * BB-325: carry what an ending left, or a late report from a steward whose + * binding ended, into the project steward's next digest as one note per + * binding. It starts no turn and folds with anything already queued for + * the same binding, so several late reports are one line. + */ + function noteEndingReport(b: Pick, text: string): void { + if (b.endedAt === null) return; + store.noteProjectFolded(b.projectId, `late report from ended binding ${b.entityKey} (${b.endReason ?? "ended"}, ${iso(b.endedAt)}): `, text); + } + + /** + * BB-325: an ended binding is closed to new writes. The refusal names the + * end and the two alternatives, so a project steward does not file a + * question on a Done ticket again (BCP-154). Only new writes are refused; + * resolving an existing item and reopening still work. + */ + function endedBindingRefusal(b: Binding): string { + return `${b.entityKey} ended (${b.endReason ?? "ended"})${b.endedAt === null ? "" : ` on ${iso(b.endedAt)}`}: an ended binding takes no new question, forward, hold or priority change. Ask at project scope by omitting binding, or reopen the entity first so its steward resumes.`; + } + + /** + * BB-325: the content of a report or escalation that arrived after its + * binding ended, carried to the project steward as one note. Nothing is + * written to the binding. + */ + function lateReportText(input: { phase: string; summary: string; nextAction: string; actor: string; waitingOn?: string; escalate?: { kind: string; question: string; context?: string; meanwhile: string }; needs?: Array<{ kind: string; what: string }> }): string { + const parts = [`${input.phase}: ${input.summary} Next: ${input.nextAction} (${input.actor})`]; + if (input.waitingOn !== undefined && input.waitingOn !== "") parts.push(`waiting on ${input.waitingOn}`); + if (input.escalate !== undefined) parts.push(`escalation (${input.escalate.kind}): ${input.escalate.question}${input.escalate.context === undefined ? "" : ` — ${input.escalate.context}`} (meanwhile: ${input.escalate.meanwhile})`); + if ((input.needs ?? []).length > 0) parts.push(`needs: ${input.needs!.map((n) => `${n.kind} ${n.what}`).join("; ")}`); + return parts.join("; "); + } + + /** + * BB-325: close any open question or escalation still attached to an ended + * binding (the BCP-154 case, a question filed after its binding ended) and + * report it once. The close is mechanical and the resolution is the record, + * so the next pass finds nothing open and reports nothing again. + */ + function closeItemsOnEndedBindings(projectId: string): void { + const byBinding = new Map; closed: string[] }>(); + for (const row of store.openOnEndedBindings(projectId)) { + let entry = byBinding.get(row.escalation.bindingId); + if (entry === undefined) { + entry = { b: { projectId, entityKey: row.entityKey, endReason: row.endReason, endedAt: row.endedAt }, closed: [] }; + byBinding.set(row.escalation.bindingId, entry); + } + entry.closed.push(closedItemLine(row.escalation)); + store.resolve(row.escalation.id, "The binding ended.", "plugin", false); + } + for (const { b, closed } of byBinding.values()) noteEndingReport(b, `closed ${closed.join("; ")}.`); + } + 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 // resolve its escalations without queuing a wake it would never read - // (BB-60). - for (const x of store.openEscalations(b.id)) store.resolve(x.id, "The binding ended.", "plugin", false); + // (BB-60). BB-325: the route-user ones (and questions) are carried into + // the project steward's next digest, since nobody else can see them; the + // resolution itself is the record, so a later pass finds nothing open. + const openBefore = store.openEscalations(b.id); + for (const x of openBefore) store.resolve(x.id, "The binding ended.", "plugin", false); + const closed = openBefore.filter((x) => x.route === "user" || x.isQuestion).map(closedItemLine); + if (closed.length > 0) noteEndingReport(b, `closed ${closed.join("; ")}.`); await releaseBehind(b, `ended (${reason})`); await stopWorkers(b); const info = b.threadId === null ? null : await threadInfo(b.threadId).catch(() => null); @@ -11010,6 +11074,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // normalised here and the stored value is always `user`. const actor: (typeof ACTORS)[number] = input.actor === "me" ? "user" : input.actor; if (input.actor === "me") bb.log.info(`stewards: steward_report actor "me" is renamed to "user"; recording this report as user (thread ${threadId}).`); + const ended = store.byThread(threadId); + if (ended !== null && ended.endedAt !== null) { + // BB-325: the binding ended while this turn was running, or the + // plugin's own stop turn reported after it. Write nothing to the + // binding; carry the report to the project steward's next digest. + noteEndingReport(ended, lateReportText(input)); + return `Reported after ${ended.entityKey} ended (${ended.endReason ?? "ended"}, ${iso(ended.endedAt)}): nothing was written to the binding, and the project steward's next wake carries it. End the turn now.`; + } let b = ownBinding(threadId); // Validate the input that does not depend on which pull request the // binding is on before a replacement moves it: a wrap-up report that @@ -11762,6 +11834,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return `${written.join("; ")}.`; } if (input.ask !== undefined && target.projectId !== projectOf) return toolError(new Error(`${target.entityKey} is not in this project.`)); + // BB-325: an ended binding takes no new question, forward, hold or + // priority change. The checks below still run for everything else: + // resolving an existing escalation, question or assumption, + // confirming, a lesson, or reopening keeps working. + if (target.endedAt !== null && (input.ask !== undefined || input.forward !== undefined || input.priority !== undefined || input.hold !== undefined)) { + return toolError(new Error(endedBindingRefusal(target))); + } const self = target.threadId === threadId; const forwarding = input.forward === undefined ? null : store.escalation(input.forward); @@ -12538,6 +12617,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P await reconcileLessons(config); applyLessonTransitions(config); applyRationaleClustering(config); + // BB-325: close any open item left on an ended binding, once. + closeItemsOnEndedBindings(config.projectId); for (const b of store.open(config.projectId)) { if (b.threadId !== null) await keepSteward(config.projectId, b.threadId); const deadline = endingDeadline(b, timing.endingTimeoutMs); @@ -13638,6 +13719,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const context = input.options.context === undefined || input.options.context.trim() === "" ? null : input.options.context.trim(); if (context !== null && context.length > 3000) throw new PluginCliError("context is at most 3000 characters.", { code: "context_too_long" }); const meanwhile = input.options.meanwhile === "continue" ? "continue" : "wait"; + if (b.endedAt !== null) { + // BB-325: the worker's binding ended while this turn was + // running. Write nothing to it; carry the escalation to the + // project steward's next digest. + noteEndingReport(b, `escalation: ${question}${context === null ? "" : ` — ${context}`} (meanwhile: ${meanwhile})`); + return { exitCode: 0, stdout: `Not filed: ${b.entityKey} ended (${b.endReason ?? "ended"}, ${iso(b.endedAt)}); the project steward's next wake carries it.` }; + } const x = store.escalate({ bindingId: b.id, kind: "decision", diff --git a/plugins/stewards/store.test.ts b/plugins/stewards/store.test.ts index 4f70844e..b7f986cc 100644 --- a/plugins/stewards/store.test.ts +++ b/plugins/stewards/store.test.ts @@ -52,6 +52,34 @@ describe("questions to the user", () => { expect(s.resolve(second.x.id, "late")).toBe(false); expect(s.openQuestions("p1")).toEqual([]); }); + + // BB-325: a question whose binding has ended is not open with the user; the + // one-time close still finds it, closes it, and finds nothing the next time. + it("hides a question on an ended binding, and lists it for the one-time close", () => { + const { s, binding } = store(); + const q = s.ask({ projectId: "p1", bindingId: binding.id, escalationId: null, question: "Why did you skip the delivery lookup?", context: null }); + const unbound = s.ask({ projectId: "p1", bindingId: null, escalationId: null, question: "Freeze on Friday?", context: null }); + s.patch(binding.id, { endedAt: 2_000, endReason: "terminal" }); + // The ended binding's question is not open; the project-scope one still is. + expect(s.openQuestions("p1").map((x) => x.id)).toEqual([unbound.id]); + expect(s.openOnEndedBindings("p1")).toMatchObject([{ escalation: { id: q.id, bindingId: binding.id }, entityKey: "ENG-12", endReason: "terminal", endedAt: 2_000 }]); + // Once closed, it is never found open again. + expect(s.resolve(q.id, "The binding ended.", "plugin", false)).toBe(true); + expect(s.openOnEndedBindings("p1")).toEqual([]); + expect(s.question(q.id)).toMatchObject({ status: "answered", answer: "The binding ended." }); + }); + + // BB-325: several late reports from one ending are one note, not one each. + it("folds a silent project note per binding", () => { + const { s } = store(); + s.noteProjectFolded("p1", "late report from ended binding ENG-12 (terminal, 2026-01-01T00:00:00Z): ", "closed question qst_1."); + s.noteProjectFolded("p1", "late report from ended binding ENG-12 (terminal, 2026-01-01T00:00:00Z): ", "escalation: Include SSO?"); + s.noteProjectFolded("p1", "late report from ended binding ENG-13 (gone, 2026-01-02T00:00:00Z): ", "escalation: Gone?"); + expect(s.peekProjectNotes("p1")).toEqual([ + "late report from ended binding ENG-12 (terminal, 2026-01-01T00:00:00Z): closed question qst_1. escalation: Include SSO?", + "late report from ended binding ENG-13 (gone, 2026-01-02T00:00:00Z): escalation: Gone?", + ]); + }); }); describe("the fingerprint map", () => { diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index cd41942e..0cddbc1a 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -1654,6 +1654,12 @@ export function createStore(db: Database.Database, now: () => number, options: S const openEscalationsForProjectStmt = db.prepare<[string], Record>( "SELECT e.* FROM escalations e JOIN bindings b ON b.id = e.binding_id WHERE b.project_id = ? AND b.ended_at IS NULL AND e.status = 'open' ORDER BY e.created_at", ); + // BB-325: a project's open escalations (questions included) still attached to + // an ended binding, with that binding's end. The one-time close reads this: + // a question filed after its binding ended (BCP-154) is the case. + const openOnEndedBindingsStmt = db.prepare<[string], Record>( + "SELECT e.*, b.entity_key AS binding_key, b.end_reason AS binding_end_reason, b.ended_at AS binding_ended_at FROM escalations e JOIN bindings b ON b.id = e.binding_id WHERE b.project_id = ? AND b.ended_at IS NOT NULL AND e.status = 'open' ORDER BY b.ended_at, e.created_at", + ); // BB-296: a project's open bindings' workers in one query, grouped by binding // in the caller. const workersForProjectStmt = db.prepare<[string], Record>( @@ -1747,7 +1753,13 @@ export function createStore(db: Database.Database, now: () => number, options: S "INSERT INTO escalations (id, project_id, binding_id, forwarded_from, question, context, choices, meanwhile, route, status, created_at, resolution_kind, url, data, is_question, kind, origin) VALUES (@id, @project_id, @binding_id, @forwarded_from, @question, @context, @choices, 'wait', 'user', 'open', @created_at, @resolution_kind, @url, @data, 1, 'decision', @origin)", ); const getQuestion = db.prepare<[string], Record>("SELECT * FROM escalations WHERE id = ? AND is_question = 1"); - const openQuestions = db.prepare<[string], Record>("SELECT * FROM escalations WHERE project_id = ? AND is_question = 1 AND status = 'open' AND (resolution_kind IS NULL OR resolution_kind NOT IN ('secret','done')) ORDER BY created_at"); + // BB-325: a question whose binding has ended is not open with the user, so it + // is left out here exactly as `openEscalationsForProject` leaves out an ended + // binding's escalations. A question about no single binding (binding_id '') + // still shows; it has no binding to end. + const openQuestions = db.prepare<[string], Record>( + "SELECT e.* FROM escalations e LEFT JOIN bindings b ON b.id = e.binding_id WHERE e.project_id = ? AND e.is_question = 1 AND e.status = 'open' AND (e.resolution_kind IS NULL OR e.resolution_kind NOT IN ('secret','done')) AND (e.binding_id IS NULL OR e.binding_id = '' OR b.ended_at IS NULL) ORDER BY e.created_at", + ); const answeredSince = db.prepare<[string, number], Record>("SELECT * FROM escalations WHERE project_id = ? AND is_question = 1 AND status = 'resolved' AND resolved_at >= ? AND (resolution_kind IS NULL OR resolution_kind NOT IN ('secret','done')) ORDER BY resolved_at"); const escalationNeedsForBinding = db.prepare<[string], Record>("SELECT * FROM escalations WHERE binding_id = ? AND route = 'user' AND kind != 'approval' AND (is_question = 0 OR resolution_kind IN ('secret','done')) AND (is_question = 1 OR NOT EXISTS (SELECT 1 FROM escalations q WHERE q.forwarded_from = escalations.id AND q.is_question = 1)) ORDER BY created_at"); // A route-`user` escalation a question or a need already covers is not listed @@ -2496,6 +2508,19 @@ export function createStore(db: Database.Database, now: () => number, options: S openEscalationsForProject(projectId: string): Escalation[] { return openEscalationsForProjectStmt.all(projectId).map(toEscalation); }, + /** + * BB-325: a project's open escalations and questions on ended bindings, + * each with its binding's key, end reason and end date. The one-time close + * reads it; once it has resolved them, the next pass finds nothing open. + */ + openOnEndedBindings(projectId: string): Array<{ escalation: Escalation; entityKey: string; endReason: string | null; endedAt: number }> { + return openOnEndedBindingsStmt.all(projectId).map((r) => ({ + escalation: toEscalation(r), + entityKey: String(r.binding_key), + endReason: r.binding_end_reason === null || r.binding_end_reason === undefined ? null : String(r.binding_end_reason), + endedAt: Number(r.binding_ended_at), + })); + }, /** A project's open bindings' workers, one query (BB-296). */ workersForProject(projectId: string): Worker[] { return workersForProjectStmt.all(projectId).map(toWorker); @@ -3471,6 +3496,20 @@ export function createStore(db: Database.Database, now: () => number, options: S const row = toProject(getProject.get(projectId)!); db.prepare("UPDATE project_stewards SET pending_notes = ? WHERE project_id = ?").run(JSON.stringify([...row.pendingNotes, text]), projectId); }, + /** + * BB-325: queue a silent note, folded into the one already queued whose text + * starts with `prefix`. Several late reports from one ending, or the items + * one ending closed, are one line in the next digest, not one per call. + */ + noteProjectFolded(projectId: string, prefix: string, text: string): void { + upsertProject.run(projectId); + const row = toProject(getProject.get(projectId)!); + const index = row.pendingNotes.findIndex((n) => n.startsWith(prefix)); + const notes = [...row.pendingNotes]; + if (index >= 0) notes[index] = `${notes[index]} ${text}`; + else notes.push(`${prefix}${text}`); + db.prepare("UPDATE project_stewards SET pending_notes = ? WHERE project_id = ?").run(JSON.stringify(notes), projectId); + }, /** The queued digest notes, without clearing them: a failed digest send must not lose them. */ peekProjectNotes(projectId: string): string[] { upsertProject.run(projectId);