From 5aedaff8139c108c766984d94ea83def83e10713 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Tue, 20 Oct 2026 16:45:48 +0000 Subject: [PATCH 1/2] stewards: record general judgements as lessons and land them in .bb (BB-3) A project steward's decision that corrects a design now becomes a lesson: a rule, the .bb file it belongs in, and a scope. Procedure lessons the project steward applies and publishes are self-merged by a new, narrow multi-repo fast-forward that only the stewards plugin may call and that refuses anything but the lesson's own file. Boundary lessons (credentials and reach, who may direct a server, irreversible production steps) are never self-merged: they are filed on the Stewards page with Merge and Drop. A lesson is merged when its text is found at .bb HEAD, listed in the nightly prompt and digest, and surfaced in bb stewards lessons and drop-lesson. --- plugins/multi-repo/contract.ts | 51 +++++ plugins/multi-repo/host.ts | 11 ++ plugins/multi-repo/merge-rpc.test.ts | 66 +++++++ plugins/multi-repo/provision.test.ts | 96 +++++++++ plugins/multi-repo/server.ts | 28 +++ plugins/multi-repo/source.ts | 75 +++++++ plugins/stewards/DESIGN.md | 72 ++++++- plugins/stewards/README.md | 11 ++ plugins/stewards/app.test.tsx | 3 + plugins/stewards/app.tsx | 36 +++- plugins/stewards/server.test.ts | 145 +++++++++++++- plugins/stewards/server.ts | 279 ++++++++++++++++++++++++++- plugins/stewards/store.test.ts | 47 +++++ plugins/stewards/store.ts | 137 +++++++++++++ plugins/stewards/wake.ts | 27 ++- 15 files changed, 1065 insertions(+), 19 deletions(-) create mode 100644 plugins/multi-repo/merge-rpc.test.ts diff --git a/plugins/multi-repo/contract.ts b/plugins/multi-repo/contract.ts index c4fdc5ae..cf5e02d2 100644 --- a/plugins/multi-repo/contract.ts +++ b/plugins/multi-repo/contract.ts @@ -489,6 +489,30 @@ export const hostContract = defineRpcContract({ }) .strict(), }, + + /** + * Fast-forward the canonical checkout to a thread's published guidance + * branch. The narrow merge a self-merged lesson uses; `source.ts` has the + * refusals. Leaves the branch in place on any refusal. + */ + mergeGuidance: { + input: z + .object({ + projectSourcePath: absolutePath, + threadId: z.string().min(1).max(100), + file: projectFilePathSchema, + text: z.string().min(1).max(20_000), + }) + .strict(), + output: z + .object({ + ok: z.boolean(), + sha: z.string().max(64).nullable(), + branch: z.string().max(300).nullable(), + message: z.string().max(2000), + }) + .strict(), + }, }); export type HostContract = typeof hostContract; @@ -597,6 +621,33 @@ export const rpcContract = defineRpcContract({ input: z.object({ projectId: z.string().min(1).max(100) }).strict(), output: repoSetViewSchema, }, + /** + * Fast-forward the canonical `.bb` checkout to a thread's published guidance + * branch. Stewards calls it, and only stewards: a lesson is the one thing + * that writes itself into the guidance every steward reads, and the project + * steward's own tooling is the only thing that may ask for it. `file` and + * `text` are the lesson's own; the host refuses a merge that would change + * anything else. + */ + mergeGuidance: { + input: z + .object({ + projectId: z.string().min(1).max(100), + threadId: z.string().min(1).max(100), + file: projectFilePathSchema, + text: z.string().min(1).max(20_000), + }) + .strict(), + output: z + .object({ + ok: z.boolean(), + sha: z.string().max(64).nullable(), + branch: z.string().max(300).nullable(), + message: z.string().max(2000), + }) + .strict(), + }, + /** * Files from the project's `.bb` repo, read from the canonical checkout's * committed `HEAD` after a fast-forward-only refresh. diff --git a/plugins/multi-repo/host.ts b/plugins/multi-repo/host.ts index fdf89b76..a1643edf 100644 --- a/plugins/multi-repo/host.ts +++ b/plugins/multi-repo/host.ts @@ -24,6 +24,7 @@ import { bootstrapProjectSource, cloneProjectSource, defaultProjectSourcePath, + mergeGuidance, projectSourceBranch, projectSourceRemote, pushGuidance, @@ -245,6 +246,16 @@ export function createMultiRepoHostEntry() { context.signal, ); }, + + async mergeGuidance(input, context) { + return mergeGuidance( + input.projectSourcePath, + input.threadId, + input.file, + input.text, + context.signal, + ); + }, }, }); } diff --git a/plugins/multi-repo/merge-rpc.test.ts b/plugins/multi-repo/merge-rpc.test.ts new file mode 100644 index 00000000..ec5da00f --- /dev/null +++ b/plugins/multi-repo/merge-rpc.test.ts @@ -0,0 +1,66 @@ +/** + * The `mergeGuidance` RPC's caller gate. + * + * The merge itself is git work, tested end to end in `provision.test.ts` + * against real repositories. What is tested here is who may ask for it: only + * the stewards plugin, because a lesson is the one thing that writes itself + * into the guidance every steward reads. A thread or another plugin calling + * the RPC directly is refused before any git runs. + */ +import { createFakePluginHost } from "@get-bb/plugin-sdk/testing"; +import { describe, expect, it } from "vitest"; +import plugin from "./server.js"; + +const PROJECT_ID = "proj_1"; +const HOST_ID = "host-a"; +const SOURCE_PATH = "/checkouts/acme"; + +const PROJECT = { + id: PROJECT_ID, + kind: "standard", + name: "acme", + gitRemoteUrl: null, + createdAt: 1, + updatedAt: 1, + sources: [{ id: "src_1", projectId: PROJECT_ID, type: "local_path", hostId: HOST_ID, path: SOURCE_PATH, isDefault: true }], +}; + +async function setup() { + const hostCalls: Array<{ method: string; input: unknown }> = []; + const { bb, harness } = createFakePluginHost({ + experimental_callHostRpc: (call: { method: string; input: unknown }) => { + hostCalls.push({ method: call.method, input: call.input }); + if (call.method === "mergeGuidance") return { ok: true, sha: "a".repeat(40), branch: "refs/heads/guidance-thr_lesson", message: "merged" }; + throw new Error(`unexpected host method ${call.method}`); + }, + }); + harness.sdk.stub("projects.get", () => PROJECT); + harness.sdk.stub("system.config", () => ({ primaryHostId: HOST_ID })); + await plugin(bb); + return { harness, hostCalls }; +} + +const input = { projectId: PROJECT_ID, threadId: "thr_lesson", file: "AGENTS.md", text: "A lesson." }; + +describe("merging a lesson through multi-repo", () => { + it("is refused for a caller that is not the stewards plugin, before any git runs", async () => { + const { harness, hostCalls } = await setup(); + const result = (await harness.callRpc("mergeGuidance", input, { experimental_caller: { kind: "plugin", pluginId: "linear" } })) as { + ok: boolean; + message: string; + }; + expect(result.ok).toBe(false); + expect(result.message).toMatch(/Only the stewards plugin merges a lesson/u); + expect(hostCalls).toEqual([]); + }); + + it("runs the host merge when the stewards plugin asks", async () => { + const { harness, hostCalls } = await setup(); + const result = (await harness.callRpc("mergeGuidance", input, { experimental_caller: { kind: "plugin", pluginId: "stewards" } })) as { + ok: boolean; + sha: string | null; + }; + expect(result).toMatchObject({ ok: true, sha: "a".repeat(40) }); + expect(hostCalls).toEqual([{ method: "mergeGuidance", input: { projectSourcePath: SOURCE_PATH, threadId: "thr_lesson", file: "AGENTS.md", text: "A lesson." } }]); + }); +}); diff --git a/plugins/multi-repo/provision.test.ts b/plugins/multi-repo/provision.test.ts index 082c0aec..ac5a3d05 100644 --- a/plugins/multi-repo/provision.test.ts +++ b/plugins/multi-repo/provision.test.ts @@ -18,6 +18,7 @@ import { bootstrapProjectSource, cloneProjectSource, defaultProjectSourcePath, + mergeGuidance, pushGuidance, readCommittedFiles, readReposJson, @@ -466,6 +467,101 @@ describe("the project source", () => { }); }); +describe("merging a published lesson branch", () => { + /** A canonical `.bb` and a clone of it, both with an identity to commit with. */ + async function pair() { + const canonical = path.join(scratch, "lesson-canonical"); + await mkdir(canonical, { recursive: true }); + await bootstrapProjectSource(canonical, EMPTY_REPOS); + await gitIn(canonical, ["config", "user.email", "test@example.invalid"]); + await gitIn(canonical, ["config", "user.name", "Test"]); + const workspaceBb = path.join(scratch, "lesson-workspace"); + await git(["clone", "--quiet", canonical, workspaceBb]); + await gitIn(workspaceBb, ["config", "user.email", "test@example.invalid"]); + await gitIn(workspaceBb, ["config", "user.name", "Test"]); + return { canonical, workspaceBb }; + } + + /** Append `text` to `file` in the workspace and commit it. */ + async function append(workspaceBb: string, file: string, text: string): Promise { + const current = await readFile(path.join(workspaceBb, file), "utf8"); + await writeFile(path.join(workspaceBb, file), `${current}\n${text}\n`, "utf8"); + await gitIn(workspaceBb, ["add", "--", file]); + await gitIn(workspaceBb, ["commit", "--quiet", "-m", "record a lesson"]); + } + + const lesson = "A new column read with SELECT * breaks the previous image."; + + it("fast-forwards the canonical checkout to the lesson's own file, and returns the sha", async () => { + const { canonical, workspaceBb } = await pair(); + await append(workspaceBb, "AGENTS.md", lesson); + await pushGuidance(canonical, workspaceBb, "thr_lesson"); + + const result = await mergeGuidance(canonical, "thr_lesson", "AGENTS.md", lesson); + expect(result).toMatchObject({ ok: true, branch: "refs/heads/guidance-thr_lesson" }); + expect(result.sha).toBe(await gitLine(workspaceBb, ["rev-parse", "HEAD"])); + expect(await gitLine(canonical, ["rev-parse", "HEAD"])).toBe(result.sha); + expect(await readFile(path.join(canonical, "AGENTS.md"), "utf8")).toContain(lesson); + }); + + it("refuses a dirty canonical checkout and leaves the branch", async () => { + const { canonical, workspaceBb } = await pair(); + await append(workspaceBb, "AGENTS.md", lesson); + await pushGuidance(canonical, workspaceBb, "thr_lesson"); + await writeFile(path.join(canonical, "AGENTS.md"), "half-written by hand\n", "utf8"); + + const result = await mergeGuidance(canonical, "thr_lesson", "AGENTS.md", lesson); + expect(result.ok).toBe(false); + expect(result.message).toMatch(/uncommitted changes/u); + // The branch is exactly where it was published: nothing was merged. + expect(await gitLine(canonical, ["rev-parse", "guidance-thr_lesson"])).toBe(await gitLine(workspaceBb, ["rev-parse", "HEAD"])); + expect(await readFile(path.join(canonical, "AGENTS.md"), "utf8")).toBe("half-written by hand\n"); + }); + + it("refuses a non-fast-forward", async () => { + const { canonical, workspaceBb } = await pair(); + // The canonical branch moves on after the workspace branched: the + // workspace's commit is no longer a descendant. + await writeFile(path.join(canonical, "canonical-only.md"), "moved on\n", "utf8"); + await gitIn(canonical, ["add", "--", "canonical-only.md"]); + await gitIn(canonical, ["commit", "--quiet", "-m", "canonical moves on"]); + await append(workspaceBb, "AGENTS.md", lesson); + await pushGuidance(canonical, workspaceBb, "thr_lesson"); + + const result = await mergeGuidance(canonical, "thr_lesson", "AGENTS.md", lesson); + expect(result.ok).toBe(false); + expect(result.message).toMatch(/not a fast-forward/u); + }); + + it("refuses a commit range that changes anything but the lesson's file", async () => { + const { canonical, workspaceBb } = await pair(); + await append(workspaceBb, "AGENTS.md", lesson); + await append(workspaceBb, "repos.json", "// unrelated\n"); + await pushGuidance(canonical, workspaceBb, "thr_lesson"); + + const result = await mergeGuidance(canonical, "thr_lesson", "AGENTS.md", lesson); + expect(result.ok).toBe(false); + expect(result.message).toMatch(/changes files other than AGENTS\.md: repos\.json/u); + }); + + it("refuses a file that does not carry the lesson text", async () => { + const { canonical, workspaceBb } = await pair(); + await append(workspaceBb, "AGENTS.md", "Something else entirely."); + await pushGuidance(canonical, workspaceBb, "thr_lesson"); + + const result = await mergeGuidance(canonical, "thr_lesson", "AGENTS.md", lesson); + expect(result.ok).toBe(false); + expect(result.message).toMatch(/does not carry the lesson text/u); + }); + + it("refuses when nothing has been published", async () => { + const { canonical } = await pair(); + const result = await mergeGuidance(canonical, "thr_lesson", "AGENTS.md", lesson); + expect(result.ok).toBe(false); + expect(result.message).toMatch(/No guidance branch refs\/heads\/guidance-thr_lesson has been published/u); + }); +}); + describe("reading project files for another plugin", () => { async function canonicalWithPlaybook() { const dir = await makeRemote("canonical"); diff --git a/plugins/multi-repo/server.ts b/plugins/multi-repo/server.ts index a3ea7691..a15a766b 100644 --- a/plugins/multi-repo/server.ts +++ b/plugins/multi-repo/server.ts @@ -1318,6 +1318,34 @@ export default async function multiRepoPlugin(bb: BbPluginApi): Promise { } }, + /** + * Fast-forward the canonical `.bb` to a thread's published guidance + * branch. Only the stewards plugin may ask: the project steward's lesson + * tooling is the one thing that writes itself into every steward's + * guidance, and a `procedure` lesson is the only thing it may write. + */ + async mergeGuidance({ projectId, threadId, file, text }, { experimental_caller: caller }) { + if (caller.kind !== "plugin" || caller.pluginId !== "stewards") { + return { ok: false, sha: null, branch: null, message: "Only the stewards plugin merges a lesson." }; + } + let location: SourceLocation | null; + try { + location = await projectSource(projectId); + } catch (error) { + return { ok: false, sha: null, branch: null, message: errorMessage(error) }; + } + if (location === null) return { ok: false, sha: null, branch: null, message: "This project has no .bb checkout on any machine." }; + try { + return await host.call( + "mergeGuidance", + { projectSourcePath: location.path, threadId, file, text }, + { hostId: location.hostId, timeoutMs: ACTION_TIMEOUT_MS }, + ); + } catch (error) { + return { ok: false, sha: null, branch: null, message: errorMessage(error) }; + } + }, + async saveRepoSet({ projectId, reposJson }) { const location = await projectSource(projectId); if (location === null) return { ok: false, error: "This project has no checkout on any machine." }; diff --git a/plugins/multi-repo/source.ts b/plugins/multi-repo/source.ts index 1d7c1999..454918e9 100644 --- a/plugins/multi-repo/source.ts +++ b/plugins/multi-repo/source.ts @@ -415,3 +415,78 @@ export async function pushGuidance( message: `Published ${head.slice(0, 8)} to ${ref} in ${projectSourcePath}. Merge it there when you are happy with it.`, }; } + +/** The `guidance-` ref a thread's published commits land on. */ +export function guidanceRef(threadId: string): string { + const safeId = threadId.replace(/[^A-Za-z0-9._-]+/gu, "-").slice(0, 60); + return `refs/heads/guidance-${safeId}`; +} + +/** Whitespace-normalised text, so a lesson matches however the playbook wraps it. */ +const normalized = (text: string) => text.replace(/\s+/gu, " ").trim(); + +export interface MergeGuidanceResult { + ok: boolean; + sha: string | null; + branch: string | null; + message: string; +} + +/** + * Fast-forward the canonical checkout to a thread's published guidance branch. + * + * {@link pushGuidance} lands a thread's `.bb` commits on `guidance-`. + * This is the other half, and the only way a self-merged lesson reaches the + * HEAD that `readCommittedFiles` reads: the canonical repo's checked-out + * branch is fast-forwarded to that ref. It is deliberately narrow. It refuses + * a detached HEAD, a dirty working tree, a non-fast-forward, a commit range + * that changes anything but `file`, or a `file` that does not carry `text` — + * and on any refusal it leaves the branch exactly where it is, for a person to + * look at. A self-merged lesson may therefore only ever add its own wording to + * its own file; it cannot smuggle in a second change. + */ +export async function mergeGuidance( + projectSourcePath: string, + threadId: string, + file: string, + text: string, + signal?: AbortSignal, +): Promise { + const branch = guidanceRef(threadId); + const options = { timeoutMs: GIT_TIMEOUT_MS, ...(signal === undefined ? {} : { signal }) }; + const refuse = (message: string): MergeGuidanceResult => ({ ok: false, sha: null, branch, message }); + + const head = await gitLine(projectSourcePath, ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], options); + if (head === null || head.length === 0) return refuse(`${projectSourcePath} is not a git repo with a commit to fast-forward.`); + const current = await gitLine(projectSourcePath, ["rev-parse", "--abbrev-ref", "HEAD"], options); + if (current === null || current === "HEAD") return refuse(`${projectSourcePath} has a detached HEAD; check out a branch first.`); + + const status = await gitIn(projectSourcePath, ["status", "--porcelain"], options); + if (status.code !== 0) return refuse(firstProblemLine(status)); + if (status.stdout.trim() !== "") return refuse(`The canonical checkout has uncommitted changes; commit or stash them, then try again.`); + + const ref = await gitLine(projectSourcePath, ["rev-parse", "--verify", "--quiet", `${branch}^{commit}`], options); + if (ref === null || ref.length === 0) return refuse(`No guidance branch ${branch} has been published; publish it first.`); + + const ancestor = await gitIn(projectSourcePath, ["merge-base", "--is-ancestor", head, ref], options); + if (ancestor.code !== 0) return refuse(`${branch} is not a fast-forward of ${current}; merge it by hand.`); + + const changed = await gitIn(projectSourcePath, ["diff", "--name-only", "-z", head, ref], options); + if (changed.code !== 0) return refuse(firstProblemLine(changed)); + const paths = splitNul(changed.stdout); + if (paths.length === 0) return refuse(`${branch} has no commits beyond ${current}; there is nothing to merge.`); + const other = paths.filter((path) => path !== file); + if (other.length > 0) { + return refuse(`${branch} changes files other than ${file}: ${other.slice(0, 5).join(", ")}. Merge it by hand.`); + } + + const content = await gitIn(projectSourcePath, ["show", `${ref}:${file}`], { ...options, maxBytes: 2_000_000 }); + if (content.code !== 0) return refuse(`${file} is not in ${branch}.`); + if (!normalized(content.stdout).includes(normalized(text))) return refuse(`${file} in ${branch} does not carry the lesson text; commit it, then try again.`); + + const merged = await gitIn(projectSourcePath, ["merge", "--ff-only", "--quiet", ref], options); + if (merged.code !== 0) return refuse(firstProblemLine(merged)); + const newHead = await gitLine(projectSourcePath, ["rev-parse", "HEAD"], options); + if (newHead === null) return refuse(`Fast-forwarded ${branch}, but the new HEAD could not be read.`); + return { ok: true, sha: newHead, branch, message: `Fast-forwarded ${current} to ${newHead.slice(0, 8)} from ${branch}.` }; +} diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index d24fa85c..74da92ac 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -665,8 +665,9 @@ follow-through: 6h # how long a terminal binding may be kept open timers, escalation routing. - **Threads:** spawning stewards, recognizing workers, building wake messages, the project's sidebar section. -- **Agent tools:** `steward_report` and `steward_update`. -- **CLI:** `bb stewards init | check | list | show | needs | done | detach | pass | digest`. +- **Agent tools:** `steward_report` and `steward_update` (which also + records and completes lessons, §20). +- **CLI:** `bb stewards init | check | list | show | needs | done | detach | pass | digest | lessons | drop-lesson`. - **UI:** the Stewards page, a nav panel with one tab per stewarded project: waiting on you (needs items with links and buttons, open questions, which you can close there, forwarded escalations and approval requests), in flight by @@ -690,7 +691,9 @@ follow-through: 6h # how long a terminal binding may be kept open ### Change to multi-repo -The cross-plugin RPC contract in §3. +The cross-plugin RPC contract in §3, plus `mergeGuidance`: the narrow +fast-forward of the canonical `.bb` to a thread's published guidance branch +that a self-merged lesson uses (§20). Only the stewards plugin may call it. ### bb-gate @@ -955,6 +958,69 @@ is off until it is wanted. The dependency watch's targets are derived from the repo set, so a repo added to `repos.json` is watched without a second edit. +## 20. Lessons + +A project steward's decision that corrects a design is a general rule, but +it reached the playbook only when a person rewrote it: the same answer was +costing a build and a review round on one ticket, then again on the next. +A **lesson** makes the answer a record and, for most of them, lands it. + +- **Recording.** The project steward calls + `steward_update { lesson: { text, file, scope } }`, usually with the + `binding` and `resolve` it is deciding. `text` is the wording as it should + read in `.bb`, `file` is the file it belongs in (`AGENTS.md`, + `stewards/linear-tickets.md`, …), and `scope` is `procedure` or + `boundary`. Only the project steward may record one — a binding steward + still escalates — and it is kept with the binding and escalation it came + from in the `lessons` table. A lesson is `pending` until its text is found + in its file at `.bb` HEAD, or it is dropped. +- **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 + `workspace_publish_guidance`; then + `steward_update { lessonAction: { id, action: "complete" } }` asks + multi-repo to fast-forward the canonical checkout to that branch. The + fast-forward is deliberately narrow: the canonical checkout must be clean + and not detached, the branch must be a fast-forward whose commits change + only the lesson's own file, and that file must carry the lesson's text + (whitespace-normalised). Anything else is refused and the + `guidance-` branch is left where it is. The merge commit's sha is + recorded on the lesson. This is the only way a self-merged lesson reaches + the HEAD that `readProjectFiles` — and so every steward — reads. +- **Boundary lessons go to the user.** Anything that would change the + steward's own escalation boundary — credentials and reach, who may direct + a server, irreversible production steps — is never self-merged. The + project steward applies, commits and publishes it, then `complete` files a + BB-15 `decide` item on the binding with the fixed choices **Merge** and + **Drop**. Merge runs the same multi-repo fast-forward from the page, as + the connected user and unsigned; Drop marks the lesson dropped. Both close + the item and wake the steward. +- **The guard.** multi-repo exposes the merge as an RPC that refuses any + caller but the stewards plugin, and stewards only calls it for a pending + lesson the project steward recorded. A `procedure` lesson may therefore + only ever add its own wording to its own file; it cannot smuggle in a + second change. +- **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 + `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. +- **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. + ## Known limits - **Multi-repo projects only.** A bb project whose source is a single diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 0243b207..543ebbae 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -189,6 +189,17 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. a choice is saved as guidance. `bb stewards done --choice