From 1b72284553ed4732d062487fded57993f2dde38c Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Wed, 21 Oct 2026 19:35:05 +0000 Subject: [PATCH 1/2] stewards: cite the lessons a decision rested on, and count hits and corrections (BB-35 step 2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every steward_update { resolve } (and a forward, whose recommendation is the decision a correction is measured against) accepts cites: [lesson ids]. The plugin records hits — one per distinct binding — corrections and lastCitedAt on the lesson, and keeps the cited lessons on the escalation. A page answer, an unsigned comment by the owner on the entity, or a CLI close that differs from the steward's recommendation counts a correction once, attributed to the cited lessons. The wake says a decision must cite what it was decided from. Counts only: nothing is promoted, retired or written to `.bb`, and no tier or threshold logic lands here. The migration is append-only and lossless: four defaulted columns on lessons, two on escalations, nothing dropped or renamed, readable by the previous build. A lesson whose scope is missing or unknown reads as boundary (fails closed). Trust: citations come only through steward_update, which only a steward or the project steward has; a correction from a comment requires the connected owner's own unsigned words, so anyone else's text on Linear or GitHub never counts. Tests cover the counters, the lossless migration, the non-owner comment and the fail-closed scope. DESIGN.md §20, README and the skill updated. --- plugins/stewards/DESIGN.md | 11 +++ plugins/stewards/README.md | 5 +- plugins/stewards/reconcile.test.ts | 31 +++++++- plugins/stewards/reconcile.ts | 34 +++++++++ plugins/stewards/server.test.ts | 62 +++++++++++++++ plugins/stewards/server.ts | 70 ++++++++++++++++- plugins/stewards/skills/stewards/SKILL.md | 4 +- plugins/stewards/store.test.ts | 92 ++++++++++++++++++++++- plugins/stewards/store.ts | 90 +++++++++++++++++++++- plugins/stewards/wake.test.ts | 9 +++ plugins/stewards/wake.ts | 6 +- 11 files changed, 402 insertions(+), 12 deletions(-) diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index 729452a0..16deb08e 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -1170,6 +1170,17 @@ A **lesson** makes the answer a record and, for most of them, lands it. steward is woken with the answer and asked whether it is a general judgement: the answer is a lesson candidate for its next turn. A plain question with no escalation behind it wakes nobody. +- **Counts (BB-35 step 2).** A `steward_update { resolve }` carries + `cites: [lesson ids]` — the lessons the decision rested on — and the wake + says a decision must cite what it was decided from. The plugin records + `hits` (one per distinct binding), `corrections` (the owner's answer or + unsigned comment on the entity differing from the steward's recommendation + on a decision that cited the lesson), and `lastCitedAt`, keeping the cited + bindings and the escalation's cited lessons. This step only records: + nothing is promoted, retired or written to `.bb` from these counts yet. + Only the owner's own words, or this project's steward or worker threads, + may create, cite or correct a lesson; a signed or non-owner comment never + does. - **Procedure lessons self-merge.** Playbook procedure, sequencing and conventions are what the project steward may already decide. It applies the text to the file in its `.bb` checkout, commits, and publishes with diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 95d84150..281379f0 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -234,7 +234,10 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. escalation on the Stewards page (or from a thread) wakes the project steward with that answer as a lesson candidate: if it is a general judgement the playbook should carry, the project steward records it as a - lesson. `bb stewards lessons [--all]` + lesson. A resolve carries `cites: [lesson ids]` — the lessons it rested on + — and the plugin counts `hits` (once per distinct binding), `corrections` + and `lastCitedAt`. Counts only for now: nothing is promoted, retired or + written to `.bb` from them yet. `bb stewards lessons [--all]` lists them, `bb stewards drop-lesson ` drops one. DESIGN.md §20. - **The nightly pass** (01:00 in the project's time zone by default, done by 02:45 so bb-gate's 03:00 restarts do not cut a turn) gives every open diff --git a/plugins/stewards/reconcile.test.ts b/plugins/stewards/reconcile.test.ts index 03a44326..acaa6b21 100644 --- a/plugins/stewards/reconcile.test.ts +++ b/plugins/stewards/reconcile.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { parsePlaybook } from "./config.js"; import { comment, issue, pull } from "./fixtures.js"; -import { approvalWanted, anyWorkerInFlight, asksForOpenApproval, classifyApproval, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, isCommentNews, lifecycle, markerLaneChange, namesUserAsBlocker, ownerApproval, prGate, resolveChecklistItem, reviewMarker, specHash, stuckDue, unheardWait, workerInFlight } from "./reconcile.js"; +import { approvalWanted, answerDiffers, anyWorkerInFlight, asksForOpenApproval, classifyApproval, commentDiffersFromRecommendation, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, isCommentNews, lifecycle, markerLaneChange, namesUserAsBlocker, ownerApproval, prGate, resolveChecklistItem, reviewMarker, specHash, stuckDue, unheardWait, workerInFlight } from "./reconcile.js"; import { readyStateSchema } from "./store.js"; import { GITHUB_REVIEWS, LINEAR_TICKETS } from "./templates.js"; @@ -177,7 +177,7 @@ describe("a worker in flight between its turns (BB-11)", () => { 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, choices: [], status: "open" as const, resolution: null, createdAt: 1, resolvedAt: null, deliveredAt: null, projectId: null, origin: { threadId: null, bindingId: null, chain: [] }, resolutionKind: null, url: null, data: {}, answeredBy: null, forwardedFrom: null, headSha: null, isQuestion: false }]; + const open = [{ id: "esc_1", bindingId: "b", kind: "decision" as const, question: "q", meanwhile: "m", route: "project" as const, recommendation: null, choices: [], status: "open" as const, resolution: null, createdAt: 1, resolvedAt: null, deliveredAt: null, projectId: null, origin: { threadId: null, bindingId: null, chain: [] }, resolutionKind: null, url: null, data: {}, answeredBy: null, forwardedFrom: null, headSha: null, isQuestion: false, citedLessons: [], correctionsCounted: false }]; 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); @@ -422,3 +422,30 @@ describe("a blockedOn naming the user", () => { expect(namesUserAsBlocker("sam's review")).toBe(false); }); }); + +// BB-35 step 2: the citation counters. A correction is the owner's own words +// differing from the steward's recommendation on a decision that cited a +// lesson; only the owner's own unsigned comment counts. +describe("a correction from a comment", () => { + it("is the connected owner's own unsigned words differing from the recommendation", () => { + const mine = comment({ author: "jane", body: "Do it the other way.", signedBy: null }); + expect(commentDiffersFromRecommendation(mine, "jane", "Do it the recommended way.")).toBe(true); + expect(commentDiffersFromRecommendation(mine, "jane", "Do it the other way.")).toBe(false); + expect(commentDiffersFromRecommendation(mine, "jane", null)).toBe(false); + expect(commentDiffersFromRecommendation(mine, null, "Do it the recommended way.")).toBe(false); + }); + + it("never counts someone else's comment, or a signed one", () => { + // A non-owner's words are information, not an instruction. + expect(commentDiffersFromRecommendation(comment({ author: "Sam", body: "No, do it the other way." }), "jane", "Do it the recommended way.")).toBe(false); + // A signed comment belongs to a thread, however it reads. + expect(commentDiffersFromRecommendation(comment({ author: "jane", body: "No, do it the other way.", signedBy: "thr_w" }), "jane", "Do it the recommended way.")).toBe(false); + }); + + it("treats an empty side as no difference", () => { + expect(answerDiffers("", "Do it.")).toBe(false); + expect(answerDiffers("Do it.", "")).toBe(false); + expect(answerDiffers(" do it. ", "Do it.")).toBe(false); + expect(answerDiffers("Don't do it.", "Do it.")).toBe(true); + }); +}); diff --git a/plugins/stewards/reconcile.ts b/plugins/stewards/reconcile.ts index 08e283c0..14100fe3 100644 --- a/plugins/stewards/reconcile.ts +++ b/plugins/stewards/reconcile.ts @@ -102,6 +102,40 @@ export function newHumanComments(entity: EntitySnapshot, cursor: string, own: Re return entity.comments.filter((c) => c.createdAt > cursor && (c.signedBy === null || !own.has(c.signedBy))); } +/** + * Whether an answer says something other than the recommendation, whitespace- + * and case-insensitively. An empty side never differs: there is nothing to + * reverse. A leading agreement adds nothing, and a negation on only one side + * flips the meaning. Used by the citation counters, where "differs" is what + * makes a correction (BB-35 step 2). + */ +const NEGATION = /(?:\b(?:no|not|never|without|avoid|reject|decline|stop|keep)\b|n't\b)/iu; +const AGREEMENT = /^(?:yes|yep|yeah|agreed?|ok(?:ay)?|sure|correct|confirmed|approved|lgtm|sounds good|do it|please do|go ahead)[\s,.:;—-]+/iu; +const words = (s: string): Set => new Set(s.split(/[^a-z0-9']+/u).filter((w) => w !== "")); +const subset = (x: Set, y: Set): boolean => [...x].every((w) => y.has(w)); +export function answerDiffers(answer: string, recommendation: string): boolean { + const a = answer.replace(/\s+/gu, " ").trim().toLowerCase(); + const r = recommendation.replace(/\s+/gu, " ").trim().toLowerCase(); + if (a === "" || r === "") return false; + if (a === r) return false; + if (NEGATION.test(a) !== NEGATION.test(r)) return true; + const aw = words(a.replace(AGREEMENT, "")); + const rw = words(r); + return !subset(rw, aw) && !subset(aw, rw); +} + +/** + * Whether a comment is the connected owner's own unsigned words that differ + * from the recommendation. Only the owner's own unsigned comment can correct a + * lesson: a signed comment belongs to a thread, and anyone else's words — on + * Linear or GitHub — never do (BB-35 step 2). + */ +export function commentDiffersFromRecommendation(c: SnapshotComment, viewer: string | null, recommendation: string | null): boolean { + if (viewer === null || recommendation === null || c.signedBy !== null) return false; + if (c.author.toLowerCase() !== viewer.toLowerCase()) return false; + return answerDiffers(c.body, recommendation); +} + export const newestCommentAt = (observed: Observed): string => [observed.entity, ...observed.pulls].flatMap((e) => e.comments.map((c) => c.createdAt)).reduce((a, b) => (a > b ? a : b), ""); diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index c1c29430..6ef49279 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -2094,6 +2094,68 @@ describe("questions to the user", () => { }); }); + // BB-35 step 2: a resolve cites the lessons it rested on, and the plugin + // counts hits, corrections and the last citation. Counts only: no tier and + // no transition, and nothing is written to `.bb`. + describe("citations and counts (BB-35 step 2)", () => { + /** A project with a recorded lesson and an escalation the project steward forwarded. */ + async function cited() { + const t = await adopted(); + const recorded = await t.tool("steward_update", { lesson: { text: "Auth is the plugin's.", file: "AGENTS.md", scope: "procedure" } }, t.project); + const lesson = /(lsn_[\w-]+)/u.exec(recorded.text)![1]!; + await t.tool("steward_report", { phase: "Todo", summary: "Scope unclear.", nextAction: "Wait", actor: "other", escalate: { kind: "decision", question: "Include SSO?", meanwhile: "Wait." } }, t.steward); + const esc = /(esc_[\w-]+) from ENG-12/u.exec(t.sends.filter((s) => s.threadId === t.project).at(-1)!.text)![1]!; + const forwarded = await t.tool("steward_update", { binding: "ENG-12", forward: esc, recommendation: "Leave SSO out.", cites: [lesson] }, t.project); + const qst = /(qst_[\w-]+)/u.exec(forwarded.text)![1]!; + return { ...t, lesson, esc, qst }; + } + + it("counts a citation once per distinct binding and keeps it on the escalation", async () => { + const t = await cited(); + expect(t.hooks.store.lesson(t.lesson)).toMatchObject({ hits: 1, corrections: 0, lastCitedAt: expect.any(Number), citedBindings: [t.hooks.store.find("ENG-12")!.id] }); + expect(t.hooks.store.escalation(t.esc)).toMatchObject({ citedLessons: [t.lesson] }); + // A second citation from the same binding refreshes the time but is not a new hit. + await t.tool("steward_update", { binding: "ENG-12", guidance: "Leave SSO out.", resolve: t.esc, cites: [t.lesson] }, t.project); + expect(t.hooks.store.lesson(t.lesson)).toMatchObject({ hits: 1 }); + }); + + it("ignores an unknown lesson id and still resolves", async () => { + const t = await cited(); + const closed = await t.tool("steward_update", { binding: "ENG-12", guidance: "Leave SSO out.", resolve: t.esc, cites: ["lsn_nope", t.lesson] }, t.project); + expect(closed.error).toBe(false); + expect(closed.text).toMatch(/not counted/u); + expect(t.hooks.store.lesson(t.lesson)).toMatchObject({ hits: 1 }); + }); + + it("counts a correction when the owner's page answer differs from the recommendation", async () => { + const t = await cited(); + expect(await t.harness.callRpc("stewardsAnswerQuestion", { questionId: t.qst, answer: "No, keep SSO." }, client)).toMatchObject({ ok: true }); + expect(t.hooks.store.lesson(t.lesson)).toMatchObject({ corrections: 1 }); + expect(t.hooks.store.escalation(t.esc)).toMatchObject({ correctionsCounted: true }); + }); + + it("does not count a correction when the owner agrees with the recommendation", async () => { + const t = await cited(); + expect(await t.harness.callRpc("stewardsAnswerQuestion", { questionId: t.qst, answer: "Agreed, leave SSO out." }, client)).toMatchObject({ ok: true }); + expect(t.hooks.store.lesson(t.lesson)).toMatchObject({ corrections: 0 }); + }); + + it("counts the owner's own unsigned comment as a correction", async () => { + const t = await cited(); + t.entities.set("uuid-12", issue({ comments: [comment({ author: "Jane", body: "Actually, keep SSO.", signedBy: null })] })); + await t.ring("linear", "uuid-12"); + expect(t.hooks.store.lesson(t.lesson)).toMatchObject({ corrections: 1 }); + }); + + it("never counts a non-owner's comment as a correction", async () => { + const t = await cited(); + t.entities.set("uuid-12", issue({ comments: [comment({ author: "Sam", body: "Actually, keep SSO.", signedBy: null })] })); + await t.ring("linear", "uuid-12"); + expect(t.hooks.store.lesson(t.lesson)).toMatchObject({ corrections: 0 }); + expect(t.hooks.store.escalation(t.esc)).toMatchObject({ correctionsCounted: false }); + }); + }); + // BB-13: one spec approval, from any surface. The page answer, the project // steward's words, an unsigned comment on the entity, and the user's own // amendment all approve the same gate. diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 0ea0eb27..6576d554 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -54,7 +54,7 @@ import { HOOKS_URL_ENV, createHooksLoop, type Lease, type Rejection } from "./ho import { nightlyDue, stillNight } from "./nightly.js"; import { classify, lookChanges, opsTargetKey, parseOpsTargetKey, type DependabotTarget, type K8sTarget, type OpsLook, type OpsTarget, type SentryTarget, type Sighting, type TicketState } from "./ops.js"; import { EVENTS_PER_LOOK, NO_TOKEN, RECENT_PER_LOOK, SENTRY_API_URL, TOKEN_SCOPES, createSentryReader, emptySentryLook, issueInOrg, recentLine, sentryChanges, sentrySightings, sentrySummary, type SentryFinding, type SentryLook, type SentryReader } from "./sentry.js"; -import { advanced, anyWorkerInFlight, approvalWanted, asksForOpenApproval, classifyApproval, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, isCommentNews, isSpecComment, lifecycle, namesUserAsBlocker, newestCommentAt, phaseAndStage, prGate, resolveChecklistItem, specHash, stuckDue, unheardWait, workerInFlight, type Change } from "./reconcile.js"; +import { advanced, answerDiffers, anyWorkerInFlight, approvalWanted, asksForOpenApproval, classifyApproval, commentDiffersFromRecommendation, compactDue, diffObserved, endingDeadline, followingThrough, gateKnownUnmet, gateState, hasLabel, isCommentNews, isSpecComment, lifecycle, namesUserAsBlocker, newHumanComments, newestCommentAt, phaseAndStage, prGate, resolveChecklistItem, specHash, stuckDue, unheardWait, workerInFlight, type Change } from "./reconcile.js"; import { SOURCE_PLUGIN_IDS, STEWARDS_PLUGIN_ID, @@ -1418,6 +1418,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const workerInFlight = anyWorkerInFlight(store.workers(b.id)); const fresh = prev === null ? [] : diffObserved(prev, observed, { own: ownThreads(b), stewardThreadId: b.threadId, approved: ready.approval !== null, cursor: b.commentCursor, workerInFlight, userThread: isUserThread }); changes.push(...fresh); + // BB-35 step 2: a fresh unsigned comment by the owner that differs from + // the recommendation on a decision that cited lessons is a correction, + // counted once. Anyone else's words never count. Only from the second + // observation on: comments already there at adoption are history, not an + // event. + if (prev !== null) countCommentCorrections(b, observed); // Criterion 4: a spec comment the user wrote from their own thread is // the user's own words. With approval: me it carries its own approval, // pinned to the spec it just changed, whether or not an earlier @@ -2447,6 +2453,38 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } } + /** + * Count a correction when the owner's answer to an escalation differs from + * the steward's recommendation on it and the decision cited lessons + * (BB-35 step 2). Observed, never asked for; `correctionsCounted` keeps one + * reversal to one count. + */ + function countCorrections(x: Escalation, answer: string): void { + if (x.correctionsCounted || x.recommendation === null || x.citedLessons.length === 0) return; + if (!answerDiffers(answer, x.recommendation)) return; + store.recordCorrections(x.citedLessons); + store.markEscalationCorrected(x.id); + } + + /** + * The same for an unsigned comment the owner wrote on the entity itself: it + * differs from the recommendation on an open escalation that cited + * lessons. A signed comment belongs to a thread, and anyone else's words + * never count (BB-35 step 2). + */ + function countCommentCorrections(b: Binding, observed: Observed): void { + const viewer = observed.entity.viewer; + if (viewer === null) return; + const comments = newHumanComments(observed.entity, b.commentCursor, ownThreads(b)); + if (comments.length === 0) return; + for (const x of store.openEscalations(b.id)) { + if (x.correctionsCounted || x.recommendation === null || x.citedLessons.length === 0) continue; + if (!comments.some((c) => commentDiffersFromRecommendation(c, viewer, x.recommendation))) continue; + store.recordCorrections(x.citedLessons); + store.markEscalationCorrected(x.id); + } + } + /** Where an escalation goes next, above where it is. */ function nextRoute(b: Binding, from: EscalationRoute | null): EscalationRoute { if (from === null) { @@ -3449,6 +3487,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (x !== null && b !== null && b.endedAt === null) { const closure = `The user chose ${chosen} for ${b.entityKey}'s forwarded escalation on the Stewards page${text === null ? "" : `: ${text}`}.`; store.addGuidance(b.id, guidance, "user"); + countCorrections(x, guidance); store.note(b.id, `The user chose ${chosen} for ${q.question}${text === null ? "" : `: ${text}`}.`); scheduleReconcile(b.id); await wakeProjectOnForwardedAnswer(b, closure, [x]); @@ -3499,6 +3538,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ? `The user closed ${b.entityKey}'s forwarded escalation on the Stewards page without an answer.` : `The user answered ${b.entityKey}'s forwarded escalation on the Stewards page: ${JSON.stringify(text)}.`; if (text !== null) store.addGuidance(b.id, text, "user"); + if (text !== null) countCorrections(x, text); store.note(b.id, text === null ? `Escalation ${x.id} was closed by the user without an answer: carry on as you said you would meanwhile, or escalate again if you still need it.` : `Escalation ${x.id} decided by the user: ${text}`); scheduleReconcile(b.id); await wakeProjectOnForwardedAnswer(b, closure, [x], text !== null); @@ -3659,13 +3699,17 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (ownEscalation !== null && ownEscalation.status === "open") { store.addGuidance(b.id, guidance, "user"); store.answerEscalation(need.id, `Chose: ${label}${text === null ? "" : ` — ${text}`}`, "user"); + countCorrections(ownEscalation, guidance); } else { store.closeNeedByKey(b.id, "decide", need.url, `Chose: ${label}${text === null ? "" : ` — ${text}`}`); store.addGuidance(b.id, guidance, "user"); const escalationId = typeof need.data.escalationId === "string" ? need.data.escalationId : null; if (escalationId !== null) { const escalation = store.escalation(escalationId); - if (escalation !== null && escalation.status === "open") store.answerEscalation(escalationId, guidance, "user"); + if (escalation !== null && escalation.status === "open") { + store.answerEscalation(escalationId, guidance, "user"); + countCorrections(escalation, guidance); + } } } store.note(b.id, `The user chose ${label} for ${need.what}${text === null ? "" : `: ${text}`}.`); @@ -4118,6 +4162,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P binding: z.string().trim().min(1).max(300).optional().describe("The entity key (ENG-12, owner/repo#3) or binding id. Leave out for this thread's own binding, or, from the project steward, for a question about no one binding."), guidance: z.string().trim().min(1).max(4000).optional().describe("Standing guidance, in the user's or your own terms. With resolve, the answer to the escalation."), resolve: z.string().trim().min(1).max(100).optional().describe("An open escalation on that binding that the guidance answers; or, from the project steward, an open question (qst_…) the user answered, with answer."), + cites: z + .array(z.string().trim().min(1).max(100)) + .max(20) + .optional() + .describe("With resolve (or forward): the lesson ids (lsn_…) this decision rested on. A lesson's hits count once per distinct binding, and a later reversal of the decision counts a correction. Counts only — nothing is promoted or retired here."), answer: z.string().trim().min(1).max(4000).optional().describe("With resolve and a question id: the user's answer, kept on the question."), ask: z .object({ @@ -4279,6 +4328,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } } + if (input.cites !== undefined && resolve === undefined && input.forward === undefined) { + return toolError(new Error("cites goes with resolve (the decision it rested on) or forward (the recommendation it rested on).")); + } + const target = bindingRef === undefined ? (projectOf !== null ? null : ownBinding(threadId)) : store.find(bindingRef); if (bindingRef !== undefined && target === null) return toolError(new Error(`No binding for ${bindingRef}.`)); if (target === null) { @@ -4413,6 +4466,17 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P done.push(...questionWrites(closing, target)); if (input.lesson !== undefined) done.push(recordLesson(target.id, resolving?.id ?? closing?.question.escalationId ?? null)); + if (input.cites !== undefined) { + // BB-35 step 2: count the citation, and keep the lessons on the + // escalation so a later reversal can be attributed. Counts only: + // nothing is promoted, retired or written to `.bb` here. + const { cited, unknown } = store.recordCitations(target.projectId, input.cites, target.id); + const citeTarget = resolving ?? forwarding; + if (citeTarget !== null) store.setEscalationCitations(citeTarget.id, cited.map((l) => l.id)); + if (cited.length === 0) done.push("no lesson cited"); + else done.push(`cited ${cited.length} lesson${cited.length === 1 ? "" : "s"}: ${cited.map((l) => `${l.id} (${l.hits} binding${l.hits === 1 ? "" : "s"})`).join(", ")}`); + if (unknown.length > 0) done.push(`not counted (no such lesson in this project): ${unknown.join(", ")}`); + } if (forwarding !== null) { const route = nextRoute(target, forwarding.route); const recommendation = input.recommendation ?? forwarding.recommendation; @@ -5104,6 +5168,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (b !== null) { const closure = `The user chose ${choice} for ${b.entityKey}'s forwarded escalation from a thread${note === null ? "" : `: ${note}`}.`; store.addGuidance(b.id, guidance, "user"); + countCorrections(x, guidance); store.note(b.id, `The user chose ${choice} for ${q.question}${note === null ? "" : `: ${note}`}.`); scheduleReconcile(b.id); await wakeProjectOnForwardedAnswer(b, closure, [x]); @@ -5120,6 +5185,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ? `The user closed ${b.entityKey}'s forwarded escalation from a thread without an answer.` : `The user answered ${b.entityKey}'s forwarded escalation from a thread: ${JSON.stringify(note)}.`; if (note !== null) store.addGuidance(b.id, note, "user"); + if (note !== null) countCorrections(x, note); store.note(b.id, note === null ? `Question ${q.id} was closed from a thread.` : `Question ${q.id} was answered from a thread: ${note}`); scheduleReconcile(b.id); await wakeProjectOnForwardedAnswer(b, closure, [x], note !== null); diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index df620b90..a3e64542 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -265,7 +265,9 @@ question. The user may also close a question on the Stewards page. A forwarded escalation they answer on the page or from a thread wakes you with the answer and asks whether it is a general judgement: if it is, record it with `steward_update { lesson: { text, file, scope } }` so it is not -asked again. Every wake lists the questions still open: list them from +asked again. A resolve carries `cites: [lesson ids]`, the lessons the +decision rested on; the plugin counts hits (once per distinct binding), +corrections and last citation from them. Every wake lists the questions still open: list them from there, never from memory, and do not ask one again. At the end of each nightly pass your reply is kept as the morning digest; the wake carries the record to write it from diff --git a/plugins/stewards/store.test.ts b/plugins/stewards/store.test.ts index 526e54c6..84fe5d32 100644 --- a/plugins/stewards/store.test.ts +++ b/plugins/stewards/store.test.ts @@ -1,6 +1,6 @@ import Database from "better-sqlite3"; import { describe, expect, it } from "vitest"; -import { BASE_MIGRATIONS, CHAIN_MIGRATIONS, MIGRATIONS, createStore } from "./store.js"; +import { BASE_MIGRATIONS, CHAIN_MIGRATIONS, LESSON_COUNTER_MIGRATIONS, MIGRATIONS, createStore, lessonScope } from "./store.js"; function store() { const db = new Database(":memory:"); @@ -165,6 +165,95 @@ describe("lessons", () => { }); }); +describe("lesson citation counts (BB-35 step 2)", () => { + const second = (s: ReturnType["s"]) => + s.create({ projectId: "p1", source: "linear", entityId: "uuid-13", entityKey: "ENG-13", url: null, title: "Other", kind: "ticket", playbook: "linear-tickets", playbookVersion: "v1", parentBindingId: null, phase: "Todo", stage: "spec" }); + const lesson = (s: ReturnType["s"], projectId = "p1") => s.addLesson({ projectId, bindingId: null, escalationId: null, file: "AGENTS.md", text: "A rule.", scope: "procedure", branch: null }); + + it("count hits once per distinct binding, refresh lastCitedAt, and ignore unknown ids", () => { + const { s, binding, advance } = store(); + const l = lesson(s); + const other = second(s); + expect(l).toMatchObject({ hits: 0, corrections: 0, lastCitedAt: null, citedBindings: [] }); + + const first = s.recordCitations("p1", [l.id], binding.id); + expect(first.unknown).toEqual([]); + expect(first.cited).toMatchObject([{ id: l.id, hits: 1, lastCitedAt: 1_000, citedBindings: [binding.id] }]); + + // The same binding again is not a new hit, but it does refresh the time. + advance(500); + expect(s.recordCitations("p1", [l.id], binding.id).cited).toMatchObject([{ hits: 1, lastCitedAt: 1_500 }]); + + // A different binding is a second hit. + advance(500); + expect(s.recordCitations("p1", [l.id], other.id).cited).toMatchObject([{ hits: 2, citedBindings: [binding.id, other.id] }]); + + // Unknown and other-project ids never count. + const stranger = lesson(s, "p2"); + const unknown = s.recordCitations("p1", ["lsn_nope", stranger.id], binding.id); + expect(unknown).toEqual({ cited: [], unknown: ["lsn_nope", stranger.id] }); + expect(s.lesson(stranger.id)).toMatchObject({ hits: 0 }); + + // A citation with no binding counts once for the project. + expect(s.recordCitations("p1", [l.id], null).cited).toMatchObject([{ hits: 3, citedBindings: [binding.id, other.id, "project:p1"] }]); + expect(s.recordCitations("p1", [l.id], null).cited).toMatchObject([{ hits: 3 }]); + }); + + it("count corrections once each, and keep them on the escalation's citations", () => { + const { s, binding } = store(); + const l = lesson(s); + const x = s.escalate({ bindingId: binding.id, kind: "decision", question: "Q", meanwhile: "m", route: "me", recommendation: "Do it." }); + expect(s.escalation(x.id)).toMatchObject({ citedLessons: [], correctionsCounted: false }); + s.setEscalationCitations(x.id, [l.id, l.id]); + expect(s.escalation(x.id)).toMatchObject({ citedLessons: [l.id] }); + s.recordCorrections([l.id, l.id]); + expect(s.lesson(l.id)).toMatchObject({ corrections: 1 }); + s.recordCorrections([l.id]); + expect(s.lesson(l.id)).toMatchObject({ corrections: 2 }); + s.markEscalationCorrected(x.id); + expect(s.escalation(x.id)).toMatchObject({ correctionsCounted: true }); + }); + + it("fails closed: a lesson with no scope or an unknown one reads as boundary", () => { + expect(lessonScope(null)).toBe("boundary"); + expect(lessonScope(undefined)).toBe("boundary"); + expect(lessonScope("procedure")).toBe("procedure"); + expect(lessonScope("anything-else")).toBe("boundary"); + }); + + it("migrates losslessly: an existing lesson keeps its values and gets the counters at zero", () => { + const db = new Database(":memory:"); + for (const sql of BASE_MIGRATIONS) db.exec(sql); + for (const sql of CHAIN_MIGRATIONS) db.exec(sql); + db.exec(`INSERT INTO bindings (id, project_id, source, entity_id, entity_key, kind, playbook, playbook_version, created_at) + VALUES ('bnd_1', 'p1', 'linear', 'uuid-12', 'ENG-12', 'ticket', 'linear-tickets', 'v1', 1000)`); + db.exec(`INSERT INTO lessons (id, project_id, binding_id, escalation_id, file, text, scope, status, branch, merge_sha, note, created_at, updated_at, resolved_at) + VALUES ('lsn_old', 'p1', 'bnd_1', NULL, 'AGENTS.md', 'An old rule.', 'boundary', 'pending', 'refs/heads/guidance-thr_x', NULL, 'kept', 1000, 1100, NULL)`); + for (const sql of LESSON_COUNTER_MIGRATIONS) db.exec(sql); + const s = createStore(db, () => 2000); + expect(s.lesson("lsn_old")).toMatchObject({ + id: "lsn_old", + projectId: "p1", + bindingId: "bnd_1", + file: "AGENTS.md", + text: "An old rule.", + scope: "boundary", + status: "pending", + branch: "refs/heads/guidance-thr_x", + note: "kept", + createdAt: 1_000, + updatedAt: 1_100, + hits: 0, + corrections: 0, + lastCitedAt: null, + citedBindings: [], + }); + // The old columns are all still there; nothing was dropped or renamed. + const columns = (db.prepare("PRAGMA table_info(lessons)").all() as Array<{ name: string }>).map((c) => c.name); + expect(columns).toEqual(expect.arrayContaining(["id", "project_id", "binding_id", "escalation_id", "file", "text", "scope", "status", "branch", "merge_sha", "note", "created_at", "updated_at", "resolved_at", "hits", "corrections", "last_cited_at", "cited_bindings"])); + }); +}); + describe("the escalation-chain migration (BB-30)", () => { function legacy() { const db = new Database(":memory:"); @@ -192,6 +281,7 @@ describe("the escalation-chain migration (BB-30)", () => { db.exec(`INSERT INTO needs (id, binding_id, kind, url, what, how, data, filed_by, status, resolution, created_at, resolved_at) VALUES ('need_approve', 'bnd_1', 'approve-pr', 'https://github.com/acme/web/pull/7', 'Approve the PR.', NULL, '{}', 'plugin', 'open', NULL, 1900, NULL)`); for (const sql of CHAIN_MIGRATIONS) db.exec(sql); + for (const sql of LESSON_COUNTER_MIGRATIONS) db.exec(sql); let now = 2000; return { db, s: createStore(db, () => now) }; } diff --git a/plugins/stewards/store.ts b/plugins/stewards/store.ts index dc678745..b9ec37b8 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -318,7 +318,24 @@ export const CHAIN_MIGRATIONS = [ )`, ]; -export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS]; +// BB-35 step 2: citations and counts, no transitions. Additive and lossless: +// every existing lesson and escalation keeps its values and gets the new +// columns at their defaults, and nothing is dropped or renamed. A later step +// reads these counts to move tiers; this step only records them. +export const LESSON_COUNTER_MIGRATIONS = [ + `ALTER TABLE lessons ADD COLUMN hits INTEGER NOT NULL DEFAULT 0`, + `ALTER TABLE lessons ADD COLUMN corrections INTEGER NOT NULL DEFAULT 0`, + `ALTER TABLE lessons ADD COLUMN last_cited_at INTEGER`, + `ALTER TABLE lessons ADD COLUMN cited_bindings TEXT NOT NULL DEFAULT '[]'`, + // The lessons a resolve or a forwarding recommendation rested on, kept on the + // escalation so a later reversal can be attributed to them. + `ALTER TABLE escalations ADD COLUMN cited_lessons TEXT NOT NULL DEFAULT '[]'`, + // 1 once a reversal has been counted, so one correction is one count however + // often the comment or answer is observed. + `ALTER TABLE escalations ADD COLUMN corrections_counted INTEGER NOT NULL DEFAULT 0`, +]; + +export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS]; // ---- values kept as JSON ------------------------------------------------------------ @@ -614,6 +631,10 @@ export type Escalation = { headSha: string | null; /** True when this row is a question the project steward kept, rather than a raw escalation. */ isQuestion: boolean; + /** The lesson ids the resolve or recommendation rested on (BB-35 step 2). */ + citedLessons: string[]; + /** True once a reversal has been counted against this escalation's citations. */ + correctionsCounted: boolean; }; /** A project steward's approval of an owner-reviewed pull request, bound to its head sha. */ @@ -693,6 +714,12 @@ export function needChoices(n: Pick): string[] { */ export const LESSON_SCOPES = ["procedure", "boundary"] as const; export type LessonScope = (typeof LESSON_SCOPES)[number]; +/** + * A lesson's scope, failing closed: anything the plugin cannot classify — a + * missing value, an unknown string from an older or hand-edited row — is + * `boundary`, the one only the user may widen. Never `procedure` by default. + */ +export const lessonScope = (value: unknown): LessonScope => (value === "procedure" ? "procedure" : "boundary"); export type LessonStatus = "pending" | "merged" | "dropped"; export type Lesson = { id: string; @@ -711,6 +738,14 @@ export type Lesson = { mergeSha: string | null; /** The last refusal or explanation from a merge attempt, for the nightly prompt. */ note: string | null; + /** How many distinct bindings have cited it (BB-35 step 2). */ + hits: number; + /** How many times the user reversed a decision that cited it (BB-35 step 2). */ + corrections: number; + /** When it was last cited, or null. */ + lastCitedAt: number | null; + /** The bindings whose decisions cited it; one `hits` each, plus the project sentinel for a citation with no binding. */ + citedBindings: string[]; createdAt: number; updatedAt: number; resolvedAt: number | null; @@ -852,6 +887,8 @@ export function createStore(db: Database.Database, now: () => number) { forwardedFrom: r.forwarded_from === null || r.forwarded_from === undefined ? null : String(r.forwarded_from), headSha: r.head_sha === null || r.head_sha === undefined ? null : String(r.head_sha), isQuestion: Number(r.is_question ?? 0) === 1, + citedLessons: json(z.array(z.string()), r.cited_lessons === null || r.cited_lessons === undefined ? null : String(r.cited_lessons), []), + correctionsCounted: Number(r.corrections_counted ?? 0) === 1, }); const toQuestion = (r: Record): Question => { const e = toEscalation(r); @@ -894,6 +931,10 @@ export function createStore(db: Database.Database, now: () => number) { const resolveLessonStmt = db.prepare( "UPDATE lessons SET status = ?, merge_sha = COALESCE(?, merge_sha), branch = COALESCE(?, branch), note = ?, updated_at = ?, resolved_at = COALESCE(resolved_at, ?) WHERE id = ?", ); + const citeLessonStmt = db.prepare("UPDATE lessons SET hits = ?, last_cited_at = ?, cited_bindings = ?, updated_at = ? WHERE id = ?"); + const correctLessonStmt = db.prepare("UPDATE lessons SET corrections = corrections + 1, updated_at = ? WHERE id = ?"); + const setEscalationCitationsStmt = db.prepare("UPDATE escalations SET cited_lessons = ? WHERE id = ?"); + const markEscalationCorrectedStmt = db.prepare("UPDATE escalations SET corrections_counted = 1 WHERE id = ?"); const toNeed = (r: Record): Need => ({ id: String(r.id), @@ -976,11 +1017,15 @@ export function createStore(db: Database.Database, now: () => number) { escalationId: r.escalation_id === null || r.escalation_id === undefined ? null : String(r.escalation_id), file: String(r.file), text: String(r.text), - scope: String(r.scope) as LessonScope, + scope: lessonScope(r.scope), status: String(r.status) as LessonStatus, branch: r.branch === null || r.branch === undefined ? null : String(r.branch), mergeSha: r.merge_sha === null || r.merge_sha === undefined ? null : String(r.merge_sha), note: r.note === null || r.note === undefined ? null : String(r.note), + hits: Number(r.hits ?? 0), + corrections: Number(r.corrections ?? 0), + lastCitedAt: r.last_cited_at === null || r.last_cited_at === undefined ? null : Number(r.last_cited_at), + citedBindings: json(z.array(z.string()), r.cited_bindings === null || r.cited_bindings === undefined ? null : String(r.cited_bindings), []), createdAt: Number(r.created_at), updatedAt: Number(r.updated_at), resolvedAt: r.resolved_at === null || r.resolved_at === undefined ? null : Number(r.resolved_at), @@ -1505,6 +1550,47 @@ export function createStore(db: Database.Database, now: () => number) { const at = now(); resolveLessonStmt.run("dropped", null, null, note, at, at, id); }, + /** + * Record the lessons one decision cited (BB-35 step 2). A lesson's `hits` + * counts distinct bindings: a second citation from the same binding + * refreshes `lastCitedAt` but does not count again. A citation with no + * binding — a project-steward decision about no one binding — counts once + * per project. `unknown` names ids that are not lessons of this project; + * they are never counted. Counts only: no tier and no transition. + */ + recordCitations(projectId: string, lessonIds: string[], bindingId: string | null): { cited: Lesson[]; unknown: string[] } { + const at = now(); + const key = bindingId ?? `project:${projectId}`; + const cited: Lesson[] = []; + const unknown: string[] = []; + for (const id of [...new Set(lessonIds)]) { + const r = getLesson.get(id); + const lesson = r === undefined ? null : toLesson(r); + if (lesson === null || lesson.projectId !== projectId) { + unknown.push(id); + continue; + } + const seen = lesson.citedBindings.includes(key); + const citedBindings = seen ? lesson.citedBindings : [...lesson.citedBindings, key]; + const hits = seen ? lesson.hits : lesson.hits + 1; + citeLessonStmt.run(hits, at, JSON.stringify(citedBindings), at, id); + cited.push({ ...lesson, hits, lastCitedAt: at, citedBindings }); + } + return { cited, unknown }; + }, + /** Count a reversal of a decision against each lesson it cited, once each (BB-35 step 2). */ + recordCorrections(lessonIds: string[]): void { + const at = now(); + for (const id of new Set(lessonIds)) correctLessonStmt.run(at, id); + }, + /** Keep the lessons an escalation's decision rested on, for a later correction. */ + setEscalationCitations(id: string, lessonIds: string[]): void { + setEscalationCitationsStmt.run(JSON.stringify([...new Set(lessonIds)]), id); + }, + /** Mark an escalation's citations counted, so one reversal is one correction. */ + markEscalationCorrected(id: string): void { + markEscalationCorrectedStmt.run(id); + }, // project stewards project(projectId: string): ProjectStewardRow { diff --git a/plugins/stewards/wake.test.ts b/plugins/stewards/wake.test.ts index 0faea1fc..7ec4e1b1 100644 --- a/plugins/stewards/wake.test.ts +++ b/plugins/stewards/wake.test.ts @@ -154,6 +154,15 @@ describe("the nightly prompt", () => { expect(wake.indexOf("## The record since")).toBeLessThan(wake.indexOf("reply with the morning digest")); }); + it("tells the project steward to cite the lessons a decision rested on (BB-35 step 2)", () => { + const { s, bind } = world(); + const b = bind("ENG-12"); + const x = s.escalate({ bindingId: b.id, kind: "decision", question: "Include SSO?", meanwhile: "Wait.", route: "project", recommendation: null }); + const wake = formatProjectWake({ reason: "escalation", bindings: [], routed: [{ escalation: x, from: b }], problems: [], digestDue: false, notes: [], bigDecisions: [], questions: [] }); + expect(wake).toMatch(/cites: \[lesson ids\]/u); + expect(wake).toMatch(/a decision must cite what it was decided from/u); + }); + it("gives dates in the project's nightly time zone", () => { const { s } = world(); const q = s.ask({ projectId: "p1", bindingId: null, escalationId: null, question: "Freeze on Friday?", context: null }); diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 6e5913b6..a5719d01 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -355,7 +355,7 @@ export function formatWake(input: WakeInput): string { for (const x of open) out.push(`- ${x.id} (${x.kind}, with ${x.route === "me" ? "the user" : x.route === "steward" ? "you" : x.route === "parent" ? "your parent steward" : "the project steward"}): ${x.question}${choicesNote(x.choices)} Meanwhile: ${x.meanwhile}${x.recommendation === null ? "" : ` Recommendation: ${x.recommendation}`}`); for (const { escalation: x, from } of input.routedToMe) { out.push(`- ${x.id} from ${from.entityKey} (${x.kind}) — routed to you: ${x.question}${choicesNote(x.choices)} Meanwhile: ${x.meanwhile}${x.recommendation === null ? "" : ` Recommendation: ${x.recommendation}`}`); - out.push(" Decide it with steward_update { binding, guidance, resolve }, or pass it up with steward_update { binding, forward, recommendation }."); + out.push(" Decide it with steward_update { binding, guidance, resolve, cites: [lesson ids] }, or pass it up with steward_update { binding, forward, recommendation }."); } out.push("", OPEN_REQUESTS_NOTE, "Asking for one that is already open counts like a missed report toward `stuck`."); } @@ -796,7 +796,7 @@ export function formatProjectWake(input: { 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, and say which entry you matched:", + "Decide each from the project's guidance (AGENTS.md, architecture and design docs) with steward_update { binding, guidance, resolve }, citing the lessons it rested on with `cites: [lesson ids]` — a decision must cite what it was decided from. Forward one to the user (steward_update { binding, forward, recommendation }) only when it is one of these big decisions, and say which entry you matched:", "", ...input.bigDecisions.map((d) => `- ${d.text}${d.decide === "user" ? " [user]" : " [project]"}`), "", @@ -824,7 +824,7 @@ export function formatProjectWake(input: { if (withUser.length > 0) { out.push("## Escalations with the user", ""); for (const { escalation: x, from } of withUser) out.push(`- ${x.id} from ${from.entityKey} (${x.kind}): ${x.question}${choicesNote(x.choices)}${x.recommendation === null ? "" : ` Your recommendation: ${x.recommendation}`}`); - out.push("", "When the user answers one — here, or on the entity itself — record it with steward_update { binding, guidance, resolve }.", ""); + out.push("", "When the user answers one — here, or on the entity itself — record it with steward_update { binding, guidance, resolve, cites: [lesson ids] }, citing the lessons the decision rested on.", ""); } const questions = input.questions ?? []; if (questions.length > 0) { From 7297978dd26d2fe3a39c944c3a4a8e8dde657236 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Wed, 21 Oct 2026 19:40:58 +0000 Subject: [PATCH 2/2] stewards: name cites on the forward guidance too (BB-35 step 2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review round 1 suggestion: a forward can carry cites — the recommendation a correction is measured against lives on the forwarded escalation — so both wake lines name it on the forward half as well as the resolve half. --- plugins/stewards/wake.test.ts | 11 +++++++++++ plugins/stewards/wake.ts | 4 ++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/plugins/stewards/wake.test.ts b/plugins/stewards/wake.test.ts index 7ec4e1b1..03662f29 100644 --- a/plugins/stewards/wake.test.ts +++ b/plugins/stewards/wake.test.ts @@ -75,6 +75,15 @@ describe("a steward's wake", () => { expect(wake).toContain("counts like a missed report toward `stuck`"); }); + it("tells the steward to cite the lessons behind a routed escalation (BB-35 step 2)", () => { + const { s, bind } = world(); + const binding = bind("ENG-12"); + const x = s.escalate({ bindingId: binding.id, kind: "decision", question: "Include SSO?", meanwhile: "Wait.", route: "steward", recommendation: null }); + const wake = formatWake(wakeInput({ binding, routedToMe: [{ escalation: x, from: binding }] })); + expect(wake).toMatch(/resolve, cites: \[lesson ids\]/u); + expect(wake).toMatch(/forward, recommendation, cites: \[lesson ids\]/u); + }); + it("names the reviewer's sha and the head when the approval is on an earlier commit", () => { const marker = comment({ id: "m1", author: "trotterdylan", body: "", signedBy: "thr_reviewer", createdAt: "2026-10-18T04:00:00Z" }); const entity = pull({ comments: [marker] }, { headSha: "aaaaaaa1", checks: { state: "success", failing: [] } }); @@ -161,6 +170,8 @@ describe("the nightly prompt", () => { const wake = formatProjectWake({ reason: "escalation", bindings: [], routed: [{ escalation: x, from: b }], problems: [], digestDue: false, notes: [], bigDecisions: [], questions: [] }); expect(wake).toMatch(/cites: \[lesson ids\]/u); expect(wake).toMatch(/a decision must cite what it was decided from/u); + // A forward can cite too: the recommendation a correction is measured against lives there. + expect(wake).toMatch(/forward, recommendation, cites: \[lesson ids\]/u); }); it("gives dates in the project's nightly time zone", () => { diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index a5719d01..30ffd6de 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -355,7 +355,7 @@ export function formatWake(input: WakeInput): string { for (const x of open) out.push(`- ${x.id} (${x.kind}, with ${x.route === "me" ? "the user" : x.route === "steward" ? "you" : x.route === "parent" ? "your parent steward" : "the project steward"}): ${x.question}${choicesNote(x.choices)} Meanwhile: ${x.meanwhile}${x.recommendation === null ? "" : ` Recommendation: ${x.recommendation}`}`); for (const { escalation: x, from } of input.routedToMe) { out.push(`- ${x.id} from ${from.entityKey} (${x.kind}) — routed to you: ${x.question}${choicesNote(x.choices)} Meanwhile: ${x.meanwhile}${x.recommendation === null ? "" : ` Recommendation: ${x.recommendation}`}`); - out.push(" Decide it with steward_update { binding, guidance, resolve, cites: [lesson ids] }, or pass it up with steward_update { binding, forward, recommendation }."); + out.push(" Decide it with steward_update { binding, guidance, resolve, cites: [lesson ids] }, or pass it up with steward_update { binding, forward, recommendation, cites: [lesson ids] }."); } out.push("", OPEN_REQUESTS_NOTE, "Asking for one that is already open counts like a missed report toward `stuck`."); } @@ -796,7 +796,7 @@ export function formatProjectWake(input: { 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 }, citing the lessons it rested on with `cites: [lesson ids]` — a decision must cite what it was decided from. Forward one to the user (steward_update { binding, forward, recommendation }) only when it is one of these big decisions, and say which entry you matched:", + "Decide each from the project's guidance (AGENTS.md, architecture and design docs) with steward_update { binding, guidance, resolve }, citing the lessons it rested on with `cites: [lesson ids]` — a decision must cite what it was decided from. Forward one to the user (steward_update { binding, forward, recommendation, cites: [lesson ids] }) only when it is one of these big decisions, and say which entry you matched:", "", ...input.bigDecisions.map((d) => `- ${d.text}${d.decide === "user" ? " [user]" : " [project]"}`), "",