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

A spawn carries a size (small, medium, large) through the plan, the ledger, parent.json, GET /api/v1/forges and MCP spawn #2984

Parked opened this
Closed without merging

scout/forge:scout/2980-a-spawn-carries-a-size-small-medium-larg → main 3 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
15 files changed +263 −5
README.md +1 −1
@@ -456,7 +456,7 @@ Unset, only this machine may say so, and the named header is never read. Everyth
456456 instance _is_ lives under the data directory — the SQLite index, the bare
457457 repos, and the SSH host key, in plain layout. Tar it up and it moves.
458458
459 `/forges/new`, `POST /api/v1/forges` and the MCP `spawn` make a client's forge from forks of the apps you pick, plus optionally one fresh app from a one-line description (`fresh`, at most 200 characters), and end in one claim link; see `docs/SPAWN.md`.
459 `/forges/new`, `POST /api/v1/forges` and the MCP `spawn` make a client's forge from forks of the apps you pick, plus optionally one fresh app from a one-line description (`fresh`, at most 200 characters), and end in one claim link; see `docs/SPAWN.md`. Each takes an optional `size` (`small`, `medium` or `large`; default `small`; an unknown one is a 422): on the page a select, in the terminal a field, in the API and MCP an input. It is recorded in the plan (only when given), the ledger, `parent.json` and `GET /api/v1/forges`, and nothing enforces it yet.
460460
461461 `FORGE_PARENT_URL` names the forge this one was spawned from. It must be
462462 `https://` with no credentials or query (the forge refuses to boot otherwise).
src/actions/spawn.ts +8
@@ -55,6 +55,7 @@ import { claimLink, hasAdmin, mintClaim, spawnedOrg } from "../spawn/claim.ts";
5555 import { childPublicUrl, parentOrigin, type Placement } from "../spawn/placement.ts";
5656 import { planSpawn, type SpawnInput, type SpawnPlan, type SpawnSource } from "../spawn/plan.ts";
5757 import { chainForChild, DEFAULT_MODE, forgeLinkOf, type FollowMode, type Hop } from "../spawn/chain.ts";
58 import { DEFAULT_SIZE, isSize, type Size } from "../spawn/sizes.ts";
5859 import { requireUser } from "./access.ts";
5960
6061 export interface Spawned {
@@ -106,6 +107,8 @@ interface Ledger {
106107 readonly forWhom?: string;
107108 readonly apps?: readonly string[];
108109 readonly createdAt?: string;
110 /** Absent on a ledger written before sizes; read as `small`. */
111 readonly size?: Size;
109112 /**
110113 * What the parent shows the child to learn its private facts (when anything
111114 * last happened); the child keeps only its hash. Never in an answer.
@@ -243,6 +246,7 @@ async function make(
243246 done: false,
244247 ...(plan.forWhom === undefined ? {} : { forWhom: plan.forWhom }),
245248 apps: plan.apps.map((a) => a.ref),
249 size: plan.size ?? DEFAULT_SIZE,
246250 createdAt: new Date().toISOString(),
247251 statusToken: secret(),
248252 beatKey: secret(),
@@ -437,6 +441,7 @@ async function copyInto(
437441 // The child's own address: <name>--<parent's host>.
438442 url: liveChildUrl(app, plan.name),
439443 keepAccess: plan.keepAccess,
444 size: plan.size ?? DEFAULT_SIZE,
440445 // Each app is a fork: where it came from, so the child can follow it.
441446 apps: plan.apps.map((a) => ({ repo: `${plan.org}/${a.ref.split("/")[1]}`, upstream: a.ref })),
442447 ...(plan.fresh === undefined ? {} : { fresh: `${plan.org}/${plan.fresh.name}` }),
@@ -645,6 +650,8 @@ export interface Child {
645650 readonly apps: readonly string[];
646651 /** When it was begun; null on a ledger older than the client list. */
647652 readonly createdAt: string | null;
653 /** What size it was asked to be; `small` when the ledger says nothing. */
654 readonly size: Size;
648655 }
649656
650657 /** The children this forge has made or begun, from its ledger, by name. */
@@ -663,6 +670,7 @@ export async function listChildren(app: App): Promise<Child[]> {
663670 for: ledger.forWhom ?? null,
664671 apps: ledger.apps ?? [],
665672 createdAt: ledger.createdAt ?? null,
673 size: isSize(ledger.size) ? ledger.size : DEFAULT_SIZE,
666674 });
667675 }
668676 return out;
src/http/mcp.ts +5
@@ -1488,6 +1488,11 @@ const TOOLS: readonly Tool[] = [
14881488 description:
14891489 "How the child follows this forge's code: tell-me (default) says when the parent has moved; take-updates takes them.",
14901490 },
1491 size: {
1492 type: "string",
1493 enum: ["small", "medium", "large"],
1494 description: "How big the child is asked to be (default small). Recorded for now; nothing enforces it yet.",
1495 },
14911496 keepAccess: {
14921497 type: "boolean",
14931498 description:
src/spawn/door.ts +1
@@ -236,6 +236,7 @@ export async function spawnDoor(
236236 budgetUsd: raw["budgetUsd"],
237237 fresh: raw["fresh"],
238238 followMode: raw["followMode"],
239 size: raw["size"],
239240 ...(anon ? {} : { for: raw["for"] }),
240241 };
241242
src/spawn/plan.ts +14
@@ -9,6 +9,7 @@
99
1010 import { err, ok, type Result } from "../kernel/result.ts";
1111 import { DEFAULT_MODE, type FollowMode } from "./chain.ts";
12 import { parseSize, type Size } from "./sizes.ts";
1213
1314 export const MAX_APPS = 50;
1415 export const MAX_BRIEFS = 100;
@@ -69,6 +70,8 @@ export interface SpawnInput {
6970 readonly fresh?: unknown;
7071 /** How the child follows the forge's code: `tell-me` (default) or `take-updates`. */
7172 readonly followMode?: unknown;
73 /** `small`, `medium` or `large`; optional, and left out of the plan when not given. */
74 readonly size?: unknown;
7275 }
7376
7477 /** What the parent has to offer. Extra fields are ignored, never copied. */
@@ -109,6 +112,8 @@ export interface SpawnPlan {
109112 readonly fresh?: PlannedFresh;
110113 /** How the child follows its parent's forge code; absent means `tell-me`. */
111114 readonly followMode?: FollowMode;
115 /** The size asked for; absent when none was, which the ledger reads as `small`. */
116 readonly size?: Size;
112117 }
113118
114119 export interface DryRun {
@@ -250,6 +255,14 @@ export function planSpawn(
250255 if (input.followMode !== DEFAULT_MODE) followMode = input.followMode;
251256 }
252257
258 // Last, so a bad size never hides a fault in a field checked before it.
259 let size: Size | undefined;
260 if (input.size !== undefined && input.size !== null && input.size !== "") {
261 const parsed = parseSize(input.size);
262 if (!parsed.ok) return refuse("size", parsed.error);
263 size = parsed.value;
264 }
265
253266 // `forWhom` only when said, so a plan without it hashes as it always did.
254267 return ok({
255268 name,
@@ -263,6 +276,7 @@ export function planSpawn(
263276 ...(forWhom === "" ? {} : { forWhom }),
264277 ...(fresh === undefined ? {} : { fresh }),
265278 ...(followMode === undefined ? {} : { followMode }),
279 ...(size === undefined ? {} : { size }),
266280 });
267281 }
268282
src/spawn/sizes.ts added +31
@@ -0,0 +1,31 @@
1 /**
2 * Sizes: what a child forge may be asked to be, as one table. Only a name and
3 * the room it stands for; nothing here enforces anything yet.
4 */
5
6 import { err, ok, type Result } from "../kernel/result.ts";
7
8 export type Size = "small" | "medium" | "large";
9
10 export interface SizeSpec {
11 readonly cpu: number;
12 readonly memoryMiB: number;
13 readonly diskMiB: number;
14 }
15
16 export const SIZES: Readonly<Record<Size, SizeSpec>> = {
17 small: { cpu: 1, memoryMiB: 512, diskMiB: 1024 },
18 medium: { cpu: 2, memoryMiB: 2048, diskMiB: 5120 },
19 large: { cpu: 4, memoryMiB: 8192, diskMiB: 20480 },
20 };
21
22 export const DEFAULT_SIZE: Size = "small";
23
24 export const isSize = (v: unknown): v is Size =>
25 typeof v === "string" && Object.hasOwn(SIZES, v);
26
27 /** A size, or one sentence saying which are allowed. */
28 export function parseSize(v: unknown): Result<Size, string> {
29 if (isSize(v)) return ok(v);
30 return err("must be small, medium or large");
31 }
src/tui/screens/newforge.ts +3
@@ -34,6 +34,7 @@ const SPECS: readonly Spec[] = [
3434 { key: "modelEndpoint", label: "API base URL", hint: "A gateway for the key; empty for Anthropic. Optional." },
3535 { key: "budgetUsd", label: "Budget in dollars", hint: `${MIN_BUDGET_USD}–${MAX_BUDGET_USD}, for the key's whole life. Needed with a key.` },
3636 { key: "followMode", label: "Follows this forge's code", hint: "tell-me (default) or take-updates. Recorded for now: nothing tells you or takes updates yet." },
37 { key: "size", label: "Size", hint: "small (default), medium or large. Recorded for now." },
3738 ];
3839
3940 /** The door's "field: reason" refusal, as the field it names and the reason. */
@@ -60,6 +61,7 @@ export function newForgeScreen(f: Session, ctx: Ctx): Screen {
6061 apps,
6162 ...(val("fresh") === "" ? {} : { fresh: val("fresh") }),
6263 followMode: val("followMode") === "" ? "tell-me" : val("followMode"),
64 ...(val("size") === "" ? {} : { size: val("size") }),
6365 ...(val("for") === "" ? {} : { for: val("for") }),
6466 ...(val("direction") === "" ? {} : { direction: val("direction") }),
6567 ...(val("modelKey") === "" ? {} : { modelKey: val("modelKey") }),
@@ -110,6 +112,7 @@ export function newForgeScreen(f: Session, ctx: Ctx): Screen {
110112 plan = [
111113 `A forge at ${childUrlOf(f.app, val("name"))}.`,
112114 `Recorded for now, not acted on: it follows this forge's code as ${val("followMode") === "" ? "tell-me" : val("followMode")}.`,
115 `Size: ${(body["plan"] as { size?: string } | undefined)?.size ?? "small"}. Recorded for now, not enforced.`,
113116 "Whoever opens the link becomes its admin.",
114117 ...(budget === null ? [] : [`Its crew runs on your key, up to $${budget} for the key's whole life.`]),
115118 "Copied into it:",
src/web/pages/new-forge.ts +17 −1
@@ -25,7 +25,8 @@ import { notFoundPage, pageHead } from "../chrome.ts";
2525 import { field, readForm, type Form } from "../form.ts";
2626 import { html, type Html } from "../html.ts";
2727 import { page } from "../layout.ts";
28 import { btn, card, field as formField } from "../ui.ts";
28 import { SIZES } from "../../spawn/sizes.ts";
29 import { btn, card, field as formField, selectField } from "../ui.ts";
2930
3031 interface Values {
3132 readonly name: string;
@@ -35,6 +36,7 @@ interface Values {
3536 readonly crew: readonly string[];
3637 readonly fresh: string;
3738 readonly followMode: string;
39 readonly size: string;
3840 readonly keepAccess: boolean;
3941 readonly budgetUsd: string;
4042 readonly modelEndpoint: string;
@@ -50,6 +52,7 @@ const EMPTY: Values = {
5052 crew: [],
5153 fresh: "",
5254 followMode: "tell-me",
55 size: "",
5356 keepAccess: false,
5457 budgetUsd: "",
5558 modelEndpoint: "",
@@ -206,6 +209,17 @@ function formView(
206209 ? html`<span class="error" id="f-followMode-err">${errors["followMode"]}</span>`
207210 : null}
208211 </fieldset>
212 ${selectField({
outdated

Hand-rolled select. Use selectField from ../ui.ts instead: DESIGN.md names it as the select component. Extend it with error (the same anatomy field() has) rather than copying that markup here.

213 name: "size",
214 label: "Size (optional)",
outdated

This hand-built select has no aria-describedby pointing at the hint and error, and no aria-invalid="true" when errors.size is set. Every field() control on this page has both, so a screen reader reaches the 422 here only by chance. Give the hint id="f-size-hint", then add aria-describedby="f-size-hint f-size-err" (the -err part only when there is an error) and aria-invalid to the select. Or teach field() in src/web/ui.ts a type: "select" with options, so the next select doesn't hand-roll it again.

215 hint: "Small unless you choose. Recorded for now; nothing enforces it yet.",
outdated

Small appears twice: "Small (the default)" with value "", then the mapped small. The capitalisation is mixed too (Small against small, medium, large). Make it one option per size: drop the empty option and select small when values.size is empty, or skip small in the map. Use the same casing for all three.

216 ...(errors["size"] ? { error: errors["size"] } : {}),
217 options: Object.keys(SIZES).map((s) => ({
218 value: s,
219 label: s,
220 selected: (values.size || "small") === s,
221 })),
222 })}
209223 ${crew.length === 0
210224 ? null
211225 : html`<fieldset class="field">
@@ -391,6 +405,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
391405 crew: all(form, "crew"),
392406 fresh: field(form, "fresh").trim(),
393407 followMode: field(form, "followMode").trim() || "tell-me",
408 size: field(form, "size").trim(),
394409 keepAccess: asBool(form, "keepAccess"),
395410 budgetUsd: field(form, "budgetUsd").trim(),
396411 modelEndpoint: field(form, "modelEndpoint").trim(),
@@ -405,6 +420,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
405420 keepAccess: values.keepAccess,
406421 ...(values.fresh === "" ? {} : { fresh: values.fresh }),
407422 followMode: values.followMode,
423 ...(values.size === "" ? {} : { size: values.size }),
408424 ...(values.forWhom === "" ? {} : { for: values.forWhom }),
409425 ...(values.direction.trim() === "" ? {} : { direction: values.direction }),
410426 ...(key === "" ? {} : { modelKey: key }),
src/web/ui.ts +15 −3
@@ -1056,9 +1056,18 @@ export function selectField(
10561056 },
10571057 ): Html {
10581058 const id = o.id ?? `f-${o.name}`;
1059 return html`<div class="field">
1059 const described = [o.hint ? `${id}-hint` : "", o.error ? `${id}-err` : ""]
1060 .filter(Boolean)
1061 .join(" ");
1062 return html`<div class="field" ${o.error ? raw("data-invalid") : null}>
10601063 <label for="${id}">${o.label}</label>
1061 <select class="input" id="${id}" name="${o.name}">
1064 <select
1065 class="input"
1066 id="${id}"
1067 name="${o.name}"
1068 ${described !== "" ? html`aria-describedby="${described}"` : null}
1069 ${o.error ? raw('aria-invalid="true"') : null}
1070 >
10621071 ${o.options.map(
10631072 (opt) =>
10641073 html`<option
@@ -1069,7 +1078,10 @@ export function selectField(
10691078 </option>`,
10701079 )}
10711080 </select>
1072 ${o.hint ? html`<span class="hint">${o.hint}</span>` : null}
1081 ${o.hint ? html`<span class="hint" id="${id}-hint">${o.hint}</span>` : null}
1082 ${o.error
1083 ? html`<span class="error" id="${id}-err">${o.error}</span>`
1084 : null}
10731085 </div>`;
10741086 }
10751087
test/select-field.test.ts added +19
@@ -0,0 +1,19 @@
1 import { expect, test } from "bun:test";
2 import { selectField } from "../src/web/ui.ts";
3
4 const options = [{ value: "a", label: "a", selected: true }];
5
6 test("selectField with an error marks the control invalid and renders the error row", () => {
7 const out = String(selectField({ name: "size", label: "Size", hint: "h", error: "bad", options }));
8 expect(out).toContain('aria-invalid="true"');
9 expect(out).toContain('aria-describedby="f-size-hint f-size-err"');
10 expect(out).toContain('id="f-size-err"');
11 expect(out).toContain("data-invalid");
12 });
13
14 test("selectField without an error stays valid", () => {
15 const out = String(selectField({ name: "size", label: "Size", hint: "h", options }));
16 expect(out).not.toContain("aria-invalid");
17 expect(out).not.toContain("data-invalid");
18 expect(out).toContain('aria-describedby="f-size-hint"');
19 });
test/spawn-api.test.ts +1
@@ -144,6 +144,7 @@ describe("spawn over the API and MCP", () => {
144144 {
145145 name: "kid",
146146 url: expect.stringContaining("kid"),
147 size: "small",
147148 bodyId: "fake-1",
148149 done: true,
149150 for: null,
test/spawn-keys.test.ts +1
@@ -364,6 +364,7 @@ describe("a spawned child's own keys and domain", () => {
364364 "keepAccess",
365365 "name",
366366 "org",
367 "size",
367368 // The hash of the parent's status secret (#776): the child keeps only
368369 // the hash, so this names nothing in the parent and reveals no secret.
369370 "statusHash",
test/spawn-sizes.test.ts added +132
@@ -0,0 +1,132 @@
1 /**
2 * A spawn carries a size (#2980): one table, optional in the input, absent
3 * from the plan when not given, `small` in the ledger and parent.json, and
4 * a 422 beside its own field on the New forge page.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, readFile, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { listChildren } from "../src/actions/spawn.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { serve, type Servers } from "../src/http/server.ts";
15 import { sha256 } from "../src/kernel/hash.ts";
16 import { usePlacement } from "../src/spawn/door.ts";
17 import { hostedPlacement, memoryBodies } from "../src/spawn/placement.ts";
18 import { planSpawn } from "../src/spawn/plan.ts";
19 import { parseSize, SIZES } from "../src/spawn/sizes.ts";
20 import { quietLogs } from "./helpers/globals.ts";
21
22 quietLogs();
23
24 const base = { name: "kid", org: "kid", apps: [], carryBriefs: false, carrySubscriptions: false };
25 const source = { catalog: [], briefs: [], subscriptions: [] };
26
27 describe("the size table", () => {
28 test("three sizes, each with cpu, memory and disk, growing", () => {
29 expect(Object.keys(SIZES)).toEqual(["small", "medium", "large"]);
30 expect(SIZES.small.cpu).toBeLessThan(SIZES.medium.cpu);
31 expect(SIZES.medium.memoryMiB).toBeLessThan(SIZES.large.memoryMiB);
32 expect(SIZES.medium.diskMiB).toBeLessThan(SIZES.large.diskMiB);
33 });
34
35 test("parseSize returns a size or one sentence", () => {
36 expect(parseSize("medium")).toEqual({ ok: true, value: "medium" });
37 for (const bad of ["huge", "", 3, null, "toString", "__proto__"]) {
38 const r = parseSize(bad);
39 expect(r.ok).toBe(false);
40 if (!r.ok) expect(r.error).toBe("must be small, medium or large");
41 }
42 });
43 });
44
45 describe("the plan", () => {
46 test("without a size it hashes as it always did", () => {
47 const r = planSpawn(base, source);
48 if (!r.ok) throw new Error("plan");
49 expect("size" in r.value).toBe(false);
50 expect(sha256(JSON.stringify(r.value))).toBe(
51 "24a0aabd3a29917ba38154bc05fb1a8a751133adf0bf4b0815ba02f96525570b",
52 );
53 });
54
55 test("a size is carried; an unknown one is refused after the other fields", () => {
56 const r = planSpawn({ ...base, size: "large" }, source);
57 expect(r.ok && r.value.size).toBe("large");
58 const bad = planSpawn({ ...base, size: "huge" }, source);
59 expect(!bad.ok && bad.error.field).toBe("size");
60 const both = planSpawn({ ...base, size: "huge", direction: 5 }, source);
61 expect(!both.ok && both.error.field).toBe("direction");
62 });
63 });
64
65 describe("the door", () => {
66 let dir = "";
67 let app: App;
68 let servers: Servers;
69 let cookie = "";
70
71 beforeAll(async () => {
72 dir = await mkdtemp(join(tmpdir(), "forge-sizes-"));
73 app = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
74 const a = await createUser(app.db, {
75 origin: "seed",
76 trusted: true,
77 username: "alice",
78 email: "[email protected]",
79 password: "a-long-sizes-passphrase",
80 isAdmin: true,
81 });
82 if (!a.ok) throw new Error("user");
83 usePlacement(app, hostedPlacement({ host: "https://forge.test", store: memoryBodies(), maxChildren: () => 10 }));
84 servers = await serve(app);
85 const res = await fetch(`${servers.url}/signin`, {
86 method: "POST",
87 body: new URLSearchParams({ username: "alice", password: "a-long-sizes-passphrase" }),
88 redirect: "manual",
89 });
90 cookie = (res.headers.get("set-cookie") ?? "").split(";")[0]!;
91 }, 30_000);
92
93 afterAll(async () => {
94 servers.stop();
95 app.close();
96 await rm(dir, { recursive: true, force: true });
97 });
98
99 const post = (form: [string, string][]) =>
100 fetch(`${servers.url}/forges/new`, {
101 method: "POST",
102 headers: { cookie, origin: "https://forge.test" },
103 body: new URLSearchParams(form),
104 redirect: "manual",
105 });
106
107 test("an unknown size is a 422 beside its field", async () => {
108 const res = await post([["name", "tiny"], ["size", "huge"]]);
109 expect(res.status).toBe(422);
110 const text = await res.text();
111 expect(text).toContain('id="f-size-err"');
112 expect(text).toContain("must be small, medium or large");
113 });
114
115 test("a bad earlier field is reported before the size", async () => {
116 const res = await post([["name", "Bad Name"], ["size", "huge"]]);
117 expect(res.status).toBe(422);
118 expect(await res.text()).not.toContain('id="f-size-err"');
119 });
120
121 test("no size means small in the ledger and parent.json; a chosen one is kept", async () => {
122 expect((await post([["name", "plain"]])).status).toBe(201);
123 expect((await post([["name", "bigger"], ["size", "large"]])).status).toBe(201);
124 const sizes = Object.fromEntries((await listChildren(app)).map((c) => [c.name, c.size]));
125 expect(sizes).toEqual({ plain: "small", bigger: "large" });
126 const ledger = JSON.parse(await readFile(join(dir, "spawn", "bigger.json"), "utf8"));
127 expect(ledger.size).toBe("large");
128 const bodyId = (await listChildren(app)).find((c) => c.name === "plain")!.bodyId;
129 const parent = JSON.parse(await readFile(join(dir, "children", bodyId, "parent.json"), "utf8"));
130 expect(parent.size).toBe("small");
131 });
132 });
test/spawn.test.ts +1
@@ -85,6 +85,7 @@ describe("spawnForge", () => {
8585 org: "kids",
8686 url: "https://kid--forge.test",
8787 keepAccess: false,
88 size: "small",
8889 // A hash only: what the parent answers to stays in its own ledger.
8990 statusHash: expect.stringMatching(/^[0-9a-f]{64}$/),
9091 // The child signs heartbeats to its parent with it (#425).
test/tui-newforge.test.ts +14
@@ -191,3 +191,17 @@ describe("the new forge screen", () => {
191191 }
192192 }));
193193 });
194
195 describe("the new forge screen's size", () => {
196 test("a size typed in the terminal reaches the ledger", () =>
197 withScreen(admin, async ({ tui, terminal }) => {
198 terminal.feed("lia" + "\t".repeat(9) + "large");
199 terminal.feed("\x10");
200 await settleApp(tui);
201 expect(tui.screen.toText()).toContain("Size: large");
202 terminal.feed("\r");
203 await settleApp(tui);
204 const ledger = JSON.parse(await Bun.file(join(dir, "spawn", "lia.json")).text());
205 expect(ledger.size).toBe("large");
206 }));
207 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs