diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index e98a452a..1cb9f805 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -1285,6 +1285,43 @@ A **lesson** makes the answer a record and, for most of them, lands it. 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. +- **Tiers and transitions (BB-35 step 3).** Every lesson carries a `tier`: + `candidate` (store only, never in a wake) → `trial` (in the store, injected + into steward and project steward wakes under `## Lessons (trial)` with its + id) → `promoted` (committed to `.bb` with a `` anchor) → + `retired` (removed from the file; the row kept). The old `status` column is + kept and still tracks the file state (`pending`, `merged`, `dropped`); the + migration maps `pending` → `trial`, `merged` → `promoted`, `dropped` → + `retired`, once and idempotently. The nightly pass (and every sweep) applies + the thresholds under `lessons` in `project.json`, with the design's defaults + when the key is absent: trial → promoted at 3 distinct-binding hits, 0 + corrections and ≥ 14 days in trial; trial → retired at 30 days uncited or + any correction; promoted → retired at 90 days uncited or 2 corrections; any + lesson → retired when a newer one in the same file supersedes it. A + citation's weight halves every `decayHalfLifeDays`, so the lowest-scoring + promoted lesson is the one displaced when a file is at `promoted.maxPerFile`. + A lesson is `trial` from the moment the project steward records it; the + nightly pass is what moves it. The thresholds and caps are the whole + mechanism — no model judges a tier. The project steward may still + `complete` a trial by hand, which promotes it at once and bypasses + `promoted.maxPerFile`; that is an explicit override, and the nightly pass is + the mechanical path, not the only one. +- **The promotion and retirement write only the lesson's own anchored text.** + A promotion the nightly pass queues is listed under `## Lessons to land`; + the project steward adds the block (`` and the wording) + to the named file, commits, publishes with `workspace_publish_guidance`, and + completes it. A retirement is listed under `## Lessons to retire`; the + project steward replaces the block with `` and + publishes, then `steward_update { lessonAction: { action: "retire" } }` + fast-forwards the canonical checkout. The same multi-repo guard applies both + ways: only the lesson's own file may change, and it must carry the anchor the + call names. A lesson's `file` may never be `stewards/project.json`, so a + lesson can never move a big decision to the project, loosen the + pull-request gate or relax an approval; the decide list, `bigDecisions` and + `prGate` are outside a lesson's reach by construction. A boundary-scope + lesson still becomes a Merge/Drop item for the user. `retireLessonAnchor` + in `lessons.ts` is the normative definition of the retirement edit; the + project steward makes it by hand and the helper is what the tests pin. - **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 @@ -1314,24 +1351,30 @@ A **lesson** makes the answer a record and, for most of them, lands it. and the revert below cover. - **Status is observed, not assumed.** Every sweep and nightly pass reads each pending lesson's file at `.bb` HEAD and marks it `merged` when the - normalised text is there, however it got there. `dropped` is set by the - user's Drop button, the project steward's `drop` action, or + anchored text is there, however it got there; a retired lesson is skipped so + an observation never resurrects it. `dropped` is set by the user's Drop + button, the project steward's `drop` action, a retirement, or `bb stewards drop-lesson `. - **The nightly prompt and the digest.** The project steward's nightly wake - lists the pending lessons and asks it to apply, commit, publish and - complete them, with the last refusal reason where one was refused. The - digest lists the lessons that landed in the window with their sha, file - and source binding/escalation, and names the branch. + lists the trial lessons to decide from, the promoted ones queued to land and + the retired ones to remove, with the last refusal reason where one was + refused. The digest carries nothing about lessons: the merged-lessons + section is gone, and `bb stewards lessons --all` is where their state is + read. - **Surfaces.** Pending lessons are on the Stewards page's Lessons section and in `bb stewards list`; `bb stewards lessons [--all]` lists them, `bb stewards drop-lesson ` drops one. - **Undo.** A merged procedure lesson is an ordinary commit on `.bb` HEAD; `bb stewards lessons --all` names its `mergeSha` and branch. To undo it, revert that commit in the canonical checkout (`git revert ` in the - project's `.bb`, then push) or edit the wording out and let the next pass - see it gone; the lesson row stays `merged` until it is dropped, which only - closes the record, not the file. A boundary lesson is undone the same way - once the user has merged it. + project's `.bb`, then push), or let the nightly pass retire it once it is + uncited for `promoted.retireDays` and remove the anchored block through + `## Lessons to retire`. The row is kept with `tier: retired` either way. A + boundary lesson is undone the same way once the user has merged it. A + lesson recorded by an image before this step gets the column default + `candidate`, and the remap has already run at its own index, so after a + roll-forward it is invisible to wakes; `bb stewards lessons --all` still + shows it, and re-recording it as a fresh trial is the way back. ## 21. The sidebar thread list diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 60e1873f..73086ab5 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -277,22 +277,29 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. or the approval code is always yours. - **Lessons** are a project steward's general judgements, made permanent in `.bb` instead of being lost with the ticket that raised them. It records - one with `steward_update { lesson: { text, file, scope } }`; a `procedure` - lesson it applies, commits and publishes, then self-merges with - `steward_update { lessonAction: { id, action: "complete" } }` (multi-repo - fast-forwards the canonical `.bb`, and only that lesson's file). A - `boundary` lesson — credentials and reach, who may direct a server, - irreversible production steps — is filed on the Stewards page with - **Merge** and **Drop**, and only you merge it. A lesson is `merged` when - its text is found in its file at `.bb` HEAD. A user's answer to a forwarded - 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. 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. + one with `steward_update { lesson: { text, file, scope } }`. A lesson + moves through tiers: `candidate` → `trial` → `promoted` → `retired`. A + recorded lesson starts `trial`; the nightly pass promotes it when it is + cited on 3 distinct bindings with no corrections and has been in trial 14 + days, and retires it at 30 days uncited or on any correction (a promoted + one at 90 days uncited or 2 corrections). The thresholds, caps and decay + half-life are under `lessons` in `stewards/project.json`; the design's + defaults apply when the key is absent. Trial lessons are injected into + wakes under `## Lessons (trial)`; only promoted ones reach `.bb`, with a + `` anchor, and only that lesson's own file (multi-repo + fast-forwards the canonical `.bb`). A `boundary` lesson — credentials and + reach, who may direct a server, irreversible production steps — is filed on + the Stewards page with **Merge** and **Drop**, and only you merge it; a + lesson can never target `stewards/project.json`, so it cannot move a big + decision to the project, loosen the pull-request gate or relax an approval. + A user's answer to a forwarded 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. A resolve carries `cites: [lesson ids]` — the + lessons it rested on — and the plugin counts `hits` (once per distinct + binding), `corrections` and `lastCitedAt`. `bb stewards lessons [--all]` + lists tiers and counts, `bb stewards drop-lesson ` drops one. The + digest carries nothing about lessons. 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 binding a turn, then wakes the project steward for the morning digest. diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index f9ebc4ce..3198a70e 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -47,6 +47,19 @@ describe("the project file", () => { if (!badDuration.ok) expect(badDuration.error).toMatch(/deps\.sla\.high/u); }); + it("fills the lesson lifecycle's defaults, and takes explicit thresholds (BB-35 step 3)", () => { + const defaults = parseProjectFile(JSON.stringify({ version: 1 })); + if (!defaults.ok) throw new Error(defaults.error); + expect(defaults.value.lessons).toEqual({ trial: { max: 5, retireDays: 30 }, promote: { hits: 3, days: 14 }, promoted: { maxPerFile: 10, retireDays: 90, corrections: 2 }, decayHalfLifeDays: 30 }); + + const explicit = parseProjectFile(JSON.stringify({ version: 1, lessons: { trial: { max: 2 }, promote: { hits: 5, days: 7 }, decayHalfLifeDays: 14 } })); + if (!explicit.ok) throw new Error(explicit.error); + expect(explicit.value.lessons).toEqual({ trial: { max: 2, retireDays: 30 }, promote: { hits: 5, days: 7 }, promoted: { maxPerFile: 10, retireDays: 90, corrections: 2 }, decayHalfLifeDays: 14 }); + + expect(parseProjectFile(JSON.stringify({ version: 1, lessons: { promote: { hits: 0 } } }))).toMatchObject({ ok: false }); + expect(parseProjectFile(JSON.stringify({ version: 1, lessons: { unknown: true } }))).toMatchObject({ ok: false }); + }); + it("takes the standing-rules list, and rejects an unknown key (BB-54)", () => { const defaults = parseProjectFile(JSON.stringify({ version: 1 })); if (!defaults.ok) throw new Error(defaults.error); diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index b08f564f..39140db2 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -208,6 +208,52 @@ export const depsSchema = z .default({ sla: { critical: "asap", high: 86_400_000, medium: 7 * 86_400_000, low: 30 * 86_400_000 }, batch: { medium: 7 * 86_400_000, low: 30 * 86_400_000 }, autoAdopt: ["critical", "high"] }); export type DepsConfig = z.infer; +/** + * The mechanical lesson lifecycle's rules (BB-35 step 3): when a trial lesson + * is promoted or retired, how many a wake may carry, and how many promoted + * lessons a file holds. The defaults are the design's; a project overrides + * any part under `lessons` and the rest fall back. `decayHalfLifeDays` + * weights a citation by age, so an old burst of use does not keep a lesson + * alive when the lowest-scoring one has to be displaced. + */ +export const lessonRulesSchema = z + .object({ + trial: z + .object({ + /** At most this many trial lessons in one wake. */ + max: z.number().int().min(1).max(50).default(5), + /** A trial lesson uncited this long is retired. */ + retireDays: z.number().positive().max(3650).default(30), + }) + .strict() + .default({ max: 5, retireDays: 30 }), + promote: z + .object({ + /** Distinct bindings a trial lesson must be cited on to be promoted. */ + hits: z.number().int().min(1).max(50).default(3), + /** Days a trial lesson must have been in trial before it may be promoted. */ + days: z.number().positive().max(3650).default(14), + }) + .strict() + .default({ hits: 3, days: 14 }), + promoted: z + .object({ + /** At most this many promoted lessons in one file; a promotion into a full file displaces the lowest-scoring one. */ + maxPerFile: z.number().int().min(1).max(100).default(10), + /** A promoted lesson uncited this long is retired. */ + retireDays: z.number().positive().max(3650).default(90), + /** Corrections that retire a promoted lesson. */ + corrections: z.number().int().min(1).max(50).default(2), + }) + .strict() + .default({ maxPerFile: 10, retireDays: 90, corrections: 2 }), + /** A citation's weight halves every this many days. */ + decayHalfLifeDays: z.number().positive().max(3650).default(30), + }) + .strict() + .default({ trial: { max: 5, retireDays: 30 }, promote: { hits: 3, days: 14 }, promoted: { maxPerFile: 10, retireDays: 90, corrections: 2 }, decayHalfLifeDays: 30 }); +export type LessonRules = z.infer; + export const projectFileSchema = z .object({ version: z.literal(1), @@ -283,6 +329,8 @@ export const projectFileSchema = z .default({ targets: [], autoAdopt: [], sentry: { resolveOnDone: false } }), /** The dependency watch: per-severity SLA, the batch window, and what auto-adopts. */ deps: depsSchema, + /** The mechanical lesson lifecycle's thresholds and caps (BB-35 step 3). */ + lessons: lessonRulesSchema, }) .strict() .superRefine((file, ctx) => { diff --git a/plugins/stewards/lessons.test.ts b/plugins/stewards/lessons.test.ts new file mode 100644 index 00000000..5106f2c2 --- /dev/null +++ b/plugins/stewards/lessons.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from "vitest"; +import { hasLessonAnchor, lessonAnchor, lessonScore, planLessonTransitions, removeLessonAnchor, retireLessonAnchor, retiredLessonAnchor, withLessonAnchor, type ScoreableLesson } from "./lessons.js"; +import type { LessonRules } from "./config.js"; + +const DAY = 86_400_000; +const T = Date.parse("2026-10-18T05:00:00Z"); + +const rules: LessonRules = { + trial: { max: 5, retireDays: 30 }, + promote: { hits: 3, days: 14 }, + promoted: { maxPerFile: 2, retireDays: 90, corrections: 2 }, + decayHalfLifeDays: 30, +}; + +function lesson(over: Partial = {}): ScoreableLesson { + return { id: "lsn_a", tier: "trial", file: "AGENTS.md", hits: 0, corrections: 0, lastCitedAt: null, createdAt: T - 20 * DAY, tierAt: T - 20 * DAY, supersededBy: null, ...over }; +} + +describe("the lesson anchor", () => { + it("carries the id in the file and finds it again", () => { + expect(lessonAnchor("lsn_1")).toBe(""); + expect(withLessonAnchor("A rule.", "lsn_1")).toBe("\nA rule."); + expect(hasLessonAnchor("x\n\nA rule.\n", "lsn_1")).toBe(true); + expect(hasLessonAnchor("x\nA rule.\n", "lsn_1")).toBe(false); + }); + + it("removes exactly its own anchored block and nothing else", () => { + const content = ["# Guidance", "", "Tail text.", "", withLessonAnchor("First rule.", "lsn_1"), "", withLessonAnchor("Second rule.", "lsn_2")].join("\n"); + const after = removeLessonAnchor(content, "lsn_1"); + expect(after).not.toContain("First rule."); + expect(after).not.toContain(lessonAnchor("lsn_1")); + // The neighbour, the headings and the tail are untouched. + expect(after).toContain(withLessonAnchor("Second rule.", "lsn_2")); + expect(after).toContain("Tail text."); + expect(after).toContain("# Guidance"); + }); + + it("removes the last block through the end of the file", () => { + const content = `# Guidance\n\n${withLessonAnchor("Only rule.", "lsn_1")}\n`; + expect(removeLessonAnchor(content, "lsn_1")).toBe("# Guidance\n\n"); + }); + + it("leaves a file without the anchor unchanged", () => { + expect(removeLessonAnchor("# Guidance\n", "lsn_1")).toBe("# Guidance\n"); + expect(retireLessonAnchor("# Guidance\n", "lsn_1")).toBe("# Guidance\n"); + }); + + it("replaces the block with a retired anchor that is not a live anchor", () => { + const content = `# Guidance\n\n${withLessonAnchor("A rule.", "lsn_1")}\n`; + const after = retireLessonAnchor(content, "lsn_1"); + expect(after).toBe(`# Guidance\n\n${retiredLessonAnchor("lsn_1")}\n`); + expect(after).not.toContain("A rule."); + expect(hasLessonAnchor(after, "lsn_1")).toBe(false); + }); +}); + +describe("the lesson score", () => { + it("halves a citation's weight every half-life", () => { + const fresh = lessonScore({ hits: 4, corrections: 0, lastCitedAt: T, createdAt: T, tierAt: T }, T, 30 * DAY); + const old = lessonScore({ hits: 4, corrections: 0, lastCitedAt: T - 30 * DAY, createdAt: T, tierAt: T }, T, 30 * DAY); + expect(fresh).toBe(4); + expect(old).toBe(2); + // A correction subtracts. + expect(lessonScore({ hits: 4, corrections: 1, lastCitedAt: T, createdAt: T, tierAt: T }, T, 30 * DAY)).toBe(3); + }); +}); + +describe("the nightly transitions", () => { + it("promotes a trial with 3 distinct bindings, no corrections, 14 days in trial", () => { + const ready = lesson({ hits: 3, lastCitedAt: T - 1 * DAY, tierAt: T - 20 * DAY }); + expect(planLessonTransitions([ready], rules, T)).toEqual([{ id: "lsn_a", action: "promote", reason: expect.stringContaining("3 bindings") }]); + // Two hits is not enough. + expect(planLessonTransitions([lesson({ hits: 2, lastCitedAt: T - 1 * DAY, tierAt: T - 20 * DAY })], rules, T)).toEqual([]); + // Under 14 days in trial is not enough. + expect(planLessonTransitions([lesson({ hits: 3, lastCitedAt: T - 1 * DAY, tierAt: T - 5 * DAY })], rules, T)).toEqual([]); + }); + + it("retires a trial uncited for 30 days, or on any correction", () => { + expect(planLessonTransitions([lesson({ tierAt: T - 31 * DAY })], rules, T)).toEqual([{ id: "lsn_a", action: "retire", reason: expect.stringContaining("uncited") }]); + expect(planLessonTransitions([lesson({ hits: 1, lastCitedAt: T - 40 * DAY, tierAt: T - 60 * DAY })], rules, T)).toEqual([{ id: "lsn_a", action: "retire", reason: expect.stringContaining("uncited") }]); + expect(planLessonTransitions([lesson({ corrections: 1, lastCitedAt: T - 1 * DAY })], rules, T)).toEqual([{ id: "lsn_a", action: "retire", reason: "corrected" }]); + }); + + it("retires a promoted lesson uncited for 90 days or with 2 corrections", () => { + expect(planLessonTransitions([lesson({ tier: "promoted", tierAt: T - 91 * DAY })], rules, T)).toEqual([{ id: "lsn_a", action: "retire", reason: expect.stringContaining("uncited") }]); + expect(planLessonTransitions([lesson({ tier: "promoted", corrections: 2, lastCitedAt: T - 1 * DAY })], rules, T)).toEqual([{ id: "lsn_a", action: "retire", reason: "2 corrections" }]); + expect(planLessonTransitions([lesson({ tier: "promoted", corrections: 1, lastCitedAt: T - 1 * DAY })], rules, T)).toEqual([]); + }); + + it("retires a superseded lesson, and never also promotes it", () => { + const superseded = lesson({ hits: 5, lastCitedAt: T - 1 * DAY, supersededBy: "lsn_new" }); + expect(planLessonTransitions([superseded], rules, T)).toEqual([{ id: "lsn_a", action: "retire", reason: "superseded by lsn_new" }]); + }); + + it("displaces the lowest-scoring promoted lesson when a file is full", () => { + const low = lesson({ id: "lsn_low", tier: "promoted", file: "AGENTS.md", hits: 1, lastCitedAt: T - 80 * DAY, tierAt: T - 200 * DAY }); + const high = lesson({ id: "lsn_high", tier: "promoted", file: "AGENTS.md", hits: 5, lastCitedAt: T - 1 * DAY, tierAt: T - 200 * DAY }); + const newcomer = lesson({ id: "lsn_new", hits: 3, lastCitedAt: T - 1 * DAY, tierAt: T - 20 * DAY }); + const plan = planLessonTransitions([low, high, newcomer], rules, T); + expect(plan).toContainEqual({ id: "lsn_low", action: "retire", reason: "displaced by lsn_new" }); + expect(plan).toContainEqual({ id: "lsn_new", action: "promote", reason: expect.stringContaining("3 bindings"), displacedId: "lsn_low" }); + // A file with room promotes without displacing. + expect(planLessonTransitions([newcomer], rules, T)).toEqual([{ id: "lsn_new", action: "promote", reason: expect.stringContaining("3 bindings") }]); + }); + + it("ignores candidates and retired lessons", () => { + expect(planLessonTransitions([lesson({ tier: "candidate", hits: 9 })], rules, T)).toEqual([]); + expect(planLessonTransitions([lesson({ tier: "retired", hits: 9 })], rules, T)).toEqual([]); + }); +}); diff --git a/plugins/stewards/lessons.ts b/plugins/stewards/lessons.ts new file mode 100644 index 00000000..7c230d99 --- /dev/null +++ b/plugins/stewards/lessons.ts @@ -0,0 +1,160 @@ +// The mechanical lesson lifecycle's pure half (BB-35 step 3): the anchor that +// makes a lesson's text findable in `.bb`, the age-weighted score that ranks +// lessons, and the thresholds and caps that decide which tier a lesson moves +// to. Nothing here touches the store or a plugin; server.ts applies what this +// returns. Keeping it pure is what makes every transition a unit test. +import type { LessonTier } from "./store.js"; +import type { LessonRules } from "./config.js"; + +const DAY_MS = 86_400_000; + +/** The HTML comment that carries a lesson's id in the file it was promoted to. */ +export const lessonAnchor = (id: string): string => ``; + +/** + * The anchor a retired lesson leaves behind. The lesson's text is removed; the + * tombstone stays so the narrow merge can verify the right file and the same + * lesson is never promoted again. It deliberately does not match + * {@link lessonAnchor}, so a reader can tell a retired lesson from a live one. + */ +export const retiredLessonAnchor = (id: string): string => ``; + +/** The wording as it lands in `.bb`: the anchor on its own line, then the lesson. */ +export const withLessonAnchor = (text: string, id: string): string => `${lessonAnchor(id)}\n${text}`; + +/** Whether a file carries a lesson's anchor. */ +export const hasLessonAnchor = (content: string, id: string): boolean => content.includes(lessonAnchor(id)); + +/** + * Remove exactly the block a lesson's anchor opens: from the start of the + * anchor's line to the line before the next lesson anchor (or the end of the + * file). Everything else is returned byte for byte, so a retirement can never + * take a neighbouring lesson or any other text with it. A file without the + * anchor is returned unchanged. + */ +export function removeLessonAnchor(content: string, id: string): string { + const marker = lessonAnchor(id); + const at = content.indexOf(marker); + if (at === -1) return content; + const start = content.lastIndexOf("\n", at) + 1; + const next = content.indexOf("`); + await t.tool("steward_update", { lessonAction: { id, action: "complete" } }, t.project); + expect(t.mergeGuidanceCalls.at(-1)).toMatchObject({ file: "AGENTS.md", text: withLessonAnchor(lesson, id) }); + }); + + it("retires an aged promoted lesson, and removes its anchored text through the same path", async () => { + const t = await adopted(); + const recorded = await t.tool("steward_update", { binding: "ENG-12", lesson: { text: lesson, file: "AGENTS.md", scope: "procedure" } }, t.project); + const id = /(lsn_[\w-]+)/u.exec(recorded.text)![1]!; + await t.tool("steward_update", { lessonAction: { id, action: "complete" } }, t.project); + expect(t.hooks.store.lesson(id)).toMatchObject({ tier: "promoted", status: "merged" }); + t.advance(91 * 86_400_000); + await t.hooks.nightlyPass("p1", "2026-10-18"); + await t.flush(); + expect(t.hooks.store.lesson(id)).toMatchObject({ tier: "retired", status: "merged" }); + const wake = t.sends.filter((s) => s.threadId === t.project).at(-1)!.text; + expect(wake).toContain("## Lessons to retire"); + const done = await t.tool("steward_update", { lessonAction: { id, action: "retire" } }, t.project); + expect(done).toMatchObject({ error: false, text: expect.stringMatching(/retired at/u) }); + expect(t.mergeGuidanceCalls.at(-1)).toMatchObject({ file: "AGENTS.md", text: retiredLessonAnchor(id) }); + expect(t.hooks.store.lesson(id)).toMatchObject({ tier: "retired", status: "dropped" }); + }); + + it("never puts a candidate lesson in a wake", async () => { + const t = await adopted(); + const candidate = t.hooks.store.addLesson({ projectId: "p1", bindingId: null, escalationId: null, file: "AGENTS.md", text: "A candidate rule.", scope: "procedure", branch: null, tier: "candidate" }); + await t.hooks.nightlyPass("p1", "2026-10-18"); + await t.flush(); + const wake = t.sends.filter((s) => s.threadId === t.project).at(-1)!.text; + expect(wake).not.toContain(candidate.id); + expect(wake).not.toContain("A candidate rule."); + }); + + it("refuses the project file as a lesson's target, so a lesson cannot widen the decide list (BB-35 limit 1)", async () => { + const t = await adopted(); + await expect(t.tool("steward_update", { lesson: { text: "Move every kind to the project.", file: "stewards/project.json", scope: "procedure" } }, t.project)).rejects.toThrow(/project file/u); + }); + + it("never lands a retired lesson", async () => { + const t = await adopted(); + const recorded = await t.tool("steward_update", { binding: "ENG-12", lesson: { text: lesson, file: "AGENTS.md", scope: "procedure" } }, t.project); + const id = /(lsn_[\w-]+)/u.exec(recorded.text)![1]!; + t.hooks.store.setLessonTier(id, "retired"); + const out = await t.tool("steward_update", { lessonAction: { id, action: "complete" } }, t.project); + expect(out).toMatchObject({ error: true, text: expect.stringMatching(/retired/u) }); + expect(t.mergeGuidanceCalls).toEqual([]); + }); + + it("drops an aged-out trial that never landed, instead of leaving it pending", async () => { + const t = await adopted(); + const recorded = await t.tool("steward_update", { binding: "ENG-12", lesson: { text: lesson, file: "AGENTS.md", scope: "procedure" } }, t.project); + const id = /(lsn_[\w-]+)/u.exec(recorded.text)![1]!; + t.advance(31 * 86_400_000); + await t.hooks.nightlyPass("p1", "2026-10-18"); + await t.flush(); + expect(t.hooks.store.lesson(id)).toMatchObject({ tier: "retired", status: "dropped" }); + expect(t.mergeGuidanceCalls).toEqual([]); + const wake = t.sends.filter((s) => s.threadId === t.project).at(-1)!.text; + expect(wake).not.toContain("## Lessons to retire"); + }); + + it("validates a supersedes: same project, same file, not already retired", async () => { + const t = await adopted(); + const recorded = await t.tool("steward_update", { binding: "ENG-12", lesson: { text: "The old rule.", file: "AGENTS.md", scope: "procedure" } }, t.project); + const olderId = /(lsn_[\w-]+)/u.exec(recorded.text)![1]!; + // A lesson in another project is never touched. + const foreign = t.hooks.store.addLesson({ projectId: "p2", bindingId: null, escalationId: null, file: "AGENTS.md", text: "Foreign rule.", scope: "procedure", branch: null }); + const foreignAttempt = await t.tool("steward_update", { lesson: { text: "The new rule.", file: "AGENTS.md", scope: "procedure", supersedes: foreign.id } }, t.project); + expect(foreignAttempt).toMatchObject({ error: true, text: expect.stringMatching(/No lesson/u) }); + expect(t.hooks.store.lesson(foreign.id)).toMatchObject({ supersededBy: null }); + // A different file is refused: a lesson only supersedes one in its own file. + const otherFile = await t.tool("steward_update", { lesson: { text: "The new rule.", file: "stewards/linear-tickets.md", scope: "procedure", supersedes: olderId } }, t.project); + expect(otherFile).toMatchObject({ error: true, text: expect.stringMatching(/same file/u) }); + // The valid one records and marks the older lesson. + const good = await t.tool("steward_update", { lesson: { text: "The new rule.", file: "AGENTS.md", scope: "procedure", supersedes: olderId } }, t.project); + expect(good).toMatchObject({ error: false }); + expect(t.hooks.store.lesson(olderId)).toMatchObject({ supersededBy: expect.stringMatching(/^lsn_/u) }); }); }); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 257908fb..92ec92c0 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -43,6 +43,7 @@ import { usesKind, type BindingKind, type EscalationKind, + type LessonRules, type ModelSpec, type Playbook, type ProjectFile, @@ -74,6 +75,7 @@ import { } from "./source-contract.js"; import { allDeployed, applyDeployment, applyDeploymentRead, applyWorkflowRun, awaitingOnRepo, deploymentLines, deploymentReportSchema, matchesWorkflow, recordMerged, reportDeployment, timeOut, timeoutsDue } from "./deploy.js"; import { ACTORS, MIGRATIONS, ESCALATED_NEED_KINDS, NEEDS_KINDS, RESOLUTION_KINDS, createStore, needChoices, type Binding, type Escalation, type EscalationRoute, type Fingerprint, type Lesson, type Need, type Observed, type Question, type ReadyState, type Store, type Worker } from "./store.js"; +import { hasLessonAnchor, planLessonTransitions, retiredLessonAnchor, withLessonAnchor } from "./lessons.js"; import { createGhWriter, parsePullRef, type GithubWriter } from "./github.js"; import { allPullsMerged, atWork, conflictsOf, finished, normalizeTouches, overlapping, touchesOverlap, type Conflict } from "./schedule.js"; import { AUTOMATIC_THREAD_LIST_PROVIDER, BUILTIN_THREAD_LIST_ID, THREAD_LIST_PROVIDER_KEY } from "./sidebar-provider.js"; @@ -1758,6 +1760,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P label: config.file.label, conflicts: conflictsOf(b, store.open(b.projectId)), deployments: b.deployments, + lessons: store.lessonsByTier(b.projectId, "trial").slice(0, config.file.lessons.trial.max), now: now(), }); if (!(await deliverWake(b, config, playbook, text))) return false; @@ -2998,7 +3001,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const bindings = open.map((binding) => ({ binding, openEscalations: store.openEscalations(binding.id) })); const questions = store.openQuestions(projectId).map((question) => ({ question, about: question.bindingId === null ? null : store.binding(question.bindingId) })); const needs = open.flatMap((b) => store.openNeeds(b.id).map((need) => ({ need, binding: b }))); - const text = formatProjectWake({ reason, bindings, routed, withUser, problems: config.problems, digestDue: opts.digestDue, notes: opts.notes ?? [], bigDecisions: config.file.bigDecisions, standingRules: config.file.standingRules, questions, needs, lessons: store.lessons(projectId), timeZone: config.file.nightly.timezone, label: config.file.label, ...(records === undefined ? {} : { records }) }); + const text = formatProjectWake({ reason, bindings, routed, withUser, problems: config.problems, digestDue: opts.digestDue, notes: opts.notes ?? [], bigDecisions: config.file.bigDecisions, standingRules: config.file.standingRules, questions, needs, lessons: store.allLessons(projectId), lessonRules: config.file.lessons, timeZone: config.file.nightly.timezone, label: config.file.label, ...(records === undefined ? {} : { records }) }); const delivered = { ids: routed.filter((r) => r.escalation.deliveredAt === null).map((r) => r.escalation.id), at: 0 }; delivered.at = store.markDelivered(delivered.ids); // A wake can be the thing that pushes the transcript over the limit. @@ -3029,7 +3032,6 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P needs: open.flatMap((b) => store.openNeeds(b.id).map((need) => ({ need, binding: b }))), stuck: openWith((x) => x.kind === "stuck"), held: open.filter((b) => b.hold !== null), - lessonsMerged: store.mergedLessonsSince(projectId, since), }; } @@ -3082,7 +3084,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P store.noteLesson(lesson.id, "The project steward has no thread yet, so nothing has been published."); return "no project steward thread"; } - const result = await mergeLesson(lesson.projectId, threadId, lesson); + // The file carries the lesson's anchor, so the merge's narrow guard can + // check the right block landed and the same lesson cannot land twice. + const result = await mergeLesson(lesson.projectId, threadId, lesson, withLessonAnchor(lesson.text, lesson.id)); if (!result.ok) { store.noteLesson(lesson.id, result.message); return `merge refused: ${result.message}`; @@ -3091,18 +3095,43 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return `merged at ${result.sha ?? "?"}${result.branch === null ? "" : ` on ${result.branch}`}`; } + /** + * Remove a retired lesson's text from `.bb` through the same narrow merge + * path, leaving the retired anchor behind. The project steward has already + * removed the text and published the branch; this fast-forwards it. A + * lesson that never reached the file is retired in the row alone. + */ + async function retireLesson(lesson: Lesson): Promise { + if (lesson.status !== "merged") { + store.markLessonDropped(lesson.id, "Retired before it reached the file."); + return "retired (it was not in the file)"; + } + const threadId = store.project(lesson.projectId).threadId; + if (threadId === null) { + store.noteLesson(lesson.id, "The project steward has no thread yet, so nothing could be removed."); + return "no project steward thread"; + } + const result = await mergeLesson(lesson.projectId, threadId, lesson, retiredLessonAnchor(lesson.id)); + if (!result.ok) { + store.noteLesson(lesson.id, result.message); + return `retire refused: ${result.message}`; + } + store.markLessonDropped(lesson.id, `Retired; the anchored text was removed from ${lesson.file}.`); + return `retired at ${result.sha ?? "?"}${result.branch === null ? "" : ` on ${result.branch}`}`; + } + /** Fast-forward the canonical `.bb` to a lesson's published branch, through multi-repo. */ - async function mergeLesson(projectId: string, threadId: string, lesson: Lesson): Promise<{ ok: boolean; sha: string | null; branch: string | null; message: string }> { + async function mergeLesson(projectId: string, threadId: string, lesson: Lesson, text: string): Promise<{ ok: boolean; sha: string | null; branch: string | null; message: string }> { try { - return await rpc(MULTI_REPO_PLUGIN_ID, "mergeGuidance", { projectId, threadId, file: lesson.file, text: lesson.text }, mergeGuidanceOutput); + return await rpc(MULTI_REPO_PLUGIN_ID, "mergeGuidance", { projectId, threadId, file: lesson.file, text }, mergeGuidanceOutput); } catch (error) { return { ok: false, sha: null, branch: lesson.branch, message: errorMessage(error) }; } } - /** Each pass, a lesson whose text is already at `.bb` HEAD is merged, however it got there. */ + /** Each pass, a lesson whose anchored text is already at `.bb` HEAD is merged, however it got there. */ async function reconcileLessons(config: ProjectConfig): Promise { - const pending = store.lessons(config.projectId); + const pending = store.lessons(config.projectId).filter((lesson) => lesson.tier !== "retired"); if (pending.length === 0) return; for (const lesson of pending) { // One lesson's file being unreadable — a bad path, a transient read @@ -3114,12 +3143,44 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P bb.log.warn(`stewards: could not read lesson ${lesson.id}'s file ${lesson.file}: ${errorMessage(error)}`); continue; } - if (content !== null && normalizeLessonText(content).includes(normalizeLessonText(lesson.text))) { + // The anchor is the marker; a lesson merged before step 3 has only the + // wording, so a plain-text match still counts. + if (content !== null && (hasLessonAnchor(content, lesson.id) || normalizeLessonText(content).includes(normalizeLessonText(lesson.text)))) { store.markLessonMerged(lesson.id, lesson.mergeSha, lesson.branch); } } } + /** + * Apply the mechanical tier transitions (BB-35 step 3): promote a trial + * that earned it, retire a trial or promoted lesson that aged out or was + * corrected, retire a superseded lesson, and displace the lowest-scoring + * promoted lesson when a file is full. The decisions are pure (lessons.ts); + * this only writes them. A promotion the project steward has not landed + * yet is still `pending`, and a retirement of a lesson that is in the file + * keeps `merged` until the text is removed. + */ + function applyLessonTransitions(config: ProjectConfig): void { + const transitions = planLessonTransitions(store.allLessons(config.projectId), config.file.lessons, now()); + for (const transition of transitions) { + const lesson = store.lesson(transition.id); + if (lesson === null || lesson.tier === "retired") continue; + if (transition.action === "promote") { + store.setLessonTier(transition.id, "promoted"); + continue; + } + // A retirement of a lesson that never landed resolves the row here: + // there is no anchored text to remove, so nothing waits on the project + // steward and the row must not linger as pending. One that is in the + // file stays `merged` until its text is removed through the wake. + if (lesson.status === "pending") store.markLessonDropped(transition.id, `Retired: ${transition.reason}.`); + else { + store.setLessonTier(transition.id, "retired"); + store.noteLesson(transition.id, `Retired: ${transition.reason}.`); + } + } + } + /** * Count a correction when the owner's answer to an escalation differs from * the steward's recommendation on it and the decision cited lessons @@ -4557,7 +4618,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (label !== "Merge") return { ok: false, message: `"${label ?? ""}" is not one of the choices: Merge, Drop.` }; const threadId = store.project(b.projectId).threadId; if (threadId === null) return { ok: false, message: "The project steward has no thread yet; nothing has been published." }; - const result = await mergeLesson(b.projectId, threadId, lesson); + const result = await mergeLesson(b.projectId, threadId, lesson, withLessonAnchor(lesson.text, lesson.id)); if (!result.ok) { store.noteLesson(lesson.id, result.message); return { ok: false, message: result.message }; @@ -5187,18 +5248,20 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P (f) => !f.startsWith("/") && !f.includes("\\") && !f.includes("\0") && f.split("/").every((s) => s !== ".." && s !== "." && s.length > 0), "a .bb-relative path with no leading /, backslash, NUL, or empty/./.. segment", ) + .refine((f) => f !== "stewards/project.json", "a guidance file (AGENTS.md or a playbook), never the project file: a lesson must not be able to move a big decision to the project, loosen the pull-request gate or relax an approval") .describe("The .bb file it belongs in, repo-relative, such as AGENTS.md or stewards/linear-tickets.md."), scope: z.enum(["procedure", "boundary"]).describe("procedure: playbook wording, sequencing, conventions the steward may already decide, which it self-merges. boundary: credentials and reach, who may direct a server, irreversible production steps — the user decides."), + supersedes: z.string().trim().min(1).max(100).optional().describe("An existing lesson id in the same file that this one replaces; the nightly pass retires the older one."), }) .optional() .describe("Project steward only: record a general rule drawn from an escalation or your own judgement, so it is made permanent in `.bb` instead of being lost with the ticket. With `binding` and `resolve`, it keeps the binding and escalation it came from. Apply and publish it, then complete it with lessonAction."), lessonAction: z .object({ id: z.string().trim().min(1).max(100).describe("The lesson id (lsn_…) from the nightly prompt or `bb stewards lessons`."), - action: z.enum(["complete", "drop"]).describe("complete: self-merge a procedure lesson, or file the user's Merge/Drop item for a boundary one. drop: discard it."), + action: z.enum(["complete", "drop", "retire"]).describe("complete: self-merge a procedure lesson, or file the user's Merge/Drop item for a boundary one. retire: remove a retired lesson's anchored text from `.bb`. drop: discard it."), }) .optional() - .describe("Project steward only: finish a pending lesson after applying and publishing it, or drop it."), + .describe("Project steward only: finish a pending lesson after applying and publishing it, retire a retired one, or drop it."), }), async execute(input, { threadId }) { try { @@ -5258,10 +5321,22 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (projectOf === null && (input.lesson !== undefined || input.lessonAction !== undefined)) { return toolError(new Error("Only the project steward records and completes lessons; a steward escalates with steward_report.")); } + if (input.lesson?.supersedes !== undefined) { + const older = store.lesson(input.lesson.supersedes); + if (older === null || older.projectId !== projectOf) return toolError(new Error(`No lesson ${input.lesson.supersedes} in this project to supersede.`)); + if (older.file !== input.lesson.file) return toolError(new Error(`Lesson ${older.id} is in ${older.file}, not ${input.lesson.file}; a lesson only supersedes one in the same file.`)); + if (older.tier === "retired") return toolError(new Error(`Lesson ${older.id} is already retired.`)); + } if (input.lessonAction !== undefined) { const lesson = store.lesson(input.lessonAction.id); if (lesson === null || lesson.projectId !== projectOf) return toolError(new Error(`No lesson ${input.lessonAction.id} in this project.`)); + if (input.lessonAction.action === "retire") { + if (lesson.tier !== "retired") return toolError(new Error(`Lesson ${lesson.id} is not retired (tier ${lesson.tier}); the nightly pass retires one that aged out or was corrected.`)); + const outcome = await retireLesson(lesson); + return `${lesson.id}: ${outcome}.`; + } if (lesson.status !== "pending") return toolError(new Error(`Lesson ${lesson.id} is already ${lesson.status}.`)); + if (lesson.tier === "retired") return toolError(new Error(`Lesson ${lesson.id} is retired; a retired lesson is never landed, only removed with action "retire".`)); const outcome = await completeLesson(lesson, input.lessonAction.action); return `${lesson.id}: ${outcome}.`; } @@ -5269,8 +5344,8 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const recordLesson = (bindingId: string | null, escalationId: string | null): string => { const projectThread = store.project(projectOf!).threadId; const branch = projectThread === null ? null : lessonBranchFor(projectThread); - const lesson = store.addLesson({ projectId: projectOf!, bindingId, escalationId, file: input.lesson!.file, text: input.lesson!.text, scope: input.lesson!.scope, branch }); - return `lesson ${lesson.id} recorded (${lesson.scope}); apply it to ${lesson.file}, commit, publish with workspace_publish_guidance, then complete it with steward_update { lessonAction: { id: "${lesson.id}", action: "complete" } }`; + const lesson = store.addLesson({ projectId: projectOf!, bindingId, escalationId, file: input.lesson!.file, text: input.lesson!.text, scope: input.lesson!.scope, branch, ...(input.lesson!.supersedes === undefined ? {} : { supersedes: input.lesson!.supersedes }) }); + return `lesson ${lesson.id} recorded (${lesson.scope}, ${lesson.tier}); it is injected into wakes and the nightly pass promotes it when it earns it. To land it now, add \`${withLessonAnchor(lesson.text, lesson.id)}\` to ${lesson.file}, commit, publish with workspace_publish_guidance, then complete it with steward_update { lessonAction: { id: "${lesson.id}", action: "complete" } }`; }; if (projectOf !== null && resolve?.startsWith("qst_") === true) { const q = store.question(resolve); @@ -5733,6 +5808,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P await keepProjectSteward(config.projectId); await syncOpsBindings(config); await reconcileLessons(config); + applyLessonTransitions(config); for (const b of store.open(config.projectId)) { if (b.threadId !== null) await keepSteward(config.projectId, b.threadId); const deadline = endingDeadline(b, timing.endingTimeoutMs); @@ -5773,6 +5849,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P bb.log.info(`stewards: nightly pass for ${config.projectId} (${night})`); if (!(await settings.get()).paused) await adoptionPass(config); await reconcileLessons(config); + applyLessonTransitions(config); const order = store .open(config.projectId) .filter((b) => b.hold === null && b.ending === null) @@ -6056,7 +6133,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const projectId = input.options.project ?? ctx.projectId; const rows = input.options.all ? store.all(projectId) : store.open(projectId); if (input.options.json) return { exitCode: 0, stdout: JSON.stringify(rows.map(({ lastSnapshot: _s, ...rest }) => rest)) }; - const lessons = projectId === undefined ? [] : store.lessons(projectId); + const lessons = projectId === undefined ? [] : store.lessons(projectId).filter((l) => l.tier !== "retired"); const lessonLines = lessons.length === 0 ? [] : ["", `Lessons pending (${lessons.length}):`, ...lessons.map((l) => ` ${l.id} — ${l.scope}, ${l.file}${l.bindingId === null ? "" : `, from ${store.binding(l.bindingId)?.entityKey ?? l.bindingId}`}: ${l.text}`)]; return { exitCode: 0, stdout: [formatBindings(rows), ...lessonLines].join("\n") }; }, @@ -6077,7 +6154,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const b = l.bindingId === null ? null : store.binding(l.bindingId); const source = [b === null ? null : `from ${b.entityKey}`, l.escalationId].filter((x) => x !== null).join(", "); const landed = l.status === "merged" ? `${l.mergeSha === null ? "merged" : `merged at ${l.mergeSha.slice(0, 8)}`}${l.branch === null ? "" : ` on ${l.branch}`}` : l.status; - return `${l.id} — ${landed}, ${l.scope}, ${l.file}${source === "" ? "" : ` (${source})`}${l.note === null ? "" : ` — ${l.note}`}\n ${l.text}`; + return `${l.id} — ${l.tier} (${landed}), ${l.scope}, ${l.file}${source === "" ? "" : ` (${source})`}${l.note === null ? "" : ` — ${l.note}`}\n ${l.text}`; }) .join("\n"), }; @@ -6251,7 +6328,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } const threadId = b === null ? null : store.project(b.projectId).threadId; if (threadId === null) throw new PluginCliError("The project steward has no thread yet; nothing has been published.", { code: "no_project_steward" }); - const result = await mergeLesson(b!.projectId, threadId, lesson); + const result = await mergeLesson(b!.projectId, threadId, lesson, withLessonAnchor(lesson.text, lesson.id)); if (!result.ok) { store.noteLesson(lesson.id, result.message); throw new PluginCliError(result.message, { code: "merge_refused" }); diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index 1242a551..0b258ede 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -300,7 +300,20 @@ 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. 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 +corrections and last citation from them. A recorded lesson starts as a +`trial`: it is injected into wakes under `## Lessons (trial)` and stays in +the store until the nightly pass promotes it (3 distinct-binding hits, no +corrections, 14 days) or retires it (30 days uncited, or a correction); a +promoted lesson is retired at 90 days uncited or 2 corrections. The +thresholds, caps and decay half-life live under `lessons` in +`stewards/project.json`. When the pass queues a promotion or a retirement +your wake lists it under `## Lessons to land` or `## Lessons to retire`: +add or replace the anchored block (``) in the named +file, commit, publish with `workspace_publish_guidance`, then +`steward_update { lessonAction: { id, action: "complete" } }` or `retire`. +A lesson may never target `stewards/project.json`, so it cannot widen the +decide list, loosen the pull-request gate or relax an approval; a boundary +lesson still goes to the user as Merge/Drop. 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 636c7db4..d4775cd7 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, LESSON_COUNTER_MIGRATIONS, MIGRATIONS, WORKER_CHECK_MIGRATIONS, createStore, lessonScope } from "./store.js"; +import { BASE_MIGRATIONS, CHAIN_MIGRATIONS, LESSON_COUNTER_MIGRATIONS, LESSON_TIER_MIGRATIONS, MIGRATIONS, WORKER_CHECK_MIGRATIONS, createStore, lessonScope } from "./store.js"; function store() { const db = new Database(":memory:"); @@ -145,8 +145,7 @@ describe("lessons", () => { expect(s.lesson(lesson.id)).toMatchObject({ status: "merged", mergeSha: "a".repeat(40), resolvedAt: 1_500 }); expect(s.lessons("p1")).toEqual([]); expect(s.lessons("p1", true)).toHaveLength(1); - expect(s.mergedLessonsSince("p1", 1_400).map((l) => l.id)).toEqual([lesson.id]); - expect(s.mergedLessonsSince("p1", 1_600)).toEqual([]); + expect(s.lesson(lesson.id)).toMatchObject({ tier: "promoted" }); // Marking it merged again is idempotent and does not move resolved_at. s.markLessonMerged(lesson.id, "b".repeat(40), null); @@ -160,9 +159,17 @@ describe("lessons", () => { s.noteLesson(lesson.id, "Refused: changes files other than AGENTS.md."); expect(s.lesson(lesson.id)).toMatchObject({ branch: "refs/heads/guidance-thr_project", note: "Refused: changes files other than AGENTS.md." }); s.markLessonDropped(lesson.id, "Dropped on the Stewards page."); - expect(s.lesson(lesson.id)).toMatchObject({ status: "dropped", resolvedAt: expect.any(Number) }); + expect(s.lesson(lesson.id)).toMatchObject({ status: "dropped", tier: "retired", resolvedAt: expect.any(Number) }); expect(s.lessons("p1")).toEqual([]); }); + + it("record which lesson a newer one supersedes", () => { + const { s, binding } = store(); + const older = s.addLesson({ projectId: "p1", bindingId: binding.id, escalationId: null, file: "AGENTS.md", text: "The old rule.", scope: "procedure", branch: null }); + const newer = s.addLesson({ projectId: "p1", bindingId: binding.id, escalationId: null, file: "AGENTS.md", text: "The new rule.", scope: "procedure", branch: null, supersedes: older.id }); + expect(s.lesson(older.id)).toMatchObject({ supersededBy: newer.id }); + expect(s.lesson(newer.id)).toMatchObject({ supersededBy: null }); + }); }); describe("lesson citation counts (BB-35 step 2)", () => { @@ -230,6 +237,7 @@ describe("lesson citation counts (BB-35 step 2)", () => { 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); + for (const sql of LESSON_TIER_MIGRATIONS) db.exec(sql); for (const sql of WORKER_CHECK_MIGRATIONS) db.exec(sql); const s = createStore(db, () => 2000); expect(s.lesson("lsn_old")).toMatchObject({ @@ -240,6 +248,10 @@ describe("lesson citation counts (BB-35 step 2)", () => { text: "An old rule.", scope: "boundary", status: "pending", + tier: "trial", + tierAt: 1_000, + clusterKey: null, + supersededBy: null, branch: "refs/heads/guidance-thr_x", note: "kept", createdAt: 1_000, @@ -251,7 +263,46 @@ describe("lesson citation counts (BB-35 step 2)", () => { }); // 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"])); + 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", "tier", "tier_at", "cluster_key", "superseded_by"])); + }); +}); + +describe("the lesson tier migration (BB-35 step 3)", () => { + const legacy = () => { + const db = new Database(":memory:"); + for (const sql of [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS]) db.exec(sql); + 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_pending', 'p1', NULL, NULL, 'AGENTS.md', 'A.', 'procedure', 'pending', NULL, NULL, NULL, 1000, 1000, NULL), + ('lsn_merged', 'p1', NULL, NULL, 'AGENTS.md', 'B.', 'procedure', 'merged', NULL, 'abc', NULL, 1100, 1100, 1200), + ('lsn_dropped', 'p1', NULL, NULL, 'AGENTS.md', 'C.', 'procedure', 'dropped', NULL, NULL, NULL, 1300, 1300, 1400)`); + for (const sql of LESSON_TIER_MIGRATIONS) db.exec(sql); + for (const sql of WORKER_CHECK_MIGRATIONS) db.exec(sql); + return db; + }; + + it("maps pending, merged and dropped onto trial, promoted and retired, keeping every old value", () => { + const s = createStore(legacy(), () => 5000); + expect(s.lesson("lsn_pending")).toMatchObject({ tier: "trial", tierAt: 1_000, status: "pending" }); + expect(s.lesson("lsn_merged")).toMatchObject({ tier: "promoted", status: "merged", mergeSha: "abc", resolvedAt: 1_200 }); + expect(s.lesson("lsn_dropped")).toMatchObject({ tier: "retired", status: "dropped", resolvedAt: 1_400 }); + }); + + it("is idempotent: re-running the tier remap does not clobber a tier a transition set", () => { + const db = legacy(); + const s = createStore(db, () => 5000); + // The nightly pass promotes a lesson whose file state is still pending. + s.setLessonTier("lsn_pending", "promoted"); + const remap = LESSON_TIER_MIGRATIONS.find((sql) => sql.startsWith("UPDATE lessons SET tier = CASE"))!; + db.exec(remap); + expect(s.lesson("lsn_pending")).toMatchObject({ tier: "promoted", status: "pending" }); + expect(s.lesson("lsn_merged")).toMatchObject({ tier: "promoted" }); + expect(s.lesson("lsn_dropped")).toMatchObject({ tier: "retired" }); + }); + + it("is appended at the end of MIGRATIONS, so a shipped statement index is never reused", () => { + // `bb.storage.migrate` records each statement by index and refuses a changed + // one; a group spliced in mid-array would fail every live database on load. + expect(MIGRATIONS.slice(-LESSON_TIER_MIGRATIONS.length)).toEqual([...LESSON_TIER_MIGRATIONS]); }); }); @@ -273,7 +324,7 @@ describe("a worker's pending model check", () => { it("reads workers from before the column existed as not pending", () => { const db = new Database(":memory:"); - for (const sql of [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS]) db.exec(sql); + for (const sql of [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...LESSON_TIER_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 workers (thread_id, binding_id, title, status, started_at) VALUES ('thr_old', 'bnd_1', 'ENG-12: Implement', 'running', 1000)`); @@ -310,6 +361,7 @@ describe("the escalation-chain migration (BB-30)", () => { 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); + for (const sql of LESSON_TIER_MIGRATIONS) db.exec(sql); for (const sql of WORKER_CHECK_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 7e8df6c4..06b0ab81 100644 --- a/plugins/stewards/store.ts +++ b/plugins/stewards/store.ts @@ -336,6 +336,24 @@ export const LESSON_COUNTER_MIGRATIONS = [ `ALTER TABLE escalations ADD COLUMN corrections_counted INTEGER NOT NULL DEFAULT 0`, ]; +// BB-35 step 3: the lifecycle tier and the fields the transitions read. The +// old `status` column is kept and still tracks the file state (pending, merged, +// dropped); the migration maps it onto the tier once, guarded so a re-run does +// not clobber a tier a later transition set. Additive and lossless. +export const LESSON_TIER_MIGRATIONS = [ + `ALTER TABLE lessons ADD COLUMN tier TEXT NOT NULL DEFAULT 'candidate'`, + `ALTER TABLE lessons ADD COLUMN tier_at INTEGER`, + `ALTER TABLE lessons ADD COLUMN cluster_key TEXT`, + `ALTER TABLE lessons ADD COLUMN superseded_by TEXT`, + // pending => trial (with a branch), merged => promoted, dropped => retired. + // `WHERE tier = 'candidate'` makes it idempotent: once mapped, a lesson's + // tier is never remapped from `status`, so a promoted lesson whose status is + // still 'pending' keeps its tier if the migration is applied again. + `UPDATE lessons SET tier = CASE status WHEN 'pending' THEN 'trial' WHEN 'merged' THEN 'promoted' WHEN 'dropped' THEN 'retired' ELSE tier END WHERE tier = 'candidate'`, + // The tier's start is the row's creation for an already-migrated lesson. + `UPDATE lessons SET tier_at = created_at WHERE tier_at IS NULL`, +]; + export const WORKER_CHECK_MIGRATIONS = [ // 1 while a worker's model and reasoning level are still to be checked: // its first turn had not been dispatched when it was created, so the check @@ -366,7 +384,7 @@ export const FINISHED_AND_DIGEST_MIGRATIONS = [ `ALTER TABLE project_stewards ADD COLUMN pending_notes TEXT NOT NULL DEFAULT '[]'`, ]; -export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS, ...DEPLOYMENT_MIGRATIONS, ...FINISHED_AND_DIGEST_MIGRATIONS]; +export const MIGRATIONS = [...BASE_MIGRATIONS, ...CHAIN_MIGRATIONS, ...LESSON_COUNTER_MIGRATIONS, ...WORKER_CHECK_MIGRATIONS, ...DECLINED_PR_MIGRATIONS, ...DEPLOYMENT_MIGRATIONS, ...FINISHED_AND_DIGEST_MIGRATIONS, ...LESSON_TIER_MIGRATIONS]; // ---- values kept as JSON ------------------------------------------------------------ @@ -784,6 +802,11 @@ export type LessonScope = (typeof LESSON_SCOPES)[number]; */ export const lessonScope = (value: unknown): LessonScope => (value === "procedure" ? "procedure" : "boundary"); export type LessonStatus = "pending" | "merged" | "dropped"; +/** The mechanical lifecycle a lesson moves through (BB-35 step 3). */ +export const LESSON_TIERS = ["candidate", "trial", "promoted", "retired"] as const; +export type LessonTier = (typeof LESSON_TIERS)[number]; +/** A tier read from a row, failing closed to `candidate` for a missing or unknown value. */ +export const lessonTier = (value: unknown): LessonTier => (LESSON_TIERS.includes(value as LessonTier) ? (value as LessonTier) : "candidate"); export type Lesson = { id: string; projectId: string; @@ -795,6 +818,14 @@ export type Lesson = { text: string; scope: LessonScope; status: LessonStatus; + /** The lifecycle tier (BB-35 step 3). `status` is kept for the file state. */ + tier: LessonTier; + /** When the tier last changed, the start of the current trial or promotion. */ + tierAt: number | null; + /** A clustering key for repeat escalations (BB-35); null until a later step fills it. */ + clusterKey: string | null; + /** The lesson that supersedes this one, or null. */ + supersededBy: string | null; /** The `guidance-` branch carrying it, once published. */ branch: string | null; /** The canonical `.bb` commit it landed at, once merged. */ @@ -995,18 +1026,21 @@ export function createStore(db: Database.Database, now: () => number, options: S const closeNeedKeyStmt = db.prepare("UPDATE needs SET status = 'done', resolution = ?, resolved_at = ? WHERE binding_id = ? AND kind = ? AND url = ? AND status = 'open'"); const insertLesson = db.prepare( - "INSERT INTO lessons (id, project_id, binding_id, escalation_id, file, text, scope, branch, created_at, updated_at) VALUES (@id, @project_id, @binding_id, @escalation_id, @file, @text, @scope, @branch, @created_at, @updated_at)", + "INSERT INTO lessons (id, project_id, binding_id, escalation_id, file, text, scope, status, tier, tier_at, cluster_key, superseded_by, branch, created_at, updated_at) VALUES (@id, @project_id, @binding_id, @escalation_id, @file, @text, @scope, 'pending', @tier, @tier_at, @cluster_key, @superseded_by, @branch, @created_at, @updated_at)", ); const getLesson = db.prepare<[string], Record>("SELECT * FROM lessons WHERE id = ?"); const lessonsFor = db.prepare<[string, number], Record>("SELECT * FROM lessons WHERE project_id = ? AND (? = 1 OR status = 'pending') ORDER BY created_at"); - const mergedLessonsSince = db.prepare<[string, number], Record>("SELECT * FROM lessons WHERE project_id = ? AND status = 'merged' AND resolved_at >= ? ORDER BY resolved_at"); const setLessonBranchStmt = db.prepare("UPDATE lessons SET branch = ?, updated_at = ? WHERE id = ? AND status = 'pending'"); - const setLessonNoteStmt = db.prepare("UPDATE lessons SET note = ?, updated_at = ? WHERE id = ? AND status = 'pending'"); + const setLessonNoteStmt = db.prepare("UPDATE lessons SET note = ?, updated_at = ? WHERE id = ?"); 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 setLessonTierStmt = db.prepare("UPDATE lessons SET tier = ?, tier_at = ?, updated_at = ? WHERE id = ?"); + const setLessonClusterStmt = db.prepare("UPDATE lessons SET cluster_key = ?, updated_at = ? WHERE id = ?"); + const setLessonSupersededStmt = db.prepare("UPDATE lessons SET superseded_by = ?, updated_at = ? WHERE id = ?"); + const lessonsByTierStmt = db.prepare<[string, string], Record>("SELECT * FROM lessons WHERE project_id = ? AND tier = ? ORDER BY created_at"); const setEscalationCitationsStmt = db.prepare("UPDATE escalations SET cited_lessons = ? WHERE id = ?"); const markEscalationCorrectedStmt = db.prepare("UPDATE escalations SET corrections_counted = 1 WHERE id = ?"); @@ -1095,6 +1129,10 @@ export function createStore(db: Database.Database, now: () => number, options: S text: String(r.text), scope: lessonScope(r.scope), status: String(r.status) as LessonStatus, + tier: lessonTier(r.tier), + tierAt: r.tier_at === null || r.tier_at === undefined ? null : Number(r.tier_at), + clusterKey: r.cluster_key === null || r.cluster_key === undefined ? null : String(r.cluster_key), + supersededBy: r.superseded_by === null || r.superseded_by === undefined ? null : String(r.superseded_by), 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), @@ -1696,7 +1734,7 @@ export function createStore(db: Database.Database, now: () => number, options: S * user drops it. `branch` is the guidance branch it will be published on, * computed from the project steward's thread when it has one. */ - addLesson(fields: { projectId: string; bindingId: string | null; escalationId: string | null; file: string; text: string; scope: LessonScope; branch: string | null }): Lesson { + addLesson(fields: { projectId: string; bindingId: string | null; escalationId: string | null; file: string; text: string; scope: LessonScope; branch: string | null; tier?: LessonTier; clusterKey?: string | null; supersedes?: string | null }): Lesson { const id = newId("lsn"); const at = now(); insertLesson.run({ @@ -1707,10 +1745,15 @@ export function createStore(db: Database.Database, now: () => number, options: S file: fields.file, text: fields.text, scope: fields.scope, + tier: fields.tier ?? "trial", + tier_at: at, + cluster_key: fields.clusterKey ?? null, + superseded_by: null, branch: fields.branch, created_at: at, updated_at: at, }); + if (fields.supersedes !== undefined && fields.supersedes !== null) setLessonSupersededStmt.run(id, at, fields.supersedes); return toLesson(getLesson.get(id)!); }, lesson(id: string): Lesson | null { @@ -1721,9 +1764,26 @@ export function createStore(db: Database.Database, now: () => number, options: S lessons(projectId: string, includeResolved = false): Lesson[] { return lessonsFor.all(projectId, includeResolved ? 1 : 0).map(toLesson); }, - /** Lessons that reached `.bb` HEAD in the window, for the digest. */ - mergedLessonsSince(projectId: string, since: number): Lesson[] { - return mergedLessonsSince.all(projectId, since).map(toLesson); + /** Every lesson of a project, whatever its file state: what the transitions read. */ + allLessons(projectId: string): Lesson[] { + return db.prepare<[string], Record>("SELECT * FROM lessons WHERE project_id = ? ORDER BY created_at").all(projectId).map(toLesson); + }, + /** The lessons in one tier, oldest first. */ + lessonsByTier(projectId: string, tier: LessonTier): Lesson[] { + return lessonsByTierStmt.all(projectId, tier).map(toLesson); + }, + /** Move a lesson to a tier, stamping when the move happened. */ + setLessonTier(id: string, tier: LessonTier): void { + const at = now(); + setLessonTierStmt.run(tier, at, at, id); + }, + /** Record the cluster a repeat escalation belongs to (BB-35; filled by a later step). */ + setLessonCluster(id: string, clusterKey: string | null): void { + setLessonClusterStmt.run(clusterKey, now(), id); + }, + /** Name the lesson a newer one supersedes, so the next pass retires the older. */ + setLessonSupersededBy(id: string, supersededBy: string | null): void { + setLessonSupersededStmt.run(supersededBy, now(), id); }, /** Remember the guidance branch a lesson is published on. */ setLessonBranch(id: string, branch: string): void { @@ -1733,15 +1793,18 @@ export function createStore(db: Database.Database, now: () => number, options: S noteLesson(id: string, note: string | null): void { setLessonNoteStmt.run(note, now(), id); }, - /** Mark a lesson merged, keeping any sha and branch already recorded. */ + /** Mark a lesson merged, keeping any sha and branch already recorded. A retired lesson stays retired: a merge observed after the fact never resurrects it. */ markLessonMerged(id: string, sha: string | null, branch: string | null, note: string | null = null): void { const at = now(); resolveLessonStmt.run("merged", sha, branch, note, at, at, id); + const row = getLesson.get(id); + if (row !== undefined && lessonTier(row.tier) !== "retired") setLessonTierStmt.run("promoted", at, at, id); }, /** Mark a lesson dropped by the user or the project steward. */ markLessonDropped(id: string, note: string | null = null): void { const at = now(); resolveLessonStmt.run("dropped", null, null, note, at, at, id); + setLessonTierStmt.run("retired", at, at, id); }, /** * Record the lessons one decision cited (BB-35 step 2). A lesson's `hits` diff --git a/plugins/stewards/templates.ts b/plugins/stewards/templates.ts index c8af3367..d9653ad0 100644 --- a/plugins/stewards/templates.ts +++ b/plugins/stewards/templates.ts @@ -32,6 +32,10 @@ export function projectFileTemplate(teams: string[]): string { // Dependabot alerts: a per-severity SLA, the batch window a medium or low // alert may wait for company, and the severities adopted when filed. deps: { sla: { critical: "asap", high: "1d", medium: "7d", low: "30d" }, batch: { medium: "7d", low: "30d" }, autoAdopt: ["critical", "high"] }, + // The mechanical lesson lifecycle (BB-35): when a trial lesson is + // promoted or retired, how many a wake may carry, and how many promoted + // lessons a file holds. Omit the block to take these defaults. + lessons: { trial: { max: 5, retireDays: 30 }, promote: { hits: 3, days: 14 }, promoted: { maxPerFile: 10, retireDays: 90, corrections: 2 }, decayHalfLifeDays: 30 }, }, null, 2, diff --git a/plugins/stewards/wake.test.ts b/plugins/stewards/wake.test.ts index 45fb0fbb..d21646f8 100644 --- a/plugins/stewards/wake.test.ts +++ b/plugins/stewards/wake.test.ts @@ -187,6 +187,48 @@ describe("the nightly prompt", () => { expect(wake).toMatch(/forward, recommendation, cites: \[lesson ids\]/u); }); + it("injects trial lessons under their own heading and never a candidate (BB-35 step 3)", () => { + const { s, bind } = world(); + const b = bind("ENG-12"); + const trial = s.addLesson({ projectId: "p1", bindingId: b.id, escalationId: null, file: "AGENTS.md", text: "Auth is the plugin's.", scope: "procedure", branch: null }); + const candidate = s.addLesson({ projectId: "p1", bindingId: null, escalationId: null, file: "AGENTS.md", text: "Maybe later.", scope: "procedure", branch: null, tier: "candidate" }); + const wake = formatWake(wakeInput({ binding: b, lessons: [trial, candidate] })); + expect(wake).toContain("## Lessons (trial)"); + expect(wake).toContain(`- ${trial.id} (procedure, AGENTS.md): Auth is the plugin's.`); + expect(wake).not.toContain(candidate.id); + expect(wake).not.toContain("Maybe later."); + }); + + it("groups the project's lessons by tier: trial to decide from, promoted to land, retired to remove (BB-35 step 3)", () => { + const { s, bind } = world(); + const b = bind("ENG-12"); + const trial = s.addLesson({ projectId: "p1", bindingId: b.id, escalationId: null, file: "AGENTS.md", text: "Auth is the plugin's.", scope: "procedure", branch: null }); + const promoted = s.addLesson({ projectId: "p1", bindingId: b.id, escalationId: null, file: "AGENTS.md", text: "Read SELECT * carefully.", scope: "procedure", branch: null }); + s.setLessonTier(promoted.id, "promoted"); + const retired = s.addLesson({ projectId: "p1", bindingId: b.id, escalationId: null, file: "AGENTS.md", text: "An old rule.", scope: "procedure", branch: null }); + s.markLessonMerged(retired.id, "a".repeat(40), null); + s.setLessonTier(retired.id, "retired"); + const wake = formatProjectWake({ reason: "nightly", bindings: [], routed: [], problems: [], digestDue: false, notes: [], bigDecisions: [], questions: [], lessons: s.allLessons("p1") }); + expect(wake).toContain("## Lessons (trial)"); + expect(wake).toContain(`- ${trial.id} (procedure, AGENTS.md): Auth is the plugin's.`); + expect(wake).toContain("## Lessons to land"); + expect(wake).toContain(``); + expect(wake).toContain("## Lessons to retire"); + expect(wake).toContain(`- ${retired.id} (AGENTS.md): An old rule.`); + // It is listed once, as to-land, not also under the trial heading. + expect(wake.split(`- ${promoted.id} `)).toHaveLength(2); + }); + + it("caps the trial lessons in a project wake at lessons.trial.max", () => { + const { s, bind } = world(); + const b = bind("ENG-12"); + const lessons = [1, 2, 3].map((n) => s.addLesson({ projectId: "p1", bindingId: b.id, escalationId: null, file: "AGENTS.md", text: `Rule ${n}.`, scope: "procedure", branch: null })); + const wake = formatProjectWake({ reason: "nightly", bindings: [], routed: [], problems: [], digestDue: false, notes: [], bigDecisions: [], questions: [], lessons: s.allLessons("p1"), lessonRules: { trial: { max: 1, retireDays: 30 }, promote: { hits: 3, days: 14 }, promoted: { maxPerFile: 10, retireDays: 90, corrections: 2 }, decayHalfLifeDays: 30 } }); + expect(wake).toContain(`- ${lessons[0]!.id} (procedure, AGENTS.md): Rule 1.`); + expect(wake).not.toContain(`- ${lessons[1]!.id} `); + expect(wake).not.toContain(`- ${lessons[2]!.id} `); + }); + it("names the five resolution kinds and how a credential is forwarded (BB-51)", () => { const { s, bind } = world(); const b = bind("ENG-12"); diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index 7e8534cf..7b7e3cb5 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -5,7 +5,7 @@ // Each wake is self-contained. A steward that has compacted away everything // it ever saw can act correctly from one wake alone, which is what lets its // transcript stop being the source of truth. -import { formatDuration, phaseInstructions, type BigDecision, type Playbook } from "./config.js"; +import { formatDuration, phaseInstructions, type BigDecision, type LessonRules, type Playbook } from "./config.js"; import { anyPending, type Deployments, type DeploymentWatch } from "./deploy.js"; import { localParts } from "./nightly.js"; import { FINDING_CLASSES, type FindingClass, type OpsFinding, type OpsLook } from "./ops.js"; @@ -250,6 +250,8 @@ export type WakeInput = { deployments?: Deployments; /** Open bindings already at work on what this one touches. */ conflicts?: Conflict[]; + /** Trial lessons of the project, already capped to `lessons.trial.max`; candidates never appear. */ + lessons?: Lesson[]; now: number; }; @@ -447,6 +449,7 @@ export function formatWake(input: WakeInput): string { out.push(`- Priority: ${binding.priority ?? "normal"}`); out.push(holdLine(binding, "take no new actions and start no workers until it is lifted.")); out.push(...schedulingLines(binding, input.conflicts ?? [], input.escalations)); + out.push(...trialLessonsLines(input.lessons ?? [])); if (binding.ready.declinedSpecHash !== null && binding.declinedSpecObjections.length > 0) { out.push("", "**Spec declined.** Address each objection in one revision, so the next review can close them all:", "", ...binding.declinedSpecObjections.map((o) => `- [ ] ${o}`)); } @@ -884,6 +887,60 @@ export function formatSentryWake(input: SentryWakeInput): string { return fit(head, snapshot, out); } +/** + * The `## Lessons (trial)` block for a binding's steward: the project's trial + * lessons, which have not earned a place in `.bb` yet. Candidates never appear. + * The list is already capped by the caller. + */ +function trialLessonsLines(lessons: Lesson[]): string[] { + const trial = lessons.filter((l) => l.tier === "trial"); + if (trial.length === 0) return []; + return [ + "", + "## Lessons (trial)", + "", + "Project rules that are not in `.bb` yet. Decide from them, and cite the ones a decision rested on with `cites: [lesson ids]`.", + ...trial.map((l) => `- ${l.id} (${l.scope}, ${l.file}): ${oneLine(l.text)}`), + ]; +} + +/** + * The project steward's lesson blocks (BB-35 step 3): the trial lessons to + * decide from, the promoted ones the nightly pass queued for landing, and the + * retired ones whose anchored text must come out. Trial is capped at + * `lessons.trial.max`; candidates never appear. + */ +function projectLessonsLines(lessons: Lesson[], rules: LessonRules | undefined): string[] { + const cap = rules?.trial.max ?? 5; + const out: string[] = []; + const trial = lessons.filter((l) => l.tier === "trial").slice(0, cap); + if (trial.length > 0) { + out.push("", "## Lessons (trial)", "", "Project rules not yet in `.bb`. Decide from them, and cite the ones a decision rested on with `cites: [lesson ids]`."); + for (const l of trial) out.push(`- ${l.id} (${l.scope}, ${l.file}): ${oneLine(l.text)}`); + } + const toLand = lessons.filter((l) => l.tier === "promoted" && l.status === "pending"); + if (toLand.length > 0) { + out.push( + "", + "## Lessons to land", + "", + 'The nightly pass promoted these. Add the anchored block to the named file in your `.bb` checkout, commit, and publish with workspace_publish_guidance; then complete it with steward_update { lessonAction: { id: "", action: "complete" } }. A `boundary` one becomes a Merge/Drop item for the user instead. If a merge was refused, the reason is on the lesson: fix the branch and complete it again, or drop it.', + ); + for (const l of toLand) out.push(`- ${l.id} (${l.scope}, ${l.file}): ${oneLine(l.text)}\n Anchor: \`\`${l.note === null ? "" : `\n Last attempt: ${oneLine(l.note)}`}`); + } + const toRetire = lessons.filter((l) => l.tier === "retired" && l.status === "merged"); + if (toRetire.length > 0) { + out.push( + "", + "## Lessons to retire", + "", + 'The nightly pass retired these. In your `.bb` checkout replace the lesson\'s anchored block (its `` line and the wording under it) with the retired anchor ``, commit, publish with workspace_publish_guidance, then retire it with steward_update { lessonAction: { id: "", action: "retire" } }. The row is kept.', + ); + for (const l of toRetire) out.push(`- ${l.id} (${l.file}): ${oneLine(l.text)}`); + } + return out; +} + /** What the project steward is woken with, at the end of a nightly pass or when an escalation reaches it. */ export function formatProjectWake(input: { reason: string; @@ -901,6 +958,8 @@ export function formatProjectWake(input: { needs?: Array<{ need: Need; binding: Binding }>; /** Pending lessons: general rules waiting to be landed in `.bb`. */ lessons?: Lesson[]; + /** The project's lesson rules, for the trial cap and the wake headings. */ + lessonRules?: LessonRules; /** With digestDue: the records the digest is written from. */ records?: DigestRecords; /** The project's nightly time zone, which dates are given in; UTC when absent. */ @@ -986,18 +1045,7 @@ export function formatProjectWake(input: { out.push("", "The Stewards page has a button for each. Do not ask the user about one in prose.", ""); } const lessons = input.lessons ?? []; - if (lessons.length > 0) { - out.push("## Lessons pending", ""); - for (const l of lessons) { - const source = [l.bindingId === null ? null : `from ${l.bindingId}`, l.escalationId === null ? null : `escalation ${l.escalationId}`].filter((x) => x !== null).join(", "); - out.push(`- ${l.id} (${l.scope}, ${l.file}${source === "" ? "" : `, ${source}`}): ${oneLine(l.text)}${l.note === null ? "" : `\n Last attempt: ${oneLine(l.note)}`}`); - } - out.push( - "", - "Apply each to the named file in your `.bb` checkout, commit it, and publish with workspace_publish_guidance. Then complete it with steward_update { lessonAction: { id: \"\", action: \"complete\" } }: a `procedure` lesson is self-merged, a `boundary` one becomes a Merge/Drop item for the user. If a merge was refused, the reason is above: fix the branch and complete it again, or drop it.", - "", - ); - } + out.push(...projectLessonsLines(lessons, input.lessonRules)); const head = out.splice(0); out.push(`## Bindings (${input.bindings.length} open)`, ""); const allOpen = input.bindings.map((x) => x.binding); @@ -1133,8 +1181,6 @@ export type DigestRecords = { held: Binding[]; /** Silent notes queued for this digest (a hold that lifted on finished work), one line each. */ notes?: string[]; - /** Lessons that reached `.bb` HEAD in the window. */ - lessonsMerged?: Lesson[]; }; function capped(lines: string[], none: string): string[] { @@ -1192,12 +1238,6 @@ export function formatRecords(r: DigestRecords, questions: Array<{ question: Que ...r.held.map((b) => `- ${b.entityKey}: on hold: ${oneLine(b.hold ?? "")}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.join(", ")})`}`), ]; out.push("### Stuck or held", "", ...capped(stuck, "Nothing."), ""); - - const lessons = (r.lessonsMerged ?? []).map((l) => { - const source = [l.bindingId === null ? null : `from ${l.bindingId}`, l.escalationId === null ? null : `escalation ${l.escalationId}`].filter((x) => x !== null).join(", "); - return `- Merged lesson ${l.id} (${l.scope}, ${l.file}) at ${l.mergeSha === null ? "?" : l.mergeSha.slice(0, 8)}${l.branch === null ? "" : ` on ${l.branch}`}${source === "" ? "" : ` (${source})`}: ${oneLine(l.text)}`; - }); - out.push("### Lessons landed", "", ...capped(lessons, "Nothing.")); return out; }