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
51 changes: 51 additions & 0 deletions plugins/multi-repo/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -489,6 +489,30 @@ export const hostContract = defineRpcContract({
})
.strict(),
},

/**
* Fast-forward the canonical checkout to a thread's published guidance
* branch. The narrow merge a self-merged lesson uses; `source.ts` has the
* refusals. Leaves the branch in place on any refusal.
*/
mergeGuidance: {
input: z
.object({
projectSourcePath: absolutePath,
threadId: z.string().min(1).max(100),
file: projectFilePathSchema,
text: z.string().min(1).max(20_000),
})
.strict(),
output: z
.object({
ok: z.boolean(),
sha: z.string().max(64).nullable(),
branch: z.string().max(300).nullable(),
message: z.string().max(2000),
})
.strict(),
},
});

export type HostContract = typeof hostContract;
Expand Down Expand Up @@ -597,6 +621,33 @@ export const rpcContract = defineRpcContract({
input: z.object({ projectId: z.string().min(1).max(100) }).strict(),
output: repoSetViewSchema,
},
/**
* Fast-forward the canonical `.bb` checkout to a thread's published guidance
* branch. Stewards calls it, and only stewards: a lesson is the one thing
* that writes itself into the guidance every steward reads, and the project
* steward's own tooling is the only thing that may ask for it. `file` and
* `text` are the lesson's own; the host refuses a merge that would change
* anything else.
*/
mergeGuidance: {
input: z
.object({
projectId: z.string().min(1).max(100),
threadId: z.string().min(1).max(100),
file: projectFilePathSchema,
text: z.string().min(1).max(20_000),
})
.strict(),
output: z
.object({
ok: z.boolean(),
sha: z.string().max(64).nullable(),
branch: z.string().max(300).nullable(),
message: z.string().max(2000),
})
.strict(),
},

/**
* Files from the project's `.bb` repo, read from the canonical checkout's
* committed `HEAD` after a fast-forward-only refresh.
Expand Down
11 changes: 11 additions & 0 deletions plugins/multi-repo/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
bootstrapProjectSource,
cloneProjectSource,
defaultProjectSourcePath,
mergeGuidance,
projectSourceBranch,
projectSourceRemote,
pushGuidance,
Expand Down Expand Up @@ -245,6 +246,16 @@ export function createMultiRepoHostEntry() {
context.signal,
);
},

async mergeGuidance(input, context) {
return mergeGuidance(
input.projectSourcePath,
input.threadId,
input.file,
input.text,
context.signal,
);
},
},
});
}
Expand Down
66 changes: 66 additions & 0 deletions plugins/multi-repo/merge-rpc.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/**
* The `mergeGuidance` RPC's caller gate.
*
* The merge itself is git work, tested end to end in `provision.test.ts`
* against real repositories. What is tested here is who may ask for it: only
* the stewards plugin, because a lesson is the one thing that writes itself
* into the guidance every steward reads. A thread or another plugin calling
* the RPC directly is refused before any git runs.
*/
import { createFakePluginHost } from "@get-bb/plugin-sdk/testing";
import { describe, expect, it } from "vitest";
import plugin from "./server.js";

const PROJECT_ID = "proj_1";
const HOST_ID = "host-a";
const SOURCE_PATH = "/checkouts/acme";

const PROJECT = {
id: PROJECT_ID,
kind: "standard",
name: "acme",
gitRemoteUrl: null,
createdAt: 1,
updatedAt: 1,
sources: [{ id: "src_1", projectId: PROJECT_ID, type: "local_path", hostId: HOST_ID, path: SOURCE_PATH, isDefault: true }],
};

async function setup() {
const hostCalls: Array<{ method: string; input: unknown }> = [];
const { bb, harness } = createFakePluginHost({
experimental_callHostRpc: (call: { method: string; input: unknown }) => {
hostCalls.push({ method: call.method, input: call.input });
if (call.method === "mergeGuidance") return { ok: true, sha: "a".repeat(40), branch: "refs/heads/guidance-thr_lesson", message: "merged" };
throw new Error(`unexpected host method ${call.method}`);
},
});
harness.sdk.stub("projects.get", () => PROJECT);
harness.sdk.stub("system.config", () => ({ primaryHostId: HOST_ID }));
await plugin(bb);
return { harness, hostCalls };
}

const input = { projectId: PROJECT_ID, threadId: "thr_lesson", file: "AGENTS.md", text: "A lesson." };

describe("merging a lesson through multi-repo", () => {
it("is refused for a caller that is not the stewards plugin, before any git runs", async () => {
const { harness, hostCalls } = await setup();
const result = (await harness.callRpc("mergeGuidance", input, { experimental_caller: { kind: "plugin", pluginId: "linear" } })) as {
ok: boolean;
message: string;
};
expect(result.ok).toBe(false);
expect(result.message).toMatch(/Only the stewards plugin merges a lesson/u);
expect(hostCalls).toEqual([]);
});

it("runs the host merge when the stewards plugin asks", async () => {
const { harness, hostCalls } = await setup();
const result = (await harness.callRpc("mergeGuidance", input, { experimental_caller: { kind: "plugin", pluginId: "stewards" } })) as {
ok: boolean;
sha: string | null;
};
expect(result).toMatchObject({ ok: true, sha: "a".repeat(40) });
expect(hostCalls).toEqual([{ method: "mergeGuidance", input: { projectSourcePath: SOURCE_PATH, threadId: "thr_lesson", file: "AGENTS.md", text: "A lesson." } }]);
});
});
96 changes: 96 additions & 0 deletions plugins/multi-repo/provision.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
bootstrapProjectSource,
cloneProjectSource,
defaultProjectSourcePath,
mergeGuidance,
pushGuidance,
readCommittedFiles,
readReposJson,
Expand Down Expand Up @@ -466,6 +467,101 @@ describe("the project source", () => {
});
});

describe("merging a published lesson branch", () => {
/** A canonical `.bb` and a clone of it, both with an identity to commit with. */
async function pair() {
const canonical = path.join(scratch, "lesson-canonical");
await mkdir(canonical, { recursive: true });
await bootstrapProjectSource(canonical, EMPTY_REPOS);
await gitIn(canonical, ["config", "user.email", "test@example.invalid"]);
await gitIn(canonical, ["config", "user.name", "Test"]);
const workspaceBb = path.join(scratch, "lesson-workspace");
await git(["clone", "--quiet", canonical, workspaceBb]);
await gitIn(workspaceBb, ["config", "user.email", "test@example.invalid"]);
await gitIn(workspaceBb, ["config", "user.name", "Test"]);
return { canonical, workspaceBb };
}

/** Append `text` to `file` in the workspace and commit it. */
async function append(workspaceBb: string, file: string, text: string): Promise<void> {
const current = await readFile(path.join(workspaceBb, file), "utf8");
await writeFile(path.join(workspaceBb, file), `${current}\n${text}\n`, "utf8");
await gitIn(workspaceBb, ["add", "--", file]);
await gitIn(workspaceBb, ["commit", "--quiet", "-m", "record a lesson"]);
}

const lesson = "A new column read with SELECT * breaks the previous image.";

it("fast-forwards the canonical checkout to the lesson's own file, and returns the sha", async () => {
const { canonical, workspaceBb } = await pair();
await append(workspaceBb, "AGENTS.md", lesson);
await pushGuidance(canonical, workspaceBb, "thr_lesson");

const result = await mergeGuidance(canonical, "thr_lesson", "AGENTS.md", lesson);
expect(result).toMatchObject({ ok: true, branch: "refs/heads/guidance-thr_lesson" });
expect(result.sha).toBe(await gitLine(workspaceBb, ["rev-parse", "HEAD"]));
expect(await gitLine(canonical, ["rev-parse", "HEAD"])).toBe(result.sha);
expect(await readFile(path.join(canonical, "AGENTS.md"), "utf8")).toContain(lesson);
});

it("refuses a dirty canonical checkout and leaves the branch", async () => {
const { canonical, workspaceBb } = await pair();
await append(workspaceBb, "AGENTS.md", lesson);
await pushGuidance(canonical, workspaceBb, "thr_lesson");
await writeFile(path.join(canonical, "AGENTS.md"), "half-written by hand\n", "utf8");

const result = await mergeGuidance(canonical, "thr_lesson", "AGENTS.md", lesson);
expect(result.ok).toBe(false);
expect(result.message).toMatch(/uncommitted changes/u);
// The branch is exactly where it was published: nothing was merged.
expect(await gitLine(canonical, ["rev-parse", "guidance-thr_lesson"])).toBe(await gitLine(workspaceBb, ["rev-parse", "HEAD"]));
expect(await readFile(path.join(canonical, "AGENTS.md"), "utf8")).toBe("half-written by hand\n");
});

it("refuses a non-fast-forward", async () => {
const { canonical, workspaceBb } = await pair();
// The canonical branch moves on after the workspace branched: the
// workspace's commit is no longer a descendant.
await writeFile(path.join(canonical, "canonical-only.md"), "moved on\n", "utf8");
await gitIn(canonical, ["add", "--", "canonical-only.md"]);
await gitIn(canonical, ["commit", "--quiet", "-m", "canonical moves on"]);
await append(workspaceBb, "AGENTS.md", lesson);
await pushGuidance(canonical, workspaceBb, "thr_lesson");

const result = await mergeGuidance(canonical, "thr_lesson", "AGENTS.md", lesson);
expect(result.ok).toBe(false);
expect(result.message).toMatch(/not a fast-forward/u);
});

it("refuses a commit range that changes anything but the lesson's file", async () => {
const { canonical, workspaceBb } = await pair();
await append(workspaceBb, "AGENTS.md", lesson);
await append(workspaceBb, "repos.json", "// unrelated\n");
await pushGuidance(canonical, workspaceBb, "thr_lesson");

const result = await mergeGuidance(canonical, "thr_lesson", "AGENTS.md", lesson);
expect(result.ok).toBe(false);
expect(result.message).toMatch(/changes files other than AGENTS\.md: repos\.json/u);
});

it("refuses a file that does not carry the lesson text", async () => {
const { canonical, workspaceBb } = await pair();
await append(workspaceBb, "AGENTS.md", "Something else entirely.");
await pushGuidance(canonical, workspaceBb, "thr_lesson");

const result = await mergeGuidance(canonical, "thr_lesson", "AGENTS.md", lesson);
expect(result.ok).toBe(false);
expect(result.message).toMatch(/does not carry the lesson text/u);
});

it("refuses when nothing has been published", async () => {
const { canonical } = await pair();
const result = await mergeGuidance(canonical, "thr_lesson", "AGENTS.md", lesson);
expect(result.ok).toBe(false);
expect(result.message).toMatch(/No guidance branch refs\/heads\/guidance-thr_lesson has been published/u);
});
});

describe("reading project files for another plugin", () => {
async function canonicalWithPlaybook() {
const dir = await makeRemote("canonical");
Expand Down
28 changes: 28 additions & 0 deletions plugins/multi-repo/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1318,6 +1318,34 @@ export default async function multiRepoPlugin(bb: BbPluginApi): Promise<void> {
}
},

/**
* Fast-forward the canonical `.bb` to a thread's published guidance
* branch. Only the stewards plugin may ask: the project steward's lesson
* tooling is the one thing that writes itself into every steward's
* guidance, and a `procedure` lesson is the only thing it may write.
*/
async mergeGuidance({ projectId, threadId, file, text }, { experimental_caller: caller }) {
if (caller.kind !== "plugin" || caller.pluginId !== "stewards") {
return { ok: false, sha: null, branch: null, message: "Only the stewards plugin merges a lesson." };
}
let location: SourceLocation | null;
try {
location = await projectSource(projectId);
} catch (error) {
return { ok: false, sha: null, branch: null, message: errorMessage(error) };
}
if (location === null) return { ok: false, sha: null, branch: null, message: "This project has no .bb checkout on any machine." };
try {
return await host.call(
"mergeGuidance",
{ projectSourcePath: location.path, threadId, file, text },
{ hostId: location.hostId, timeoutMs: ACTION_TIMEOUT_MS },
);
} catch (error) {
return { ok: false, sha: null, branch: null, message: errorMessage(error) };
}
},

async saveRepoSet({ projectId, reposJson }) {
const location = await projectSource(projectId);
if (location === null) return { ok: false, error: "This project has no checkout on any machine." };
Expand Down
75 changes: 75 additions & 0 deletions plugins/multi-repo/source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -415,3 +415,78 @@ export async function pushGuidance(
message: `Published ${head.slice(0, 8)} to ${ref} in ${projectSourcePath}. Merge it there when you are happy with it.`,
};
}

/** The `guidance-<thread>` ref a thread's published commits land on. */
export function guidanceRef(threadId: string): string {
const safeId = threadId.replace(/[^A-Za-z0-9._-]+/gu, "-").slice(0, 60);
return `refs/heads/guidance-${safeId}`;
}

/** Whitespace-normalised text, so a lesson matches however the playbook wraps it. */
const normalized = (text: string) => text.replace(/\s+/gu, " ").trim();

export interface MergeGuidanceResult {
ok: boolean;
sha: string | null;
branch: string | null;
message: string;
}

/**
* Fast-forward the canonical checkout to a thread's published guidance branch.
*
* {@link pushGuidance} lands a thread's `.bb` commits on `guidance-<threadId>`.
* This is the other half, and the only way a self-merged lesson reaches the
* HEAD that `readCommittedFiles` reads: the canonical repo's checked-out
* branch is fast-forwarded to that ref. It is deliberately narrow. It refuses
* a detached HEAD, a dirty working tree, a non-fast-forward, a commit range
* that changes anything but `file`, or a `file` that does not carry `text` —
* and on any refusal it leaves the branch exactly where it is, for a person to
* look at. A self-merged lesson may therefore only ever add its own wording to
* its own file; it cannot smuggle in a second change.
*/
export async function mergeGuidance(
projectSourcePath: string,
threadId: string,
file: string,
text: string,
signal?: AbortSignal,
): Promise<MergeGuidanceResult> {
const branch = guidanceRef(threadId);
const options = { timeoutMs: GIT_TIMEOUT_MS, ...(signal === undefined ? {} : { signal }) };
const refuse = (message: string): MergeGuidanceResult => ({ ok: false, sha: null, branch, message });

const head = await gitLine(projectSourcePath, ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], options);
if (head === null || head.length === 0) return refuse(`${projectSourcePath} is not a git repo with a commit to fast-forward.`);
const current = await gitLine(projectSourcePath, ["rev-parse", "--abbrev-ref", "HEAD"], options);
if (current === null || current === "HEAD") return refuse(`${projectSourcePath} has a detached HEAD; check out a branch first.`);

const status = await gitIn(projectSourcePath, ["status", "--porcelain"], options);
if (status.code !== 0) return refuse(firstProblemLine(status));
if (status.stdout.trim() !== "") return refuse(`The canonical checkout has uncommitted changes; commit or stash them, then try again.`);

const ref = await gitLine(projectSourcePath, ["rev-parse", "--verify", "--quiet", `${branch}^{commit}`], options);
if (ref === null || ref.length === 0) return refuse(`No guidance branch ${branch} has been published; publish it first.`);

const ancestor = await gitIn(projectSourcePath, ["merge-base", "--is-ancestor", head, ref], options);
if (ancestor.code !== 0) return refuse(`${branch} is not a fast-forward of ${current}; merge it by hand.`);

const changed = await gitIn(projectSourcePath, ["diff", "--name-only", "-z", head, ref], options);
if (changed.code !== 0) return refuse(firstProblemLine(changed));
const paths = splitNul(changed.stdout);
if (paths.length === 0) return refuse(`${branch} has no commits beyond ${current}; there is nothing to merge.`);
const other = paths.filter((path) => path !== file);
if (other.length > 0) {
return refuse(`${branch} changes files other than ${file}: ${other.slice(0, 5).join(", ")}. Merge it by hand.`);
}

const content = await gitIn(projectSourcePath, ["show", `${ref}:${file}`], { ...options, maxBytes: 2_000_000 });
if (content.code !== 0) return refuse(`${file} is not in ${branch}.`);
if (!normalized(content.stdout).includes(normalized(text))) return refuse(`${file} in ${branch} does not carry the lesson text; commit it, then try again.`);

const merged = await gitIn(projectSourcePath, ["merge", "--ff-only", "--quiet", ref], options);
if (merged.code !== 0) return refuse(firstProblemLine(merged));
const newHead = await gitLine(projectSourcePath, ["rev-parse", "HEAD"], options);
if (newHead === null) return refuse(`Fast-forwarded ${branch}, but the new HEAD could not be read.`);
return { ok: true, sha: newHead, branch, message: `Fast-forwarded ${current} to ${newHead.slice(0, 8)} from ${branch}.` };
}
Loading
Loading