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

The real-cell proof walks the stranger's path: claim link, first ask makes a new app, green lands live, second change lands #12058

Parked opened this
Closed without merging

torque/forge:torque/12050-the-real-cell-proof-walks-the-stranger-s → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
6 files changed +546 −0
docs/features/real-cell-proof.md +8
@@ -8,3 +8,11 @@
88 `childEnvFor` (src/spawn/cell.ts, over `cellEnv`) now passes the parent's `FORGE_CLAUDE` to a cell child, so the child's crew can run a stand-in written under the child's own directory (the one place both sides see: the cell hides the parent's data and `/tmp`). Production children read it too (`main.ts`), so a parent with Claude off `PATH` has children that find it. Unit-tested in `test/spawn-cell.test.ts`.
99
1010 Still not proved, and still open in #12001: the walk itself in a real 2 GiB, 1-core cell, and a real memory breach restarting a child. Both need bwrap and socat with user namespaces, which the sandbox this was written in refuses.
11
12 ## The stranger's path, in a real cell (#12050)
13
14 `test/spawn-stranger-cell.test.ts` (its walk is `test/helpers/real-stranger-e2e.ts`) spawns a child at size small (1 CPU, 2 GiB) into a real cell and then does what a person does: opens the claim link and claims it with the forge's own name as username and no email; reads the home's form and asks through it for "a page that says hello and shows today's date". It asserts the ask is filed on a new app (never `<name>/forge`), that the first pull lands on green and the app's own address serves `/hello`, that a second ask lands and the page changes, and that no request was ever answered 429 and the host recorded no memory stop. Skipped, and says so, where there is no bwrap, socat or real unix socket (`FORGE_TEST_SOCKET`).
15
16 The only stand-in is the model: `stranger-standin.ts` writes a fixed edit (`stranger-builder.ts`: a `/hello` route and its test, then a changed sentence) and a reviewer's approval under the child's own directory, which its cell shows, and `FORGE_CLAUDE` (#12001) points the child's crew at it. The cell, the crew, the check, the merge and the deploy are the forge's. What the edit does is proved with no cell in `test/stranger-standin.test.ts`.
17
18 Budget: the phases add up to 21 minutes at the worst (spawn 5, up 3, each ask 5 + 1.5); a normal walk is a few minutes. Run it by hand on production's code the same way: `bun test test/spawn-stranger-cell.test.ts` on a machine with bwrap and socat; its last line of output starts `stranger walk:` and is the run to paste.
test/helpers/real-stranger-e2e.ts added +253
@@ -0,0 +1,253 @@
1 /**
2 * The stranger's path, in a real cell (#12050, part of #11975), as
3 * `test/spawn-stranger-cell.test.ts` drives it. Its own process, for the reason
4 * `real-spawn-e2e.ts` is: a check sets `FORGE_CELLS=off` for the forges its tests boot.
5 *
6 * A parent with the real server spawns a child at size small into a cell, for
7 * no one (a stranger's). Then, through the parent's address for the child
8 * (`kid--forge.test`), as a person with a browser would:
9 *
10 * 1. opens the claim link's page and claims it: the forge's own name as
11 * username, a password, no email;
12 * 2. opens the home and reads the form it shows, then asks through that form
13 * for "a page that says hello and shows today's date";
14 * 3. waits for the first pull to land on green and the new app's address to
15 * serve the page;
16 * 4. asks again through the form, now with an app, and waits for that pull to
17 * land and the page to say the new thing.
18 *
19 * Only the model is a stand-in (`stranger-standin.ts`, a fixed edit); the
20 * cell, the child's crew, its check, its merge and its deploy are real. Every
21 * status the child answered is noted, so a 429 at any moment is reported, and
22 * the host's own record of a stop is read at the end. Printed: one JSON line
23 * of what was seen, or `error` naming the step that did not happen.
24 */
25 import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
26 import { tmpdir } from "node:os";
27 import { join } from "node:path";
28 import { createRepo } from "../../src/actions/repos.ts";
29 import { childDirOf, spawnForge } from "../../src/actions/spawn.ts";
30 import { createApp } from "../../src/app.ts";
31 import { cellsAvailable } from "../../src/apps/contain.ts";
32 import { slugFor } from "../../src/core/apps.ts";
33 import { createUser } from "../../src/core/users.ts";
34 import { repoDir } from "../../src/git/repos.ts";
35 import { commitFiles } from "../../src/git/write.ts";
36 import { serve } from "../../src/http/server.ts";
37 import { cellChildren, cellPlacement, stopCellChildren } from "../../src/spawn/cell.ts";
38 import { bootHostedChild } from "../../src/spawn/host.ts";
39 import { memoryBodies } from "../../src/spawn/placement.ts";
40 import { lastStop } from "../../src/spawn/stopped.ts";
41 import "./roomy-disk.ts";
42 import { FIRST_WORDS, SECOND_WORDS } from "./stranger-builder.ts";
43 import { writeStrangerStandIn } from "./stranger-standin.ts";
44
45 /** Each phase has its own budget, in ms, so a run that ran out says which phase did. */
46 export const BUDGET = { spawn: 300_000, up: 180_000, firstLands: 300_000, firstServes: 90_000, secondLands: 300_000, secondServes: 90_000 } as const;
47
48 export const FIRST_ASK = "a page that says hello and shows today's date";
49 export const SECOND_ASK = "Make the hello page say good morning too";
50
51 const NAME = "kid";
52 const HOST = `${NAME}--forge.test`;
53 const ORIGIN = `https://${HOST}`;
54 const PASSWORD = "a-long-claim-passphrase";
55
56 const cells = await cellsAvailable();
57 if (!cells.ok) {
58 console.log(JSON.stringify({ skipped: cells.reason }));
59 process.exit(0);
60 }
61
62 const dataDir = mkdtempSync(join(tmpdir(), "real-stranger-"));
63 mkdirSync(dataDir, { recursive: true });
64 const parent = createApp({ dataDir, url: "https://forge.test", port: 0, forgeRepo: "alice/forge" });
65 const servers = await serve(parent);
66 let cleanup: () => Promise<void> = async () => {
67 servers.stop();
68 await stopCellChildren(parent);
69 };
70 process.on("SIGTERM", () => void cleanup().finally(() => process.exit(143)));
71
72 /** What was seen, printed at the end whatever happened. */
73 const seen: Record<string, unknown> = { statuses: [] as number[] };
74 const statuses = new Set<number>();
75 let cookie = "";
76
77 class Step extends Error {}
78
79 /** One request to the child through the parent, as a browser would. Every status is noted. */
80 async function call(path: string, init: { method?: string; form?: Record<string, string>; host?: string } = {}): Promise<{ status: number; text: string; headers: Headers }> {
81 const host = init.host ?? HOST;
82 const res = await fetch(`${servers.url}${path}`, {
83 method: init.method ?? (init.form === undefined ? "GET" : "POST"),
84 redirect: "manual",
85 headers: { host, ...(init.form === undefined ? {} : { origin: ORIGIN }), ...(cookie === "" ? {} : { cookie }) },
86 ...(init.form === undefined ? {} : { body: new URLSearchParams(init.form) }),
87 });
88 statuses.add(res.status);
89 return { status: res.status, text: await res.text(), headers: res.headers };
90 }
91
92 const sleep = (ms: number) => Bun.sleep(ms);
93
94 /** Polls `read` every second until it answers a value; names the phase when its budget ends. */
95 async function until<T>(phase: string, ms: number, read: () => Promise<T | undefined>): Promise<T> {
96 const end = Date.now() + ms;
97 for (;;) {
98 const value = await read().catch(() => undefined);
99 if (value !== undefined) return value;
100 if (Date.now() >= end) throw new Step(`${phase}: not within ${ms / 1000}s`);
101 await sleep(1000);
102 }
103 }
104
105 const unescape = (s: string) => s.replaceAll("&quot;", '"').replaceAll("&#39;", "'").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
106
107 /**
108 * The form a person sees to tell the crew: the first form posting to `/tell`. Its hidden
109 * fields, the text field's name, and the app it sends to by default (a hidden field's
110 * value, or a select's first option).
111 */
112 function tellForm(page: string): { fields: Record<string, string>; textName: string; target: string } {
113 const form = /<form\b[^>]*action="\/tell"[^>]*>([\s\S]*?)<\/form>/.exec(page)?.[1];
114 if (form === undefined) throw new Step("the home shows no form to tell the crew");
115 const fields: Record<string, string> = {};
116 for (const m of form.matchAll(/<input\b[^>]*type="hidden"[^>]*>/g)) {
117 const name = /name="([^"]*)"/.exec(m[0])?.[1];
118 const value = /value="([^"]*)"/.exec(m[0])?.[1] ?? "";
119 if (name !== undefined) fields[name] = unescape(value);
120 }
121 const textName = /<(?:textarea|input)\b(?![^>]*type="hidden")[^>]*name="([^"]*)"/.exec(form)?.[1];
122 if (textName === undefined) throw new Step("the form has nowhere to type");
123 const select = /<select\b[^>]*name="([^"]*)"[^>]*>([\s\S]*?)<\/select>/.exec(form);
124 if (select !== null) fields[select[1]!] = unescape(/<option\b[^>]*value="([^"]*)"/.exec(select[2]!)?.[1] ?? "");
125 return { fields, textName, target: fields["app"] ?? "" };
126 }
127
128 /** Asks through the home's form; the repository the ask was filed on, as the redirect names it. */
129 async function ask(text: string): Promise<{ target: string; location: string; repo: string }> {
130 const home = await call("/");
131 if (home.status !== 200) throw new Step(`the home answered ${home.status}`);
132 const form = tellForm(home.text);
133 const res = await call("/tell", { form: { ...form.fields, [form.textName]: text } });
134 const location = res.headers.get("location") ?? "";
135 if (res.status !== 303 && res.status !== 200 && res.status !== 201) throw new Step(`the ask answered ${res.status}: ${res.text.slice(0, 200)}`);
136 const repo = /^\/([^/]+\/[^/?#]+)/.exec(location)?.[1] ?? "";
137 return { target: form.target, location, repo };
138 }
139
140 /** The pull of `repo` that is not in `known`, once it is merged; the check word it ended on. */
141 async function pullLands(phase: string, repo: string, known: ReadonlySet<number>, ms: number) {
142 return until(phase, ms, async () => {
143 const res = await call(`/api/v1/repos/${repo}/pulls?state=all`);
144 if (res.status !== 200) return undefined;
145 const items = (JSON.parse(res.text) as { items?: { number: number; state: string; mergedAt: string | null; check?: string }[] }).items ?? [];
146 const pull = items.find((p) => !known.has(p.number));
147 seen[`${phase}Pull`] = pull === undefined ? null : { number: pull.number, state: pull.state, merged: pull.mergedAt !== null, check: pull.check ?? null };
148 return pull !== undefined && pull.mergedAt !== null ? pull : undefined;
149 });
150 }
151
152 async function knownPulls(repo: string): Promise<Set<number>> {
153 const res = await call(`/api/v1/repos/${repo}/pulls?state=all`);
154 const items = res.status === 200 ? ((JSON.parse(res.text) as { items?: { number: number }[] }).items ?? []) : [];
155 return new Set(items.map((p) => p.number));
156 }
157
158 const today = () => new Date().toISOString().slice(0, 10);
159
160 /** The page at the app's address, once it says `words` and today's date (UTC). */
161 async function pageSays(phase: string, slug: string, words: string, ms: number): Promise<string> {
162 return until(phase, ms, async () => {
163 const before = today();
164 const res = await call("/hello", { host: `${slug}--${HOST}` });
165 seen[`${phase}Page`] = { status: res.status, body: res.text.slice(0, 200) };
166 const after = today();
167 return res.status === 200 && (res.text === words + before || res.text === words + after) ? res.text : undefined;
168 });
169 }
170
171 try {
172 // A forge's own code, so the child has its `<org>/forge` copy as a claimed forge has.
173 const alice = await createUser(parent.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", isAdmin: true });
174 if (!alice.ok) throw new Error("user");
175 const code = await createRepo(parent, alice.value, { name: "forge", visibility: "public" });
176 if (!code.ok) throw new Error("repo");
177 const committed = await commitFiles(repoDir(parent.reposRoot, "alice", "forge"), {
178 branch: "main",
179 message: "the forge's code",
180 files: [{ path: "README.md", content: "# forge\n" }],
181 author: { name: "a", email: "[email protected]" },
182 });
183 if (!committed.ok) throw new Error("commit");
184
185 // A stranger's child at size small, with a model key (never called) and a budget.
186 const spawning = (async () => {
187 const made = await spawnForge(
188 parent,
189 undefined,
190 { name: NAME, org: NAME, apps: [], carryBriefs: false, carrySubscriptions: false, keepAccess: false, size: "small", budgetUsd: 5 },
191 { catalog: [], briefs: [], subscriptions: [] },
192 {
193 placement: cellPlacement(parent, memoryBodies(), () => 10),
194 request: new Request("https://forge.test/x", { method: "POST", headers: { origin: "https://forge.test" } }),
195 url: new URL("https://forge.test/x"),
196 modelKey: "sk-ant-api03-stand-in-for-the-model-the-walk-never-calls",
197 },
198 );
199 if (!made.ok) throw new Step(`spawn: ${JSON.stringify(made.error)}`);
200 // The stand-in lives under the child's own directory, which its cell shows.
201 // Its crew reads FORGE_CLAUDE at start.
202 process.env["FORGE_CLAUDE"] = writeStrangerStandIn(childDirOf(parent, made.value.bodyId)).fake;
203 await bootHostedChild(parent, NAME);
204 return made;
205 })();
206 const made = await Promise.race([
207 spawning,
208 sleep(BUDGET.spawn).then((): never => {
209 throw new Step(`spawn and boot: not within ${BUDGET.spawn / 1000}s`);
210 }),
211 ]);
212 seen["placement"] = made.value.placement;
213 seen["claimUrl"] = made.value.claimUrl === undefined ? null : made.value.claimUrl.split("#")[0];
214 const token = made.value.claimUrl?.split("#")[1] ?? "";
215 const held = cellChildren(parent).list()[0];
216 seen["limits"] = held?.limits ?? null;
217
218 // 1. The claim link: its page opens, then the forge's own name as username, a password, no email.
219 await until("the claim page", BUDGET.up, async () => ((await call("/claim")).status === 200 ? true : undefined));
220 const claimed = await call("/claim", { form: { token, username: NAME, password: PASSWORD } });
221 seen["claim"] = claimed.status;
222 cookie = claimed.headers.getSetCookie().map((c) => c.split(";")[0]).join("; ");
223 if (claimed.status !== 303 || !cookie.includes("=")) throw new Step(`the claim answered ${claimed.status}: ${claimed.text.slice(0, 200)}`);
224
225 // 2. The first ask, through the form a stranger sees.
226 const first = await ask(FIRST_ASK);
227 seen["firstTarget"] = first.target;
228 seen["firstFiledOn"] = first.repo;
229 if (first.repo === "") throw new Step(`the first ask went nowhere a repository: ${first.location}`);
230 const repo = first.repo;
231 const slug = slugFor(repo.split("/")[1]!);
232 seen["slug"] = slug;
233
234 // 3. The first pull lands on green; the app's address serves the page.
235 await pullLands("firstLands", repo, new Set(), BUDGET.firstLands);
236 seen["firstPage"] = await pageSays("firstServes", slug, FIRST_WORDS, BUDGET.firstServes);
237
238 // 4. The second ask, through the same form, now with an app of the person's own.
239 const known = await knownPulls(repo);
240 const second = await ask(SECOND_ASK);
241 seen["secondTarget"] = second.target;
242 seen["secondFiledOn"] = second.repo;
243 await pullLands("secondLands", repo, known, BUDGET.secondLands);
244 seen["secondPage"] = await pageSays("secondServes", slug, SECOND_WORDS, BUDGET.secondServes);
245 seen["stopped"] = lastStop(parent, held?.bodyId ?? "")?.why ?? null;
246 } catch (e) {
247 seen["error"] = e instanceof Step ? e.message : `the walk stopped unexpectedly: ${e instanceof Error ? e.stack : String(e)}`;
248 }
249 seen["statuses"] = [...statuses];
250 console.log(JSON.stringify(seen));
251 await cleanup();
252 parent.close();
253 rmSync(dataDir, { recursive: true, force: true });
test/helpers/stranger-builder.ts added +93
@@ -0,0 +1,93 @@
1 /**
2 * What `stranger-standin.ts`'s stand-in does, run by `bun` in the clone it is
3 * given (#12050). It is the model's place in the stranger's real-cell walk and
4 * nothing else of the walk is faked. It reads no network and keeps no state,
5 * and it is self-contained (it imports nothing of the repository), because it
6 * is copied under the child forge's own directory, the one place the cell shows
7 * it. Argument: the file holding the prompt.
8 *
9 * - a builder prompt that asks for a page that says hello and shows today's
10 * date adds `GET /hello` to the template's routes, with its test;
11 * - one that says "good morning" changes what that page says, and its test;
12 * - the app's own `bun test` runs in the clone, and the work is committed and
13 * pushed only when it passes (a red test ends the run as a failure);
14 * - a reviewer prompt approves the pull through the forge's API.
15 */
16 import { readFileSync, writeFileSync } from "node:fs";
17
18 /** The line in the template's routes the first change is put before. */
19 export const ANCHOR = " // Up or not, for the forge and for anyone watching";
20 export const FIRST_WORDS = "hello, today is ";
21 export const SECOND_WORDS = "hello and good morning, today is ";
22
23 const route = (words: string): string =>
24 ` { method: "GET", path: "/hello", handle: () => text(${JSON.stringify(words)} + new Date().toISOString().slice(0, 10)) },\n\n`;
25
26 const testOf = (words: string): string => `import { afterAll, expect, test } from "bun:test";
27 import { mkdtempSync, rmSync } from "node:fs";
28 import { tmpdir } from "node:os";
29 import { join } from "node:path";
30 import { serve } from "./server.ts";
31
32 const dataDir = mkdtempSync(join(tmpdir(), "hello-"));
33 const server = serve({ port: 0, dataDir, identityKey: "a-key-only-the-forge-holds" });
34 afterAll(() => {
35 server.stop(true);
36 rmSync(dataDir, { recursive: true, force: true });
37 });
38
39 test("/hello says hello and today's date (UTC)", async () => {
40 const res = await fetch(\`http://\${server.hostname}:\${server.port}/hello\`);
41 expect(res.status).toBe(200);
42 expect(await res.text()).toBe(${JSON.stringify(words)} + new Date().toISOString().slice(0, 10));
43 });
44 `;
45
46 const finish = (ok: boolean, result: string): void =>
47 console.log(
48 JSON.stringify({ type: "result", subtype: ok ? "success" : "error_during_execution", is_error: !ok, result, total_cost_usd: 0.01, num_turns: 1, session_id: "stranger-1", terminal_reason: ok ? "completed" : "tool_error" }),
49 );
50
51 const git = (...args: string[]): void => {
52 const r = Bun.spawnSync(["git", ...args], { stdout: "pipe", stderr: "pipe" });
53 if (r.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr.toString()}`);
54 };
55
56 async function review(prompt: string): Promise<void> {
57 const path = /api\/v1\/repos\/[^"\\\s]*\/review-states/.exec(prompt)?.[0];
58 const base = (process.env["FORGE_URL"] ?? "").replace(/\/$/, "");
59 if (path === undefined || base === "") return finish(false, "the review prompt named no place to answer");
60 const res = await fetch(`${base}/${path}`, {
61 method: "POST",
62 headers: { authorization: `Bearer ${process.env["FORGE_TOKEN"] ?? ""}`, "content-type": "application/json" },
63 body: JSON.stringify({ state: "approved", body: "Says what was asked; its tests pass." }),
64 });
65 finish(res.ok, res.ok ? "Reviewed: approved." : `the review was refused: ${res.status}`);
66 }
67
68 async function build(prompt: string): Promise<void> {
69 const second = /good morning/i.test(prompt);
70 if (!second && !/hello/i.test(prompt)) return finish(true, "DECLINED: nothing here I know how to build.");
71 const words = second ? SECOND_WORDS : FIRST_WORDS;
72 const routes = readFileSync("src/routes.ts", "utf8");
73 if (second) {
74 if (!routes.includes(JSON.stringify(FIRST_WORDS))) return finish(false, "there is no first change to change");
75 writeFileSync("src/routes.ts", routes.replace(JSON.stringify(FIRST_WORDS), JSON.stringify(SECOND_WORDS)));
76 } else {
77 if (!routes.includes(ANCHOR)) return finish(false, "the template's routes have changed shape");
78 writeFileSync("src/routes.ts", routes.replace(ANCHOR, route(words) + ANCHOR));
79 }
80 writeFileSync("src/hello.test.ts", testOf(words));
81 const tested = Bun.spawnSync(["bun", "test"], { stdout: "pipe", stderr: "pipe" });
82 if (tested.exitCode !== 0) return finish(false, `its tests failed: ${tested.stderr.toString().slice(-300)}`);
83 git("add", "-A");
84 git("commit", "-qm", second ? "Say good morning too" : "Add a hello page with today's date");
85 git("push", "-q", "-u", "origin", "HEAD");
86 finish(true, `Changed the hello page, tests pass.`);
87 }
88
89 if (import.meta.main) {
90 const prompt = readFileSync(process.argv[2]!, "utf8");
91 if (prompt.includes("You are the reviewer on this crew")) await review(prompt);
92 else await build(prompt);
93 }
test/helpers/stranger-standin.ts added +27
@@ -0,0 +1,27 @@
1 /**
2 * The stand-in for the model in the stranger's real-cell walk (#12050). A
3 * shell script, as `build-standin.ts`'s is, that hands the prompt to
4 * `stranger-builder.ts`. Both are written into `dir`, never read from the
5 * repository: a cell child sees its own directory, and `dir` is that.
6 */
7 import { chmodSync, copyFileSync, writeFileSync } from "node:fs";
8 import { join } from "node:path";
9
10 /** The binary to hand a crew (or `FORGE_CLAUDE`), and the builder it runs, both under `dir`. */
11 export function writeStrangerStandIn(dir: string): { readonly fake: string; readonly builder: string } {
12 const builder = join(dir, "stranger-builder.ts");
13 copyFileSync(join(import.meta.dir, "stranger-builder.ts"), builder);
14 const promptFile = join(dir, "stranger-standin.prompt");
15 const fake = join(dir, "stranger-claude");
16 writeFileSync(
17 fake,
18 `#!/bin/sh
19 if [ "$1" = "--version" ]; then echo "2.1.0 (stranger stand-in)"; exit 0; fi
20 IFS= read -r first; printf '%s\\n' "$first" > "${promptFile}.$$"
21 echo '{"type":"system","subtype":"init","session_id":"stranger-1","model":"stand-in"}'
22 exec ${JSON.stringify(process.execPath)} "${builder}" "${promptFile}.$$"
23 `,
24 );
25 chmodSync(fake, 0o755);
26 return { fake, builder };
27 }
test/spawn-stranger-cell.test.ts added +75
@@ -0,0 +1,75 @@
1 /**
2 * The stranger's path in a real cell (#12050, item C of #11975). The proofs
3 * before it passed while production failed, because none of them walked the
4 * path a person takes. This one does, in a child forge at size small
5 * (1 CPU, 2 GiB) in a real cell: claim it through its claim link (the forge's
6 * own name as username, no email); ask through the form a stranger sees for
7 * "a page that says hello and shows today's date"; the ask is filed on a NEW
8 * app, never `<name>/forge`; its first pull lands on green and the app's own
9 * address serves the page; a second ask lands too and the page says the new
10 * thing. At no point is there a 429 ("the forge is full") or a recorded
11 * memory stop.
12 *
13 * The model call is the one stand-in (`helpers/stranger-standin.ts`, a fixed
14 * edit, no credit); the cell, the child's crew, its check, its merge and its
15 * deploy are real. What the stand-in edits is proved apart, with no cell, in
16 * `stranger-standin.test.ts`. The walk is `helpers/real-stranger-e2e.ts`.
17 *
18 * Runs where bwrap and socat are and FORGE_TEST_SOCKET is not set; it says it
19 * skipped otherwise. Its budget is its own: the phases in the helper add up to
20 * 21 minutes at the very worst (spawn 5, up 3, then 5 + 1.5 for each ask);
21 * the usual walk is a few minutes. The test's timeout is the sum plus slack.
22 */
23 import { expect, test } from "bun:test";
24 import { join } from "node:path";
25 import { portInsteadOfSocket } from "../src/git/hook-address.ts";
26 import { missing } from "./helpers/tools.ts";
27 import { failedWith } from "./helpers/machine-note.ts";
28 import { resultLine } from "./helpers/result-line.ts";
29
30 const cellTools = process.platform === "linux" && !portInsteadOfSocket() && !missing("bwrap", "socat");
31 if (!cellTools) console.log("SKIPPING test/spawn-stranger-cell.test.ts: it needs bwrap and socat and a real unix socket (FORGE_TEST_SOCKET is set where they are not), so no stranger's walk was made");
32
33 const WORST_MS = 21 * 60_000;
34
35 test.skipIf(!cellTools)("a stranger claims a small child, asks for a page, and the first and the second change land live, with no 429", async () => {
36 const env: Record<string, string> = {};
37 for (const [k, v] of Object.entries(process.env)) if (v !== undefined && k !== "FORGE_CELLS" && k !== "FORGE_CLAUDE") env[k] = v;
38 const proc = Bun.spawn([process.execPath, join(import.meta.dir, "helpers", "real-stranger-e2e.ts")], { env, stdout: "pipe", stderr: "pipe", timeout: WORST_MS });
39 const [out, errText] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
40 let seen: Record<string, unknown>;
41 try {
42 seen = JSON.parse(resultLine(out)) as Record<string, unknown>;
43 } catch {
44 throw new Error(failedWith("the stranger's walk printed no result", out.slice(-800), errText));
45 }
46 if (typeof seen["skipped"] === "string") {
47 console.log(`SKIPPING: this host refuses a cell inside the test (${seen["skipped"]}), so no stranger's walk was made`);
48 return;
49 }
50 // The run, as the pull pastes it from the check.
51 console.log(`stranger walk: ${JSON.stringify(seen)}`);
52 const fail = (what: string) => failedWith(what, { seen }, errText);
53 if (seen["error"] !== undefined) throw new Error(fail(`the walk did not finish: ${String(seen["error"])}`));
54
55 const limits = seen["limits"] as { memoryMiB?: number; cpus?: number } | null;
56 if (seen["placement"] !== "cell" || limits?.memoryMiB !== 2048 || limits.cpus !== 1) throw new Error(fail("the child was not a small one in a cell"));
57 expect(seen["claim"]).toBe(303);
58
59 // The ask is filed on a new app, whatever it is named, never on the forge's own copy.
60 expect(seen["firstTarget"]).toBe("new-app");
61 for (const key of ["firstFiledOn", "secondFiledOn"]) {
62 const repo = String(seen[key]);
63 if (!/^kid\/[^/]+$/.test(repo) || repo === "kid/forge") throw new Error(fail(`the ask was filed on ${repo}, not on a new app of the person's`));
64 }
65 expect(seen["secondFiledOn"]).toBe(seen["firstFiledOn"]);
66
67 // Each pull landed and its page is served at the app's own address.
68 for (const key of ["firstLandsPull", "secondLandsPull"]) expect((seen[key] as { merged?: boolean }).merged).toBe(true);
69 expect((seen["firstPage"] as string).startsWith("hello, today is ")).toBe(true);
70 expect((seen["secondPage"] as string).startsWith("hello and good morning, today is ")).toBe(true);
71
72 // No memory stop, and no 429 at any point.
73 expect(seen["stopped"]).toBeNull();
74 expect(seen["statuses"] as number[]).not.toContain(429);
75 }, WORST_MS + 30_000);
test/stranger-standin.test.ts added +90
@@ -0,0 +1,90 @@
1 /**
2 * The stand-in of the stranger's real-cell walk (#12050), run where cells
3 * are not needed: on a clone of the template's files with a bare origin, as
4 * the crew's run does. It is what keeps the cell walk's one fixed edit honest:
5 * the first ask's edit makes the app's own tests pass and is pushed, the
6 * second changes what the page says and is pushed, a prompt it does not know
7 * is declined with nothing pushed, and an edit whose tests are red is never
8 * pushed. The walk itself is `spawn-stranger-cell.test.ts`.
9 */
10 import { afterAll, beforeAll, expect, test } from "bun:test";
11 import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
12 import { tmpdir } from "node:os";
13 import { dirname, join } from "node:path";
14 import { gitClientEnv } from "./helpers/git-client.ts";
15 import { FIRST_WORDS, SECOND_WORDS } from "./helpers/stranger-builder.ts";
16 import { writeStrangerStandIn } from "./helpers/stranger-standin.ts";
17
18 let dir = "";
19 let clone = "";
20 let origin = "";
21 let fake = "";
22
23 const git = (cwd: string, ...args: string[]) => {
24 const r = Bun.spawnSync(["git", ...args], { cwd, stdout: "pipe", stderr: "pipe", env: gitClientEnv() });
25 if (r.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${r.stderr.toString()}`);
26 return r.stdout.toString().trim();
27 };
28
29 /** The stand-in as the crew runs it: the prompt as one line on stdin, in the clone. */
30 async function run(prompt: string, env: Record<string, string> = {}) {
31 const proc = Bun.spawn([fake], { cwd: clone, stdin: new Blob([`${prompt}\n`]), stdout: "pipe", stderr: "pipe", env: { ...gitClientEnv(), PATH: process.env["PATH"] ?? "", ...env } });
32 const [out] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
33 const last = JSON.parse(out.trim().split("\n").at(-1) ?? "{}") as { is_error?: boolean; result?: string };
34 return last;
35 }
36
37 beforeAll(() => {
38 dir = mkdtempSync(join(tmpdir(), "stranger-standin-"));
39 origin = join(dir, "origin.git");
40 clone = join(dir, "clone");
41 mkdirSync(clone);
42 git(dir, "init", "-q", "--bare", "-b", "main", origin);
43 const template = JSON.parse(readFileSync(join(import.meta.dir, "..", "templates", "app-template.json"), "utf8")) as { files: Record<string, string> };
44 for (const [path, content] of Object.entries(template.files)) {
45 mkdirSync(dirname(join(clone, path)), { recursive: true });
46 writeFileSync(join(clone, path), content);
47 }
48 git(clone, "init", "-q", "-b", "main");
49 git(clone, "-c", "user.name=t", "-c", "[email protected]", "add", "-A");
50 git(clone, "-c", "user.name=t", "-c", "[email protected]", "commit", "-qm", "template");
51 git(clone, "remote", "add", "origin", origin);
52 git(clone, "push", "-q", "origin", "main");
53 git(clone, "config", "user.name", "stand-in");
54 git(clone, "config", "user.email", "[email protected]");
55 fake = writeStrangerStandIn(dir).fake;
56 });
57
58 afterAll(() => rmSync(dir, { recursive: true, force: true }));
59
60 test("a prompt it does not know is declined and nothing is pushed", async () => {
61 const said = await run("please paint the fence");
62 expect(said.is_error).toBe(false);
63 expect(said.result).toStartWith("DECLINED");
64 expect(git(origin, "rev-list", "--count", "main")).toBe("1");
65 });
66
67 test("the first ask's edit passes the app's own tests and is pushed", async () => {
68 const said = await run("A page that says hello and shows today's date");
69 expect(said.is_error, said.result).toBe(false);
70 expect(git(origin, "rev-list", "--count", "main")).toBe("2");
71 expect(readFileSync(join(clone, "src", "routes.ts"), "utf8")).toContain(JSON.stringify(FIRST_WORDS));
72 }, 120_000);
73
74 test("the second ask changes what the page says and is pushed", async () => {
75 const said = await run("Make the hello page say good morning too");
76 expect(said.is_error, said.result).toBe(false);
77 expect(git(origin, "rev-list", "--count", "main")).toBe("3");
78 const routes = readFileSync(join(clone, "src", "routes.ts"), "utf8");
79 expect(routes).toContain(JSON.stringify(SECOND_WORDS));
80 expect(routes).not.toContain(JSON.stringify(FIRST_WORDS));
81 }, 120_000);
82
83 test("an edit whose tests are red is not pushed", async () => {
84 // The first change is not in the routes, so the edit has nothing to land on: a failed run.
85 const routes = readFileSync(join(clone, "src", "routes.ts"), "utf8");
86 writeFileSync(join(clone, "src", "routes.ts"), routes.replace(JSON.stringify(SECOND_WORDS), '"something else"'));
87 const said = await run("Make the hello page say good morning too");
88 expect(said.is_error).toBe(true);
89 expect(git(origin, "rev-list", "--count", "main")).toBe("3");
90 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs