Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 109 additions & 0 deletions plugins/stewards/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
92 changes: 90 additions & 2 deletions plugins/stewards/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Binding, "projectId" | "entityKey" | "endReason" | "endedAt">, 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<string, { b: Pick<Binding, "projectId" | "entityKey" | "endReason" | "endedAt">; 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<void> {
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);
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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",
Expand Down
28 changes: 28 additions & 0 deletions plugins/stewards/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
Loading
Loading