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

Take updates from trevato/forge-upstream #1305

Closed opened this in answer to
Closed without merging

mason/forge:mason/1303-take-updates-from-trevato-forge-upstream → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
18 files changed +351 −100
docs/RESTORE.md added +35
@@ -0,0 +1,35 @@
1 # Restore card — the forge back on a fresh machine
2
3 Print this. Keep it somewhere that is not the forge.
4
5 ## Have ready
6
7 - The **passphrase** (`FORGE_SNAPSHOT_PASSPHRASE`). Without it every sealed
8 value is lost and set again by hand; the rest restores.
9 - The **store address**: the directory (`FORGE_SNAPSHOT_DIR`) or the bucket
10 (`S3_ENDPOINT`, `S3_BUCKET`, `S3_ACCESS_KEY`, `S3_SECRET_KEY`,
11 `S3_REGION`; export them in place of line 3).
12 - The **keys**: access to the forge's git remote and the store's credentials.
13 The forge's own host key and secret key come out of the snapshot.
14 - A machine with `git`, `bun` and an empty data directory.
15
16 ## The lines
17
18 Replace `<store-dir>`, `<data-dir>` and `<passphrase>`. A line ending
19 `# network` needs the network and `# boot` starts the forge and does not
20 return; `test/restore-card.test.ts` runs every other line against a test
21 snapshot, so this card cannot drift from the command.
22
23 1. `git clone https://forge.open-platform.sh/trevato/forge.git forge && cd forge # network`
24 2. `bun install # network`
25 3. `export FORGE_SNAPSHOT_DIR=<store-dir>`
26 4. `export FORGE_SNAPSHOT_PASSPHRASE=<passphrase>`
27 5. `bun run src/snapshot/restore.ts latest <data-dir>`
28 6. `test -s <data-dir>/forge.db`
29 7. `FORGE_DATA=<data-dir> bun run src/main.ts # boot`
30
31 The restore prints what it brought back. A wrong passphrase refuses before
32 writing anything; a missing one restores without the key and lists the
33 sealed values to set again. To pick an older snapshot, put its name
34 (`2026-09-22T08-00-00Z`) where line 5 says `latest`. Details:
35 [SNAPSHOT.md](SNAPSHOT.md).
docs/SNAPSHOT.md +2
@@ -72,6 +72,8 @@ The store is `Bun.S3Client` or a directory behind one small interface
7272
7373 ## Restore
7474
75 The printable card, seven lines, is [RESTORE.md](RESTORE.md); a test runs it.
76
7577 ```sh
7678 # same S3_* as the forge runs under, or FORGE_SNAPSHOT_DIR
7779 FORGE_SNAPSHOT_PASSPHRASE=… \
scripts/gate.ts +13 −16
@@ -26,6 +26,7 @@ export const GATE: readonly string[] = [
2626 "test/agents.test.ts",
2727 "test/app-domains.test.ts",
2828 "test/app.test.ts",
29 "test/apps-idle.test.ts",
2930 "test/body-limits.test.ts",
3031 "test/claim-link.test.ts",
3132 "test/client-address.test.ts",
@@ -38,6 +39,7 @@ export const GATE: readonly string[] = [
3839 "test/enterable-apps.test.ts",
3940 "test/event-order.test.ts",
4041 "test/refresh-meta.test.ts",
42 "test/restore-card.test.ts",
4143 "test/returns.test.ts",
4244 "test/review-route.test.ts",
4345 "test/review-lines.test.ts",
@@ -57,6 +59,7 @@ export const GATE: readonly string[] = [
5759 "test/scale.test.ts",
5860 "test/sealed-private-work.test.ts",
5961 "test/settings.test.ts",
62 "test/signin-throttle.test.ts",
6063 "test/signins.test.ts",
6164 "test/sole-owner-suspend.test.ts",
6265 "test/standing-every-process.test.ts",
@@ -141,6 +144,7 @@ export const GATE: readonly string[] = [
141144 "test/spawn-first-boot.test.ts",
142145 "test/spawn-keys.test.ts",
143146 "test/web-apps.test.ts",
147 "test/web-ui.test.ts",
144148 "test/fleet-ops.test.ts",
145149 "test/meter.test.ts",
146150 "test/told-by.test.ts",
@@ -206,6 +210,15 @@ export const GATE: readonly string[] = [
206210 "test/report-discovery.test.ts",
207211 "test/apps-report.test.ts",
208212 "test/private-app.test.ts",
213 "test/pacing.test.ts",
214 "test/palette.test.ts",
215 "test/qr.test.ts",
216 "test/branches.test.ts",
217 "test/cli-sync.test.ts",
218 "test/code.test.ts",
219 "test/counts.test.ts",
220 "test/crew-loop.test.ts",
221 "test/crew-totals.test.ts",
209222 ];
210223
211224 export const EXCLUDED: readonly Exclusion[] = [
@@ -213,7 +226,6 @@ export const EXCLUDED: readonly Exclusion[] = [
213226 { file: "test/api-errors.test.ts", reason: "not yet admitted", issue: 261 },
214227 { file: "test/app-env.test.ts", reason: "not yet admitted", issue: 261 },
215228 { file: "test/apps-api.test.ts", reason: "not yet admitted", issue: 261 },
216 { file: "test/apps-idle.test.ts", reason: "not yet admitted", issue: 261 },
217229 {
218230 file: "test/apps-open-host.test.ts",
219231 reason: "not yet admitted",
@@ -229,19 +241,11 @@ export const EXCLUDED: readonly Exclusion[] = [
229241 "red: an app with spend and nothing shipped is missing from the board",
230242 issue: 555,
231243 },
232 { file: "test/branches.test.ts", reason: "not yet admitted", issue: 261 },
233 { file: "test/cli-sync.test.ts", reason: "not yet admitted", issue: 261 },
234 { file: "test/code.test.ts", reason: "not yet admitted", issue: 261 },
235 { file: "test/counts.test.ts", reason: "not yet admitted", issue: 261 },
236244 {
237245 file: "test/crew-interrupted.test.ts",
238246 reason: "not yet admitted",
239247 issue: 261,
240248 },
241 { file: "test/crew-loop.test.ts", reason: "not yet admitted", issue: 261 },
242 { file: "test/crew-totals.test.ts", reason: "not yet admitted", issue: 261 },
243 { file: "test/pacing.test.ts", reason: "not yet admitted", issue: 261 },
244 { file: "test/palette.test.ts", reason: "not yet admitted", issue: 261 },
245249 { file: "test/parity.test.ts", reason: "not yet admitted", issue: 261 },
246250 { file: "test/policy.test.ts", reason: "not yet admitted", issue: 261 },
247251 { file: "test/probe.test.ts", reason: "not yet admitted", issue: 261 },
@@ -249,7 +253,6 @@ export const EXCLUDED: readonly Exclusion[] = [
249253 { file: "test/prompts.test.ts", reason: "not yet admitted", issue: 261 },
250254 { file: "test/public-url.test.ts", reason: "not yet admitted", issue: 261 },
251255 { file: "test/push-through.test.ts", reason: "not yet admitted", issue: 261 },
252 { file: "test/qr.test.ts", reason: "not yet admitted", issue: 261 },
253256 { file: "test/read-api.test.ts", reason: "not yet admitted", issue: 261 },
254257 { file: "test/revert.test.ts", reason: "not yet admitted", issue: 261 },
255258 {
@@ -268,11 +271,6 @@ export const EXCLUDED: readonly Exclusion[] = [
268271 issue: 261,
269272 },
270273 { file: "test/security-xss.test.ts", reason: "not yet admitted", issue: 261 },
271 {
272 file: "test/signin-throttle.test.ts",
273 reason: "not yet admitted",
274 issue: 261,
275 },
276274 {
277275 file: "test/snapshot-destination.test.ts",
278276 reason: "not yet admitted",
@@ -344,7 +342,6 @@ export const EXCLUDED: readonly Exclusion[] = [
344342 issue: 291,
345343 },
346344 { file: "test/web-phone.test.ts", reason: "not yet admitted", issue: 261 },
347 { file: "test/web-ui.test.ts", reason: "not yet admitted", issue: 261 },
348345 {
349346 file: "test/web-workflows.test.ts",
350347 reason: "not yet admitted",
src/kernel/vitals.ts +3 −10
@@ -1,5 +1,7 @@
11 /**
2 * The forge's standing: is it fine, and if not, what is off. Plain data in,
2 * The forge's standing: is it fine, and if not, what is off. Only what needs
3 * a person now is a need; a setting that is not the default is a note on its
4 * own page (`web/pages/capacity.ts`), never here. Plain data in,
35 * plain data out — the disk under `FORGE_DATA`, this process's memory, the
46 * queue, runs that stopped making progress, and how many apps are serving,
57 * asleep or previewed. A fixed handful of queries however many runs and
@@ -12,11 +14,6 @@ import { freemem, totalmem } from "node:os";
1214 import { recentErrors, type ErrorLine } from "./log.ts";
1315 import { leaseLapsed, listRunning, queueDepth } from "../core/runs.ts";
1416 import { STALE_AFTER_MS } from "../runs/lease.ts";
15 import { egressSetting } from "../core/capacity.ts";
16
17 /** What every new cell may reach while egress is only reported. */
18 export const EGRESS_REPORTED =
19 "Egress is reported, not enforced: every new app, preview, terminal and check cell may reach any public host on ports 80 and 443. Set it back to enforce under Settings → Capacity.";
2017
2118 /** Free disk under this share of the volume is something to say. */
2219 export const DISK_FREE_MIN = 0.1;
@@ -114,10 +111,6 @@ export function vitals(input: VitalsInput): Vitals {
114111 `${seen.lastHour} errors in the last hour (${ERROR_BURST} or more is a burst).`,
115112 );
116113
117 // Deliberate, and still to be said while it lasts (`core/capacity.ts`):
118 // only an admin sees vitals, so naming what is open here tells nobody else.
119 if (egressSetting(input.db) === "report") needs.push(EGRESS_REPORTED);
120
121114 return {
122115 ok: needs.length === 0,
123116 needs,
src/snapshot/restore.ts +13 −4
@@ -8,7 +8,10 @@
88 * It refuses a data directory that is not empty: a restore over a live
99 * forge is not a restore, it is a mess.
1010 *
11 * bun run src/snapshot/restore.ts <snapshot-name> <data-dir>
11 * bun run src/snapshot/restore.ts <snapshot-name|latest> <data-dir>
12 *
13 * `latest` is the newest snapshot the store holds, for the person at a
14 * fresh machine who does not know the name (`docs/RESTORE.md`).
1215 *
1316 * with the same `S3_*` variables the forge runs under, or
1417 * `FORGE_SNAPSHOT_DIR` for a directory store.
@@ -24,7 +27,7 @@ import { dirname, join } from "node:path";
2427 import { runGit } from "../git/env.ts";
2528 import { installHooks } from "../git/hooks.ts";
2629 import { repoDir } from "../git/repos.ts";
27 import { keyOf, SNAPSHOT_PREFIX, type Manifest } from "./snapshot.ts";
30 import { keyOf, listSnapshots, SNAPSHOT_PREFIX, type Manifest } from "./snapshot.ts";
2831 import { unwrapKey, WRAPPED_KEY } from "./wrap.ts";
2932 import { resolveDestination } from "./destination.ts";
3033 import type { Store } from "./store.ts";
@@ -159,7 +162,7 @@ if (import.meta.main) {
159162 if (!name || !dataDir) {
160163 // CLI usage on stderr for the person at the terminal, not a forge event.
161164 console.error(
162 "usage: bun run src/snapshot/restore.ts <snapshot-name> <data-dir>",
165 "usage: bun run src/snapshot/restore.ts <snapshot-name|latest> <data-dir>",
163166 );
164167 process.exit(2);
165168 }
@@ -173,7 +176,13 @@ if (import.meta.main) {
173176 );
174177 process.exit(2);
175178 }
176 const done = await restoreSnapshot(store, name, dataDir, {
179 const newest = name === "latest" ? (await listSnapshots(store))[0] : undefined;
180 if (name === "latest" && newest === undefined) {
181 // CLI message on stderr for the person at the terminal.
182 console.error(`no snapshot in ${store.where}`);
183 process.exit(1);
184 }
185 const done = await restoreSnapshot(store, newest?.name ?? name, dataDir, {
177186 passphrase: process.env["FORGE_SNAPSHOT_PASSPHRASE"] || undefined,
178187 });
179188 console.log(
src/web/pages/capacity.ts +4 −5
@@ -103,13 +103,12 @@ export function capacityPage(ctx: Ctx): Response {
103103 );
104104 const body = html`${when(
105105 reported,
106 () => html`<p class="error-note mb" id="egress-reported">
107 ${icon("alert")} Egress is reported, not enforced: every new app,
106 () => html`<p class="muted small mb" id="egress-reported">
107 ${icon("activity")} Egress is reported, not enforced: every new app,
108108 preview, terminal and check cell may reach any public host on ports
109109 80 and 443, declared or not. Private, loopback and cluster addresses,
110 and every other port, stay refused. The forge's vitals (the board's
111 strip, the health check for admins) say so while it lasts. Set it back to enforce once each app's reported hosts
112 are in its forge.json.
110 and every other port, stay refused. Set it back to enforce once each
111 app's reported hosts are in its forge.json.
113112 </p>`,
114113 )}
115114 ${card(
test/agents.test.ts +10 −4
@@ -34,6 +34,7 @@ import { Gate, gitGate, runGit } from "../src/git/env.ts";
3434 import { quietLogs } from "./helpers/globals.ts";
3535 import { isBusy, transact } from "../src/kernel/db.ts";
3636 import { repoDir } from "../src/git/repos.ts";
37 import { gitClientEnv } from "./helpers/git-client.ts";
3738
3839 quietLogs();
3940
@@ -170,12 +171,16 @@ describe("fifty agents at once", () => {
170171 // through the same pre-receive path a real one takes... except that the
171172 // hook only runs for a transport. So drive real ones, in parallel, over
172173 // HTTP — the socket's backlog is exactly what is under test.
174 // Never inherit the host's git configuration: a crew machine carries an
175 // http.extraHeader Authorization that beats the token in the URL, and
176 // every push then comes back "auth required" (test/helpers/git-client.ts).
177 const env = gitClientEnv();
173178 const clones = await mkdtemp(join(tmpdir(), "forge-agents-push-"));
174179 const remote = `${base.replace("http://", `http://cora:${token}@`)}/cora/swarm.git`;
175180
176181 const clone = await Bun.spawn(
177182 ["git", "clone", "--quiet", remote, join(clones, "work")],
178 { stdout: "ignore", stderr: "pipe" },
183 { stdout: "ignore", stderr: "pipe", env },
179184 );
180185 expect(await clone.exited).toBe(0);
181186 const work = join(clones, "work");
@@ -187,9 +192,10 @@ describe("fifty agents at once", () => {
187192 cwd: work,
188193 stdout: "ignore",
189194 stderr: "ignore",
195 env,
190196 }).exited;
191197 await Bun.write(join(work, `agent-${i}.txt`), `work from agent ${i}\n`);
192 await Bun.spawn(["git", "add", "."], { cwd: work, stdout: "ignore" })
198 await Bun.spawn(["git", "add", "."], { cwd: work, stdout: "ignore", env })
193199 .exited;
194200 await Bun.spawn(
195201 [
@@ -203,7 +209,7 @@ describe("fifty agents at once", () => {
203209 "-m",
204210 `agent ${i}`,
205211 ],
206 { cwd: work, stdout: "ignore", stderr: "ignore" },
212 { cwd: work, stdout: "ignore", stderr: "ignore", env },
207213 ).exited;
208214 }
209215
@@ -211,7 +217,7 @@ describe("fifty agents at once", () => {
211217 Array.from({ length: WRITERS }, (_, i) =>
212218 Bun.spawn(
213219 ["git", "push", "--quiet", "origin", `agent-${i}:agent-${i}`],
214 { cwd: work, stdout: "pipe", stderr: "pipe" },
220 { cwd: work, stdout: "pipe", stderr: "pipe", env },
215221 ),
216222 ).map(async (proc) => ({
217223 code: await proc.exited,
test/app-domains.test.ts +32 −14
@@ -29,6 +29,7 @@ import { addDomain, getDomain, TOKEN_LENGTH } from "../src/core/domains.ts";
2929 import { listEvents } from "../src/core/events.ts";
3030 import type { Repo } from "../src/core/repos.ts";
3131 import { listRuns, type Run } from "../src/core/runs.ts";
32 import { readRunLogTail } from "../src/runs/log.ts";
3233 import { createToken } from "../src/core/tokens.ts";
3334 import { createUser, type User } from "../src/core/users.ts";
3435 import { serve, type Servers } from "../src/http/server.ts";
@@ -267,21 +268,35 @@ describe("an app gets its own domain", () => {
267268 return `${(response.headers.get("set-cookie") ?? "").split(";")[0]!}; forge_mode=dev`;
268269 };
269270
270 async function until<T>(read: () => T | undefined, ms = 60_000): Promise<T> {
271 /** A deploy run as the hook reports it: its state, summary and log tail. */
272 const said = (run: Run): string =>
273 [
274 `deploy ${run.id} is ${run.state}: ${run.summary || "(no summary)"}`,
275 ...readRunLogTail(dataDir, run.id, 20).lines,
276 ].join("\n");
277 /**
278 * The deploy's own end: the first matching run that is `ok` or `failed`.
279 * Out of time, it names where the latest matching run stood instead.
280 */
281 async function settled(
282 where: (run: Run) => boolean,
283 ms = 60_000,
284 ): Promise<Run> {
271285 const deadline = Date.now() + ms;
286 let latest: Run | undefined;
272287 while (Date.now() < deadline) {
273 const value = read();
274 if (value !== undefined) return value;
288 const runs = listRuns(app.db, repo.id, { kind: "deploy", limit: 50 });
289 const done = runs.find(
290 (r) => where(r) && (r.state === "ok" || r.state === "failed"),
291 );
292 if (done !== undefined) return done;
293 latest = runs.find(where);
275294 await Bun.sleep(100);
276295 }
277 throw new Error("did not happen in time");
278 }
279 const settled = (where: (run: Run) => boolean) =>
280 until(() =>
281 listRuns(app.db, repo.id, { kind: "deploy", limit: 50 }).find(
282 (r) => where(r) && (r.state === "ok" || r.state === "failed"),
283 ),
296 throw new Error(
297 `no deploy settled in ${ms} ms; ${latest === undefined ? "none was queued" : said(latest)}`,
284298 );
299 }
285300 const kinds = (prefix: string): string[] =>
286301 listEvents(app.db, { repoId: repo.id, limit: 100 })
287302 .map((e) => e.kind)
@@ -346,15 +361,18 @@ describe("an app gets its own domain", () => {
346361 if (!row.ok) throw new Error(row.error);
347362 other = row.value;
348363 const run = await settled((r) => r.env === "production");
364 // A failed deploy says why in the check's log, not only "failed".
365 if (run.state !== "ok") throw new Error(said(run));
349366 expect(run.state).toBe("ok");
350367 expect((await viaHost(`notes.${DOMAIN}`)).status).toBe(200);
351368 }, 120_000);
352369
353370 afterAll(async () => {
354 await runtime.stop();
355 servers.stop();
356 app.close();
357 await rm(dataDir, { recursive: true, force: true });
371 // A setup that failed part-way leaves later handles unset: stop what started.
372 await runtime?.stop();
373 servers?.stop();
374 app?.close();
375 if (dataDir) await rm(dataDir, { recursive: true, force: true });
358376 });
359377
360378 test("what a domain may be: a hostname someone can own, and not the forge's", () => {
test/board.test.ts +24
@@ -11,6 +11,7 @@ import { mkdtemp, rm } from "node:fs/promises";
1111 import { tmpdir } from "node:os";
1212 import { join } from "node:path";
1313 import { createApp, type App } from "../src/app.ts";
14 import { changeCapacity } from "../src/actions/capacity.ts";
1415 import { enableApp } from "../src/actions/apps.ts";
1516 import { addToCrew, createAgent } from "../src/actions/crew.ts";
1617 import { openIssue } from "../src/actions/issues.ts";
@@ -455,6 +456,26 @@ describe("the board's forge strip", () => {
455456 expect(other).not.toContain("stuck.");
456457 });
457458
459 test("a setting that is not the default is no incident: the strip stays fine and the cards render", async () => {
460 const made = await createRepo(app, admin, { name: "calm" });
461 if (!made.ok) throw new Error(String(made.error));
462 const enabled = await enableApp(app, admin, made.value, { slug: "calm" });
463 if (!enabled.ok) throw new Error(String(enabled.error));
464 claimRun(app.db, createRun(app.db, { repoId: made.value.id, kind: "agent" }).id);
465 // Clear the stuck run the first test left behind.
466 app.db.query("UPDATE run SET state = 'failed' WHERE heartbeat_at = ?1").run("2020-01-01T00:00:00.000Z");
467 expect(changeCapacity(app, admin, "cells.egress", "report").ok).toBe(true);
468 try {
469 const text = await board("root");
470 expect(text).toContain("All fine");
471 expect(text).not.toContain("board-forge-need");
472 expect(text).not.toContain("error-note");
473 expect(text).toContain("board-card board-run");
474 } finally {
475 changeCapacity(app, admin, "cells.egress", "enforce");
476 }
477 });
478
458479 test("a blocked rollout shows in the status line, escaped, for an admin only", async () => {
459480 const guard = mkdtempSync(join(tmpdir(), "forge-board-guard-"));
460481 process.env["FORGE_GUARD_DIR"] = guard;
@@ -467,6 +488,9 @@ describe("the board's forge strip", () => {
467488 const blocked = await board("root");
468489 expect(blocked).toContain("rollout blocked: quota refused &lt;i&gt;8Gi&lt;/i&gt;");
469490 expect(blocked).not.toContain("<i>8Gi</i>");
491 // One line, and the board beneath it still renders.
492 expect(blocked.match(/class="board-forge-need"/g)?.length).toBe(1);
493 expect(blocked).toContain("board-card board-run");
470494 expect(await board("bob")).not.toContain("rollout blocked");
471495 } finally {
472496 delete process.env["FORGE_GUARD_DIR"];
test/capacity.test.ts +3 −5
@@ -35,7 +35,6 @@ import { createUser, type User } from "../src/core/users.ts";
3535 import { startCrew } from "../src/crew/dispatch.ts";
3636 import { Gate } from "../src/git/env.ts";
3737 import { readHealth } from "../src/actions/health.ts";
38 import { EGRESS_REPORTED } from "../src/kernel/vitals.ts";
3938 import { serve, type Servers } from "../src/http/server.ts";
4039 import { readRunLog } from "../src/runs/log.ts";
4140
@@ -344,12 +343,12 @@ describe("report mode is loud to admins, and to nobody else", () => {
344343 const needs = (who: User | undefined): string[] =>
345344 "needs" in readHealth(app, who) ? (readHealth(app, who) as { needs: string[] }).needs : [];
346345
347 test("reported: the admin's vitals and the Capacity page name what is open", async () => {
346 test("reported: the Capacity page says it once, as a note; vitals do not", async () => {
348347 expect(changeCapacity(app, alice, "cells.egress", "report").ok).toBe(true);
349 expect(needs(alice)).toContain(EGRESS_REPORTED);
350 expect(EGRESS_REPORTED).toContain("any public host on ports 80 and 443");
348 expect(needs(alice)).toEqual([]);
351349 const shown = await page();
352350 expect(shown).toContain('id="egress-reported"');
351 expect(shown).not.toMatch(/error-note[^>]*id="egress-reported"/);
353352 expect(shown.replace(/\s+/g, " ")).toContain("may reach any public host on ports 80 and 443");
354353 });
355354
@@ -365,7 +364,6 @@ describe("report mode is loud to admins, and to nobody else", () => {
365364
366365 test("enforced: no warning anywhere", async () => {
367366 expect(changeCapacity(app, alice, "cells.egress", "enforce").ok).toBe(true);
368 expect(needs(alice)).not.toContain(EGRESS_REPORTED);
369367 expect(await page()).not.toContain('id="egress-reported"');
370368 });
371369 });
test/looks.test.ts +8 −5
@@ -424,6 +424,8 @@ describe("the look", () => {
424424 });
425425
426426 test("a look is taken from `app.serving`, while the deploy's tests are still running, and a red check afterward does not remove it", async () => {
427 // The app's test blocks on this file until the look has been taken.
428 const gate = join(dataDir, "slow-red-test.gate");
427429 const branch = await commitToBranch(app, alice, repo, {
428430 branch: "slow-red-test",
429431 base: repo.defaultBranch,
@@ -435,7 +437,7 @@ describe("the look", () => {
435437 {
436438 app: {
437439 run: "bun run src/server.ts",
438 test: "sleep 2 && exit 1",
440 test: `while [ ! -e '${gate}' ]; do sleep 0.05; done; exit 1`,
439441 tty: "bun run src/tty.ts",
440442 },
441443 },
@@ -455,8 +457,8 @@ describe("the look", () => {
455457 const env = `pull-${opened.value.number}`;
456458 const commitOid = branch.value.commitOid;
457459
458 // Pictured well before the two-second test step could have finished —
459 // the run is still open, checking.
460 // Pictured while the test step is held at the gate — the run is still
461 // open, checking.
460462 const rows = await pictured(env, commitOid);
461463 expect(rows.every((l) => l.error === null)).toBe(true);
462464 const run = listRuns(app.db, repo.id, { env }).find(
@@ -469,8 +471,9 @@ describe("the look", () => {
469471 expect(serving?.payload["env"]).toBe(env);
470472 expect(serving?.payload["testsRunning"]).toBe(true);
471473
472 // The test then finishes red; the run fails, but the picture already
473 // taken of what is serving is untouched.
474 // The gate opens and the test finishes red; the run fails, but the
475 // picture already taken of what is serving is untouched.
476 writeFileSync(gate, "");
474477 const failed = await settled(
475478 (r) => r.env === env && r.commitOid === commitOid,
476479 );
test/restore-card.test.ts added +104
@@ -0,0 +1,104 @@
1 /**
2 * The restore card (`docs/RESTORE.md`) runs. Its numbered command lines are
3 * parsed out of the document and executed, in order, against a snapshot
4 * taken here into a temporary directory; a card that drifts from the
5 * command goes red. Only the lines marked `# network` (clone, install) and
6 * `# boot` (start the forge) are skipped, and the test names them so a line
7 * cannot dodge the run by being marked.
8 */
9 import { afterAll, beforeAll, expect, test } from "bun:test";
10 import { existsSync, mkdtempSync, readFileSync } from "node:fs";
11 import { rm } from "node:fs/promises";
12 import { tmpdir } from "node:os";
13 import { join } from "node:path";
14 import { createApp, type App } from "../src/app.ts";
15 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
16 import { createUser } from "../src/core/users.ts";
17 import { dirStore } from "../src/snapshot/store.ts";
18 import { takeSnapshot } from "../src/snapshot/snapshot.ts";
19
20 const PASS = "correct horse battery staple";
21 const card = readFileSync(join(import.meta.dir, "../docs/RESTORE.md"), "utf8");
22 const lines = [...card.matchAll(/^(\d+)\. `(.+)`$/gm)].map((m) => ({
23 n: Number(m[1]),
24 text: m[2]!,
25 }));
26
27 let root: string;
28 let app: App;
29
30 beforeAll(async () => {
31 root = mkdtempSync(join(tmpdir(), "forge-restore-card-"));
32 app = createApp({ dataDir: join(root, "live"), port: 0 });
33 const u = await createUser(app.db, {
34 trusted: true,
35 username: "alice",
36 email: "[email protected]",
37 password: "a-good-passphrase",
38 adminIfFirst: true,
39 });
40 if (!u.ok) throw new Error(u.error);
41 const repo = await createRepo(app, u.value, { name: "notes", visibility: "private" });
42 if (!repo.ok) throw new Error(String(repo.error));
43 const c = await commitToBranch(app, u.value, repo.value, {
44 message: "first",
45 files: [{ path: "README.md", content: "# notes\n" }],
46 });
47 if (!c.ok) throw new Error(JSON.stringify(c.error));
48 await takeSnapshot(
49 {
50 db: app.db,
51 dataDir: app.config.dataDir,
52 reposRoot: app.reposRoot,
53 version: "t",
54 passphrase: PASS,
55 },
56 dirStore(join(root, "store")),
57 new Date("2026-09-22T08:00:00Z"),
58 );
59 });
60
61 afterAll(async () => {
62 app.close();
63 await rm(root, { recursive: true, force: true });
64 });
65
66 test("the card is at most ten numbered lines, in order", () => {
67 expect(lines.length).toBeGreaterThan(0);
68 expect(lines.length).toBeLessThanOrEqual(10);
69 expect(lines.map((l) => l.n)).toEqual(lines.map((_, i) => i + 1));
70 });
71
72 test("only network and boot lines are skipped, and they are the known ones", () => {
73 const skipped = lines.filter((l) => /# (network|boot)$/.test(l.text));
74 expect(skipped.map((l) => l.text.replace(/ # (network|boot)$/, "")).sort()).toEqual([
75 "FORGE_DATA=<data-dir> bun run src/main.ts",
76 "bun install",
77 "git clone https://forge.open-platform.sh/trevato/forge.git forge && cd forge",
78 ]);
79 });
80
81 test("the card's own lines restore the snapshot into an empty directory", async () => {
82 const store = join(root, "store");
83 const data = join(root, "restored");
84 const script = lines
85 .filter((l) => !/# (network|boot)$/.test(l.text))
86 .map((l) =>
87 l.text
88 .replaceAll("<store-dir>", store)
89 .replaceAll("<data-dir>", data)
90 .replaceAll("<passphrase>", PASS),
91 );
92 for (const l of script) expect(l).not.toMatch(/<[a-z-]+>/);
93 const run = Bun.spawnSync(["sh", "-ec", script.join("\n")], {
94 cwd: join(import.meta.dir, ".."),
95 env: { PATH: process.env["PATH"] ?? "", HOME: process.env["HOME"] ?? root },
96 stdout: "pipe",
97 stderr: "pipe",
98 });
99 const out = run.stdout.toString() + run.stderr.toString();
100 expect(out).toContain("restored 2026-09-22T08-00-00Z");
101 expect(run.exitCode).toBe(0);
102 expect(existsSync(join(data, "forge.db"))).toBe(true);
103 expect(existsSync(join(data, "repos"))).toBe(true);
104 });
test/sealed-release.test.ts +12 −4
@@ -43,6 +43,14 @@ const ok = <T>(
4343 return r.value;
4444 };
4545
46 /**
47 * Each case that calls `reportAndFix` runs a commit, a pull and a merge
48 * through real git processes: on a loaded runner that is more than bun's
49 * 5 s default, and a case cut off there reads as red though nothing it
50 * asserts is wrong. They get the room `beforeAll` has.
51 */
52 const GIT_WORK_MS = 30_000;
53
4654 /** A sealed report, and a merged pull that closes it. */
4755 async function reportAndFix(
4856 slug: string,
@@ -156,7 +164,7 @@ describe("the way out: its fix released", () => {
156164 { ref: "refs/heads/main", newOid: baseOid },
157165 ], alice),
158166 ).toEqual([]);
159 });
167 }, GIT_WORK_MS);
160168
161169 test("a tag that contains the merged fix unseals the report and its pull, recorded as the release's", async () => {
162170 const { report, mergeOid, pull } = await reportAndFix("late");
@@ -172,7 +180,7 @@ describe("the way out: its fix released", () => {
172180 e.kind === "issue.unsealed" && e.payload["number"] === report.number,
173181 );
174182 expect(record?.payload["released"]).toBe("v1.0.1");
175 });
183 }, GIT_WORK_MS);
176184 });
177185
178186 describe("a release is a person's", () => {
@@ -188,7 +196,7 @@ describe("a release is a person's", () => {
188196 ),
189197 ).toEqual([]);
190198 expect(getIssue(app.db, repo.id, report.number)!.sealed).toBe(true);
191 });
199 }, GIT_WORK_MS);
192200
193201 test("through a real git push of a writer's tag, the report opens", async () => {
194202 const { report, mergeOid } = await reportAndFix("pushed");
@@ -215,7 +223,7 @@ describe("a release is a person's", () => {
215223 await Bun.sleep(100);
216224 expect(getIssue(app.db, repo.id, report.number)!.sealed).toBe(false);
217225 await rm(work, { recursive: true, force: true });
218 });
226 }, GIT_WORK_MS);
219227 });
220228
221229 describe("what is assigned to you", () => {
test/signin-throttle.test.ts +11
@@ -36,6 +36,17 @@ describe("sign-in attempts are throttled", () => {
3636 adminIfFirst: true,
3737 });
3838 if (!a.ok) throw new Error(a.error);
39 // The throttle counts before the hash runs, so what it counts need not be
40 // costly: alice's stored hash is the cheapest argon2id (verify reads the
41 // cost from the hash itself), keeping twenty guesses to milliseconds.
42 const cheap = await Bun.password.hash("a-good-passphrase", {
43 algorithm: "argon2id",
44 memoryCost: 8,
45 timeCost: 1,
46 });
47 app.db.run("UPDATE user SET password_hash = ?1 WHERE username = 'alice'", [
48 cheap,
49 ]);
3950 });
4051
4152 afterAll(async () => {
test/studio.test.ts +42 −8
@@ -51,6 +51,7 @@ import {
5151 createRun,
5252 finishRun,
5353 getRun,
54 isTerminal,
5455 listRuns,
5556 markServing,
5657 noteRunProgress,
@@ -2540,6 +2541,41 @@ describe("every open pull's preview on the studio page", () => {
25402541 redirect: "manual",
25412542 });
25422543
2544 const WAIT_MS = 60_000;
2545
2546 /** The deploys this repo has not finished, as "env:state" words. */
2547 const unfinished = () =>
2548 listRuns(app.db, repo.id, { kind: "deploy", limit: 50 })
2549 .filter((r) => !isTerminal(r.state))
2550 .map((r) => `${r.env}:${r.state}`);
2551
2552 /** Wait until the runtime has no deploy open or queued, so the next case
2553 * does not queue behind this one's (concurrency is 1). */
2554 async function deploysIdle(): Promise<void> {
2555 const deadline = Date.now() + WAIT_MS;
2556 while (unfinished().length > 0) {
2557 if (Date.now() > deadline)
2558 throw new Error(`deploys still open: ${unfinished().join(", ")}`);
2559 await Bun.sleep(50);
2560 }
2561 }
2562
2563 /** Wait for `env` to serve; fail naming the state it reached. */
2564 async function previewServes(record: AppRecord, env: EnvName): Promise<void> {
2565 const deadline = Date.now() + WAIT_MS;
2566 while (runtime.envStatus(record, env)?.state !== "running") {
2567 if (Date.now() > deadline) {
2568 const status = runtime.envStatus(record, env);
2569 throw new Error(
2570 `${env} did not serve within ${WAIT_MS} ms: state ${status?.state ?? "absent"}` +
2571 (status?.error ? ` (${status.error})` : "") +
2572 `; open deploys: ${unfinished().join(", ") || "none"}`,
2573 );
2574 }
2575 await Bun.sleep(50);
2576 }
2577 }
2578
25432579 beforeAll(async () => {
25442580 dataDir = await mkdtemp(join(tmpdir(), "forge-studio-previews-"));
25452581 app = createApp({ dataDir, port: 0 });
@@ -2637,7 +2673,10 @@ describe("every open pull's preview on the studio page", () => {
26372673 const after = await (await get("/alice/widget")).text();
26382674 expect(after).not.toContain("<h2>Previews</h2>");
26392675 expect(after).not.toContain(`pull-${pull.number}/open`);
2640 }, 30_000);
2676 // The merge queues production's deploy and the pull's was cut short;
2677 // leave the single deploy slot free for the next case.
2678 await deploysIdle();
2679 }, 120_000);
26412680
26422681 test("a change's page names its preview's data as its own copy and gives the moment it was taken; production's card does not", async () => {
26432682 const alice = getUserByName(app.db, "alice")!;
@@ -2659,12 +2698,7 @@ describe("every open pull's preview on the studio page", () => {
26592698 const record = getAppByRepo(app.db, repo.id)!;
26602699 const env = `pull-${pull.number}` as const;
26612700
2662 const deadline = Date.now() + 30_000;
2663 while (
2664 Date.now() < deadline &&
2665 runtime.envStatus(record, env)?.state !== "running"
2666 )
2667 await Bun.sleep(100);
2701 await previewServes(record, env);
26682702 expect(runtime.envStatus(record, env)?.state).toBe("running");
26692703
26702704 const note = "its own copy of production's data, taken";
@@ -2680,7 +2714,7 @@ describe("every open pull's preview on the studio page", () => {
26802714 ).text();
26812715 expect(changePage).toContain("<h2>Preview</h2>");
26822716 expect(changePage).toContain(note);
2683 }, 30_000);
2717 }, 120_000);
26842718 });
26852719
26862720 /**
test/vitals.test.ts +2 −2
@@ -148,8 +148,8 @@ test("the number of queries does not grow with runs", () => {
148148 if (i % 2) app.db.query("UPDATE run SET state='running' WHERE id=?1").run(r.id);
149149 }
150150 expect(count()).toBe(before);
151 // The queue, the running runs, and the egress mode (`core/capacity.ts`).
152 expect(before).toBe(3);
151 // The queue and the running runs.
152 expect(before).toBe(2);
153153 });
154154
155155 test("errors are counted, bounded, redacted, and a burst is said", async () => {
test/web-apps.test.ts +19 −23
@@ -363,32 +363,28 @@ describe("apps, runs and the crew on the web", () => {
363363 // Match the real <meta> / data-stream= attributes — not the same
364364 // strings inside studioRunJs (a bare includes("http-equiv=…") stays
365365 // true after the meta is gone because the script still quotes it).
366 const fresh = listRuns(app.db, hello.id).find((r) => r.id === run!.id)!;
367 const going = fresh.state === "queued" || fresh.state === "running";
366 const isGoing = (): boolean => {
367 const s = listRuns(app.db, hello.id).find((r) => r.id === run!.id)!.state;
368 return s === "queued" || s === "running";
369 };
368370 const hasMetaRefresh = (html: string): boolean =>
369371 /<meta[^>]*http-equiv="refresh"/.test(html);
370 const hasLiveMarkers = (html: string): boolean =>
371 html.includes("data-stream=") || hasMetaRefresh(html);
372 let livePage = page;
373 if (going) {
374 expect(livePage.includes("data-stream=")).toBe(true);
375 expect(hasMetaRefresh(livePage)).toBe(true);
376 } else {
377 // DB already terminal; poll until the page drops both live markers
378 // (one re-fetch was not always enough under CI timing).
379 const deadline = Date.now() + 3_000;
380 for (;;) {
381 livePage = await bodyOf(alice, `/alice/hello/runs/${run!.id}`);
382 if (!hasLiveMarkers(livePage)) break;
383 if (Date.now() >= deadline) {
384 throw new Error(
385 `run ${run!.id} is ${fresh.state} but the page still streams/refreshes after settle`,
386 );
387 }
388 await Bun.sleep(200);
372 // Read the state before and after the render and assert only when they
373 // agree: a run that settles mid-render says nothing, so render again.
374 // A run only moves forward, so this ends once it is done.
375 const deadline = Date.now() + 5_000;
376 for (;;) {
377 const before = isGoing();
378 const html = await bodyOf(alice, `/alice/hello/runs/${run!.id}`);
379 const after = isGoing();
380 if (before === after) {
381 expect(html.includes("data-stream=")).toBe(before);
382 expect(hasMetaRefresh(html)).toBe(before);
383 break;
384 }
385 if (Date.now() >= deadline) {
386 throw new Error(`run ${run!.id} never held one state across a render`);
389387 }
390 expect(livePage.includes("data-stream=")).toBe(false);
391 expect(hasMetaRefresh(livePage)).toBe(false);
392388 }
393389
394390 const door = await web(alice, `/runs/${run!.id}`);
test/web.test.ts +14
@@ -410,6 +410,20 @@ describe("web pages end to end", () => {
410410 expect(stale.status).toBe(404);
411411 });
412412
413 test("the home carries no error-note for a setting that is not the default", async () => {
414 const { changeCapacity } = await import("../src/actions/capacity.ts");
415 const { getUserByName } = await import("../src/core/users.ts");
416 const ada = getUserByName(app.db, "ada")!;
417 expect(changeCapacity(app, ada, "cells.egress", "report").ok).toBe(true);
418 try {
419 const text = await (await fetch(base, { headers: { cookie } })).text();
420 expect(text).not.toContain("error-note");
421 expect(text).not.toContain("Egress is reported");
422 } finally {
423 changeCapacity(app, ada, "cells.egress", "enforce");
424 }
425 });
426
413427 test("new repo via the form, empty state renders", async () => {
414428 const response = await fetch(`${base}/new`, {
415429 method: "POST",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs