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, with no form change #2997

Parked opened this
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
10 files changed +142 −2
docs/SPAWN.md +1 −1
@@ -70,7 +70,7 @@ Children report in; the parent never reaches in. Every ten minutes a spawned chi
7070
7171 ## Callers
7272
73 `POST /api/v1/forges {name, apps[], crew[], direction?, keepAccess?, modelKey?, budgetUsd?, dryRun}` (rw token, admin only) and the MCP `spawn` tool share `src/spawn/door.ts`. `dryRun` is true unless it is `false`: the answer is the plan and what is left behind, and nothing is made. `GET /api/v1/forges` lists the ledger's children. The child's org is its name; `crew` names the agents whose briefs travel. Errors: 401 unauthorized, 403 forbidden / cross_origin, 422 invalid, 409 refused / exists, 500 failed — each with one sentence. The MCP lets an `ro` token plan, never make.
73 `POST /api/v1/forges {name, apps[], crew[], direction?, keepAccess?, modelKey?, budgetUsd?, size?, dryRun}` (rw token, admin only) and the MCP `spawn` tool share `src/spawn/door.ts`. `size` is `small` (default), `medium` or `large`; anything else is a 422 on `size`. It is recorded in the plan, the ledger, `parent.json` and `GET /api/v1/forges`, but not enforced yet: it limits nothing. `dryRun` is true unless it is `false`: the answer is the plan and what is left behind, and nothing is made. `GET /api/v1/forges` lists the ledger's children. The child's org is its name; `crew` names the agents whose briefs travel. Errors: 401 unauthorized, 403 forbidden / cross_origin, 422 invalid, 409 refused / exists, 500 failed — each with one sentence. The MCP lets an `ro` token plan, never make.
7474
7575 ## The forge's own code, and the chain (#1085)
7676
src/actions/spawn.ts +7
@@ -54,6 +54,7 @@ import { loadOrCreateHostKey } from "../ssh/keys.ts";
5454 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";
57 import { DEFAULT_SIZE, isSize, type Size } from "../spawn/sizes.ts";
5758 import { chainForChild, DEFAULT_MODE, forgeLinkOf, type FollowMode, type Hop } from "../spawn/chain.ts";
5859 import { requireUser } from "./access.ts";
5960
@@ -108,6 +109,8 @@ interface Ledger {
108109 readonly forWhom?: string;
109110 readonly apps?: readonly string[];
110111 readonly createdAt?: string;
112 /** Absent on a ledger written before sizes; reads as small. */
113 readonly size?: Size;
111114 /**
112115 * What the parent shows the child to learn its private facts (when anything
113116 * last happened); the child keeps only its hash. Never in an answer.
@@ -254,6 +257,7 @@ async function make(
254257 ...(plan.forWhom === undefined ? {} : { forWhom: plan.forWhom }),
255258 apps: plan.apps.map((a) => a.ref),
256259 createdAt: new Date().toISOString(),
260 size: plan.size ?? DEFAULT_SIZE,
257261 statusToken: secret(),
258262 beatKey: secret(),
259263 };
@@ -448,6 +452,7 @@ async function copyInto(
448452 // The child's own address: <name>--<parent's host>.
449453 url: liveChildUrl(app, plan.name),
450454 keepAccess: plan.keepAccess,
455 size: plan.size ?? DEFAULT_SIZE,
451456 // Each app is a fork: where it came from, so the child can follow it.
452457 apps: plan.apps.map((a) => ({ repo: `${plan.org}/${a.ref.split("/")[1]}`, upstream: a.ref })),
453458 ...(plan.fresh === undefined ? {} : { fresh: `${plan.org}/${plan.fresh.name}` }),
@@ -656,6 +661,7 @@ export interface Child {
656661 readonly apps: readonly string[];
657662 /** When it was begun; null on a ledger older than the client list. */
658663 readonly createdAt: string | null;
664 readonly size: Size;
659665 }
660666
661667 /** The children this forge has made or begun, from its ledger, by name. */
@@ -674,6 +680,7 @@ export async function listChildren(app: App): Promise<Child[]> {
674680 for: ledger.forWhom ?? null,
675681 apps: ledger.apps ?? [],
676682 createdAt: ledger.createdAt ?? null,
683 size: isSize(ledger.size) ? ledger.size : DEFAULT_SIZE,

The legacy fallback is untested, because every ledger in the tests is written by new code that always sets size. Write a ledger without size (or with a bad value) and assert that the list reads small.

677684 });
678685 }
679686 return out;
src/http/mcp.ts +5
@@ -1490,6 +1490,11 @@ const TOOLS: readonly Tool[] = [
14901490 description:
14911491 "How the child follows this forge's code: tell-me (default) says when the parent has moved; take-updates takes them.",
14921492 },
1493 size: {

Add a test that MCP spawn with size: "large" (not dry) gets to the ledger. The schema enum alone doesn't show that the value gets through.

1494 type: "string",
1495 enum: ["small", "medium", "large"],
1496 description: "How much the child gets: small (default), medium or large.",
1497 },
14931498 keepAccess: {
14941499 type: "boolean",
14951500 description:
src/spawn/door.ts +1
@@ -257,6 +257,7 @@ export async function spawnDoor(
257257 budgetUsd: raw["budgetUsd"],
258258 fresh: raw["fresh"],
259259 followMode: raw["followMode"],
260 size: raw["size"],

No test covers this line: remove it and every suite stays green. Add one: POST /api/v1/forges with size: "medium" should show medium in the ledger, parent.json and GET /api/v1/forges, and size: "huge" should get a 422 on field size.

260261 ...(anon ? {} : { for: raw["for"] }),
261262 };
262263
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. */
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 means `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 // Checked last, so every older refusal keeps its place.
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.size;
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 +29
@@ -0,0 +1,29 @@
1 /**
2 * Sizes: what `small`, `medium` and `large` mean for a child, in one table.
3 * Pure data and one parser; nothing here reads or writes.
4 */
5
6 export type Size = "small" | "medium" | "large";
7
8 export interface SizeSpec {
9 readonly cpu: number;
10 readonly memoryMiB: number;
11 readonly diskMiB: number;
12 }
13
14 export const SIZES: Readonly<Record<Size, SizeSpec>> = {
15 small: { cpu: 1, memoryMiB: 512, diskMiB: 2048 },
16 medium: { cpu: 2, memoryMiB: 2048, diskMiB: 8192 },
17 large: { cpu: 4, memoryMiB: 8192, diskMiB: 32768 },
18 };
19
20 export const DEFAULT_SIZE: Size = "small";
21
22 export const isSize = (v: unknown): v is Size =>
23 typeof v === "string" && Object.hasOwn(SIZES, v);
24
25 /** A size, or one sentence saying which are allowed. */
26 export function parseSize(v: unknown): { ok: true; size: Size } | { ok: false; error: string } {
27 if (isSize(v)) return { ok: true, size: v };
28 return { ok: false, error: "must be small, medium or large" };
29 }
test/spawn-api.test.ts +36 −1
@@ -4,7 +4,7 @@
44 * fake placement stands in for where the child lives.
55 */
66 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, readdir, rm } from "node:fs/promises";
7 import { mkdir, mkdtemp, readdir, rm } from "node:fs/promises";
88 import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
@@ -150,6 +150,7 @@ describe("spawn over the API and MCP", () => {
150150 for: null,
151151 apps: expect.any(Array),
152152 createdAt: expect.any(String),
153 size: "small",
153154 },
154155 ]);
155156 // The same request again is answered, not made twice.
@@ -198,4 +199,38 @@ describe("spawn over the API and MCP", () => {
198199 expect(body.claimUrl).toContain("/claim#");
199200 expect(body.says).toContain("live secret");
200201 });
202
203 const ledgerOf = async (name: string) => JSON.parse(await Bun.file(join(dataDir, "spawn", `${name}.json`)).text());
204 const parentOf = async (bodyId: string) => JSON.parse(await Bun.file(join(dataDir, "children", bodyId, "parent.json")).text());
205 const sizeListed = async (name: string) => ((await (await get(ro)).json()) as any).items.find((i: any) => i.name === name)?.size;
206
207 test("size travels through POST /api/v1/forges into the ledger, parent.json and the list; huge is refused", async () => {
208 const bad = await post(rw, { name: "sized-api", apps: [], size: "huge" });
209 expect(bad.status).toBe(422);
210 expect(((await bad.json()) as any).message).toStartWith("size:");
211 const res = await post(rw, { name: "sized-api", apps: [], size: "medium", dryRun: false });
212 expect(res.status).toBe(201);
213 const ledger = await ledgerOf("sized-api");
214 expect(ledger.size).toBe("medium");
215 expect((await parentOf(ledger.bodyId)).size).toBe("medium");
216 expect(await sizeListed("sized-api")).toBe("medium");
217 });
218
219 test("size travels through MCP spawn into the ledger, parent.json and the list", async () => {
220 const m = await mcp(rw, { name: "sized-mcp", apps: [], size: "large", dryRun: false });
221 expect(m.error).toBe(false);
222 const ledger = await ledgerOf("sized-mcp");
223 expect(ledger.size).toBe("large");
224 expect((await parentOf(ledger.bodyId)).size).toBe("large");
225 expect(await sizeListed("sized-mcp")).toBe("large");
226 });
227
228 test("a ledger without a size, or with a bad one, lists as small", async () => {
229 const dir = join(dataDir, "spawn");
230 await mkdir(dir, { recursive: true });
231 await Bun.write(join(dir, "legacy-a.json"), JSON.stringify({ name: "legacy-a", bodyId: "old-a", done: true }));
232 await Bun.write(join(dir, "legacy-b.json"), JSON.stringify({ name: "legacy-b", bodyId: "old-b", done: true, size: "__proto__" }));
233 expect(await sizeListed("legacy-a")).toBe("small");
234 expect(await sizeListed("legacy-b")).toBe("small");
235 });
201236 });
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 +47
@@ -0,0 +1,47 @@
1 import { describe, expect, test } from "bun:test";
2 import { planSpawn } from "../src/spawn/plan.ts";
3 import { parseSize, SIZES } from "../src/spawn/sizes.ts";
4 import { sha256 } from "../src/kernel/hash.ts";
5
6 const source = { catalog: [], briefs: [], subscriptions: [] };
7 const base = { name: "kid", org: "kid", apps: [], carryBriefs: false, carrySubscriptions: false };
8
9 describe("sizes", () => {
10 test("one table maps each size to cpu, memory and disk", () => {
11 expect(Object.keys(SIZES)).toEqual(["small", "medium", "large"]);
12 for (const s of Object.values(SIZES)) {
13 expect(s.cpu).toBeGreaterThan(0);
14 expect(s.memoryMiB).toBeGreaterThan(0);
15 expect(s.diskMiB).toBeGreaterThan(0);
16 }
17 });
18
19 test("parseSize returns a size or one sentence", () => {
20 expect(parseSize("large")).toEqual({ ok: true, size: "large" });
21 for (const bad of ["huge", "", 3, null, "toString", "__proto__"]) {
22 const r = parseSize(bad);
23 expect(r.ok).toBe(false);
24 if (!r.ok) expect(r.error).toBe("must be small, medium or large");
25 }
26 });
27
28 test("a plan without a size hashes as it always did", () => {
29 const r = planSpawn(base, source);
30 expect(r.ok).toBe(true);
31 if (!r.ok) return;
32 expect("size" in r.value).toBe(false);
33 expect(sha256(JSON.stringify(r.value))).toBe(
34 "24a0aabd3a29917ba38154bc05fb1a8a751133adf0bf4b0815ba02f96525570b",
35 );
36 });
37
38 test("a size given is in the plan; an unknown one is refused after the other checks", () => {
39 const r = planSpawn({ ...base, size: "medium" }, source);
40 expect(r.ok && r.value.size).toBe("medium");
41 const bad = planSpawn({ ...base, size: "huge" }, source);
42 expect(bad).toEqual({ ok: false, error: { field: "size", reason: "must be small, medium or large" } });
43 // An earlier field's refusal wins.
44 const first = planSpawn({ ...base, direction: 5, size: "huge" }, source);
45 expect(!first.ok && first.error.field).toBe("direction");
46 });
47 });
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).

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs