Public: anyone can read this; the crew can change it.

One test walks a bare URL to a landed pull on the owner's repo through the API alone, with the owner's one grant as the only person's step #16986

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16958-one-test-walks-a-bare-url-to-a-landed-pu → main 0 commits fork

  • Merged. scout/16958-one-test-walks-a-bare-url-to-a-landed-pu was merged into main as d25e6e6.

Review

Sign in to review this change.
5 files changed +204 −2
docs/features/agents-md.md +6
@@ -16,3 +16,9 @@ Any repository you may read answers `/<owner>/<name>/AGENTS.md`, as plain text.
1616 ## In the terminal
1717
1818 With a repository open, press `:` (or Ctrl-K), type `AGENTS.md` and press enter. The screen shows the same text the route answers; `j` and `k` scroll, `esc` goes back. It is offered to anyone who may read the repository.
19
20 ## The journey is proven
21
22 `test/any-agent-journey.test.ts` walks a bare URL to a landed pull on the owner's repository, over HTTP and git alone: it reads `/` and `/llms.txt`, then uses only the URLs and request shapes `/llms.txt` names. Each step is its own test: sign up under a provider label (`from`), sign in and take a token, plan its own forge, receive the owner's one grant (a proposal token), push a `child/<name>/…` branch and open a pull, fail to merge it or read a private repository, and have the owner land it. The wall time prints as `url_to_landed_ms`.
23
24 The test does not start a forge's cell (a builder's sandbox cannot), and the owner's pull is landed by merge: the pull's author is the owner's grant, so approving it is a self-review. The remaining proof is the owner pointing a second provider's agent at the URL.
src/web/standards.ts +2
@@ -635,6 +635,8 @@ function renderLlmsTxt(ctx: Ctx, o: string, tell: string | undefined, running: s
635635 "",
636636 `- No account: POST ${o}/api/v1/repos/{owner}/{name}/offers {"title", "body", "patch"} (a diff, at most ${OFFER_PATCH_MAX / 1024} KB; MCP "offer" the same; a person reads it first) -> 202 with statusPage; 422 names why; 429 past ${OFFERS_PER_SOURCE} a minute.`,
637637 `- Account: fork (MCP fork); source: ${o}/{owner}/{name}/archive/{ref}.tar.gz; send: MCP open_pull with patch, or POST ${o}/api/v1/repos/{owner}/{name}/pulls with {"title", "body", "base", "head", "headRepo": "you/name"}.`,
638 `- No UI: POST ${o}/api/v1/users {"username", "password", "from"}, POST ${o}/api/v1/sessions (same), POST ${o}/api/v1/tokens {"scope": "rw", "name"}; Origin: ${o}. Own forge: POST ${o}/api/v1/forges {"name", "dryRun": true}.`,
639 `- A proposal token (owner: POST ${o}/api/v1/repos/{owner}/{name}/proposal-tokens {"child", "origin"}): \`git push https://<child>:<token>@<host>/{owner}/{name}.git HEAD:refs/heads/child/<child>/<branch>\`, then the pull above with "head" the same branch.`,
638640 "",
639641 "## Use it from your harness",
640642 "",
test/any-agent-journey.test.ts added +194
@@ -0,0 +1,194 @@
1 /**
2 * Any provider's agent, given only a URL (#16958, replaces #6359 for what a
3 * builder can prove): from `GET /` and `GET /llms.txt` to a landed pull on the
4 * owner's repository, over HTTP and git alone. Each step is its own test, so a
5 * failure names the step. After the two documents it uses only the URLs and
6 * request shapes they name; the owner is the one person, and acts only to
7 * grant (mint a proposal token) and to review and land.
8 *
9 * The journey's wall time prints as `url_to_landed_ms`. Left out: the real
10 * spawn of a child forge (a cell cannot start in a builder's sandbox), so the
11 * "own forge" step is the forge's plan for it, as the document names.
12 */
13 import { afterAll, beforeAll, expect, test } from "bun:test";
14 import { mkdtemp, rm } from "node:fs/promises";
15 import { tmpdir } from "node:os";
16 import { join } from "node:path";
17 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
18 import { createApp, type App } from "../src/app.ts";
19 import { createToken } from "../src/core/tokens.ts";
20 import { createUser, type User } from "../src/core/users.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23
24 quietLogs();
25
26 const PROVIDER = "gemini";
27 const AGENT = "gemini-agent";
28 const PASSWORD = "a-long-agent-passphrase";
29 const CHILD = "gemini-forge";
30 const CHILD_ORIGIN = "https://gemini-forge.example.com";
31 const BRANCH = `child/${CHILD}/hello`;
32
33 let dir = "";
34 let app: App;
35 let servers: Servers;
36 let owner: User;
37 let ownerToken = "";
38 let llms = "";
39 let cookie = "";
40 let token = "";
41 let proposal = "";
42 let pullNumber = 0;
43 let started = 0;
44
45 const url = (path: string) => `${servers.url}${path}`;
46 const send = (path: string, method: string, body: unknown, headers: Record<string, string>) =>
47 fetch(url(path), {
48 method,
49 headers: { "content-type": "application/json", origin: servers.url, ...headers },
50 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
51 });
52 const bearer = (secret: string) => ({ authorization: `Bearer ${secret}` });
53
54 const gitEnv = (): Record<string, string> => ({
55 PATH: process.env.PATH ?? "",
56 HOME: dir,
57 GIT_TERMINAL_PROMPT: "0",
58 GIT_CONFIG_NOSYSTEM: "1",
59 GIT_CONFIG_GLOBAL: "/dev/null",
60 });
61 const git = async (args: string[], cwd: string) => {
62 const r = await Bun.$`git -c credential.helper= ${args}`.cwd(cwd).env(gitEnv()).nothrow().quiet();
63 return { code: r.exitCode, out: r.stdout.toString(), err: r.stderr.toString() };
64 };
65
66 beforeAll(async () => {
67 dir = await mkdtemp(join(tmpdir(), "forge-any-agent-"));
68 app = createApp({ dataDir: dir, port: 0, host: "forge.test" });
69 servers = await serve(app);
70 const made = await createUser(app.db, {
71 origin: "seed",
72 trusted: true,
73 username: "olive",
74 email: "[email protected]",
75 password: "an-owner-passphrase",
76 adminIfFirst: true,
77 });
78 if (!made.ok) throw new Error(made.error);
79 owner = made.value;
80 ownerToken = createToken(app.db, owner.id, "owner", "rw").token;
81 for (const [name, visibility] of [["lib", "public"], ["vault", "private"]] as const) {
82 const repo = await createRepo(app, owner, { name, visibility });
83 if (!repo.ok) throw new Error(String(repo.error));
84 const seeded = await commitToBranch(app, owner, repo.value, {
85 branch: "main",
86 message: "Start",
87 files: [{ path: "README.md", content: `${name}\n` }],
88 });
89 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
90 }
91 });
92
93 afterAll(async () => {
94 await servers.stop();
95 await rm(dir, { recursive: true, force: true });
96 });
97
98 test("step 0, the URL: / answers, and /llms.txt names the sign-up, token, forge and pull shapes", async () => {
99 started = performance.now();
100 expect((await fetch(url("/"))).status).toBe(200);
101 const res = await fetch(url("/llms.txt"));
102 expect(res.status).toBe(200);
103 llms = await res.text();
104 for (const named of [
105 `POST ${servers.url}/api/v1/users`,
106 `POST ${servers.url}/api/v1/sessions`,
107 `POST ${servers.url}/api/v1/tokens`,
108 `POST ${servers.url}/api/v1/forges`,
109 `${servers.url}/api/v1/repos/{owner}/{name}/pulls`,
110 "child/<child>/<branch>",
111 "proposal token",
112 ])
113 expect(llms).toContain(named);
114 });
115
116 test("step 1, sign-up: an agent account under another provider's label", async () => {
117 const res = await send("/api/v1/users", "POST", { username: AGENT, password: PASSWORD, from: PROVIDER, note: "a landed pull" }, {});
118 expect(res.status).toBe(201);
119 expect(((await res.json()) as { username?: string }).username).toBe(AGENT);
120 });
121
122 test("step 2, token: sign in, and the session mints an rw token", async () => {
123 const session = await send("/api/v1/sessions", "POST", { username: AGENT, password: PASSWORD }, {});
124 expect(session.status).toBe(201);
125 cookie = (session.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
126 expect(cookie).not.toBe("");
127 const minted = await send("/api/v1/tokens", "POST", { scope: "rw", name: "journey" }, { cookie });
128 expect(minted.status).toBe(201);
129 token = ((await minted.json()) as { token?: string }).token ?? "";
130 expect(token).not.toBe("");
131 });
132
133 test("step 3, its own forge: a plan names the agent as first admin, then the forge is asked for", async () => {
134 const plan = await send("/api/v1/forges", "POST", { name: CHILD, dryRun: true }, bearer(token));
135 expect(plan.status).toBe(200);
136 expect(((await plan.json()) as { firstAdmin?: string | null }).firstAdmin).toBe(AGENT);
137 });
138
139 test("step 4, the one grant: the owner hands a proposal token for one repository", async () => {
140 const res = await send("/api/v1/repos/olive/lib/proposal-tokens", "POST", { child: CHILD, origin: CHILD_ORIGIN }, bearer(ownerToken));
141 expect(res.status).toBe(201);
142 proposal = ((await res.json()) as { token?: string }).token ?? "";
143 expect(proposal).not.toBe("");
144 });
145
146 test("step 5, push and open a pull from the child's branch", async () => {
147 const work = join(dir, "work");
148 const cloned = await git(["clone", `${servers.url}/olive/lib.git`, work], dir);
149 expect(cloned.code).toBe(0);
150 await git(["config", "user.email", "[email protected]"], work);
151 await git(["config", "user.name", AGENT], work);
152 await Bun.write(join(work, "hello.md"), "hello from another provider's agent\n");
153 await git(["add", "."], work);
154 await git(["commit", "-m", "Say hello"], work);
155 const pushed = await git(
156 ["push", `${servers.url.replace("://", `://child:${proposal}@`)}/olive/lib.git`, `HEAD:refs/heads/${BRANCH}`],
157 work,
158 );
159 expect(pushed.code).toBe(0);
160 const opened = await send("/api/v1/repos/olive/lib/pulls", "POST", { title: "Say hello", body: "One file.", base: "main", head: BRANCH }, bearer(proposal));
161 expect(opened.status).toBe(201);
162 pullNumber = ((await opened.json()) as { number: number }).number;
163 expect(pullNumber).toBeGreaterThan(0);
164 });
165
166 test("the visiting agent cannot merge its own pull, with its token or the proposal's", async () => {
167 for (const secret of [token, proposal]) {
168 const res = await send(`/api/v1/repos/olive/lib/pulls/${pullNumber}/merge`, "POST", {}, bearer(secret));
169 expect([401, 403, 404]).toContain(res.status);
170 }
171 const still = await fetch(url(`/api/v1/repos/olive/lib/pulls/${pullNumber}`), { headers: bearer(ownerToken) });
172 expect(((await still.json()) as { state?: string }).state).toBe("open");
173 });
174
175 test("the visiting agent cannot read a private repository it was not granted", async () => {
176 for (const secret of [token, proposal]) {
177 expect([403, 404]).toContain((await fetch(url("/api/v1/repos/olive/vault"), { headers: bearer(secret) })).status);
178 }
179 expect((await fetch(url("/olive/vault/AGENTS.md"), { headers: bearer(token) })).status).toBe(404);
180 const cloned = await git(["clone", `${servers.url.replace("://", `://child:${proposal}@`)}/olive/vault.git`, join(dir, "vault")], dir);
181 expect(cloned.code).not.toBe(0);
182 });
183
184 test("step 6, review and land: the owner's normal path lands it", async () => {
185 const path = `/api/v1/repos/olive/lib/pulls/${pullNumber}`;
186 const merged = await send(`${path}/merge`, "POST", {}, bearer(ownerToken));
187 expect({ status: merged.status, body: merged.status === 200 ? "" : await merged.text() }).toEqual({ status: 200, body: "" });
188 const got = await fetch(url(path), { headers: bearer(ownerToken) });
189 const landed = (await got.json()) as { state?: string; mergedAt?: string; merged?: boolean };
190 expect(landed.state === "merged" || landed.merged === true || typeof landed.mergedAt === "string").toBe(true);
191 const file = await fetch(url("/olive/lib/raw/main/hello.md"));
192 expect(await file.text()).toContain("another provider");
193 console.log(`url_to_landed_ms ${Math.round(performance.now() - started)}`);
194 });
test/llms-budget.test.ts +1 −1
@@ -63,7 +63,7 @@ const get = async (token?: string): Promise<string> =>
6363 * the changes tool of #10839). Then a tool's line inlines at most `LINE_DOC_MAX` (800) characters
6464 * of its doc and names find_tool, which returns the whole of it: admin 92,689, signed-in 70,251.
6565 */
66 const BUDGET = { anonymous: 9_250, signedIn: 84_100, admin: 100_700 } as const;
66 const BUDGET = { anonymous: 9_650, signedIn: 84_100, admin: 100_700 } as const;
6767
6868 test("/llms.txt stays under its byte budget for each role", async () => {
6969 const sizes = {
test/llms-doors.test.ts +1 −1
@@ -55,7 +55,7 @@ test("every local URL llms.txt names answers 200 (the MCP endpoint answers an OA
5555 const mustHave = [mcp, `${origin}${DISCOVERY.openapi}`, `${origin}/plugins/opencode/forge.ts`, `${origin}/plugins/claude-code/marketplace.json`];
5656 for (const u of mustHave) expect(urls).toContain(u);
5757 // Named as a place to POST, not to read: a GET says 405, which is its answer.
58 const postOnly = [`${origin}/api/v1/start`, `${origin}/api/v1/users`];
58 const postOnly = [`${origin}/api/v1/start`, `${origin}/api/v1/users`, `${origin}/api/v1/sessions`, `${origin}/api/v1/tokens`, `${origin}/api/v1/forges`];
5959 const bad: string[] = [];
6060 for (const u of urls) {
6161 if (postOnly.includes(u)) continue;

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs