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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 14 additions & 4 deletions plugins/stewards/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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-<threadId>` 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-<threadId>` 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/<default>` 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.
Expand Down
6 changes: 4 additions & 2 deletions plugins/stewards/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<default>`
(`project-source.ts`):

```
stewards/
Expand Down
1 change: 1 addition & 0 deletions plugins/stewards/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,7 @@ function ProjectStatus({ project: p, now }: { project: Project; now: number }) {
) : (
<dl className="flex flex-col gap-1">
<Row label="Linear teams">{p.linearTeams.join(", ") || "none"}</Row>
<Row label="Project source">{p.source === null ? "unknown" : p.source === "native" ? "native git (origin's default branch)" : "multi-repo plugin"}</Row>
<Row label="Repos">{p.repos.join(", ") || "none"}</Row>
{p.excludedRepos.length > 0 && <Row label="Excluded">{p.excludedRepos.join(", ")}</Row>}
<Row label="Label">
Expand Down
21 changes: 19 additions & 2 deletions plugins/stewards/host-contract.ts
Original file line number Diff line number Diff line change
@@ -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/<default>` 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), fetch: z.boolean().default(true) }).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(),
},
});
6 changes: 5 additions & 1 deletion plugins/stewards/host.ts
Original file line number Diff line number Diff line change
@@ -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/<default>` 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;
Expand All @@ -31,5 +34,6 @@ export default experimental_defineHostEntry({
contract: hostContract,
handlers: {
opsKubectl: ({ args, timeoutMs }) => runKubectlHere(args, timeoutMs),
gitProjectFiles: ({ path, files, fetch }) => readProjectGit({ path, files, fetch }),
},
});
135 changes: 135 additions & 0 deletions plugins/stewards/project-git.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
// The native project source's git handler (project-git.ts): it must read the
// committed `origin/<default>`, 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",
// 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<string> {
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("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");
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 });
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([]);
});

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();
});
});
Loading
Loading