From 3f428f5029e68809f519467bb7dfe5a5163e8a69 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Wed, 28 Oct 2026 21:29:11 +0000 Subject: [PATCH 1/3] stewards: a native git project source when multi-repo is absent (BB-107) Add a project-source seam in plugins/stewards with two implementations, chosen once per project at config load and cached with the config: multi-repo (the readProjectFiles/repoSet/mergeGuidance RPCs as today) and native (a git handler in host.ts beside kubectl, reading .bb from origin/ after a fetch, never the working tree, with the repo set from the checkout's own origin). Only an unknown-plugin RPC error selects native; any other failure keeps the last good multi-repo config and shows a problem line. Native mode spawns on project-default and its wake text carries no --environment-provider flag. schedule.ts overlap now handles repo-prefixed and repo-relative touches, and the source shows in bb stewards show/check and on the Stewards page. --- plugins/stewards/DESIGN.md | 18 +- plugins/stewards/README.md | 6 +- plugins/stewards/app.tsx | 1 + plugins/stewards/host-contract.ts | 21 ++- plugins/stewards/host.ts | 6 +- plugins/stewards/project-git.test.ts | 105 +++++++++++ plugins/stewards/project-git.ts | 147 +++++++++++++++ plugins/stewards/project-source.ts | 129 +++++++++++++ plugins/stewards/schedule.test.ts | 12 ++ plugins/stewards/schedule.ts | 42 ++++- plugins/stewards/server.test.ts | 112 ++++++++++++ plugins/stewards/server.ts | 212 ++++++++++++++++------ plugins/stewards/skills/stewards/SKILL.md | 10 +- 13 files changed, 749 insertions(+), 72 deletions(-) create mode 100644 plugins/stewards/project-git.test.ts create mode 100644 plugins/stewards/project-git.ts create mode 100644 plugins/stewards/project-source.ts diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index 657b3d9d..6947aff6 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -97,7 +97,8 @@ These were settled while designing; each changes what gets built. and repos the project holds. - **Models are a playbook field per role**, and whichever thread spawned a binding may override them. -- **Configuration lives in the project's `.bb`**, read through multi-repo. +- **Configuration lives in the project's `.bb`**, read through multi-repo, or + through native git on the checkout when multi-repo is not installed (BB-107). - **People make only the big decisions.** Stewards and the project steward decide everything the project's own guidance (AGENTS.md, architecture and design docs, the playbooks) settles. Only what the project file lists as a @@ -236,11 +237,20 @@ it on the host. It gains one small cross-plugin RPC contract: checkout's committed `master`. - `repoSet({ projectId })` — the parsed repo set. -multi-repo still depends on no other plugin; stewards depends on it. Only -committed `master` is read, so a playbook edit published from a thread lands as -a `guidance-` branch and takes effect when it is merged. That is the +multi-repo still depends on no other plugin; stewards uses it when it is +installed and falls back to native git when it is not (BB-107). Only committed +`master` is read, so a playbook edit published from a thread lands as a +`guidance-` branch and takes effect when it is merged. That is the review step, and it is deliberate. +When multi-repo is not installed, stewards reads `.bb` through a git handler in +its own host entry: `origin/` after a fetch, never the developer's +working tree, with the repo set taken from the checkout's own `origin`. The two +reads sit behind one `ProjectSource` seam (`project-source.ts`), chosen once +per project at config load and cached with the config; only an unknown-plugin +RPC error selects native, and a spawn in native mode uses core's +`project-default` environment. + multi-repo's host-side read fetches and fast-forwards (`--ff-only`) the canonical checkout at most once every ten minutes, then reads committed HEAD; a checkout with local commits is left as it is and read as it is. diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index 65303ca1..c0422650 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -509,8 +509,10 @@ the choice is per developer. ## Configuration -In the project's `.bb` (the multi-repo project repo), read from committed -HEAD through multi-repo's `readProjectFiles` and `repoSet`: +In the project's `.bb`, read from the default branch's committed tip through +multi-repo's `readProjectFiles` and `repoSet`, or — when multi-repo is not +installed — through native git on the project checkout's `origin/` +(`project-source.ts`): ``` stewards/ diff --git a/plugins/stewards/app.tsx b/plugins/stewards/app.tsx index 31c15929..f91cee4e 100644 --- a/plugins/stewards/app.tsx +++ b/plugins/stewards/app.tsx @@ -358,6 +358,7 @@ function ProjectStatus({ project: p, now }: { project: Project; now: number }) { ) : (
{p.linearTeams.join(", ") || "none"} + {p.source === null ? "unknown" : p.source === "native" ? "native git (origin's default branch)" : "multi-repo plugin"} {p.repos.join(", ") || "none"} {p.excludedRepos.length > 0 && {p.excludedRepos.join(", ")}} diff --git a/plugins/stewards/host-contract.ts b/plugins/stewards/host-contract.ts index af1c1237..ff4212e1 100644 --- a/plugins/stewards/host-contract.ts +++ b/plugins/stewards/host-contract.ts @@ -1,12 +1,29 @@ // What stewards' server asks of its host entry (host.ts), on the developer's -// machine. One method: run kubectl, for the ops kind, with arguments that -// pass kubectlRefusal on both sides. +// machine. Two methods: run kubectl for the ops kind, with arguments that +// pass kubectlRefusal on both sides, and read `.bb` from a project checkout's +// `origin/` for the native project source (project-git.ts). import { defineRpcContract } from "@get-bb/plugin-sdk"; import { z } from "zod"; +/** A project-relative `.bb` file path: letters, digits, dot, dash, underscore, slash; no traversal. */ +const projectFilePath = z.string().min(1).max(300).regex(/^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/u, "a project file path"); + export const hostContract = defineRpcContract({ opsKubectl: { input: z.object({ args: z.array(z.string().min(1).max(300)).min(1).max(30), timeoutMs: z.number().int().min(1000).max(120_000) }).strict(), output: z.object({ exitCode: z.number().int(), stdout: z.string(), stderr: z.string(), missing: z.boolean() }).strict(), }, + gitProjectFiles: { + input: z.object({ path: z.string().min(1).max(2000), files: z.array(projectFilePath).max(64) }).strict(), + output: z + .object({ + head: z.string().max(64).nullable(), + files: z.array(z.object({ path: z.string().max(300), content: z.string().nullable() })).max(64), + remote: z.string().max(2000).nullable(), + defaultBranch: z.string().max(300).nullable(), + layout: z.enum(["primary", "standalone"]), + error: z.string().max(2000).nullable(), + }) + .strict(), + }, }); diff --git a/plugins/stewards/host.ts b/plugins/stewards/host.ts index bad1ae2f..34c3381e 100644 --- a/plugins/stewards/host.ts +++ b/plugins/stewards/host.ts @@ -1,10 +1,13 @@ // The host entry: the part of stewards that runs on the developer's machine, // where kubectl and its kubeconfig are. It runs only what kubectlRefusal -// allows (get, describe, logs, auth can-i), whatever the server sends. +// allows (get, describe, logs, auth can-i), whatever the server sends, and it +// reads a project checkout's `.bb` from `origin/` for the native +// project source (project-git.ts). import { execFile } from "node:child_process"; import { experimental_defineHostEntry, experimental_sanitizeInheritedChildProcessEnv } from "@get-bb/plugin-sdk/host"; import { hostContract } from "./host-contract.js"; import { kubectlRefusal } from "./kubectl.js"; +import { readProjectGit } from "./project-git.js"; /** A namespace's pods as JSON can be large; past this, kubectl's output is cut and fails to parse rather than flooding the call. */ const MAX_OUTPUT_BYTES = 16 * 1024 * 1024; @@ -31,5 +34,6 @@ export default experimental_defineHostEntry({ contract: hostContract, handlers: { opsKubectl: ({ args, timeoutMs }) => runKubectlHere(args, timeoutMs), + gitProjectFiles: ({ path, files }) => readProjectGit({ path, files }), }, }); diff --git a/plugins/stewards/project-git.test.ts b/plugins/stewards/project-git.test.ts new file mode 100644 index 00000000..66d34475 --- /dev/null +++ b/plugins/stewards/project-git.test.ts @@ -0,0 +1,105 @@ +// The native project source's git handler (project-git.ts): it must read the +// committed `origin/`, never the working tree or a local branch, and +// must not touch the working tree while doing so. +import { execFileSync } from "node:child_process"; +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { readProjectGit } from "./project-git.js"; + +const roots: string[] = []; + +const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }); + +async function tempRoot(): Promise { + const dir = await mkdtemp(path.join(tmpdir(), "bb-stewards-git-")); + roots.push(dir); + return dir; +} + +afterEach(async () => { + await Promise.all(roots.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); +}); + +/** A bare origin and a clone of it, both under a fresh temp root. */ +async function world(): Promise<{ origin: string; checkout: string }> { + const root = await tempRoot(); + const origin = path.join(root, "origin.git"); + const checkout = path.join(root, "checkout"); + git(root, "init", "--bare", "--quiet", "-b", "main", origin); + git(root, "clone", "--quiet", origin, checkout); + git(checkout, "config", "user.email", "test@example.com"); + git(checkout, "config", "user.name", "Test"); + await mkdir(path.join(checkout, ".bb", "stewards"), { recursive: true }); + await writeFile(path.join(checkout, ".bb", "stewards", "project.json"), '{"version":1,"marker":"committed"}\n', "utf8"); + await writeFile(path.join(checkout, ".bb", "AGENTS.md"), "committed guidance\n", "utf8"); + git(checkout, "add", "-A"); + git(checkout, "commit", "--quiet", "-m", "add .bb"); + git(checkout, "push", "--quiet", "-u", "origin", "main"); + return { origin, checkout }; +} + +describe("the native git project source", () => { + it("reads .bb from origin/main, never the working tree or a local commit", async () => { + const { checkout } = await world(); + // A dirty edit the developer is halfway through, and a local commit not + // pushed: neither is the project's. + await writeFile(path.join(checkout, ".bb", "stewards", "project.json"), '{"version":1,"marker":"dirty"}\n', "utf8"); + await writeFile(path.join(checkout, ".bb", "AGENTS.md"), "dirty guidance\n", "utf8"); + await writeFile(path.join(checkout, ".bb", "stewards", "other.json"), "{}\n", "utf8"); + git(checkout, "add", ".bb/stewards/other.json"); + git(checkout, "commit", "--quiet", "-m", "local only"); + + const read = await readProjectGit({ path: checkout, files: ["stewards/project.json", "AGENTS.md", "stewards/roles.json"] }); + expect(read.error).toBeNull(); + expect(read.defaultBranch).toBe("main"); + expect(read.layout).toBe("primary"); + const byPath = new Map(read.files.map((f) => [f.path, f.content])); + expect(byPath.get("stewards/project.json")).toContain('"marker":"committed"'); + expect(byPath.get("stewards/project.json")).not.toContain("dirty"); + expect(byPath.get("AGENTS.md")).toBe("committed guidance\n"); + expect(byPath.get("stewards/roles.json")).toBeNull(); + }); + + it("leaves the working tree, HEAD and branch exactly as they were", async () => { + const { checkout } = await world(); + await writeFile(path.join(checkout, ".bb", "stewards", "project.json"), '{"version":1,"marker":"dirty"}\n', "utf8"); + const headBefore = git(checkout, "rev-parse", "HEAD").trim(); + const branchBefore = git(checkout, "rev-parse", "--abbrev-ref", "HEAD").trim(); + const statusBefore = git(checkout, "status", "--porcelain"); + + await readProjectGit({ path: checkout, files: ["stewards/project.json"] }); + + expect(git(checkout, "rev-parse", "HEAD").trim()).toBe(headBefore); + expect(git(checkout, "rev-parse", "--abbrev-ref", "HEAD").trim()).toBe(branchBefore); + expect(git(checkout, "status", "--porcelain")).toBe(statusBefore); + expect(await readFile(path.join(checkout, ".bb", "stewards", "project.json"), "utf8")).toContain("dirty"); + }); + + it("reads a standalone .bb checkout at its root, and reports its origin", async () => { + const { origin, checkout } = await world(); + const standalone = path.join(path.dirname(checkout), "standalone"); + git(path.dirname(checkout), "clone", "--quiet", origin, standalone); + // A standalone checkout keeps the definition at the root instead of `.bb/`. + await rm(path.join(standalone, ".bb"), { recursive: true, force: true }); + await mkdir(path.join(standalone, "stewards"), { recursive: true }); + await writeFile(path.join(standalone, "stewards", "project.json"), '{"version":1,"marker":"standalone"}\n', "utf8"); + git(standalone, "add", "-A"); + git(standalone, "commit", "--quiet", "-m", "standalone layout"); + git(standalone, "push", "--quiet", "origin", "main"); + + const read = await readProjectGit({ path: standalone, files: ["stewards/project.json"] }); + expect(read.error).toBeNull(); + expect(read.layout).toBe("standalone"); + expect(read.files[0]?.content).toContain("standalone"); + expect(read.remote).toBe(origin); + }); + + it("refuses a traversal path rather than running git with it", async () => { + const { checkout } = await world(); + const read = await readProjectGit({ path: checkout, files: ["../secret"] }); + expect(read.error).toMatch(/not a project file path/u); + expect(read.files).toEqual([]); + }); +}); diff --git a/plugins/stewards/project-git.ts b/plugins/stewards/project-git.ts new file mode 100644 index 00000000..8a8101c1 --- /dev/null +++ b/plugins/stewards/project-git.ts @@ -0,0 +1,147 @@ +// The native project source's git half, run on the developer's machine by the +// host entry (host.ts) beside the kubectl handler. +// +// It reads `.bb` from the default branch's tip on `origin`, after a fetch: +// never the working tree, never a feature branch, never a local commit. The +// checkout is a person's directory as well as the plugin's, so an edit +// someone is halfway through there is not the project's. `git fetch` is the +// only command that changes anything, and it changes only remote-tracking +// refs; nothing here checks out, resets, stashes, commits or writes the +// working tree or a local branch. +// +// Every path is a fixed argument from the plugin, passed after `--`, so a +// file name can never become an option. Paths are validated again here even +// though the host contract already checks them: this is the boundary. +import { execFile } from "node:child_process"; +import { experimental_sanitizeInheritedChildProcessEnv } from "@get-bb/plugin-sdk/host"; +import type { NativeGitRead, ProjectGitFile } from "./project-source.js"; + +const GIT_TIMEOUT_MS = 30_000; +const MAX_OUTPUT_BYTES = 16 * 1024 * 1024; +/** A playbook or project file past this is not read, rather than truncated into a valid-looking one. */ +const MAX_FILE_CHARS = 200_000; +const REGULAR_FILE_MODES = new Set(["100644", "100755"]); +const SAFE_PATH = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/u; + +type GitRun = { code: number; stdout: string; stderr: string; truncated: boolean }; + +function runGit(dir: string, args: string[], opts: { timeoutMs?: number; maxBytes?: number } = {}): Promise { + return new Promise((resolve) => { + execFile( + "git", + ["-C", dir, ...args], + { + timeout: opts.timeoutMs ?? GIT_TIMEOUT_MS, + maxBuffer: opts.maxBytes ?? MAX_OUTPUT_BYTES, + env: { ...experimental_sanitizeInheritedChildProcessEnv({ env: process.env }), NO_COLOR: "1", GIT_TERMINAL_PROMPT: "0" }, + windowsHide: true, + }, + (error, stdout, stderr) => { + const e = error as (Omit & { code?: string | number; killed?: boolean }) | null; + if (e?.code === "ENOENT") return resolve({ code: 127, stdout: "", stderr: "git: not found", truncated: false }); + const exitCode = e === null ? 0 : typeof e.code === "number" ? e.code : 1; + resolve({ code: exitCode, stdout: String(stdout), stderr: e !== null && e.killed ? `git did not finish in ${(opts.timeoutMs ?? GIT_TIMEOUT_MS) / 1000}s` : String(stderr), truncated: false }); + }, + ); + }); +} + +async function gitLine(dir: string, args: string[]): Promise { + const r = await runGit(dir, args); + const line = r.stdout.split(/\r?\n/u).map((l) => l.trim()).find((l) => l !== ""); + return r.code === 0 && line !== undefined ? line : null; +} + +const firstProblemLine = (r: GitRun): string => r.stderr.split(/\r?\n/u).map((l) => l.trim()).find((l) => l !== "") ?? `git exited ${r.code}`; + +async function refExists(dir: string, ref: string): Promise { + const r = await runGit(dir, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]); + return r.code === 0 && r.stdout.trim() !== ""; +} + +async function objectExists(dir: string, spec: string): Promise { + const r = await runGit(dir, ["cat-file", "-e", spec]); + return r.code === 0; +} + +/** + * The default branch's name, from `origin/HEAD`, then the conventional names. + * Never the checked-out branch: a feature branch is not the project's. + */ +async function originDefaultBranch(dir: string): Promise { + const head = await gitLine(dir, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]); + if (head !== null && head.startsWith("origin/")) return head.slice("origin/".length); + for (const candidate of ["main", "master"]) { + if (await refExists(dir, `refs/remotes/origin/${candidate}`)) return candidate; + } + return null; +} + +/** + * The committed `.bb` prefix: `.bb/` for the primary layout (a directory on + * the primary repo's default branch, BB-106), `""` for a standalone `.bb` + * checkout whose root is the definition. + */ +async function definitionPrefix(dir: string, head: string): Promise<".bb/" | ""> { + if (await objectExists(dir, `${head}:.bb/stewards/project.json`)) return ".bb/"; + if (await objectExists(dir, `${head}:stewards/project.json`)) return ""; + return ".bb/"; +} + +/** Whether every path is a fixed, relative, traversal-free path the plugin may ask for. */ +export function projectGitPathProblem(path: string): string | null { + if (!SAFE_PATH.test(path) || path.split("/").includes("..")) return `${JSON.stringify(path)} is not a project file path`; + return null; +} + +/** + * Read the named files out of the project checkout's `origin/` at + * its committed tip. A fetch is attempted first; a fetch that fails (no + * network, no remote) still reads the last fetched commit rather than + * failing the read. The working tree and every local branch are untouched. + */ +export async function readProjectGit(input: { path: string; files: readonly string[] }): Promise { + const dir = input.path; + for (const file of input.files) { + const problem = projectGitPathProblem(file); + if (problem !== null) return { head: null, files: [], remote: null, defaultBranch: null, layout: "primary", error: problem }; + } + const remote = await gitLine(dir, ["config", "--get", "remote.origin.url"]); + const fetched = await runGit(dir, ["fetch", "--quiet", "origin"]); + const branch = await originDefaultBranch(dir); + if (branch === null) { + return { head: null, files: [], remote, defaultBranch: null, layout: "primary", error: fetched.code === 0 ? `${dir} has no origin default branch to read.` : `Could not fetch the project source: ${firstProblemLine(fetched)}` }; + } + const ref = `refs/remotes/origin/${branch}`; + const head = await gitLine(dir, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]); + if (head === null) { + return { head: null, files: [], remote, defaultBranch: branch, layout: "primary", error: `Could not fetch the project source: ${firstProblemLine(fetched)}` }; + } + const prefix = await definitionPrefix(dir, head); + const layout = prefix === "" ? ("standalone" as const) : ("primary" as const); + if (input.files.length === 0) return { head, files: [], remote, defaultBranch: branch, layout, error: null }; + + // One `ls-tree` for every path: which the commit holds, and as what. + // Literal pathspecs and `--`, so a name is only ever a name. + const listed = await runGit(dir, ["--literal-pathspecs", "ls-tree", "-z", "--full-tree", head, "--", ...input.files.map((file) => `${prefix}${file}`)]); + if (listed.code !== 0) return { head, files: [], remote, defaultBranch: branch, layout, error: firstProblemLine(listed) }; + const blobs = new Map(); + for (const entry of listed.stdout.split("\0")) { + const match = /^(\d+) (\w+) ([0-9a-f]+)\t(.*)$/su.exec(entry); + if (match === null || match[2] !== "blob" || !REGULAR_FILE_MODES.has(match[1]!)) continue; + blobs.set(match[4]!, match[3]!); + } + + const files: ProjectGitFile[] = []; + for (const file of input.files) { + const object = blobs.get(`${prefix}${file}`); + if (object === undefined) { + files.push({ path: file, content: null }); + continue; + } + const read = await runGit(dir, ["cat-file", "blob", object], { maxBytes: MAX_FILE_CHARS * 3 + 1 }); + if (read.code !== 0) return { head, files: [], remote, defaultBranch: branch, layout, error: firstProblemLine(read) }; + files.push({ path: file, content: read.stdout.length > MAX_FILE_CHARS ? null : read.stdout }); + } + return { head, files, remote, defaultBranch: branch, layout, error: null }; +} diff --git a/plugins/stewards/project-source.ts b/plugins/stewards/project-source.ts new file mode 100644 index 00000000..a195eb6d --- /dev/null +++ b/plugins/stewards/project-source.ts @@ -0,0 +1,129 @@ +// The project-source seam: how stewards reads a project's `.bb` and how it +// spawns a fresh environment. Two implementations, chosen once per project at +// config load and cached with the config (server.ts): +// +// * `multi-repo` — the three RPCs, exactly as before: `readProjectFiles`, +// `repoSet`, `mergeGuidance`. Every project that has the plugin installed +// stays here, so nothing changes for them. +// * `native` — a git handler in the plugin's host entry (host.ts, +// project-git.ts) that reads `.bb` from `origin/` after a fetch, +// never the developer's working tree, and takes the repo set from the +// checkout's own `origin`. It is chosen only when the multi-repo RPC +// reports the plugin is missing (`isMissingPlugin`), so a single-repo +// project on a stock bb install can run stewards. +// +// A source carries the environment choice too: multi-repo spawns a fresh +// thread on the `multi-repo-workspace` provider when the project has a +// machine, native always leaves it to core (`project-default`). Wake text, +// the stewards skill and `bb stewards spawn-flags` all read the same seam, so +// they cannot disagree with what the plugin actually spawns. +// +// `mergeGuidance` is unsupported natively under BB-107; a lesson that would +// have fast-forwarded the canonical checkout reports that it needs a pull +// request instead (BB-108 already lands lessons as pull requests). +import { isMissingPlugin } from "./source-contract.js"; + +export const MULTI_REPO_PLUGIN_ID = "multi-repo"; +/** multi-repo's environment provider: where every thread of a multi-repo project works. */ +export const MULTI_REPO_ENVIRONMENT_PROVIDER_ID = "multi-repo-workspace"; + +export type ProjectSourceKind = "multi-repo" | "native"; + +/** A fresh environment for a spawn, as `bb.sdk.threads.spawn` takes it. */ +export type FreshEnvironment = + | { type: "project-default" } + | { type: "provider"; environmentProviderId: string; inputs: null; machine: { type: "existing"; hostId: string } }; + +/** The repo set a project source returns, the shape both implementations share. */ +export type ProjectRepoSet = { + repos: Array<{ dir: string; url: string }>; + /** The project source's own origin, for a lesson's pull request (BB-108). */ + primary: { dir: string; url: string } | null; + layout: "primary" | "standalone"; + error: string | null; +}; + +/** One file read from the project's `.bb` at the default branch's tip. */ +export type ProjectGitFile = { path: string; content: string | null }; + +/** What a native host read returns: the files, and enough about the checkout for the repo set. */ +export type NativeGitRead = { + head: string | null; + files: ProjectGitFile[]; + remote: string | null; + defaultBranch: string | null; + layout: "primary" | "standalone"; + error: string | null; +}; + +export type MergeGuidanceResult = { ok: boolean; sha: string | null; branch: string | null; message: string }; + +/** + * One project's source. `readFiles` and `repoSet` are what server.ts reads + * configuration and guidance through; `freshEnvironment` and + * `environmentFlags` are how a spawn (and the command a wake shows) is built. + */ +export type ProjectSource = { + kind: ProjectSourceKind; + readFiles(paths: string[]): Promise>; + repoSet(): Promise; + mergeGuidance(threadId: string, file: string, text: string): Promise; + freshEnvironment(hostId: string | null): FreshEnvironment; + environmentFlags(hostId: string | null): string; +}; + +export type MultiRepoOps = { + readFiles(paths: string[]): Promise>; + repoSet(): Promise; + mergeGuidance(threadId: string, file: string, text: string): Promise; +}; + +/** The multi-repo environment for a spawn: the workspace provider on the project's machine. */ +export const multiRepoFreshEnvironment = (hostId: string | null): FreshEnvironment => + hostId === null + ? { type: "project-default" } + : { type: "provider", environmentProviderId: MULTI_REPO_ENVIRONMENT_PROVIDER_ID, inputs: null, machine: { type: "existing", hostId } }; + +/** The same as `bb thread spawn` flags, for the worker command a wake shows. */ +export const multiRepoEnvironmentFlags = (hostId: string | null): string => + hostId === null ? "" : `--environment-provider ${MULTI_REPO_ENVIRONMENT_PROVIDER_ID} --machine ${hostId}`; + +/** The multi-repo implementation: the RPCs as they always were. */ +export function multiRepoSource(ops: MultiRepoOps): ProjectSource { + return { + kind: "multi-repo", + readFiles: ops.readFiles, + repoSet: ops.repoSet, + mergeGuidance: ops.mergeGuidance, + freshEnvironment: multiRepoFreshEnvironment, + environmentFlags: multiRepoEnvironmentFlags, + }; +} + +export type NativeOps = { + readFiles(paths: string[]): Promise>; + repoSet(): Promise; +}; + +/** The native implementation: git on the checkout, and core's default environment. */ +export function nativeSource(ops: NativeOps): ProjectSource { + return { + kind: "native", + readFiles: ops.readFiles, + repoSet: ops.repoSet, + mergeGuidance: async () => ({ ok: false, sha: null, branch: null, message: "A native project has no guidance merge; land the lesson as a pull request." }), + freshEnvironment: () => ({ type: "project-default" }), + environmentFlags: () => "", + }; +} + +/** A short human label for a project source, for `bb stewards show`/`check` and the Stewards page. */ +export const projectSourceLabel = (kind: ProjectSourceKind | null): string => + kind === null ? "unknown" : kind === "native" ? "native git (origin's default branch)" : "multi-repo plugin"; + +/** + * Whether an RPC failure means the multi-repo plugin is not installed (so + * native is the right source) rather than that it is installed and failing. + * Re-exported so server.ts and tests share one rule. + */ +export const sourceRpcMissing = (error: unknown): boolean => isMissingPlugin(error); diff --git a/plugins/stewards/schedule.test.ts b/plugins/stewards/schedule.test.ts index 88062615..b33c7111 100644 --- a/plugins/stewards/schedule.test.ts +++ b/plugins/stewards/schedule.test.ts @@ -29,6 +29,18 @@ describe("touches", () => { expect(touchesOverlap(["web/src"], ["web/srcs", "api/src"])).toEqual([]); expect(touchesOverlap(["bb-plugins/plugins/stewards", "bb-gate"], ["bb-gate/docker", "bb-plugins/plugins/linear"])).toEqual(["bb-gate/docker"]); }); + + it("overlap across the repo-prefixed and native repo-relative forms (BB-107)", () => { + // Both repo-relative (native). + expect(touchesOverlap(["plugins/stewards"], ["plugins/stewards/wake.ts"])).toEqual(["plugins/stewards/wake.ts"]); + // Mixed: a multi-repo touch that moved to native keeps overlapping. + expect(touchesOverlap(["bb-plugins/plugins/stewards"], ["plugins/stewards/wake.ts"])).toEqual(["bb-plugins/plugins/stewards"]); + expect(touchesOverlap(["plugins/stewards/wake.ts"], ["bb-plugins/plugins/stewards"])).toEqual(["bb-plugins/plugins/stewards"]); + expect(touchesOverlap(["bb-plugins/plugins/stewards"], ["plugins/stewards"])).toEqual(["bb-plugins/plugins/stewards"]); + // Two repos' same-named tails must not meet, in either direction. + expect(touchesOverlap(["bb-plugins/plugins/stewards"], ["bb-gate/plugins/stewards"])).toEqual([]); + expect(touchesOverlap(["web/src"], ["api/src"])).toEqual([]); + }); }); describe("conflicts", () => { diff --git a/plugins/stewards/schedule.ts b/plugins/stewards/schedule.ts index 09cabf1e..c65c94db 100644 --- a/plugins/stewards/schedule.ts +++ b/plugins/stewards/schedule.ts @@ -3,11 +3,16 @@ // and acts on what it says (a `schedule` escalation to the project steward, a // hold placed behind the binding already at work). // -// A touch is a repo-relative path with the repo directory first, as the -// steward reports it: "bb-plugins/plugins/stewards", "bb-gate/docker". Two -// bindings overlap when one touch is the other or a parent directory of it, -// so "bb-plugins" overlaps everything in that repo and -// "bb-plugins/plugins/stewards/wake.ts" overlaps "bb-plugins/plugins/stewards". +// A touch is a path the steward reported: with the repo directory first when +// the project is read through multi-repo ("bb-plugins/plugins/stewards"), and +// repo-relative without it when it is read through the native git source +// ("plugins/stewards"). Two bindings overlap when one touch is the other or a +// parent directory of it, comparing both the path as reported and the path +// with its first segment stripped, so a repo-prefixed touch and a native +// repo-relative touch can meet. That stripping is what lets a project that +// moved from multi-repo to native keep its old bindings' touches meaningful; +// it can also match two different repos' same-named directory, which is +// harmless (an extra schedule question) and unavoidable without the repo set. import type { Binding, Observed } from "./store.js"; /** A touch as compared: lower case, forward slashes, no leading "./" or surrounding slashes, inner runs of slashes collapsed. */ @@ -28,10 +33,33 @@ export function normalizeTouches(raw: readonly string[]): string[] { const under = (path: string, dir: string) => path === dir || path.startsWith(`${dir}/`); -/** Whether two touch sets name the same place: a touch of one is, or is inside, a touch of the other. */ +/** + * A touch's repo-relative form: the path with its first segment stripped, + * when it has one. Null when it is already a single segment. + */ +function stripped(touch: string): string | null { + const slash = touch.indexOf("/"); + return slash > 0 ? touch.slice(slash + 1) : null; +} + +/** + * Whether two touches name the same place: either full path is the other or + * inside it, or one full path is the other's repo-relative form or inside + * that. Comparing a stripped form only against a full path (never against + * another stripped form) is what stops `web/src` matching `api/src`: they + * share a tail, not a place. + */ +function touchesMeet(x: string, y: string): boolean { + if (under(x, y) || under(y, x)) return true; + const sx = stripped(x); + const sy = stripped(y); + return (sx !== null && (under(sx, y) || under(y, sx))) || (sy !== null && (under(x, sy) || under(sy, x))); +} + +/** Whether two touch sets name the same place, in either form. */ export function touchesOverlap(a: readonly string[], b: readonly string[]): string[] { const hits = new Set(); - for (const x of a) for (const y of b) if (under(x, y) || under(y, x)) hits.add(x.length >= y.length ? x : y); + for (const x of a) for (const y of b) if (touchesMeet(x, y)) hits.add(x.length >= y.length ? x : y); return [...hits].sort(); } diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 0a9f2090..a1e08e67 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -3752,6 +3752,118 @@ describe("stale-while-revalidate project configuration (BB-104)", () => { }); }); +// BB-107: without the multi-repo plugin, stewards reads `.bb` from native git +// on the project checkout and spawns on core's project-default environment. +// Only a missing-plugin RPC error selects native; any other failure keeps the +// last good multi-repo source and shows a problem line. +describe("the native project source (BB-107)", () => { + type Loaded = { source: { kind: string }; file: { linear: { teams: string[] } }; repos: string[]; problems: string[] }; + const load = (t: Awaited>) => t.hooks.loadConfig("p1", true) as Promise; + + /** A default `.bb` for the git fake, matching what world() seeds multi-repo with. */ + const defaultFiles = (): Record => ({ + [PROJECT_FILE]: projectFileTemplate(["ENG"]), + [playbookPath("linear-tickets")]: LINEAR_TICKETS, + [playbookPath("github-prs")]: GITHUB_PRS, + [playbookPath("github-reviews")]: GITHUB_REVIEWS, + }); + + /** A world whose multi-repo plugin is missing: native git serves `.bb`, and every multi-repo RPC is a 404. */ + const nativeWorld = async (missing = true) => { + let files: Record = defaultFiles(); + const gitCalls: Array<{ path: string; hostId: string | null; files: string[] }> = []; + const t = await setup({ + git: async ({ hostId, path, files: paths }) => { + gitCalls.push({ path, hostId, files: paths }); + return { head: "abc", files: paths.map((p) => ({ path: p, content: files[p] ?? null })), remote: "https://github.com/acme/web.git", defaultBranch: "main", layout: "primary" as const, error: null }; + }, + }); + files = t.files; + t.hooks.forgetConfigs(); + const original = t.sdk.plugins.callRpc; + if (missing) { + t.harness.sdk.stub("plugins.callRpc", async (args: { pluginId: string; method: string; input?: unknown; outputSchema: { parse(v: unknown): unknown } }) => { + if (args.pluginId === "multi-repo") throw Object.assign(new Error(`unknown ${args.pluginId}.${args.method}`), { status: 404 }); + return original(args); + }); + } + return { t, gitCalls }; + }; + + it("loads from native git when the multi-repo RPC reports unknown plugin", async () => { + const { t, gitCalls } = await nativeWorld(); + const config = await load(t); + expect(config).not.toBeNull(); + expect(config!.source.kind).toBe("native"); + expect(config!.file.linear.teams).toEqual(["ENG"]); + // The repo set is the checkout's own origin. + expect(config!.repos).toEqual(["acme/web"]); + // It read the project file through the git handler, on the checkout. + expect(gitCalls.some((c) => c.files.includes(PROJECT_FILE))).toBe(true); + }); + + it("keeps the multi-repo source and reports a problem line when the RPC fails for another reason", async () => { + const t = await setup(); + await t.flush(); + const before = await load(t); + expect(before!.source.kind).toBe("multi-repo"); + const original = t.sdk.plugins.callRpc; + t.harness.sdk.stub("plugins.callRpc", async (args: { pluginId: string; method: string; input?: unknown; outputSchema: { parse(v: unknown): unknown } }) => { + if (args.method === "readProjectFiles") throw Object.assign(new Error("the .bb is unreachable"), { code: "handler_error" }); + return original(args); + }); + const after = await load(t); + expect(after).not.toBeNull(); + expect(after!.source.kind).toBe("multi-repo"); + expect(after!.problems.some((p) => p.includes("the .bb is unreachable"))).toBe(true); + }); + + it("spawns on project-default and carries no multi-repo flag in native mode", async () => { + const { t } = await nativeWorld(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + expect(t.spawns[0]).toMatchObject({ environment: { type: "project-default" } }); + const flags = await t.harness.behavior.runCli(["spawn-flags", "ENG-12", "--project", "p1"]); + expect(flags.stdout).toContain("bb thread spawn"); + expect(flags.stdout).not.toContain("--environment-provider multi-repo-workspace"); + expect(flags.stdout).not.toContain("--machine"); + expect(t.sends.map((s) => s.text).join("\n")).not.toContain("--environment-provider multi-repo-workspace"); + }); + + it("keeps an existing binding when the source switches to native", async () => { + // Start on multi-repo, adopt a binding, then let multi-repo disappear. + const { t } = await nativeWorld(false); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); + await t.ring("linear", "uuid-12"); + const before = t.hooks.store.find("ENG-12", "p1"); + expect(before).not.toBeNull(); + const original = t.sdk.plugins.callRpc; + t.harness.sdk.stub("plugins.callRpc", async (args: { pluginId: string; method: string; input?: unknown; outputSchema: { parse(v: unknown): unknown } }) => { + if (args.pluginId === "multi-repo") throw Object.assign(new Error(`unknown ${args.pluginId}.${args.method}`), { status: 404 }); + return original(args); + }); + t.hooks.forgetConfigs(); + const config = await load(t); + expect(config!.source.kind).toBe("native"); + expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ id: before!.id, entityKey: "ENG-12" }); + expect((await t.harness.behavior.runCli(["list", "--project", "p1"])).stdout).toContain("ENG-12"); + }); + + it("names the project source in check and the overview, for both sources", async () => { + const multi = await setup(); + await multi.flush(); + expect((await multi.harness.behavior.runCli(["check", "--project", "p1"])).stdout).toContain("Project source: multi-repo plugin"); + const multiOverview = (await multi.harness.callRpc("stewardsOverview", null)) as { projects: Array<{ projectId: string; source: string | null }> }; + expect(multiOverview.projects.find((p) => p.projectId === "p1")?.source).toBe("multi-repo"); + + const { t } = await nativeWorld(); + await t.flush(); + expect((await t.harness.behavior.runCli(["check", "--project", "p1"])).stdout).toContain("Project source: native git"); + const nativeOverview = (await t.harness.callRpc("stewardsOverview", null)) as { projects: Array<{ projectId: string; source: string | null }> }; + expect(nativeOverview.projects.find((p) => p.projectId === "p1")?.source).toBe("native"); + }); +}); + describe("the stewards sidebar call", () => { type Sidebar = { projects: Array<{ projectId: string; name: string; needsCount: number }>; diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index d9dfe76f..136456a5 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -10,8 +10,9 @@ // below looks, compares with the last observation, and wakes the steward only // when something actionable changed. // -// Configuration lives in the project's `.bb`, read through multi-repo's RPC -// from the canonical checkout's committed HEAD. Nothing here reads a file. +// Configuration lives in the project's `.bb`, read through a project source +// (project-source.ts): multi-repo's RPCs when it is installed, native git on +// the project checkout when it is not. Nothing here reads a file. import { randomBytes } from "node:crypto"; import { PluginCliError, cliCommand, defineCli, defineRpcContract, type BbPluginApi, type ExperimentalPluginRpcHandlersWithContext, type PluginCliCommand } from "@get-bb/plugin-sdk"; import { z } from "zod"; @@ -61,6 +62,7 @@ import { import { decideFor, decideForPull, decideForRefusal } from "./decisions.js"; import { alertFingerprint, batchAlert, deadlineAt, depsLookSchema, isBatchable, priorityFor, repoOfFingerprint, sightingOf, type DepsFinding, type DepsLook, type DepsTicket } from "./deps.js"; import { hostContract } from "./host-contract.js"; +import { MULTI_REPO_ENVIRONMENT_PROVIDER_ID, MULTI_REPO_PLUGIN_ID, multiRepoEnvironmentFlags, multiRepoFreshEnvironment, multiRepoSource, nativeSource, projectSourceLabel, sourceRpcMissing, type FreshEnvironment, type NativeGitRead, type ProjectSource } from "./project-source.js"; import { KUBECTL_VERBS, createKubectlReader, kubectlRefusal, type KubectlResult, type OpsAccess, type OpsReader } from "./kubectl.js"; import { HOOKS_URL_ENV, createHooksLoop, type Lease, type Rejection } from "./hooks-client.js"; import { nightlyDue, stillNight } from "./nightly.js"; @@ -96,9 +98,7 @@ import { PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; import type { DeploymentTarget } from "./config.js"; import { PROJECT_STEWARD_INTRO, choicesNote, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatSentryWake, formatSessionWake, formatWake, spawnCommand, workerQuestion, workerReportedError, workerWaiting, workflowRunLine, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; -export const MULTI_REPO_PLUGIN_ID = "multi-repo"; -/** multi-repo's environment provider: where every thread of a stewards project works. */ -export const MULTI_REPO_ENVIRONMENT_PROVIDER_ID = "multi-repo-workspace"; +export { MULTI_REPO_ENVIRONMENT_PROVIDER_ID, MULTI_REPO_PLUGIN_ID }; /** * The per-turn system context the SDK injects is truncated at 4096 characters; @@ -167,6 +167,8 @@ export interface StewardsDeps { timing?: Partial; /** Runs kubectl for ops bindings: on the project's machine, through the host entry, by default. */ kubectl?: (args: string[], where: { projectId: string; hostId: string | null }) => Promise; + /** Reads the project's `.bb` from `origin/` for the native source: the host entry by default. */ + git?: (input: { projectId: string; hostId: string | null; path: string; files: string[] }) => Promise; /** The GitHub writer the page's Approve and Merge buttons use; the server's gh login by default. */ github?: GithubWriter; /** What reads Sentry and subscribes to bb-gate-hooks for it; global fetch by default. */ @@ -228,6 +230,13 @@ const repoSetOutput = z error: z.string().nullable(), }) .loose(); +const mergeGuidanceOutput = z.object({ ok: z.boolean(), sha: z.string().nullable(), branch: z.string().nullable(), message: z.string() }).loose(); + +/** A project checkout fetch can be slow; the git host call is allowed this long. */ +const GIT_TIMEOUT_MS = 60_000; + +/** The checkout directory's own name, for a native project's single repo entry. */ +const checkoutDirName = (path: string): string => path.replace(/[\\/]+$/u, "").split(/[\\/]/u).filter((part) => part !== "").at(-1) ?? "project"; /** * The `guidance-` ref a thread's `.bb` commits are published on. @@ -355,6 +364,8 @@ export const rpcContract = defineRpcContract({ projectId: z.string(), name: z.string(), configured: z.boolean(), + /** Which project source reads this project's `.bb`: multi-repo or native git (BB-107). */ + source: z.enum(["multi-repo", "native"]).nullable(), label: z.string().nullable(), linearTeams: z.array(z.string()), repos: z.array(z.string()), @@ -598,6 +609,8 @@ const ENDED_ON_BOARD_MS = 14 * 86_400_000; type ProjectConfig = { projectId: string; + /** The chosen project source (multi-repo or native), cached with the config. */ + source: ProjectSource; file: ProjectFile; /** The roles file, when one is present and parses (or its last good copy). */ roles: RolesFile | null; @@ -954,10 +967,76 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P */ const configReads = new Map>(); + /** The RPC-backed multi-repo source for one project: the three RPCs as they always were. */ + function multiRepoSourceFor(projectId: string): ProjectSource { + return multiRepoSource({ + readFiles: async (paths) => { + const out = await rpc(MULTI_REPO_PLUGIN_ID, "readProjectFiles", { projectId, paths }, readFilesOutput); + if (out.error !== null && out.files.length === 0) throw new Error(out.error); + return new Map(out.files.map((f) => [f.path, f.content])); + }, + repoSet: async () => { + const set = await rpc(MULTI_REPO_PLUGIN_ID, "repoSet", { projectId }, repoSetOutput); + return { repos: set.repos, primary: set.primary, layout: set.layout, error: set.error }; + }, + mergeGuidance: (threadId, file, text) => rpc(MULTI_REPO_PLUGIN_ID, "mergeGuidance", { projectId, threadId, file, text }, mergeGuidanceOutput), + }); + } + + /** + * The git-backed native source for one project. The host entry does the + * fetch and the read (project-git.ts), on the checkout's own machine; the + * server never touches a file. `deps.git` is the test seam. + */ + function nativeSourceFor(projectId: string): ProjectSource { + const run = async (files: string[]): Promise<{ read: NativeGitRead; path: string | null }> => { + const checkout = await projectCheckout(projectId); + if (checkout === null) return { read: { head: null, files: [], remote: null, defaultBranch: null, layout: "primary", error: null }, path: null }; + const read = + deps.git !== undefined + ? await deps.git({ projectId, hostId: checkout.hostId, path: checkout.path, files }) + : await (hostClient ??= bb.hosts.experimental_client({ contract: hostContract })).call("gitProjectFiles", { path: checkout.path, files }, { hostId: checkout.hostId, timeoutMs: GIT_TIMEOUT_MS }); + return { read, path: checkout.path }; + }; + return nativeSource({ + readFiles: async (paths) => { + const { read } = await run(paths); + if (read.error !== null && read.files.length === 0) throw new Error(read.error); + return new Map(read.files.map((f) => [f.path, f.content])); + }, + repoSet: async () => { + const { read, path } = await run([]); + const entry = read.remote === null || path === null ? null : { dir: checkoutDirName(path), url: read.remote }; + return { repos: entry === null ? [] : [entry], primary: entry, layout: read.layout, error: read.error }; + }, + }); + } + + /** + * Choose the project source once per config load. The multi-repo read is + * the probe: only a missing-plugin error selects native (BB-107); any + * other failure keeps multi-repo and propagates, so the last good config + * is kept and the failure is shown as a problem line (readConfigShared). + */ + async function selectProjectSource(projectId: string): Promise<{ source: ProjectSource; files: Map | null }> { + try { + const out = await rpc(MULTI_REPO_PLUGIN_ID, "readProjectFiles", { projectId, paths: [PROJECT_FILE, ROLES_FILE] }, readFilesOutput); + if (out.error !== null && out.files.length === 0) throw new Error(out.error); + return { source: multiRepoSourceFor(projectId), files: new Map(out.files.map((f) => [f.path, f.content])) }; + } catch (error) { + if (sourceRpcMissing(error)) { + bb.log.info(`stewards: multi-repo is not installed; reading project ${projectId} from native git`); + return { source: nativeSourceFor(projectId), files: null }; + } + throw error; + } + } + + /** Read `.bb` files through the project's chosen source, for callers that do not already hold the config. */ async function readFiles(projectId: string, paths: string[]): Promise> { - const out = await rpc(MULTI_REPO_PLUGIN_ID, "readProjectFiles", { projectId, paths }, readFilesOutput); - if (out.error !== null && out.files.length === 0) throw new Error(out.error); - return new Map(out.files.map((f) => [f.path, f.content])); + const config = await loadConfig(projectId); + if (config === null) throw new Error(`no ${PROJECT_FILE} for project ${projectId}`); + return config.source.readFiles(paths); } /** @@ -974,9 +1053,16 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return value; }) .catch((error: unknown) => { - // Unreachable `.bb` is not "no stewards": keep what we had. + // Unreachable `.bb` is not "no stewards": keep what we had. A + // non-missing RPC failure stays on the last good source (BB-107) and + // is shown as a problem line rather than silently swallowed. bb.log.warn(`stewards: could not read the configuration of project ${projectId}: ${errorMessage(error)}`); - return configs.get(projectId)?.value ?? null; + const last = configs.get(projectId)?.value ?? null; + if (last !== null) { + const line = `could not read the configuration: ${errorMessage(error)}`; + if (!last.problems.includes(line)) last.problems.push(line); + } + return last; }) .finally(() => { if (configReads.get(projectId) === promise) configReads.delete(projectId); @@ -1007,7 +1093,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P async function readConfig(projectId: string): Promise { const problems: string[] = []; - const configFiles = await readFiles(projectId, [PROJECT_FILE, ROLES_FILE]); + const selected = await selectProjectSource(projectId); + const source = selected.source; + const configFiles = selected.files ?? (await source.readFiles([PROJECT_FILE, ROLES_FILE])); const projectText = configFiles.get(PROJECT_FILE) ?? null; if (projectText === null) return null; let file: ProjectFile; @@ -1086,7 +1174,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const names = new Map(kinds.map((k) => [k, playbookNameFor(file, k)] as const)); const depsAlertsName = depsAlertsPlaybookName(file); const depsPrsName = depsPrsPlaybookName(file); - const texts = await readFiles(projectId, [...new Set([...names.values(), depsAlertsName, depsPrsName])].map(playbookPath)); + const texts = await source.readFiles([...new Set([...names.values(), depsAlertsName, depsPrsName])].map(playbookPath)); const playbooks: Partial> = {}; for (const [kind, name] of names) { const text = texts.get(playbookPath(name)) ?? null; @@ -1136,7 +1224,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P let repos: string[] = []; try { - const set = await rpc(MULTI_REPO_PLUGIN_ID, "repoSet", { projectId }, repoSetOutput); + const set = await source.repoSet(); if (set.error !== null) problems.push(`repos.json: ${set.error}`); const all = set.repos.map((r) => githubRepoOf(r.url)).filter((r): r is string => r !== null); repos = all.filter((r) => !file.github.exclude.some((x) => lc(x) === lc(r))); @@ -1166,7 +1254,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P problems.push(stewardProblem); } } - return { projectId, file, roles, rolesPresent, rolesUnreadable, githubLogin, linearLogin, role, playbooks, depsAlerts, depsPrs, repos, problems, loadedAt: now() }; + return { projectId, source, file, roles, rolesPresent, rolesUnreadable, githubLogin, linearLogin, role, playbooks, depsAlerts, depsPrs, repos, problems, loadedAt: now() }; } // ---- the hand-written guidance's meter (BB-35 step 6) ------------------------------ @@ -1192,7 +1280,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (config.depsAlerts !== null) names.add(config.depsAlerts.name); if (config.depsPrs !== null) names.add(config.depsPrs.name); const paths = ["AGENTS.md", ...[...names].map(playbookPath)]; - const files = await readFiles(projectId, paths); + const files = await config.source.readFiles(paths); for (const path of paths) { const content = files.get(path) ?? null; if (content !== null) value.push(...parseGuidanceUnits(path, content)); @@ -1588,7 +1676,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * cannot await this. */ const projectHostCache = new Map(); - async function projectHost(projectId: string): Promise { + + /** + * The project's checkout on a machine bb can reach: a `local_path` source, + * preferring one on a connected host. Null when the project has none. The + * native project source reads `.bb` here (server.ts, project-git.ts). + */ + async function projectCheckout(projectId: string): Promise<{ hostId: string; path: string } | null> { try { const [project, hosts] = await Promise.all([bb.sdk.projects.get({ projectId }), bb.sdk.hosts.list().catch(() => [])]); const sources = project.sources.filter((source) => source.type === "local_path"); @@ -1598,15 +1692,19 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P sources.find((source) => connected.has(source.hostId)) ?? sources.find((source) => source.isDefault) ?? sources[0]; - projectHostCache.set(projectId, { at: now(), hostId: pick?.hostId ?? null }); - return pick?.hostId ?? null; + return pick === undefined ? null : { hostId: pick.hostId, path: pick.path }; } catch (error) { - bb.log.warn(`stewards: could not find the machine for ${projectId} (${errorMessage(error)}); leaving it to bb's default`); - projectHostCache.set(projectId, { at: now(), hostId: null }); + bb.log.warn(`stewards: could not find the checkout of ${projectId} (${errorMessage(error)}); leaving it to bb's default`); return null; } } + async function projectHost(projectId: string): Promise { + const checkout = await projectCheckout(projectId); + projectHostCache.set(projectId, { at: now(), hostId: checkout?.hostId ?? null }); + return checkout?.hostId ?? null; + } + /** * The cached project machine, or undefined when it was never read or is * older than a sweep. The synchronous per-turn brief cannot await @@ -1619,14 +1717,17 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return entry === undefined || now() - entry.at > timing.sweepMs ? undefined : entry.hostId; } - /** A fresh environment for a project's thread: a multi-repo workspace on its machine. */ - const freshEnvironment = (hostId: string | null) => - hostId === null - ? ({ type: "project-default" } as const) - : ({ type: "provider", environmentProviderId: MULTI_REPO_ENVIRONMENT_PROVIDER_ID, inputs: null, machine: { type: "existing", hostId } } as const); + /** + * A fresh environment for a project's thread, from its chosen source. A + * null source (no config) keeps the old multi-repo choice, so a spawn that + * outlives its configuration is unchanged. + */ + const freshEnvironment = (source: ProjectSource | null, hostId: string | null): FreshEnvironment => + source === null ? multiRepoFreshEnvironment(hostId) : source.freshEnvironment(hostId); /** The same, as `bb thread spawn` flags, for the worker command a wake shows. */ - const environmentFlags = (hostId: string | null) => (hostId === null ? "" : `--environment-provider ${MULTI_REPO_ENVIRONMENT_PROVIDER_ID} --machine ${hostId}`); + const environmentFlags = (source: ProjectSource | null, hostId: string | null): string => + source === null ? multiRepoEnvironmentFlags(hostId) : source.environmentFlags(hostId); /** The project's name in bb, or "" when bb cannot say. */ const projectName = (projectId: string): Promise => @@ -1969,7 +2070,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const sectionId = await projectSection(config.projectId); const thread = await bb.sdk.threads.spawn({ projectId: config.projectId, - environment: freshEnvironment(await projectHost(config.projectId)), + environment: freshEnvironment(config.source, await projectHost(config.projectId)), prompt: PROJECT_STEWARD_INTRO, title, ...modelArgs(config.file.projectSteward.model ?? null), @@ -2063,11 +2164,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }; let thread: { id: string }; try { - thread = await bb.sdk.threads.spawn({ ...base, environment: env === null ? freshEnvironment(await projectHost(b.projectId)) : { type: "reuse", environmentId: env } }); + thread = await bb.sdk.threads.spawn({ ...base, environment: env === null ? freshEnvironment(config.source, await projectHost(b.projectId)) : { type: "reuse", environmentId: env } }); } catch (error) { if (env === null) throw error; bb.log.warn(`stewards: could not share the project steward's environment for ${b.entityKey} (${errorMessage(error)}); giving it its own`); - thread = await bb.sdk.threads.spawn({ ...base, environment: freshEnvironment(await projectHost(b.projectId)) }); + thread = await bb.sdk.threads.spawn({ ...base, environment: freshEnvironment(config.source, await projectHost(b.projectId)) }); } tagged.add(thread.id); kept.add(thread.id); @@ -2121,7 +2222,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const sectionId = await projectSection(b.projectId); const thread = await bb.sdk.threads.spawn({ projectId: b.projectId, - environment: freshEnvironment(hostId), + environment: freshEnvironment(config?.source ?? null, hostId), prompt: requesterPrompt(b, need, writeEnv), title, ...modelArgs(model), @@ -2259,7 +2360,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P workers: store.workers(b.id), workerQuestions, children: store.children(b.id).map((c) => ({ binding: c, openEscalations: store.openEscalations(c.id) })), - workerFlags: [environmentFlags(await projectHost(b.projectId)), workerFlags(workerModel(b, playbook))].filter((f) => f !== "").join(" "), + workerFlags: [environmentFlags(config.source, await projectHost(b.projectId)), workerFlags(workerModel(b, playbook))].filter((f) => f !== "").join(" "), sectionId: await projectSection(b.projectId), changes, needs: store.openNeeds(b.id), @@ -3678,22 +3779,21 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } /** - * The primary repo a lesson's pull request opens on, from multi-repo's repo - * set. - * - * TODO(BB-107): when stewards has a native git project source, this must - * read the primary repo from that seam instead, and the publish in - * `workspace_publish_guidance` must be replaced by the native handler. Until - * BB-107 lands, a project with no multi-repo reports the lesson PR refused - * rather than opening one; the branch push is multi-repo's. + * The primary repo a lesson's pull request opens on, from the project's + * chosen source (BB-107): multi-repo's repo set, or native git's checkout + * `origin`. A native project can open the pull request the same way once + * its `guidance-` branch is published; the branch push itself is + * still multi-repo's `workspace_publish_guidance`. */ async function lessonRepo(projectId: string): Promise<{ repo: string } | { error: string }> { - let set: z.infer; + const config = await loadConfig(projectId); + if (config === null) return { error: "the project has no readable configuration to read its primary repo from" }; + let set: Awaited>; try { - set = await rpc(MULTI_REPO_PLUGIN_ID, "repoSet", { projectId }, repoSetOutput); + set = await config.source.repoSet(); } catch (error) { bb.log.warn(`stewards: could not read the repo set for a lesson pull request: ${errorMessage(error)}`); - return { error: "could not read the project's primary repo; is multi-repo installed?" }; + return { error: "could not read the project's primary repo" }; } if (set.primary === null) return { error: "the project source has no origin to open a lesson pull request on" }; const repo = githubRepoOf(set.primary.url); @@ -3925,7 +4025,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // failure — must not stop every other lesson being checked. let content: string | null = null; try { - content = (await readFiles(config.projectId, [lesson.file])).get(lesson.file) ?? null; + content = (await config.source.readFiles([lesson.file])).get(lesson.file) ?? null; } catch (error) { bb.log.warn(`stewards: could not read lesson ${lesson.id}'s file ${lesson.file}: ${errorMessage(error)}`); continue; @@ -4782,12 +4882,13 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } async function validateWorkerSpawn(thread: { id: string; providerId: string }, owner: Binding): Promise { const config = await loadConfig(owner.projectId); - const playbook = config === null ? null : bindingPlaybook(config, owner); + if (config === null) return; + const playbook = bindingPlaybook(config, owner); if (playbook === null || playbook.kind === "ops") return; const expected = workerModel(owner, playbook); if (expected === null) return; const hostId = await projectHost(owner.projectId); - const expectedEnv = hostId === null ? null : MULTI_REPO_ENVIRONMENT_PROVIDER_ID; + const expectedEnv = config.source.kind === "native" || hostId === null ? null : MULTI_REPO_ENVIRONMENT_PROVIDER_ID; // undefined means "could not read it": validate what is known, never // stop a worker over a fact the plugin could not observe. let actualModel: string | null = null; @@ -4821,7 +4922,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return; } store.setWorkerModelCheckPending(thread.id, false); - const flags = [environmentFlags(hostId), workerFlags(expected)].filter((f) => f !== "").join(" "); + const flags = [environmentFlags(config.source, hostId), workerFlags(expected)].filter((f) => f !== "").join(" "); store.setWorker(thread.id, "stopped", `Started with the wrong ${problems.join(", ")}; stopped.`); await quietly(`stop mis-spawned worker ${thread.id}`, () => bb.sdk.threads.stop({ threadId: thread.id })); bb.log.warn(`stewards: stopped worker ${thread.id}: ${problems.join(", ")}`); @@ -5321,6 +5422,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P projectId, name: named.get(projectId) ?? projectId, configured: config !== null, + source: config?.source.kind ?? null, label: config?.file.label ?? null, linearTeams: config?.file.linear.teams ?? [], repos: config?.repos ?? [], @@ -5935,7 +6037,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ].join("\n"); } const hostId = cachedProjectHost(b.projectId); - const flags = hostId === undefined ? null : [environmentFlags(hostId), workerFlags(workerModel(b, playbook))].filter((f) => f !== "").join(" "); + const flags = hostId === undefined ? null : [environmentFlags(config?.source ?? null, hostId), workerFlags(workerModel(b, playbook))].filter((f) => f !== "").join(" "); const cachedSection = sectionCache.get(b.projectId); const sectionId = cachedSection === undefined ? store.project(b.projectId).sectionId : cachedSection; return formatBrief( @@ -7306,15 +7408,16 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return own; } - /** The worker spawn flags for a binding: the project's environment first, then the playbook's worker model. */ - async function workerFlagsFor(b: Binding, playbook: Playbook): Promise { - return [environmentFlags(await projectHost(b.projectId)), workerFlags(workerModel(b, playbook))].filter((f) => f !== "").join(" "); + /** The worker spawn flags for a binding: the project source's environment first, then the playbook's worker model. */ + async function workerFlagsFor(b: Binding, playbook: Playbook, source: ProjectSource | null): Promise { + return [environmentFlags(source, await projectHost(b.projectId)), workerFlags(workerModel(b, playbook))].filter((f) => f !== "").join(" "); } async function check(projectId: string): Promise<{ ok: boolean; lines: string[] }> { const config = await loadConfig(projectId, true); if (config === null) return { ok: false, lines: [`No ${PROJECT_FILE} on the project's .bb (committed HEAD). Run bb stewards init.`] }; const lines: string[] = [...config.problems.map((p) => `problem: ${p}`)]; + lines.push(`Project source: ${projectSourceLabel(config.source.kind)}`); const ticket = config.playbooks.ticket; lines.push(`Linear teams: ${config.file.linear.teams.join(", ") || "(none)"}; repos: ${config.repos.join(", ") || "(none)"}${config.file.github.exclude.length > 0 ? ` (excluded: ${config.file.github.exclude.join(", ")})` : ""}; label ${config.file.label}`); lines.push( @@ -7452,7 +7555,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (config === null || playbook === null) throw new PluginCliError(`No playbook for ${b.entityKey}: run bb stewards check.`, { code: "playbook_missing" }); return { exitCode: 0, - stdout: formatBrief({ binding: b, playbook, gate: briefGate(b, playbook), workerFlags: await workerFlagsFor(b, playbook), sectionId: await projectSection(b.projectId), escalations: store.openEscalations(b.id), conflicts: conflictsOf(b, store.open(b.projectId)) }), + stdout: formatBrief({ binding: b, playbook, gate: briefGate(b, playbook), workerFlags: await workerFlagsFor(b, playbook, config.source), sectionId: await projectSection(b.projectId), escalations: store.openEscalations(b.id), conflicts: conflictsOf(b, store.open(b.projectId)) }), }; }, }), @@ -7467,7 +7570,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const config = await loadConfig(b.projectId); const playbook = config === null ? null : bindingPlaybook(config, b); if (config === null || playbook === null) throw new PluginCliError(`No playbook for ${b.entityKey}: run bb stewards check.`, { code: "playbook_missing" }); - return { exitCode: 0, stdout: spawnCommand({ projectId: b.projectId, entityKey: b.entityKey, workerFlags: await workerFlagsFor(b, playbook), sectionId: await projectSection(b.projectId) }) }; + return { exitCode: 0, stdout: spawnCommand({ projectId: b.projectId, entityKey: b.entityKey, workerFlags: await workerFlagsFor(b, playbook, config.source), sectionId: await projectSection(b.projectId) }) }; }, }), @@ -7569,9 +7672,10 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P options: { project: PROJECT_OPTION, json: JSON_OPTION }, async run(input, ctx) { const b = bindingOrThrow(input.positionals.key, input.options.project ?? ctx.projectId); + const config = await loadConfig(b.projectId); const detail = { binding: b, escalations: store.escalations(b.id), needs: store.needs(b.id, true), workers: store.workers(b.id), children: store.children(b.id).map((c) => c.entityKey), fingerprints: store.fingerprints(b.id) }; - if (input.options.json) return { exitCode: 0, stdout: JSON.stringify(detail) }; - const lines = [formatBindings([b]), "", `Playbook ${b.playbook}@${b.playbookVersion}; stage ${b.stage ?? "?"}; created ${iso(b.createdAt)}${b.requeueAt === null ? "" : `; requeue ${iso(b.requeueAt)}`}`]; + if (input.options.json) return { exitCode: 0, stdout: JSON.stringify({ ...detail, projectSource: config?.source.kind ?? null }) }; + const lines = [formatBindings([b]), "", `Project source: ${projectSourceLabel(config?.source.kind ?? null)}`, `Playbook ${b.playbook}@${b.playbookVersion}; stage ${b.stage ?? "?"}; created ${iso(b.createdAt)}${b.requeueAt === null ? "" : `; requeue ${iso(b.requeueAt)}`}`]; if (b.kind !== "ops") lines.push(`Ready: ${b.ready.checklist.map((c) => `[${c.met ? "x" : " "}] ${c.item}`).join("; ") || "not reported"}; substantial ${b.ready.substantial ?? "?"}; approval ${b.ready.approval === null ? "none" : iso(b.ready.approval.at)}`); if (b.kind !== "ops") { const conflicts = conflictsOf(b, store.open(b.projectId)); diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index 60912c5b..22c9eb73 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -382,8 +382,14 @@ owner never reaches you until the owner confirms it by id. ## Setting up a project (`bb stewards …`) -The project must be a multi-repo project: configuration is read from its -`.bb` repo, committed HEAD only. +Configuration is read from the project's `.bb` at the default branch's +committed tip only. With the multi-repo plugin installed that is the +canonical checkout's committed `HEAD`; without it, stewards falls back to a +native git read of `.bb` from the checkout's `origin/`, and spawns +workers on bb's own `project-default` environment. `bb stewards check` and +`bb stewards show` name the source in use. The worker spawn command always +comes from `bb stewards spawn-flags` (or the wake): never hand-write an +`--environment-provider`. 1. From a thread in the project: `bb stewards init` writes `.bb/stewards/project.json` (Linear teams you belong to, or `--teams From e8e3f961023b978a73fe70059509bb876db39a0d Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Wed, 28 Oct 2026 21:39:38 +0000 Subject: [PATCH 2/3] stewards: review round 1 fixes (BB-107) - project-git.test.ts: give every test commit a git identity (CI has none). - project-git.ts: throttle the native fetch to once per minute, name an oversized file instead of a bare git error, and keep the other files. - server.ts: qualify the workspace_publish_guidance guidance for native projects, where the tool does not exist. --- plugins/stewards/project-git.test.ts | 23 ++++++++++++- plugins/stewards/project-git.ts | 50 ++++++++++++++++++++++++---- plugins/stewards/server.ts | 6 ++-- 3 files changed, 68 insertions(+), 11 deletions(-) diff --git a/plugins/stewards/project-git.test.ts b/plugins/stewards/project-git.test.ts index 66d34475..c0d4e420 100644 --- a/plugins/stewards/project-git.test.ts +++ b/plugins/stewards/project-git.test.ts @@ -10,7 +10,13 @@ import { readProjectGit } from "./project-git.js"; const roots: string[] = []; -const git = (cwd: string, ...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }); +const git = (cwd: string, ...args: string[]) => + execFileSync("git", args, { + cwd, + encoding: "utf8", + // A CI runner has no global git identity; every commit in these tests gets one. + env: { ...process.env, GIT_AUTHOR_NAME: "Test", GIT_AUTHOR_EMAIL: "test@example.com", GIT_COMMITTER_NAME: "Test", GIT_COMMITTER_EMAIL: "test@example.com" }, + }); async function tempRoot(): Promise { const dir = await mkdtemp(path.join(tmpdir(), "bb-stewards-git-")); @@ -81,6 +87,8 @@ describe("the native git project source", () => { const { origin, checkout } = await world(); const standalone = path.join(path.dirname(checkout), "standalone"); git(path.dirname(checkout), "clone", "--quiet", origin, standalone); + git(standalone, "config", "user.email", "test@example.com"); + git(standalone, "config", "user.name", "Test"); // A standalone checkout keeps the definition at the root instead of `.bb/`. await rm(path.join(standalone, ".bb"), { recursive: true, force: true }); await mkdir(path.join(standalone, "stewards"), { recursive: true }); @@ -102,4 +110,17 @@ describe("the native git project source", () => { expect(read.error).toMatch(/not a project file path/u); expect(read.files).toEqual([]); }); + + it("names an oversized file instead of returning a bare git error", async () => { + const { checkout } = await world(); + await writeFile(path.join(checkout, ".bb", "stewards", "big.json"), "x".repeat(700_000), "utf8"); + git(checkout, "add", "-A"); + git(checkout, "commit", "--quiet", "-m", "big"); + git(checkout, "push", "--quiet", "origin", "main"); + const read = await readProjectGit({ path: checkout, files: ["stewards/project.json", "stewards/big.json"] }); + expect(read.error).toMatch(/Larger than 200000 characters, so not read: stewards\/big\.json/u); + const byPath = new Map(read.files.map((f) => [f.path, f.content])); + expect(byPath.get("stewards/big.json")).toBeNull(); + expect(byPath.get("stewards/project.json")).not.toBeNull(); + }); }); diff --git a/plugins/stewards/project-git.ts b/plugins/stewards/project-git.ts index 8a8101c1..77509f40 100644 --- a/plugins/stewards/project-git.ts +++ b/plugins/stewards/project-git.ts @@ -13,6 +13,8 @@ // file name can never become an option. Paths are validated again here even // though the host contract already checks them: this is the boundary. import { execFile } from "node:child_process"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; import { experimental_sanitizeInheritedChildProcessEnv } from "@get-bb/plugin-sdk/host"; import type { NativeGitRead, ProjectGitFile } from "./project-source.js"; @@ -22,23 +24,28 @@ const MAX_OUTPUT_BYTES = 16 * 1024 * 1024; const MAX_FILE_CHARS = 200_000; const REGULAR_FILE_MODES = new Set(["100644", "100755"]); const SAFE_PATH = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/u; +/** One config load makes several reads; only the first fetches within this window. */ +const FETCH_TTL_MS = 60_000; +const FETCH_MARKER = ".git/bb-stewards-fetched-at"; type GitRun = { code: number; stdout: string; stderr: string; truncated: boolean }; function runGit(dir: string, args: string[], opts: { timeoutMs?: number; maxBytes?: number } = {}): Promise { + const maxBytes = opts.maxBytes ?? MAX_OUTPUT_BYTES; return new Promise((resolve) => { execFile( "git", ["-C", dir, ...args], { timeout: opts.timeoutMs ?? GIT_TIMEOUT_MS, - maxBuffer: opts.maxBytes ?? MAX_OUTPUT_BYTES, + maxBuffer: maxBytes, env: { ...experimental_sanitizeInheritedChildProcessEnv({ env: process.env }), NO_COLOR: "1", GIT_TERMINAL_PROMPT: "0" }, windowsHide: true, }, (error, stdout, stderr) => { const e = error as (Omit & { code?: string | number; killed?: boolean }) | null; if (e?.code === "ENOENT") return resolve({ code: 127, stdout: "", stderr: "git: not found", truncated: false }); + if (e?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") return resolve({ code: 1, stdout: "", stderr: `git output exceeded ${maxBytes} bytes`, truncated: true }); const exitCode = e === null ? 0 : typeof e.code === "number" ? e.code : 1; resolve({ code: exitCode, stdout: String(stdout), stderr: e !== null && e.killed ? `git did not finish in ${(opts.timeoutMs ?? GIT_TIMEOUT_MS) / 1000}s` : String(stderr), truncated: false }); }, @@ -54,6 +61,20 @@ async function gitLine(dir: string, args: string[]): Promise { const firstProblemLine = (r: GitRun): string => r.stderr.split(/\r?\n/u).map((l) => l.trim()).find((l) => l !== "") ?? `git exited ${r.code}`; +/** + * Fetch `origin`, at most once per {@link FETCH_TTL_MS}, and return the run + * (null when the TTL skipped it). A failed fetch still reads the last fetched + * commit, and does not mark the window, so the next call retries. + */ +async function fetchOrigin(dir: string): Promise { + const marker = join(dir, FETCH_MARKER); + const last = await readFile(marker, "utf8").then((raw) => Number.parseInt(raw.trim(), 10), () => Number.NaN); + if (Number.isFinite(last) && Date.now() - last < FETCH_TTL_MS) return null; + const fetched = await runGit(dir, ["fetch", "--quiet", "origin"]); + if (fetched.code === 0) await writeFile(marker, String(Date.now()), "utf8").catch(() => undefined); + return fetched; +} + async function refExists(dir: string, ref: string): Promise { const r = await runGit(dir, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]); return r.code === 0 && r.stdout.trim() !== ""; @@ -107,15 +128,16 @@ export async function readProjectGit(input: { path: string; files: readonly stri if (problem !== null) return { head: null, files: [], remote: null, defaultBranch: null, layout: "primary", error: problem }; } const remote = await gitLine(dir, ["config", "--get", "remote.origin.url"]); - const fetched = await runGit(dir, ["fetch", "--quiet", "origin"]); + const fetched = await fetchOrigin(dir); const branch = await originDefaultBranch(dir); if (branch === null) { - return { head: null, files: [], remote, defaultBranch: null, layout: "primary", error: fetched.code === 0 ? `${dir} has no origin default branch to read.` : `Could not fetch the project source: ${firstProblemLine(fetched)}` }; + const why = fetched === null || fetched.code === 0 ? `${dir} has no origin default branch to read.` : `Could not fetch the project source: ${firstProblemLine(fetched)}`; + return { head: null, files: [], remote, defaultBranch: null, layout: "primary", error: why }; } const ref = `refs/remotes/origin/${branch}`; const head = await gitLine(dir, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]); if (head === null) { - return { head: null, files: [], remote, defaultBranch: branch, layout: "primary", error: `Could not fetch the project source: ${firstProblemLine(fetched)}` }; + return { head: null, files: [], remote, defaultBranch: branch, layout: "primary", error: `Could not fetch the project source: ${fetched === null ? "no commit on origin's default branch" : firstProblemLine(fetched)}` }; } const prefix = await definitionPrefix(dir, head); const layout = prefix === "" ? ("standalone" as const) : ("primary" as const); @@ -133,6 +155,7 @@ export async function readProjectGit(input: { path: string; files: readonly stri } const files: ProjectGitFile[] = []; + const tooLarge: string[] = []; for (const file of input.files) { const object = blobs.get(`${prefix}${file}`); if (object === undefined) { @@ -140,8 +163,21 @@ export async function readProjectGit(input: { path: string; files: readonly stri continue; } const read = await runGit(dir, ["cat-file", "blob", object], { maxBytes: MAX_FILE_CHARS * 3 + 1 }); - if (read.code !== 0) return { head, files: [], remote, defaultBranch: branch, layout, error: firstProblemLine(read) }; - files.push({ path: file, content: read.stdout.length > MAX_FILE_CHARS ? null : read.stdout }); + if (read.code !== 0) { + if (read.truncated) { + tooLarge.push(file); + files.push({ path: file, content: null }); + continue; + } + return { head, files: [], remote, defaultBranch: branch, layout, error: firstProblemLine(read) }; + } + if (read.stdout.length > MAX_FILE_CHARS) { + tooLarge.push(file); + files.push({ path: file, content: null }); + continue; + } + files.push({ path: file, content: read.stdout }); } - return { head, files, remote, defaultBranch: branch, layout, error: null }; + const error = tooLarge.length === 0 ? null : `Larger than ${MAX_FILE_CHARS} characters, so not read: ${tooLarge.join(", ")}`; + return { head, files, remote, defaultBranch: branch, layout, error }; } diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 136456a5..c0607bff 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -6721,7 +6721,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const cluster = lessonClusterFor(bindingId, escalationId); const lesson = store.addLesson({ projectId: projectOf!, bindingId, escalationId, file: input.lesson!.file, text: input.lesson!.text, scope: input.lesson!.scope, branch, ...(cluster === null ? {} : { clusterKey: cluster }), ...(input.lesson!.supersedes === undefined ? {} : { supersedes: input.lesson!.supersedes }) }); if (cluster !== null) store.settleClusterRationale(projectOf!, cluster); - 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" } }`; + 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 it with workspace_publish_guidance on a multi-repo project (on a native project, commit and open the pull request yourself), then complete it with steward_update { lessonAction: { id: "${lesson.id}", action: "complete" } }`; }; if (projectOf !== null && resolve?.startsWith("qst_") === true) { const q = store.question(resolve); @@ -7505,7 +7505,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P init: cliCommand({ summary: "Write stewards/project.json and the default playbooks into a .bb checkout", description: - "Run from a thread in a multi-repo workspace: writes into /.bb on the thread's machine unless --dir is given. Existing files are left alone unless --force. Then commit inside .bb and publish it (workspace_publish_guidance); stewards reads committed HEAD only.", + "Run from a thread in a project workspace: writes into /.bb on the thread's machine unless --dir is given. Existing files are left alone unless --force. Then commit inside .bb and publish it (workspace_publish_guidance on a multi-repo project; on a native project, commit and merge the guidance branch yourself); stewards reads committed HEAD only.", options: { teams: { type: "string", description: "Linear team keys, comma-separated; the teams you belong to when left out" }, dir: { type: "string", description: "The .bb directory to write into" }, @@ -7535,7 +7535,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const result = (await bb.sdk.files.write({ path, content, ...(input.options.force ? {} : { expectedSha256: null }), ...(hostId === undefined ? {} : { hostId }) } as never)) as { outcome: string }; lines.push(`${result.outcome === "written" ? "wrote" : "kept existing"} ${rel}`); } - lines.push("", `Teams: ${teams.join(", ") || "(none; add them to linear.teams)"}`, "Next: review the files, commit inside .bb, publish with workspace_publish_guidance, merge the guidance branch, then run bb stewards check."); + lines.push("", `Teams: ${teams.join(", ") || "(none; add them to linear.teams)"}`, "Next: review the files, commit inside .bb, publish with workspace_publish_guidance (multi-repo) or open the guidance pull request yourself (native), merge the guidance branch, then run bb stewards check."); return { exitCode: 0, stdout: lines.join("\n") }; }, }), From 12eefbdbb5eec710569a0b8e800b671a6d9e7060 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Wed, 28 Oct 2026 21:46:19 +0000 Subject: [PATCH 3/3] stewards: keep the native fetch throttle out of the checkout (BB-107) Move the fetch TTL to the server-side seam: the host handler takes a fetch flag and writes nothing of its own, so the checkout stays untouched (and a linked worktree's .git file no longer silently disables the throttle). Surface a host read error through the native source as a problem line, and test the no-fetch read adds no file to the checkout. --- plugins/stewards/host-contract.ts | 2 +- plugins/stewards/host.ts | 2 +- plugins/stewards/project-git.test.ts | 9 ++++++++ plugins/stewards/project-git.ts | 34 ++++++++-------------------- plugins/stewards/server.test.ts | 33 +++++++++++++++++++++++---- plugins/stewards/server.ts | 19 ++++++++++++---- 6 files changed, 63 insertions(+), 36 deletions(-) diff --git a/plugins/stewards/host-contract.ts b/plugins/stewards/host-contract.ts index ff4212e1..38b5c829 100644 --- a/plugins/stewards/host-contract.ts +++ b/plugins/stewards/host-contract.ts @@ -14,7 +14,7 @@ export const hostContract = defineRpcContract({ output: z.object({ exitCode: z.number().int(), stdout: z.string(), stderr: z.string(), missing: z.boolean() }).strict(), }, gitProjectFiles: { - input: z.object({ path: z.string().min(1).max(2000), files: z.array(projectFilePath).max(64) }).strict(), + input: z.object({ path: z.string().min(1).max(2000), files: z.array(projectFilePath).max(64), fetch: z.boolean().default(true) }).strict(), output: z .object({ head: z.string().max(64).nullable(), diff --git a/plugins/stewards/host.ts b/plugins/stewards/host.ts index 34c3381e..f3c51a76 100644 --- a/plugins/stewards/host.ts +++ b/plugins/stewards/host.ts @@ -34,6 +34,6 @@ export default experimental_defineHostEntry({ contract: hostContract, handlers: { opsKubectl: ({ args, timeoutMs }) => runKubectlHere(args, timeoutMs), - gitProjectFiles: ({ path, files }) => readProjectGit({ path, files }), + gitProjectFiles: ({ path, files, fetch }) => readProjectGit({ path, files, fetch }), }, }); diff --git a/plugins/stewards/project-git.test.ts b/plugins/stewards/project-git.test.ts index c0d4e420..30fb4af1 100644 --- a/plugins/stewards/project-git.test.ts +++ b/plugins/stewards/project-git.test.ts @@ -83,6 +83,15 @@ describe("the native git project source", () => { expect(await readFile(path.join(checkout, ".bb", "stewards", "project.json"), "utf8")).toContain("dirty"); }); + it("adds nothing at all to the checkout when it does not fetch", async () => { + const { checkout } = await world(); + const listing = () => execFileSync("find", [checkout, "-type", "f"], { encoding: "utf8" }).trim().split("\n").filter(Boolean).sort(); + const before = listing(); + const read = await readProjectGit({ path: checkout, files: ["stewards/project.json"], fetch: false }); + expect(read.error).toBeNull(); + expect(listing()).toEqual(before); + }); + it("reads a standalone .bb checkout at its root, and reports its origin", async () => { const { origin, checkout } = await world(); const standalone = path.join(path.dirname(checkout), "standalone"); diff --git a/plugins/stewards/project-git.ts b/plugins/stewards/project-git.ts index 77509f40..10b4e19d 100644 --- a/plugins/stewards/project-git.ts +++ b/plugins/stewards/project-git.ts @@ -7,14 +7,13 @@ // someone is halfway through there is not the project's. `git fetch` is the // only command that changes anything, and it changes only remote-tracking // refs; nothing here checks out, resets, stashes, commits or writes the -// working tree or a local branch. +// working tree or a local branch, and this handler leaves no state of its own +// in the checkout (the caller throttles the fetch). // // Every path is a fixed argument from the plugin, passed after `--`, so a // file name can never become an option. Paths are validated again here even // though the host contract already checks them: this is the boundary. import { execFile } from "node:child_process"; -import { readFile, writeFile } from "node:fs/promises"; -import { join } from "node:path"; import { experimental_sanitizeInheritedChildProcessEnv } from "@get-bb/plugin-sdk/host"; import type { NativeGitRead, ProjectGitFile } from "./project-source.js"; @@ -24,9 +23,6 @@ const MAX_OUTPUT_BYTES = 16 * 1024 * 1024; const MAX_FILE_CHARS = 200_000; const REGULAR_FILE_MODES = new Set(["100644", "100755"]); const SAFE_PATH = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/u; -/** One config load makes several reads; only the first fetches within this window. */ -const FETCH_TTL_MS = 60_000; -const FETCH_MARKER = ".git/bb-stewards-fetched-at"; type GitRun = { code: number; stdout: string; stderr: string; truncated: boolean }; @@ -61,20 +57,6 @@ async function gitLine(dir: string, args: string[]): Promise { const firstProblemLine = (r: GitRun): string => r.stderr.split(/\r?\n/u).map((l) => l.trim()).find((l) => l !== "") ?? `git exited ${r.code}`; -/** - * Fetch `origin`, at most once per {@link FETCH_TTL_MS}, and return the run - * (null when the TTL skipped it). A failed fetch still reads the last fetched - * commit, and does not mark the window, so the next call retries. - */ -async function fetchOrigin(dir: string): Promise { - const marker = join(dir, FETCH_MARKER); - const last = await readFile(marker, "utf8").then((raw) => Number.parseInt(raw.trim(), 10), () => Number.NaN); - if (Number.isFinite(last) && Date.now() - last < FETCH_TTL_MS) return null; - const fetched = await runGit(dir, ["fetch", "--quiet", "origin"]); - if (fetched.code === 0) await writeFile(marker, String(Date.now()), "utf8").catch(() => undefined); - return fetched; -} - async function refExists(dir: string, ref: string): Promise { const r = await runGit(dir, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]); return r.code === 0 && r.stdout.trim() !== ""; @@ -117,18 +99,20 @@ export function projectGitPathProblem(path: string): string | null { /** * Read the named files out of the project checkout's `origin/` at - * its committed tip. A fetch is attempted first; a fetch that fails (no - * network, no remote) still reads the last fetched commit rather than - * failing the read. The working tree and every local branch are untouched. + * its committed tip. `fetch` (default true) asks for a `git fetch origin` + * first; the caller throttles it, so the checkout gets no plugin-owned state + * of its own. A fetch that fails (no network, no remote) still reads the last + * fetched commit rather than failing the read. The working tree and every + * local branch are untouched. */ -export async function readProjectGit(input: { path: string; files: readonly string[] }): Promise { +export async function readProjectGit(input: { path: string; files: readonly string[]; fetch?: boolean }): Promise { const dir = input.path; for (const file of input.files) { const problem = projectGitPathProblem(file); if (problem !== null) return { head: null, files: [], remote: null, defaultBranch: null, layout: "primary", error: problem }; } const remote = await gitLine(dir, ["config", "--get", "remote.origin.url"]); - const fetched = await fetchOrigin(dir); + const fetched = input.fetch === false ? null : await runGit(dir, ["fetch", "--quiet", "origin"]); const branch = await originDefaultBranch(dir); if (branch === null) { const why = fetched === null || fetched.code === 0 ? `${dir} has no origin default branch to read.` : `Could not fetch the project source: ${firstProblemLine(fetched)}`; diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index a1e08e67..e1b1f54e 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -3771,11 +3771,12 @@ describe("the native project source (BB-107)", () => { /** A world whose multi-repo plugin is missing: native git serves `.bb`, and every multi-repo RPC is a 404. */ const nativeWorld = async (missing = true) => { let files: Record = defaultFiles(); - const gitCalls: Array<{ path: string; hostId: string | null; files: string[] }> = []; + let hostError: string | null = null; + const gitCalls: Array<{ path: string; hostId: string | null; files: string[]; fetch: boolean }> = []; const t = await setup({ - git: async ({ hostId, path, files: paths }) => { - gitCalls.push({ path, hostId, files: paths }); - return { head: "abc", files: paths.map((p) => ({ path: p, content: files[p] ?? null })), remote: "https://github.com/acme/web.git", defaultBranch: "main", layout: "primary" as const, error: null }; + git: async ({ hostId, path, files: paths, fetch }) => { + gitCalls.push({ path, hostId, files: paths, fetch }); + return { head: "abc", files: paths.map((p) => ({ path: p, content: files[p] ?? null })), remote: "https://github.com/acme/web.git", defaultBranch: "main", layout: "primary" as const, error: hostError }; }, }); files = t.files; @@ -3787,7 +3788,7 @@ describe("the native project source (BB-107)", () => { return original(args); }); } - return { t, gitCalls }; + return { t, gitCalls, setHostError: (message: string | null) => (hostError = message) }; }; it("loads from native git when the multi-repo RPC reports unknown plugin", async () => { @@ -3849,6 +3850,28 @@ describe("the native project source (BB-107)", () => { expect((await t.harness.behavior.runCli(["list", "--project", "p1"])).stdout).toContain("ENG-12"); }); + it("fetches once per window and skips the next read's fetch", async () => { + const { t, gitCalls } = await nativeWorld(); + t.advance(2 * 60_000); + gitCalls.length = 0; + await load(t); + expect(gitCalls.some((c) => c.fetch)).toBe(true); + const before = gitCalls.length; + await load(t); + const after = gitCalls.slice(before); + expect(after.length).toBeGreaterThan(0); + expect(after.every((c) => c.fetch === false)).toBe(true); + }); + + it("surfaces a host read error as a problem line", async () => { + const { t, setHostError } = await nativeWorld(); + expect(await load(t)).not.toBeNull(); + setHostError("Larger than 200000 characters, so not read: stewards/big.md"); + const after = await load(t); + expect(after).not.toBeNull(); + expect(after!.problems.some((p) => p.includes("Larger than 200000 characters"))).toBe(true); + }); + it("names the project source in check and the overview, for both sources", async () => { const multi = await setup(); await multi.flush(); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index c0607bff..6823c175 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -168,7 +168,7 @@ export interface StewardsDeps { /** Runs kubectl for ops bindings: on the project's machine, through the host entry, by default. */ kubectl?: (args: string[], where: { projectId: string; hostId: string | null }) => Promise; /** Reads the project's `.bb` from `origin/` for the native source: the host entry by default. */ - git?: (input: { projectId: string; hostId: string | null; path: string; files: string[] }) => Promise; + git?: (input: { projectId: string; hostId: string | null; path: string; files: string[]; fetch: boolean }) => Promise; /** The GitHub writer the page's Approve and Merge buttons use; the server's gh login by default. */ github?: GithubWriter; /** What reads Sentry and subscribes to bb-gate-hooks for it; global fetch by default. */ @@ -234,6 +234,8 @@ const mergeGuidanceOutput = z.object({ ok: z.boolean(), sha: z.string().nullable /** A project checkout fetch can be slow; the git host call is allowed this long. */ const GIT_TIMEOUT_MS = 60_000; +/** One config load makes several native reads; only the first fetches within this window. */ +const NATIVE_FETCH_TTL_MS = 60_000; /** The checkout directory's own name, for a native project's single repo entry. */ const checkoutDirName = (path: string): string => path.replace(/[\\/]+$/u, "").split(/[\\/]/u).filter((part) => part !== "").at(-1) ?? "project"; @@ -983,6 +985,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }); } + /** The last native fetch per project, so one config load's several reads fetch once. */ + const nativeFetchedAt = new Map(); + /** * The git-backed native source for one project. The host entry does the * fetch and the read (project-git.ts), on the checkout's own machine; the @@ -992,16 +997,22 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const run = async (files: string[]): Promise<{ read: NativeGitRead; path: string | null }> => { const checkout = await projectCheckout(projectId); if (checkout === null) return { read: { head: null, files: [], remote: null, defaultBranch: null, layout: "primary", error: null }, path: null }; + const last = nativeFetchedAt.get(projectId) ?? 0; + const fetch = now() - last >= NATIVE_FETCH_TTL_MS; + if (fetch) nativeFetchedAt.set(projectId, now()); const read = deps.git !== undefined - ? await deps.git({ projectId, hostId: checkout.hostId, path: checkout.path, files }) - : await (hostClient ??= bb.hosts.experimental_client({ contract: hostContract })).call("gitProjectFiles", { path: checkout.path, files }, { hostId: checkout.hostId, timeoutMs: GIT_TIMEOUT_MS }); + ? await deps.git({ projectId, hostId: checkout.hostId, path: checkout.path, files, fetch }) + : await (hostClient ??= bb.hosts.experimental_client({ contract: hostContract })).call("gitProjectFiles", { path: checkout.path, files, fetch }, { hostId: checkout.hostId, timeoutMs: GIT_TIMEOUT_MS }); return { read, path: checkout.path }; }; return nativeSource({ readFiles: async (paths) => { const { read } = await run(paths); - if (read.error !== null && read.files.length === 0) throw new Error(read.error); + // The host names a file it could not read (too large, a bad object); + // surface it even when other files came back, so the problem line + // names it instead of a silent missing file. + if (read.error !== null) throw new Error(read.error); return new Map(read.files.map((f) => [f.path, f.content])); }, repoSet: async () => {