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 #12062

Parked opened this
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +285 −6
docs/features/real-cell-proof.md +20 −6
@@ -1,10 +1,24 @@
1 # Real-cell proof: the build half, in process (#11999)
1 # The real-cell proof walks the stranger's path
22
3 - `test/helpers/build-standin.ts` (its work in `build-standin-builder.ts`) is a deterministic stand-in for the model: it adds a `/reading` route and its test to the template's app (`READING-V1` in the prompt), or changes what it says (`READING-V2`), runs the app's real `bun test`, and pushes only when that passes.
4 - `test/build-journey.test.ts` walks a first ask to production in one process: `newApp` copies the template, the crew's stand-in builds, the pull's preview run says its tests passed, a person lands it, production serves `/reading`, and a second change lands the same way. About 8 s.
3 `test/spawn-stranger-cell.test.ts` (walk: `test/helpers/real-stranger-e2e.ts`) starts a forge
4 the way a stranger does and follows what they do, in a real cell at the default size
5 (Small: 1 CPU, 2 GiB):
56
6 ## The cell half, begun (#12001)
7 1. the home page's form asks for a forge named `asker`, no account;
8 2. the claim link is opened and claimed with the forge's own name as username, a password, no email;
9 3. "a page that says hello and shows today's date" goes in through the form on the forge's first screen;
10 4. the ask must be filed on a new app, never `asker/forge`; its first pull lands on green and the app's URL serves the page;
11 5. a second ask lands too (after the reviewer's approval: the first-change rule applies once);
12 6. no 429 and no stop at any point.
713
8 `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`.
14 The one stub is the model call: `test/helpers/stranger-claude.sh` is the child's Claude Code
15 (`FORGE_CLAUDE`, which a parent hands to its cells). It makes a fixed edit to `src/page.ts` and
16 approves as the reviewer, so the run needs no credit. The cell, the crew's clone and push, the
17 pull, its check and the deploy are the real ones.
918
10 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.
19 It needs bwrap, socat and a unix socket: under `FORGE_TEST_SOCKET` it is skipped and says so, and
20 the forge's check runs it. Budget: up to about 9 minutes (the test's timeout is 560 s); named
21 because the pull's check, not the test, is what a person reads.
22
23 Production: the same journey by hand is the proof that closes #11975 — open the home page, ask for
24 a forge, claim it, ask for the page, and watch the first pull land and the app answer.
test/helpers/real-stranger-e2e.ts added +181
@@ -0,0 +1,181 @@
1 /**
2 * The stranger's path in a real cell (#12050, item C of #11975), as
3 * `test/spawn-stranger-cell.test.ts` drives it. Its own process, for the
4 * reason `real-child-forge.ts` is: a check sets `FORGE_CELLS=off`.
5 *
6 * A parent with the real server is asked, with no account, for a forge named
7 * `asker` (the form a stranger sees). The child comes up in a real cell at the
8 * door's default size, and the walk is a person's: its claim link, the forge's
9 * own name as username and a password, no email; then one sentence through the
10 * form on the forge's first screen, "a page that says hello and shows today's
11 * date"; then a second sentence. Nothing is faked but the model call:
12 * `stranger-claude.sh` is the child's Claude Code (FORGE_CLAUDE, passed to the
13 * cell as it is for any child), so the cell, the crew's clone and push, the
14 * pull, its check, the review and the deploy are the real ones.
15 *
16 * Every status the walk saw is kept, so a 429 or a stop at any moment is
17 * reported. Printed: one JSON line of what was seen (`error` when it broke).
18 */
19 import { mkdtempSync, rmSync } from "node:fs";
20 import { tmpdir } from "node:os";
21 import { join } from "node:path";
22
23 // Set before anything starts a cell: the child's environment is built from this process's.
24 process.env["FORGE_CLAUDE"] = join(import.meta.dir, "stranger-claude.sh");
25
26 const { createApp } = await import("../../src/app.ts");
27 const { cellsAvailable } = await import("../../src/apps/contain.ts");
28 const { serve } = await import("../../src/http/server.ts");
29 const { cellChildren, stopCellChildren } = await import("../../src/spawn/cell.ts");
30 const { bootHostedChild } = await import("../../src/spawn/host.ts");
31 const { lastStop } = await import("../../src/spawn/stopped.ts");
32 await import("./roomy-disk.ts");
33
34 // Each phase has its own budget, so a run that ran out says which phase did.
35 const UP_MS = 120_000;
36 const LAND_MS = 240_000;
37 const SERVE_MS = 180_000;
38 const NAME = "asker";
39 const PARENT = "forge.test";
40 const ASK = "a page that says hello and shows today's date";
41 const SECOND = "also say goodbye above the notes";
42
43 const cells = await cellsAvailable();
44 if (!cells.ok) {
45 console.log(JSON.stringify({ skipped: cells.reason }));
46 process.exit(0);
47 }
48
49 const dataDir = mkdtempSync(join(tmpdir(), "real-stranger-"));
50 const parent = createApp({ dataDir, url: `https://${PARENT}`, port: 0 });
51 const servers = await serve(parent);
52 const statuses = new Set<number>();
53 const seen: Record<string, unknown> = { statuses: [] };
54 let cookie = "";
55
56 process.on("SIGTERM", () => void stopCellChildren(parent).finally(() => process.exit(143)));
57
58 /** One request to the parent's server, as the browser would reach `host`; its status is noted. */
59 async function ask(host: string, path: string, init: { method?: string; body?: URLSearchParams; cookie?: boolean } = {}): Promise<Response> {
60 const headers: Record<string, string> = { host };
61 if (init.cookie === true) headers["cookie"] = cookie;
62 const res = await fetch(`${servers.url}${path}`, {
63 method: init.method ?? "GET",
64 headers,
65 ...(init.body === undefined ? {} : { body: init.body }),
66 redirect: "manual",
67 });
68 statuses.add(res.status);
69 return res;
70 }
71
72 /** Ask every `everyMs` until `done` holds of the answer, or `budgetMs` passes;
73 * says which phase ran out. */
74 async function until<T>(phase: string, budgetMs: number, everyMs: number, step: () => Promise<T | undefined>): Promise<T> {
75 const end = Date.now() + budgetMs;
76 for (;;) {
77 const got = await step().catch(() => undefined);
78 if (got !== undefined) return got;
79 if (Date.now() > end) throw new Error(`the ${phase} phase did not finish in ${budgetMs / 1000}s`);
80 await Bun.sleep(everyMs);
81 }
82 }
83
84 const child = `${NAME}--${PARENT}`;
85 interface PullRow { number: number; state: string; mergedAt: string | null; check: unknown; title: string }
86 const rows = (j: unknown): unknown[] => (Array.isArray(j) ? j : ((j as { items?: unknown[] }).items ?? []));
87
88 /** The form a person sees on the forge's first screen: its hidden inputs and its text field,
89 * filled with `said`. */
90 async function tell(said: string): Promise<number> {
91 const home = await ask(child, "/", { cookie: true });
92 const page = await home.text();
93 const form = /<form[^>]*action="\/tell"[^>]*>([\s\S]*?)<\/form>/.exec(page);
94 if (form === null) throw new Error(`the forge's home has no ask form (status ${home.status})`);
95 const fields = new URLSearchParams();
96 for (const m of form[1]!.matchAll(/<input[^>]*type="hidden"[^>]*>/g)) {
97 const name = /name="([^"]+)"/.exec(m[0])?.[1];
98 if (name) fields.set(name, /value="([^"]*)"/.exec(m[0])?.[1] ?? "");
99 }
100 const text = /<textarea[^>]*name="([^"]+)"/.exec(form[1]!)?.[1];
101 if (text === undefined) throw new Error("the ask form has no text field");
102 fields.set(text, said);
103 const posted = await ask(child, "/tell", { method: "POST", body: fields, cookie: true });
104 return posted.status;
105 }
106
107 async function pulls(repo: string): Promise<PullRow[]> {
108 const res = await ask(child, `/api/v1/repos/${repo}/pulls?state=all&limit=50`, { cookie: true });
109 if (res.status !== 200) return [];
110 return rows(await res.json()) as PullRow[];
111 }
112
113 const today = () => new Date().toISOString().slice(0, 10);
114
115 try {
116 // 1. The form on the home page: a name, no account.
117 const started = await ask(PARENT, "/forges/start", { method: "POST", body: new URLSearchParams({ name: NAME, js: "1" }) });
118 const to = started.headers.get("location") ?? "";
119 const token = to.split("#")[1] ?? "";
120 if (started.status !== 303 || token === "") throw new Error(`starting a forge answered ${started.status} to ${to}`);
121 await bootHostedChild(parent, NAME);
122
123 // 2. The claim link: the form answers once the cell is up.
124 await until("cell up", UP_MS, 1000, async () => ((await ask(child, "/claim")).status === 200 ? true : undefined));
125 const held = cellChildren(parent).list()[0];
126 seen["limits"] = held?.limits ?? null;
127 const claimed = await ask(child, "/claim", { method: "POST", body: new URLSearchParams({ token, username: NAME, password: "a-long-stranger-passphrase" }) });
128 cookie = claimed.headers.getSetCookie().map((c) => c.split(";")[0]).join("; ");
129 if (claimed.status !== 303 || cookie === "") throw new Error(`the claim answered ${claimed.status}`);
130
131 // 3. The first ask, through the form.
132 const told = await tell(ASK);
133 const repos = rows(await (await ask(child, "/api/v1/repos?limit=50", { cookie: true })).json()) as { ownerName?: string; name: string }[];
134 seen["repos"] = repos.map((r) => `${r.ownerName}/${r.name}`);
135 seen["madeRow"] = repos.find((r) => r.name !== "forge") ?? null;
136 const made = repos.find((r) => r.name !== "forge");
137 seen["tell"] = told;
138 if (made === undefined) throw new Error("the ask made no app");
139 const repo = `${made.ownerName ?? NAME}/${made.name}`;
140 seen["app"] = repo;
141 const forgeIssues = await ask(child, `/api/v1/repos/${NAME}/forge/issues?state=all`, { cookie: true });
142 seen["forgeIssues"] = forgeIssues.status === 200 ? rows(await forgeIssues.json()).length : null;
143
144 // 4. The first pull lands on green, and the app's URL serves the page.
145 const landed = await until("first pull", LAND_MS, 2000, async () => {
146 const list = await pulls(repo);
147 seen["pulls"] = list.map((p) => ({ n: p.number, state: p.state, merged: p.mergedAt !== null, check: p.check }));
148 return list.find((p) => p.mergedAt !== null);
149 });
150 seen["first"] = { number: landed.number, check: landed.check };
151 const appHost = `${made.name}--${child}`;
152 const page = async (word: string) =>
153 until(`app serving ${word}`, SERVE_MS, 1500, async () => {
154 const res = await ask(appHost, "/");
155 const body = await res.text();
156 seen["lastApp"] = { host: appHost, status: res.status, app: res.headers.get("x-forge-app"), head: body.slice(0, 160) };
157 return res.status === 200 && body.includes(word) ? body : undefined;
158 });
159 const body = await page("Hello!");
160 seen["firstDate"] = body.includes(today()) || body.includes(new Date(Date.now() - 86_400_000).toISOString().slice(0, 10));
161
162 // 5. A second ask lands too.
163 seen["second"] = { tell: await tell(SECOND) };
164 const second = await until("second pull", LAND_MS, 2000, async () => {
165 const list = await pulls(repo);
166 seen["pulls"] = list.map((p) => ({ n: p.number, state: p.state, merged: p.mergedAt !== null, check: p.check }));
167 return list.find((p) => p.mergedAt !== null && p.number !== landed.number);
168 });
169 Object.assign(seen["second"] as object, { number: second.number, check: second.check });
170 seen["goodbye"] = (await page("Goodbye")).includes("Hello!");
171 seen["stopped"] = held === undefined ? null : (lastStop(parent, held.bodyId)?.why ?? null);
172 } catch (error) {
173 seen["error"] = error instanceof Error ? error.message : String(error);
174 } finally {
175 seen["statuses"] = [...statuses].sort();
176 console.log(JSON.stringify(seen));
177 servers.stop();
178 await stopCellChildren(parent);
179 parent.close();
180 rmSync(dataDir, { recursive: true, force: true });
181 }
test/helpers/stranger-claude.sh added +27
@@ -0,0 +1,27 @@
1 #!/bin/sh
2 # The model call of the real-cell stranger proof (test/spawn-stranger-cell.test.ts, #12050):
3 # a stand-in for Claude Code that makes one fixed edit and spends nothing. A child forge's
4 # crew runs it as its `claude` (FORGE_CLAUDE, the way tests put a stand-in in a cell, #12001);
5 # it lives in the repository because the cell reveals the forge's code and nothing under tmp.
6 # Everything around it is real: the clone, the push, the pull, the check, the deploy.
7 #
8 # an ask that says "goodbye" -> adds a goodbye line to the home page
9 # any other builder prompt -> adds a line that says hello and shows today's date
10 # the reviewer's prompt -> approves the pull
11 if [ "$1" = "--version" ]; then echo "2.1.0 (stranger stand-in)"; exit 0; fi
12 IFS= read -r prompt
13 echo '{"type":"system","subtype":"init","session_id":"stranger-1","model":"stand-in"}'
14 if printf '%s' "$prompt" | grep -q "You are the reviewer on this crew"; then
15 path=$(printf '%s' "$prompt" | grep -o 'api/v1/repos/[^"\\]*/review-states' | head -1)
16 curl -sS -X POST -H "authorization: Bearer $FORGE_TOKEN" -H "content-type: application/json" "${FORGE_URL%/}/$path" -d '{"state":"approved","body":"Looks right."}' >/dev/null
17 echo '{"type":"result","subtype":"success","is_error":false,"result":"Approved.","total_cost_usd":0,"num_turns":1,"session_id":"stranger-1","terminal_reason":"completed"}'
18 exit 0
19 fi
20 set -e
21 if printf '%s' "$prompt" | grep -qi goodbye; then
22 sed -i 's|<section class="card">${composer}</section>|<p id="goodbye">Goodbye, see you tomorrow.</p><section class="card">${composer}</section>|' src/page.ts
23 else
24 sed -i 's|<section class="card">${composer}</section>|<p id="hello">Hello! Today is ${new Date().toISOString().slice(0, 10)}.</p><section class="card">${composer}</section>|' src/page.ts
25 fi
26 git add -A && git commit -qm "The crew's edit" && git push -q -u origin HEAD
27 echo '{"type":"result","subtype":"success","is_error":false,"result":"Edited the home page.","total_cost_usd":0,"num_turns":1,"session_id":"stranger-1","terminal_reason":"completed"}'
test/spawn-stranger-cell.test.ts added +57
@@ -0,0 +1,57 @@
1 /**
2 * The stranger's path in a real cell (#12050, item C of #11975): "the real-cell
3 * proof passes while production fails" was because the proofs started past the
4 * stranger's first step. This one walks it: a forge asked for with a name and
5 * nothing else, a child in a real cell, its claim link, the forge's own name as
6 * username and no email, one sentence through the form ("a page that says hello
7 * and shows today's date"). The ask must be filed on a new app, never
8 * `<name>/forge`; its first pull must land on green and the app's URL must serve
9 * the page; a second ask must land too (after the reviewer's approval, as the
10 * first-change rule says). No 429 and no stop at any moment. The model call is
11 * the one stub (`stranger-claude.sh`), so it needs no credit; the cell, the
12 * check and the deploy are the real ones. The walk is `helpers/real-stranger-e2e.ts`.
13 *
14 * Runs where bwrap and socat are and the cell can be bound to a socket; under
15 * FORGE_TEST_SOCKET, like the other cell suites, it is skipped and named as
16 * skipped. Budget: named, not hidden: up to ~14 minutes (cell up 2 min, each pull
17 * 4 min at worst, serving 3 min each); a normal run is a few minutes.
18 */
19 import { expect, test } from "bun:test";
20 import { join } from "node:path";
21 import { portInsteadOfSocket } from "../src/git/hook-address.ts";
22 import { missing } from "./helpers/tools.ts";
23 import { failedWith } from "./helpers/machine-note.ts";
24 import { resultLine } from "./helpers/result-line.ts";
25
26 const cellTools = process.platform === "linux" && !portInsteadOfSocket() && !missing("bwrap", "socat");
27
28 if (!cellTools) console.log("SKIPPED: the stranger's real-cell walk needs bwrap, socat and a unix socket (not FORGE_TEST_SOCKET)");
29
30 test.skipIf(!cellTools)("a stranger claims a forge in a real cell, asks for a page, and both changes land live", async () => {
31 const env: Record<string, string> = {};
32 for (const [k, v] of Object.entries(process.env)) if (v !== undefined && k !== "FORGE_CELLS") env[k] = v;
33 const proc = Bun.spawn([process.execPath, join(import.meta.dir, "helpers", "real-stranger-e2e.ts")], { env, stdout: "pipe", stderr: "pipe", timeout: 840_000 });
34 const [out, errText] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
35 let seen: Record<string, unknown>;
36 try {
37 seen = JSON.parse(resultLine(out)) as Record<string, unknown>;
38 } catch {
39 throw new Error(failedWith("the stranger run printed no result", out.slice(-800), errText));
40 }
41 if (typeof seen["skipped"] === "string") {
42 console.log(`SKIPPING: this host refuses a cell inside the test (${seen["skipped"]}), so no stranger's forge was started`);
43 return;
44 }
45 const fail = (what: string) => new Error(failedWith(what, seen, errText));
46 if (typeof seen["error"] === "string") throw fail(`the stranger's path broke: ${seen["error"]}`);
47 const limits = seen["limits"] as { memoryMiB?: number; cpus?: number } | null;
48 if (limits?.memoryMiB !== 2048 || limits.cpus !== 1) throw fail("the stranger's forge did not hold the Small limits");
49 const app = String(seen["app"]);
50 if (!app.includes("/") || app.endsWith("/forge")) throw fail("the ask was not filed on a new app");
51 if (seen["forgeIssues"] !== null && seen["forgeIssues"] !== 0) throw fail("the ask was filed on the forge's own copy");
52 if ((seen["statuses"] as number[]).includes(429)) throw fail("a request was answered 429, the sentence for a full host");
53 if (seen["stopped"] !== null) throw fail("the stranger's forge was stopped");
54 if (seen["firstDate"] !== true) throw fail("the first page did not show today's date");
55 if (seen["goodbye"] !== true) throw fail("the second change did not land live with the first kept");
56 expect(app.split("/")[0]).toBe("asker");
57 }, 860_000);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs