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

A child forge's spawn refuses a name already taken with the taken name and two free suggestions #13058

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/13047-a-child-forge-s-spawn-refuses-a-name-alr → main 10 commits fork 2 threads · 2 unresolved

  • Merged. mason/13047-a-child-forge-s-spawn-refuses-a-name-alr was merged into main as fe6d4e2.

Review

Sign in to review this change.
7 files changed +179 −26
docs/features/README.md +1
@@ -314,6 +314,7 @@ Read with the guide page [Hosting forges for others, and getting paid](../guide-
314314 - [The page that answers "make me a forge"](forge-made.md)
315315 - [The Plan row in a forge's settings](plan-row.md)
316316 - [The selling funnel](selling-funnel.md)
317 - [A taken forge name: refused with two free ones](spawn-name-taken.md)
317318 - [The spawner's claim link](spawner-claim-link.md)
318319 - [The statement — what the forge would charge an app](statement.md)
319320 - [Ways to the fleet graph](fleet-graph-doors.md)
docs/features/spawn-name-taken.md added +9
@@ -0,0 +1,9 @@
1 # A taken forge name
2
3 Asking to spawn a forge under a name that is already a child here (in the spawn ledger, or being made right now) is refused `422 invalid`, with the message `name: <name> is taken; free now: <a>, <b>`. The two suggestions are the next numbered names (`acme-2`, `acme-3`, …) that pass the name rules, are not reserved words, and get a `free` verdict from the same check the name itself got (`forgeNameVerdict`). It never says who holds the name.
4
5 One answer on every door, because each goes through `spawnDoor`: `POST /api/v1/forges` (a plan with `dryRun` and the real spawn), the MCP `spawn` tool, the New forge page, Start my forge, and the terminal's New forge and Start forge screens, which show the same message.
6
7 **Contract change:** a different plan for a name already held (a different template, apps or crew) used to answer `409 exists`. It now answers this `422`, since the name is what is taken. The same plan again is unchanged: `200` with `existed: true`. `409 exists` is gone from this path.
8
9 Code: `src/spawn/name_verdict.ts` (`suggestNames`, `takenWords`), `src/actions/spawn.ts` (`takenReason`), `src/spawn/door.ts`. Test: `test/spawn-name-taken.test.ts`.
src/actions/spawn.ts +49 −15
@@ -12,7 +12,7 @@
1212 * idempotent — and a finished one is answered, not made twice.
1313 */
1414
15 import { nameShapeVerdict, nameVerdict, type NameVerdict } from "../spawn/name_verdict.ts";
15 import { nameShapeVerdict, nameVerdict, suggestNames, takenWords, type NameVerdict } from "../spawn/name_verdict.ts";
1616 import { readdirSync, readFileSync } from "node:fs";
1717 import { mkdir, readdir } from "node:fs/promises";
1818 import { join } from "node:path";
@@ -105,7 +105,10 @@ export interface SpawnDeps {
105105 /** The request that asked, for the same-origin check on this mutation. */
106106 readonly request: Request;
107107 readonly url: URL;
108 /** The plan was given by a gift code the caller has already claimed (`actions/codes.ts`): no admin, no payment. */
108 /**
109 * The plan was given by a gift code the caller has already claimed (`actions/codes.ts`): no
110 * admin, no payment.
111 */
109112 readonly gift?: boolean;
110113 /**
111114 * The child's own model key, when the spawner gives it one: an API key, or
@@ -117,7 +120,10 @@ export interface SpawnDeps {
117120 readonly modelKey?: string;
118121 /** Anthropic-compatible API base URL sealed with the starter key (OpenRouter, etc.). */
119122 readonly modelEndpoint?: string;
120 /** The nightly drill's own forge: its spawn events carry `drill`, so the boards keep it as its own series. */
123 /**
124 * The nightly drill's own forge: its spawn events carry `drill`, so the boards keep it as its own
125 * series.
126 */
121127 readonly drill?: boolean;
122128 }
123129
@@ -131,7 +137,10 @@ interface Ledger {
131137 readonly forWhom?: string;
132138 readonly apps?: readonly string[];
133139 readonly createdAt?: string;
134 /** The person who made it, counted against their forges (`spawn/sleep.ts`); absent for a stranger's. */
140 /**
141 * The person who made it, counted against their forges (`spawn/sleep.ts`); absent for a
142 * stranger's.
143 */
135144 readonly ownerId?: string;
136145 /** Absent on a ledger written before sizes; reads as small. */
137146 readonly size?: Size;
@@ -183,11 +192,17 @@ export const childDirOf = (app: App, bodyId: string): string =>
183192 const ledgerPath = (app: App, name: string): string =>
184193 join(app.config.dataDir, "spawn", `${name}.json`);
185194
186 /** Live child URL from name + the parent's origin (ignores stale ledger.url), so old subdomain ledgers still resolve. */
195 /**
196 * Live child URL from name + the parent's origin (ignores stale ledger.url), so old subdomain
197 * ledgers still resolve.
198 */
187199 export const liveChildUrl = (app: App, name: string): string =>
188200 childPublicUrl(name, parentOrigin(app.config));
189201
190 /** A ledger file's text as a `Ledger`, or undefined when it is not JSON or lacks name, bodyId and done: the one check every reader shares. */
202 /**
203 * A ledger file's text as a `Ledger`, or undefined when it is not JSON or lacks name, bodyId and
204 * done: the one check every reader shares.
205 */
191206 export function parseLedger(text: string): Ledger | undefined {
192207 let v: unknown;
193208 try {
@@ -293,7 +308,7 @@ export async function spawnForge(
293308 return err({ kind: "invalid", field: "briefs", reason: `a brief is at most ${BRIEF_MAX} characters` });
outdated

Only ledger files and inFlight are consulted; existing forges that make a name taken are not, so a suggestion can be taken. Use forgeNameVerdict per candidate.

294309 }
295310
296 if (inFlight.has(plan.name)) return err({ kind: "exists", message: "that child is being made" });
311 if (inFlight.has(plan.name)) return err({ kind: "invalid", field: "name", reason: await takenReason(app, plan.name) });
297312 inFlight.add(plan.name);
298313 try {
299314 return await make(app, owner, plan, deps);
@@ -302,6 +317,11 @@ export async function spawnForge(
302317 }
303318 }
304319
320 /** "is taken" and two names free now, each proven free by the verdict the name itself got. */
321 export async function takenReason(app: App, name: string): Promise<string> {
322 return takenWords(name, await suggestNames(name, async (c) => (await forgeNameVerdict(app, c)).verdict !== "free"));
323 }
324
305325 async function make(
306326 app: App,
307327 owner: User | undefined,
@@ -314,7 +334,7 @@ async function make(
314334 let ledger = await readLedger(app, plan.name);
315335 if (ledger) {
316336 if (ledger.planHash !== planHash)
317 return err({ kind: "exists", message: `a different child named ${plan.name} already exists` });
337 return err({ kind: "invalid", field: "name", reason: await takenReason(app, plan.name) });
318338 // The plan names that there is a key, never which: a retry with another
319339 // key is refused plainly rather than quietly keeping the first.
320340 if (deps.modelKey !== undefined) {
@@ -335,12 +355,14 @@ async function make(
335355 // A retry of an unfinished child is a new attempt: its failure has a start.
336356 app.bus.append({ kind: "forge.spawn.started", payload: { ...(deps.drill === true ? { drill: 1 } : {}) } });
337357 } else {
338 // A paid plan is held to its own count, never the free one; the free plan keeps today's per-person limits.
358 // A paid plan is held to its own count, never the free one; the free plan keeps today's
359 // per-person limits.
339360 const chosen = plan.plan === undefined ? undefined : getPlan(app.db, plan.plan);
340361 if (plan.plan !== undefined && chosen === undefined)
341362 return err({ kind: "invalid", field: "plan", reason: `${plan.plan} is not a plan this forge offers` });
342363 if (chosen !== undefined && chosen.key !== FREE && deps.gift === true) {
343 // A redeemed gift code (`actions/codes.ts`) or a paid order (`actions/order.ts`) is what lends this plan: it asks no admin.
364 // A redeemed gift code (`actions/codes.ts`) or a paid order (`actions/order.ts`) is what
365 // lends this plan: it asks no admin.
344366 } else if (chosen !== undefined && chosen.key !== FREE) {
345367 if (owner === undefined) return err({ kind: "refused", reason: "plan", message: `the ${chosen.name} plan is for a signed-in person; sign in first` });
346368 if (!owner.isAdmin) return err({ kind: "refused", reason: "plan", message: PAID_PLAN_ADMIN_ONLY(chosen.name) });
@@ -724,7 +746,8 @@ async function startFresh(
724746 * undefined when it has none yet (or the child's database is not there).
725747 */
726748 async function heldKey(dir: string): Promise<string | undefined> {
727 // The child's database is asked off this thread (`spawn/child_db.ts`); only the sealed row comes back.
749 // The child's database is asked off this thread (`spawn/child_db.ts`); only the sealed row comes
750 // back.
728751 const row = await childSubscription(dir, STARTER_KEY);
729752 if (row === undefined) return undefined;
730753 try {
@@ -786,12 +809,17 @@ export async function reissueClaimFor(
786809 }
787810 }
788811
789 /** What this forge shows a child it made to learn its private facts; undefined for an older child. */
812 /**
813 * What this forge shows a child it made to learn its private facts; undefined for an older child.
814 */
790815 export async function statusTokenOf(app: App, name: string): Promise<string | undefined> {
791816 return (await readLedger(app, name))?.statusToken;
792817 }
793818
794 /** The key a child of this forge signs heartbeats with; undefined for a name this forge did not make. */
819 /**
820 * The key a child of this forge signs heartbeats with; undefined for a name this forge did not
821 * make.
822 */
795823 export async function beatKeyOf(app: App, name: string): Promise<string | undefined> {
796824 return (await readLedger(app, name))?.beatKey;
797825 }
@@ -815,7 +843,10 @@ export interface Child {
815843 readonly placementNote: string | null;
816844 /** Where its move into a cell of its own stands, when one was ever tried (`spawn/where.ts`). */
817845 readonly sandbox?: SandboxNotes;
818 /** The person who made it (their id here); absent for a stranger's or a ledger from before it was kept. */
846 /**
847 * The person who made it (their id here); absent for a stranger's or a ledger from before it was
848 * kept.
849 */
819850 readonly ownerId?: string;
820851 }
821852
@@ -852,7 +883,10 @@ export async function listChildren(app: App): Promise<Child[]> {
852883 return ledgers.flatMap((ledger) => (ledger ? [childOf(app, ledger)] : []));
853884 }
854885
855 /** `listChildren`, read at once: for a terminal command that draws in the same turn (one small file per child). */
886 /**
887 * `listChildren`, read at once: for a terminal command that draws in the same turn (one small file
888 * per child).
889 */
856890 export function listChildrenNow(app: App): Child[] {
857891 const dir = join(app.config.dataDir, "spawn");
858892 let files: string[];
src/spawn/door.ts +18 −8
@@ -12,7 +12,7 @@ import { nameShapeVerdict } from "./name_verdict.ts";
1212 import { linkRequestVisitor } from "../perf/visitor_link.ts";
1313 import { startWatch, probeOf, type Probe } from "./live.ts";
1414 import { firstProof, reachWords, settleChild } from "./reach.ts";
15 import { founderClash, reissueClaim, spawnForge, type SpawnError } from "../actions/spawn.ts";
15 import { forgeNameVerdict, founderClash, reissueClaim, spawnForge, takenReason, type SpawnError } from "../actions/spawn.ts";
1616 import type { App } from "../app.ts";
1717 import { maxChildren } from "../core/capacity.ts";
1818 import { getAgentByName } from "../core/agents.ts";
@@ -55,7 +55,10 @@ const MAX_CREW = 100;
5555 const placements = new WeakMap<App, Placement>();
5656 const probes = new WeakMap<App, (url: string) => Probe>();
5757
58 /** The probe this forge asks a child's address with: the test's when one was set, else `/healthz` within `timeoutMs`. */
58 /**
59 * The probe this forge asks a child's address with: the test's when one was set, else `/healthz`
60 * within `timeoutMs`.
61 */
5962 export function probeFor(app: App, url: string, timeoutMs: number): Probe {
6063 const swapped = probes.get(app);
6164 return swapped ? swapped(url) : probeOf(url, timeoutMs);
@@ -191,9 +194,10 @@ export async function spawnDoor(
191194 user: User | undefined,
192195 raw: Record<string, unknown>,
193196 /**
194 * `paid`: the plan was bought (`actions/order.ts`), so a paid plan needs no admin and a stranger's rate limits do not apply.
195 * `page`: a person is waiting on this answer in a browser, so it does not wait on the first reach proof: the page shows
196 * the forge starting (`web/forge_made.ts`) and the proof goes on behind it, an alarm if it never comes.
197 * `paid`: the plan was bought (`actions/order.ts`), so a paid plan needs no admin and a
198 * stranger's rate limits do not apply. `page`: a person is waiting on this answer in a browser,
199 * so it does not wait on the first reach proof: the page shows the forge starting
200 * (`web/forge_made.ts`) and the proof goes on behind it, an alarm if it never comes.
197201 */
198202 opts: { readonly paid?: boolean; readonly page?: boolean } = {},
199203 ): Promise<Door> {
@@ -290,7 +294,8 @@ export async function spawnDoor(
290294 // A plan (`settings/plans.ts`) gives the child its size; read now, so an edit governs this spawn.
291295 let planKey: string | undefined;
292296 let size = raw["size"];
293 // A gift code (`actions/codes.ts`) names the plan itself: no admin, no payment, whatever the provider.
297 // A gift code (`actions/codes.ts`) names the plan itself: no admin, no payment, whatever the
298 // provider.
294299 const giftIn = raw["code"];
295300 let giftSeen: { plan: string } | undefined;
296301 if (giftIn !== undefined && giftIn !== null && giftIn !== "") {
@@ -315,6 +320,9 @@ export async function spawnDoor(
315320 if (typeof raw["name"] === "string") {
316321 const said = nameShapeVerdict(raw["name"]);
317322 if (said?.verdict === "reserved") return invalid("name", said.why);
323 // A plan for a taken name says so now, with free names, not after the form is filled in.
324 if (dry && said === undefined && (await forgeNameVerdict(ctx.app, raw["name"])).verdict === "taken")
325 return invalid("name", await takenReason(ctx.app, raw["name"]));
318326 }
319327 const input = {
320328 name: raw["name"],
@@ -366,7 +374,8 @@ export async function spawnDoor(
366374 },
367375 };
368376 }
369 // The use is spent just before the forge is made, in one statement; it goes back if no forge is made.
377 // The use is spent just before the forge is made, in one statement; it goes back if no forge is
378 // made.
370379 let gift: Code | undefined;
371380 if (giftIn !== undefined && giftIn !== null && giftIn !== "") {
372381 const claimed = claimCode(ctx.app.db, giftIn);
@@ -374,7 +383,8 @@ export async function spawnDoor(
374383 gift = claimed.value;
375384 }
376385 const startedAt = Date.now();
377 // The use is given back unless the forge was made and the redemption recorded: a throw settles it too.
386 // The use is given back unless the forge was made and the redemption recorded: a throw settles it
387 // too.
378388 let settled = false;
379389 let made: Awaited<ReturnType<typeof spawnForge>>;
380390 try {
src/spawn/name_verdict.ts +25 −1
@@ -20,10 +20,34 @@ export function nameShapeVerdict(name: string): NameVerdict | undefined {
2020 return undefined;
2121 }
2222
23 /** The verdict for `name`; `exists` says whether a child of that name is in the ledger or being made. */
23 /**
24 * The verdict for `name`; `exists` says whether a child of that name is in the ledger or being
25 * made.
26 */
2427 export function nameVerdict(name: string, exists: boolean): NameVerdict {
2528 const shape = nameShapeVerdict(name);
2629 if (shape !== undefined) return shape;
2730 if (exists) return { verdict: "taken", why: `a forge named ${name} already exists` };
2831 return { verdict: "free", why: `${name} is free` };
2932 }
33
34 /**
35 * Up to two free names near a taken one, each passing the name rules and the
36 * reserved list. `taken` says whether a candidate is spoken for; the caller
37 * answers it with the same verdict the name itself got, so nothing here knows why a name is taken.
38 */
39 export async function suggestNames(name: string, taken: (candidate: string) => boolean | Promise<boolean>): Promise<string[]> {
40 const out: string[] = [];
41 const stem = name.replace(/-\d+$/, "");
42 for (let n = 2; out.length < 2 && n < 100; n++) {
43 const candidate = `${stem.slice(0, 39 - String(n).length - 1).replace(/-+$/, "")}-${n}`;
44 if (nameShapeVerdict(candidate) === undefined && !(await taken(candidate))) out.push(candidate);
45 }
46 return out;
47 }
48
49 /** The one sentence a taken name gets, on every door. Never says who holds it. */
50 export function takenWords(name: string, suggestions: readonly string[]): string {
51 const tail = suggestions.length === 0 ? "" : `; free now: ${suggestions.join(", ")}`;
52 return `${name} is taken${tail}`;
53 }
test/spawn-name-taken.test.ts added +72
@@ -0,0 +1,72 @@
1 /** A taken forge name is refused 422 as "is taken" with two free suggestions. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp } from "../src/app.ts";
7 import type { Ctx } from "../src/http/context.ts";
8 import { spawnDoor } from "../src/spawn/door.ts";
9 import { isSystemName } from "../src/core/reserved.ts";
10 import { takenReason } from "../src/actions/spawn.ts";
11 import { suggestNames, takenWords } from "../src/spawn/name_verdict.ts";
12
13 let dir = "";
14 let app: ReturnType<typeof createApp>;
15 const ctx = (): Ctx => ({
16 app,
17 request: new Request("http://localhost/"),
18 url: new URL("http://localhost/"),
19 params: {},
20 auth: { user: undefined, scope: undefined, via: "none" },
21 theme: undefined,
22 });
23
24 beforeAll(async () => {
25 dir = await mkdtemp(join(tmpdir(), "spawn-name-taken-"));
26 app = createApp({ dataDir: dir, port: 0 });
27 await mkdir(join(dir, "spawn"), { recursive: true });
28 for (const n of ["acme", "acme-2"]) await writeFile(join(dir, "spawn", `${n}.json`), JSON.stringify({ name: n, bodyId: "b", done: true }));
29 });
30 afterAll(async () => {
31 app.close();
32 await rm(dir, { recursive: true, force: true });
33 });
34
35 test("taken: 422, says taken, offers two free names and no more", async () => {
36 const door = await spawnDoor(ctx(), undefined, { name: "acme", apps: [], crew: [], dryRun: true });
37 expect(door.status).toBe(422);
38 expect(door.body["message"]).toBe("name: acme is taken; free now: acme-3, acme-4");
39 });
40
41 test("reserved is still reserved; a free name still plans", async () => {
42 const r = await spawnDoor(ctx(), undefined, { name: "admin", apps: [], crew: [], dryRun: true });
43 expect(r.status).toBe(422);
44 expect(String(r.body["message"])).not.toContain("taken");
45 const f = await spawnDoor(ctx(), undefined, { name: "fresh-one", apps: [], crew: [], dryRun: true });
46 expect(f.status).toBe(200);
47 });
48
49 test("suggestions pass the name rules and skip the reserved list", async () => {
outdated

Add a candidate that is reserved, and tests for spawnForge non-dry, in-flight, and the API/MCP response; takenWords("a", []) is trivial.

50 const long = await suggestNames("x".repeat(39), () => false);
51 expect(long.length).toBe(2);
52 expect(long.every((s) => s.length <= 39 && /^[a-z0-9-]+$/.test(s))).toBe(true);
53 expect(await suggestNames("acme", (c) => c === "acme-2")).toEqual(["acme-3", "acme-4"]);
54 // forge-5 reads as the reserved word "forges": never offered, though nobody holds it.
55 expect(isSystemName("forge-5")).toBe(true);
56 expect(await suggestNames("forge-1", (c) => c !== "forge-3" && c !== "forge-4" && c !== "forge-6")).toEqual(["forge-3", "forge-4"]);
57 expect(await suggestNames("forge-1", (c) => c === "forge-2" || c === "forge-3" || c === "forge-4")).toEqual(["forge-6", "forge-7"]);
58 expect(takenWords("acme", ["acme-3"])).toBe("acme is taken; free now: acme-3");
59 expect(takenWords("acme", [])).toBe("acme is taken");
60 });
61
62 test("a suggestion is never an existing forge or one being made", async () => {
63 await writeFile(join(dir, "spawn", "beta-2.json"), JSON.stringify({ name: "beta-2", bodyId: "b", done: true }));
64 await writeFile(join(dir, "spawn", "beta.json"), JSON.stringify({ name: "beta", bodyId: "b", done: true }));
65 expect(await takenReason(app, "beta")).toBe("beta is taken; free now: beta-3, beta-4");
66 });
67
68 test("the real spawn, not a plan, is refused 422 with the same words", async () => {
69 const door = await spawnDoor(ctx(), undefined, { name: "acme", apps: [], crew: [], dryRun: false });
70 expect(door.status).toBe(422);
71 expect(door.body["message"]).toBe("name: acme is taken; free now: acme-3, acme-4");
72 });
test/spawn-template-api.test.ts +5 −2
@@ -142,8 +142,11 @@ describe("choosing a template for a new forge", () => {
142142
143143 // Another template is another child: refused, as a different plan is.
144144 const retry = await post({ name: "tpl", apps: ["alice/notes"], template: "blank", dryRun: false });
145 expect(retry.status).toBe(409);
146 expect(((await retry.json()) as any).error).toBe("exists");
145 expect(retry.status).toBe(422);
146 expect(((await retry.json()) as any).message).toContain("tpl is taken");
147 const viaMcp = await mcp("spawn", { name: "tpl", apps: ["alice/notes"], template: "blank", dryRun: false });
148 expect(viaMcp.error).toBe(true);
149 expect(viaMcp.text).toContain("tpl is taken; free now: tpl-2, tpl-3");
147150 const same = await post({ name: "tpl", apps: ["alice/notes"], template: "starter", dryRun: false });
148151 expect(same.status).toBe(200);
149152 expect(((await same.json()) as any).existed).toBe(true);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs