Public: anyone can read this; the crew can change it.
Making a new forge can name a template, and its code and apps come from that repository #12831
Check · Review · Land · Live done — Landed and live in production.
mason/forge:mason/12432-making-a-new-forge-can-name-a-template-a → main 8 commits fork 4 threads · 4 unresolved
docs/MCP.md +1 −1
| @@ -204,7 +204,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`; | ||
| 204 | 204 | | `signup` | — | Sign-ups: open (default); invite lets in only a person with an open invite link; closed refuses every new account | 324 | |
| 205 | 205 | | `sizes` | — | A child forge's sizes: small, medium and large, each with CPU, memory and disk | 196 | |
| 206 | 206 | | `snapshot_now` | — | Take a snapshot now, as Backups does (admin) | 133 | |
| 207 | | `spawn` | — | Spawn a child forge | 946 | | |
| 207 | | `spawn` | — | Spawn a child forge | 980 | | |
| 208 | 208 | | `spend` | — | Report what your session spent outside forge runs: who, model, tokens or dollars, issue | 470 | |
| 209 | 209 | | `ssh_keys` | `list`, `add`, `remove` | Your SSH keys; add: key, remove: id | 250 | |
| 210 | 210 | | `steer` | — | Say a word to one crew run by its id | 224 | |
docs/features/README.md +1
| @@ -34,6 +34,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md). | ||
| 34 | 34 | - [](home-plans.md) |
| 35 | 35 | - [](returning-visitors.md) |
| 36 | 36 | - [](repo-template.md) |
| 37 | - [](new-forge-template.md) | |
| 37 | 38 | - [](explore.md) |
| 38 | 39 | - [](feed-cursor.md) |
| 39 | 40 | - [](fork-tree.md) |
docs/features/new-forge-template.md added +7
| @@ -0,0 +1,7 @@ | ||
| 1 | # New forge from a template | |
| 2 | ||
| 3 | A new forge can start from a template repository: one an admin marked at Settings → Templates and the maker can read. The New forge page has one Template select (default "The forge's own code", then Blank, Starter app and each readable template repository); the terminal's New forge screen cycles the same list with left and right, or takes `owner/name` typed. `POST /api/v1/forges` and the MCP spawn tool take `template: "owner/name"`. An unmarked or unreadable repository answers 422 saying which. | |
| 4 | ||
| 5 | The template's code becomes the child's own `forge` repository. It keeps the template's visibility: a private template never becomes a public repository in the child. | |
| 6 | ||
| 7 | Code: `src/spawn/templates.ts` (ids and words), `src/spawn/forge_code.ts` (the fork), `src/actions/spawn.ts` (the checks). |
src/actions/spawn.ts +16 −2
| @@ -44,6 +44,7 @@ import { commitFiles } from "../git/write.ts"; | ||
| 44 | 44 | import { adoptForgeCode, forkForgeCode } from "../spawn/forge_code.ts"; |
| 45 | 45 | import { lendIncludedCredit } from "../spawn/included_credit.ts"; |
| 46 | 46 | import { seedStarterCrew } from "../spawn/starter_crew.ts"; |
| 47 | import { repoTemplateRef, templateNotMarked, templateNotReadable } from "../spawn/templates.ts"; | |
| 47 | 48 | import { birthFromTemplate, type TemplateMark } from "../spawn/template_birth.ts"; |
| 48 | 49 | import { writePrivate } from "../kernel/file_modes.ts"; |
| 49 | 50 | import { sha256 } from "../kernel/hash.ts"; |
| @@ -278,6 +279,15 @@ export async function spawnForge( | ||
| 278 | 279 | if (!repo || !canRead(app.db, repo, owner)) |
| 279 | 280 | return err({ kind: "invalid", field: "apps", reason: `${a.ref} is not readable by you` }); |
| 280 | 281 | } |
| 282 | // The same read check the apps pass; a template is also marked. | |
| 283 | const templateRef = plan.template === undefined ? undefined : repoTemplateRef(plan.template); | |
| 284 | if (templateRef !== undefined) { | |
| 285 | const [o, n] = templateRef.split("/") as [string, string]; | |
| 286 | const repo = getRepo(app.db, o, n); | |
| 287 | if (!repo || !canRead(app.db, repo, owner)) | |
| 288 | return err({ kind: "invalid", field: "template", reason: templateNotReadable(templateRef) }); | |
| 289 | if (!repo.template) return err({ kind: "invalid", field: "template", reason: templateNotMarked(templateRef) }); | |
| 290 | } | |
| 281 | 291 | for (const b of plan.briefs) { |
| 282 | 292 | if (b.text.length > BRIEF_MAX) |
| 283 | 293 | return err({ kind: "invalid", field: "briefs", reason: `a brief is at most ${BRIEF_MAX} characters` }); |
| @@ -524,7 +534,11 @@ async function copyInto( | ||
| 524 | 534 | // smallest app that answers, committed once. |
| 525 | 535 | // With a template, the sentence describes the template's app instead: |
| 526 | 536 | // one repository, not two (`spawn/template_birth.ts`). |
| 527 | if (plan.template !== undefined) { | |
| 537 | // A template repository supplies the code below instead; the sentence, if any, still | |
| 538 | // begins a fresh app. | |
| 539 | const fromRepo = plan.template === undefined ? undefined : repoTemplateRef(plan.template); | |
| 540 | if (fromRepo !== undefined) templateMark = { id: fromRepo, repo: fromRepo }; | |
| 541 | if (plan.template !== undefined && fromRepo === undefined) { | |
| 528 | 542 | const born = await birthFromTemplate(child, org, { |
| 529 | 543 | template: plan.template, |
| 530 | 544 | ...(plan.fresh === undefined ? {} : { fresh: plan.fresh }), |
| @@ -543,7 +557,7 @@ async function copyInto( | ||
| 543 | 557 | // A cross-forge fork: the history is copied by git, and the upstream |
| 544 | 558 | // is recorded in parent.json for the child to pull from. Skipped when |
| 545 | 559 | // the forge does not name its code repository (`forgeRepo`). |
| 546 | const forgeCode = await forkForgeCode(app, child, org.username, plan.followMode ?? DEFAULT_MODE); | |
| 560 | const forgeCode = await forkForgeCode(app, child, org.username, plan.followMode ?? DEFAULT_MODE, fromRepo); | |
| 547 | 561 | if (!forgeCode.ok) return err(forgeCode.error); |
| 548 | 562 | |
| 549 | 563 | for (const b of plan.briefs) { |
src/http/mcp/tools/spawn.ts +1 −1
| @@ -45,7 +45,7 @@ export const tool: Tool = { | ||
| 45 | 45 | }, |
| 46 | 46 | template: { |
| 47 | 47 | type: "string", |
| 48 | description: "From `templates`.", | |
| 48 | description: "From `templates`, or owner/name of a template repo.", | |
| 49 | 49 | }, |
| 50 | 50 | keepAccess: { |
| 51 | 51 | type: "boolean", |
src/http/mcp/tools/templates.ts +1 −1
| @@ -3,7 +3,7 @@ import { good, type Tool } from "../shared.ts"; | ||
| 3 | 3 | |
| 4 | 4 | export const tool: Tool = { |
| 5 | 5 | name: "templates", |
| 6 | doc: "the templates a child forge may start from (`blank` first, the default), each with id, title, one sentence and source; pass an id as `spawn`'s `template`", | |
| 6 | doc: "the templates a child forge may start from (`blank` first, the default), each with id, title, one sentence and source; pass an id as `spawn`'s `template`; so may the `owner/name` of a repository marked as a template", | |
| 7 | 7 | description: "The templates a child forge may start from.", |
| 8 | 8 | inputSchema: { type: "object", properties: {} }, |
| 9 | 9 | writes: false, |
src/spawn/forge_code.ts +9 −3
| @@ -57,8 +57,10 @@ export async function forkForgeCode( | ||
| 57 | 57 | child: App, |
| 58 | 58 | orgName: string, |
| 59 | 59 | mode: FollowMode, |
| 60 | /** A template repository (`owner/name`) whose code stands in for the forge's own (#12432). */ | |
| 61 | template?: string, | |
| 60 | 62 | ): Promise<Result<ForgeCode | undefined, string>> { |
| 61 | const ref = await forgeCodeRef(app); | |
| 63 | const ref = template ?? (await forgeCodeRef(app)); | |
| 62 | 64 | if (ref === undefined) return ok(undefined); |
| 63 | 65 | const [o, n] = ref.split("/") as [string, string]; |
| 64 | 66 | const parent = getRepo(app.db, o, n); |
| @@ -69,8 +71,12 @@ export async function forkForgeCode( | ||
| 69 | 71 | const made = await createRepo(child.db, child.reposRoot, { |
| 70 | 72 | ownerId: org.id, |
| 71 | 73 | name: FORGE_CODE_NAME, |
| 72 | visibility: "public", | |
| 73 | description: `A fork of ${o}/${n}: the forge's own code, following its parent.`, | |
| 74 | // A template's code is no more public in the child than it is here. | |
| 75 | visibility: template === undefined ? "public" : parent.visibility, | |
| 76 | description: | |
| 77 | template === undefined | |
| 78 | ? `A fork of ${o}/${n}: the forge's own code, following its parent.` | |
| 79 | : `A fork of the template ${o}/${n}: this forge's code and apps.`, | |
| 74 | 80 | defaultBranch: parent.defaultBranch, |
| 75 | 81 | }); |
| 76 | 82 | if (!made.ok) return err(`could not make the child's forge repo: ${made.error}`); |
src/spawn/templates.ts +31 −8
| @@ -36,18 +36,41 @@ export const TEMPLATES: readonly Template[] = [ | ||
| 36 | 36 | }, |
| 37 | 37 | ]; |
| 38 | 38 | |
| 39 | /** A template id, or one sentence naming the valid ones. */ | |
| 40 | export function parseTemplate(v: unknown): Result<string, string> { | |
| 41 | if (typeof v === "string" && TEMPLATES.some((t) => t.id === v)) return ok(v); | |
| 42 | const ids = TEMPLATES.map((t) => t.id); | |
| 43 | return err(`template must be ${ids.slice(0, -1).join(", ")} or ${ids[ids.length - 1]}`); | |
| 39 | /** A template repository, named `owner/name` (#12432). */ | |
| 40 | const REPO_REF = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}\/[A-Za-z0-9._-]{1,100}$/; | |
| 41 | ||
| 42 | /** The `owner/name` a template id names, or undefined for a built-in one. */ | |
| 43 | export function repoTemplateRef(id: string): string | undefined { | |
| 44 | return REPO_REF.test(id) ? id : undefined; | |
| 44 | 45 | } |
| 45 | 46 | |
| 46 | /** The title of a template already validated by `parseTemplate`. */ | |
| 47 | export function templateOf(id: string): Template { | |
| 48 | return TEMPLATES.find((t) => t.id === id) ?? TEMPLATES[0]!; | |
| 47 | /** | |
| 48 | * A template id (built in, or `owner/name` of a template repository), or one sentence naming | |
| 49 | * the valid ones. | |
| 50 | */ | |
| 51 | export function parseTemplate(v: unknown): Result<string, string> { | |
| 52 | if (typeof v === "string" && TEMPLATES.some((t) => t.id === v)) return ok(v); | |
| 53 | if (typeof v === "string" && repoTemplateRef(v) !== undefined) return ok(v); | |
The refusal for an invalid id still says 'template must be blank, starter' only; with owner/name now valid, the sentence is wrong. Update it and the tests that pin it. |
||
| 54 | const ids = TEMPLATES.map((t) => t.id); | |
| 55 | return err(`template must be ${ids.join(", ")} or the owner/name of a template repository`); | |
| 49 | 56 | } |
| 50 | 57 | |
| 58 | /** The title of a template already validated by `parseTemplate`; a repository's is its name. */ | |
| 59 | export function templateOf(id: string): Template { | |
| 60 | const built = TEMPLATES.find((t) => t.id === id); | |
| 61 | if (built !== undefined) return built; | |
| 62 | if (repoTemplateRef(id) !== undefined) | |
| 63 | return { id, title: id, says: "The code and apps of that repository.", source: "repo", repo: id }; | |
| 64 | return TEMPLATES[0]!; | |
| 65 | } | |
| 66 | ||
| 67 | /** | |
| 68 | * The refusal's words when a repository cannot serve as a template; one place, so the page, | |
| 69 | * the door and the MCP say the same. | |
| 70 | */ | |
| 71 | export const templateNotMarked = (ref: string): string => `${ref} is not marked as a template`; | |
| 72 | export const templateNotReadable = (ref: string): string => `${ref} is not readable by you`; | |
| 73 | ||
| 51 | 74 | /** What each template is, for a page or an agent to offer. */ |
| 52 | 75 | export function templatesView(): { templates: readonly Template[]; default: string } { |
| 53 | 76 | return { templates: TEMPLATES, default: DEFAULT_TEMPLATE }; |
src/tui/screens/newforge.ts +19 −12
| @@ -7,8 +7,9 @@ | ||
| 7 | 7 | * dialog, and kept nowhere. Any signed-in person's, as the page is. |
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | import { listReposVisibleTo } from "../../core/repos.ts"; | |
| 10 | 11 | import { DEFAULT_SIZE, SIZES, type Size } from "../../spawn/sizes.ts"; |
| 11 | import { DEFAULT_TEMPLATE, TEMPLATES, templateOf } from "../../spawn/templates.ts"; | |
| 12 | import { DEFAULT_TEMPLATE, repoTemplateRef, TEMPLATES, templateOf } from "../../spawn/templates.ts"; | |
| 12 | 13 | import { childUrlOf, spawnDoor } from "../../spawn/door.ts"; |
| 13 | 14 | import { quotaFull } from "../../spawn/quota.ts"; |
| 14 | 15 | import { FOLLOW_LINE, FOLLOW_WORDS } from "../../spawn/follow_words.ts"; |
| @@ -35,7 +36,7 @@ const SIZE_CHOICES = Object.keys(SIZES) as Size[]; | ||
| 35 | 36 | |
| 36 | 37 | const TEMPLATE_CHOICES = TEMPLATES.map((t) => t.id); |
| 37 | 38 | |
| 38 | const TEMPLATE_HINT = "blank (default) or starter: left and right choose, or type it."; | |
| 39 | const TEMPLATE_HINT = "blank (default), starter or a template repository as owner/name: left and right choose, or type it."; | |
| 39 | 40 | |
| 40 | 41 | const SPECS: readonly Spec[] = [ |
| 41 | 42 | { key: "name", label: "Name", hint: "Lowercase letters, digits and dashes." }, |
| @@ -54,7 +55,8 @@ const SPECS: readonly Spec[] = [ | ||
| 54 | 55 | /** The chosen template's own sentence; a typed id that is no template keeps the general hint. */ |
| 55 | 56 | function templateHint(id: string): string { |
| 56 | 57 | const t = TEMPLATES.find((x) => x.id === id); |
| 57 | return t === undefined ? TEMPLATE_HINT : t.says; | |
| 58 | if (t !== undefined) return t.says; | |
| 59 | return repoTemplateRef(id) === undefined ? TEMPLATE_HINT : templateOf(id).says; | |
| 58 | 60 | } |
| 59 | 61 | |
| 60 | 62 | /** The door's "field: reason" refusal, as the field it names and the reason. */ |
| @@ -65,6 +67,11 @@ function refusal(body: Record<string, unknown>): { key?: string; text: string } | ||
| 65 | 67 | } |
| 66 | 68 | |
| 67 | 69 | export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, string> = {}): Screen { |
| 70 | // The built-in templates, then the template repositories this person can read: the page's list. | |
New behaviour with no test: the choices list now includes the readable template repos, and a typed owner/name gets that repo sentence. Add a tui-newforge test that fails without this (cycle right to the repo; an unmarked or private-unreadable repo is absent). |
||
| 71 | const repoTemplates = listReposVisibleTo(f.app.db, f.user, { templatesOnly: true, limit: 50 }).map( | |
| 72 | (r) => `${r.ownerName}/${r.name}`, | |
| 73 | ); | |
| 74 | const specs = SPECS.map((s) => (s.key === "template" ? { ...s, choices: [...TEMPLATE_CHOICES, ...repoTemplates] } : s)); | |
| 68 | 75 | const values: Record<string, string> = { ...initial }; |
| 69 | 76 | let focus = 0; |
| 70 | 77 | let errorKey: string | undefined; |
| @@ -114,7 +121,7 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str | ||
| 114 | 121 | values["modelKey"] = ""; |
| 115 | 122 | error = r.text; |
| 116 | 123 | errorKey = r.key; |
| 117 | const at = SPECS.findIndex((s) => s.key === r.key); | |
| 124 | const at = specs.findIndex((s) => s.key === r.key); | |
| 118 | 125 | if (at >= 0) focus = at; |
| 119 | 126 | plan = undefined; |
| 120 | 127 | ctx.toast(r.text, "danger"); |
| @@ -194,9 +201,9 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str | ||
| 194 | 201 | } |
| 195 | 202 | // Three rows a field; the window scrolls so the focused one is in view. |
| 196 | 203 | const rows = Math.max(1, Math.floor(area.h / 3)); |
| 197 | const first = Math.max(0, Math.min(focus - rows + 1, SPECS.length - rows)); | |
| 204 | const first = Math.max(0, Math.min(focus - rows + 1, specs.length - rows)); | |
| 198 | 205 | let cursor: { x: number; y: number } | null = null; |
| 199 | SPECS.slice(first, first + rows).forEach((spec, n) => { | |
| 206 | specs.slice(first, first + rows).forEach((spec, n) => { | |
| 200 | 207 | const i = first + n; |
| 201 | 208 | const raw = spec.choices === undefined ? (values[spec.key] ?? "") : (values[spec.key] || spec.choices[0]!); |
| 202 | 209 | const shown = spec.secret === true ? "•".repeat([...raw].length) : raw; |
| @@ -215,7 +222,7 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str | ||
| 215 | 222 | }, |
| 216 | 223 | paste(text) { |
| 217 | 224 | if (plan !== undefined) return true; |
| 218 | const k = SPECS[focus]!.key; | |
| 225 | const k = specs[focus]!.key; | |
| 219 | 226 | values[k] = (values[k] ?? "") + text.replace(/\s+/g, " ").trim(); |
| 220 | 227 | return true; |
| 221 | 228 | }, |
| @@ -230,27 +237,27 @@ export function newForgeScreen(f: Session, ctx: Ctx, initial: Record<string, str | ||
| 230 | 237 | return true; |
| 231 | 238 | } |
| 232 | 239 | if (e.key === "tab" || e.key === "enter") { |
| 233 | focus = (focus + 1) % SPECS.length; | |
| 240 | focus = (focus + 1) % specs.length; | |
| 234 | 241 | return true; |
| 235 | 242 | } |
| 236 | const choices = SPECS[focus]!.choices; | |
| 243 | const choices = specs[focus]!.choices; | |
| 237 | 244 | const step = e.key === "left" ? -1 : e.key === "right" || e.key === " " || e.key === "space" ? 1 : 0; |
| 238 | 245 | if (choices !== undefined && step !== 0) { |
| 239 | 246 | // A choice can be cycled or typed; both end in a value the door checks. |
| 240 | const k = SPECS[focus]!.key; | |
| 247 | const k = specs[focus]!.key; | |
| 241 | 248 | const at = Math.max(0, choices.indexOf(values[k] || choices[0]!)); |
| 242 | 249 | values[k] = choices[(at + step + choices.length) % choices.length]!; |
| 243 | 250 | error = undefined; |
| 244 | 251 | return true; |
| 245 | 252 | } |
| 246 | 253 | if (e.key === "backspace") { |
| 247 | const k = SPECS[focus]!.key; | |
| 254 | const k = specs[focus]!.key; | |
| 248 | 255 | values[k] = [...(values[k] ?? "")].slice(0, -1).join(""); |
| 249 | 256 | error = undefined; |
| 250 | 257 | return true; |
| 251 | 258 | } |
| 252 | 259 | if (!e.ctrl && !e.alt && [...e.key].length === 1) { |
| 253 | const k = SPECS[focus]!.key; | |
| 260 | const k = specs[focus]!.key; | |
| 254 | 261 | values[k] = (values[k] ?? "") + e.key; |
| 255 | 262 | error = undefined; |
| 256 | 263 | return true; |
src/web/pages/new-forge.ts +22 −12
| @@ -11,7 +11,7 @@ | ||
| 11 | 11 | |
| 12 | 12 | import { getPack, resolveRepos } from "../../packs/curated.ts"; |
| 13 | 13 | import { listAgents } from "../../core/agents.ts"; |
| 14 | import { listReposToTake } from "../../core/repos.ts"; | |
| 14 | import { listReposToTake, listReposVisibleTo } from "../../core/repos.ts"; | |
| 15 | 15 | import type { User } from "../../core/users.ts"; |
| 16 | 16 | import type { Ctx } from "../../http/context.ts"; |
| 17 | 17 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| @@ -101,11 +101,14 @@ interface Reads { | ||
| 101 | 101 | readonly quota: string | undefined; |
| 102 | 102 | readonly repos: ReturnType<typeof listReposToTake>; |
| 103 | 103 | readonly crew: ReturnType<typeof listAgents>; |
| 104 | /** Repositories marked as templates that the viewer can read (`full_name`), listed in the | |
| 105 | * Template select. */ | |
| 106 | readonly templates: readonly string[]; | |
| 104 | 107 | } |
| 105 | 108 | |
| 106 | 109 | function readsFor(ctx: Ctx, user: User | undefined): Reads { |
| 107 | 110 | const full = timePhase(ctx.request, "room", () => noRoom(ctx.app)); |
| 108 | if (full) return { full, quota: undefined, repos: [], crew: [] }; | |
| 111 | if (full) return { full, quota: undefined, repos: [], crew: [], templates: [] }; | |
| 109 | 112 | const quota = quotaFull(ctx.app.config.dataDir); |
| 110 | 113 | // Each repository once, as its source, and public only; a stranger sees |
| 111 | 114 | // none and no crew: nothing private travels to a child they have not claimed. |
| @@ -116,7 +119,10 @@ function readsFor(ctx: Ctx, user: User | undefined): Reads { | ||
| 116 | 119 | user === undefined |
| 117 | 120 | ? [] |
| 118 | 121 | : timePhase(ctx.request, "crew", () => listAgents(ctx.app.db)); |
| 119 | return { full, quota, repos, crew }; | |
| 122 | const templates = timePhase(ctx.request, "templates", () => | |
| 123 | listReposVisibleTo(ctx.app.db, user, { templatesOnly: true, limit: 50 }).map((r) => `${r.ownerName}/${r.name}`), | |
| 124 | ); | |
| 125 | return { full, quota, repos, crew, templates }; | |
| 120 | 126 | } |
| 121 | 127 | |
| 122 | 128 | /** The three sizes, the one asked for chosen (small when the value is not one of them). */ |
| @@ -133,13 +139,17 @@ function sizeOptions(chosen: string): { value: string; label: string; selected?: | ||
| 133 | 139 | } |
| 134 | 140 | |
| 135 | 141 | /** The templates in order, Blank first; the one asked for chosen (Blank when it is not one of them). */ |
| 136 | function templateOptions(chosen: string): { value: string; label: string; selected?: boolean }[] { | |
| 137 | const at = TEMPLATES.some((t) => t.id === chosen) ? chosen : DEFAULT_TEMPLATE; | |
| 138 | return TEMPLATES.map((t) => ({ | |
| 139 | value: t.id, | |
| 140 | label: `${t.title}: ${lower(t.says)}`, | |
| 141 | selected: t.id === at, | |
| 142 | })); | |
| 142 | function templateOptions(chosen: string, repos: readonly string[]): { value: string; label: string; selected?: boolean }[] { | |
| 143 | const known = TEMPLATES.some((t) => t.id === chosen) || repos.includes(chosen); | |
| 144 | const at = known ? chosen : DEFAULT_TEMPLATE; | |
| 145 | return [ | |
| 146 | ...TEMPLATES.map((t) => ({ | |
| 147 | value: t.id, | |
Issue box 3: the default option must read 'the forge's own code' (and the built-in Blank/Starter stay listed). Principle 1/8: plain words, one sentence per option. Label the default as the issue says. |
||
| 148 | label: t.id === DEFAULT_TEMPLATE ? `The forge's own code: ${lower(t.says)}` : `${t.title}: ${lower(t.says)}`, | |
| 149 | selected: t.id === at, | |
| 150 | })), | |
| 151 | ...repos.map((ref) => ({ value: ref, label: `${ref}: ${lower(templateOf(ref).says)}`, selected: ref === at })), | |
| 152 | ]; | |
| 143 | 153 | } |
| 144 | 154 | |
| 145 | 155 | /** The page's words for what the data names in the API's terms (#10787); the data keeps its own. */ |
| @@ -188,7 +198,7 @@ function formView( | ||
| 188 | 198 | plan: Html | null, |
| 189 | 199 | reads: Reads, |
| 190 | 200 | ): Html { |
| 191 | const { full, quota, repos, crew } = reads; | |
| 201 | const { full, quota, repos, crew, templates } = reads; | |
| 192 | 202 | if (full) |
| 193 | 203 | return html`<div class="narrow-wide" data-forges> |
| 194 | 204 | ${pageHead("New forge")} |
| @@ -358,7 +368,7 @@ function formView( | ||
| 358 | 368 | label: "Template", |
| 359 | 369 | name: "template", |
| 360 | 370 | hint: "What the new forge starts from besides the apps you fork. Blank is the default.", |
| 361 | options: templateOptions(values.template), | |
| 371 | options: templateOptions(values.template, templates), | |
| 362 | 372 | ...(errors["template"] ? { error: errors["template"] } : {}), |
| 363 | 373 | })} |
| 364 | 374 | ${selectField({ |
test/new-forge.test.ts +2 −2
| @@ -138,7 +138,7 @@ describe("+ New forge", () => { | ||
| 138 | 138 | const at = page.indexOf('name="template"'); |
| 139 | 139 | expect(at).toBeGreaterThan(0); |
| 140 | 140 | const field = page.slice(at, page.indexOf("</select>", at)); |
| 141 | expect(field).toMatch(/<option value="blank" selected >\s*Blank/); | |
| 141 | expect(field).toMatch(/<option value="blank" selected >\s*The forge's own code/); | |
| 142 | 142 | expect(field.indexOf('value="blank"')).toBeLessThan(field.indexOf('value="starter"')); |
| 143 | 143 | expect(field).toContain("Starter app"); |
| 144 | 144 | |
| @@ -154,7 +154,7 @@ describe("+ New forge", () => { | ||
| 154 | 154 | const bad = await post(admin, [["name", "tpl"], ["do", "plan"], ["template", "nope"]]); |
| 155 | 155 | expect(bad.status).toBe(422); |
| 156 | 156 | const body = await bad.text(); |
| 157 | expect(body).toContain("template must be blank or starter"); | |
| 157 | expect(body).toContain("template must be blank, starter or the owner/name of a template repository"); | |
| 158 | 158 | expect(body).toContain('value="tpl"'); |
| 159 | 159 | expect(await children()).toBe(0); |
| 160 | 160 | }); |
test/spawn-template-api.test.ts +2 −2
| @@ -95,11 +95,11 @@ describe("choosing a template for a new forge", () => { | ||
| 95 | 95 | expect(res.status).toBe(422); |
| 96 | 96 | const body = (await res.json()) as any; |
| 97 | 97 | expect(body.error).toBe("invalid"); |
| 98 | expect(body.message).toBe("template: template must be blank or starter"); | |
| 98 | expect(body.message).toBe("template: template must be blank, starter or the owner/name of a template repository"); | |
| 99 | 99 | } |
| 100 | 100 | const viaMcp = await mcp("spawn", { name: "kid", template: "nope" }); |
| 101 | 101 | expect(viaMcp.error).toBe(true); |
| 102 | expect(viaMcp.text).toContain("template: template must be blank or starter"); | |
| 102 | expect(viaMcp.text).toContain("template: template must be blank, starter or the owner/name of a template repository"); | |
| 103 | 103 | }); |
| 104 | 104 | |
| 105 | 105 | test("the templates list is public and ETagged", async () => { |
test/spawn-template.test.ts added +148
| @@ -0,0 +1,148 @@ | ||
| 1 | /** | |
| 2 | * A new forge may name a template (#12432): `owner/name` of a repository an | |
| 3 | * admin marked, readable by the maker. Its code is the child's own code; | |
| 4 | * without one the child is today's. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtemp, readFile, rm } from "node:fs/promises"; | |
| 8 | import { tmpdir } from "node:os"; | |
| 9 | import { join } from "node:path"; | |
| 10 | import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { getRepo } from "../src/core/repos.ts"; | |
| 13 | import { createUser, type User } from "../src/core/users.ts"; | |
| 14 | import { createSession } from "../src/core/sessions.ts"; | |
| 15 | import { createToken } from "../src/core/tokens.ts"; | |
| 16 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 17 | import { ok } from "../src/kernel/result.ts"; | |
| 18 | import { usePlacement, useProbe } from "../src/spawn/door.ts"; | |
| 19 | import { FORGE_CODE_NAME } from "../src/spawn/forge_code.ts"; | |
| 20 | import { templateNotMarked, templateNotReadable } from "../src/spawn/templates.ts"; | |
| 21 | import { quietLogs } from "./helpers/globals.ts"; | |
| 22 | ||
| 23 | quietLogs(); | |
| 24 | ||
| 25 | describe("a new forge from a template repository", () => { | |
| 26 | let dir = ""; | |
| 27 | let app: App; | |
| 28 | let alice: User; | |
| 29 | let bob: User; | |
| 30 | let placed = 0; | |
| 31 | ||
| 32 | let base = ""; | |
| 33 | let servers: Servers; | |
| 34 | const tokens = new Map<string, string>(); | |
| 35 | /** The door's answer: `ok`, or the refusal's field and words. */ | |
| 36 | const spawn = async (who: User, input: Record<string, unknown>) => { | |
| 37 | const res = await fetch(`${base}/api/v1/forges`, { | |
| 38 | method: "POST", | |
| 39 | headers: { "content-type": "application/json", authorization: `Bearer ${tokens.get(who.id)}` }, | |
| 40 | body: JSON.stringify({ apps: [], dryRun: false, ...input }), | |
| 41 | }); | |
| 42 | const body = (await res.json()) as { message?: string }; | |
| 43 | return { status: res.status, message: body.message ?? "" }; | |
| 44 | }; | |
| 45 | const fake = { | |
| 46 | place: async (plan: { name: string }) => ok({ url: `https://${plan.name}.fake.test`, bodyId: `fake-${++placed}` }), | |
| 47 | retire: async () => ok(), | |
| 48 | }; | |
| 49 | ||
| 50 | beforeAll(async () => { | |
| 51 | dir = await mkdtemp(join(tmpdir(), "forge-spawn-template-")); | |
| 52 | app = createApp({ dataDir: dir, port: 0 }); | |
| 53 | const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 54 | const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }); | |
| 55 | if (!a.ok || !b.ok) throw new Error("users"); | |
| 56 | alice = a.value; | |
| 57 | bob = b.value; | |
| 58 | for (const u of [alice, bob]) tokens.set(u.id, createToken(app.db, u.id, "rw", "rw").token); | |
| 59 | servers = await serve(app); | |
| 60 | base = servers.url; | |
| 61 | useProbe(app, () => async () => true); | |
| 62 | usePlacement(app, fake); | |
| 63 | for (const [name, visibility] of [["kit", "public"], ["plain", "public"], ["secret", "private"]] as const) { | |
| 64 | const made = await createRepo(app, alice, { name, visibility }); | |
| 65 | if (!made.ok) throw new Error(name); | |
| 66 | await commitToBranch(app, alice, made.value, { message: "seed", files: [{ path: "kit.txt", content: name }] }); | |
| 67 | } | |
| 68 | for (const name of ["kit", "secret"]) { | |
| 69 | const r = getRepo(app.db, "alice", name)!; | |
| 70 | const done = await updateRepoSettings(app, alice, r, { template: true }); | |
| 71 | if (!done.ok) throw new Error("mark"); | |
| 72 | } | |
| 73 | }, 30_000); | |
| 74 | ||
| 75 | afterAll(async () => { | |
| 76 | servers?.stop(); | |
| 77 | app?.close(); | |
| 78 | await rm(dir, { recursive: true, force: true }); | |
| 79 | }); | |
| 80 | ||
| 81 | test("none is today's path: no template, no template record", async () => { | |
| 82 | const made = await spawn(alice, { name: "plainkid" }); | |
| 83 | expect(made.status).toBe(201); | |
| 84 | const parent = JSON.parse(await readFile(join(dir, "children", "fake-1", "parent.json"), "utf8")); | |
| 85 | expect(parent.template).toBeUndefined(); | |
| 86 | }); | |
| 87 | ||
| 88 | test("a marked template is used: recorded, and its code is the child's", async () => { | |
| 89 | const made = await spawn(bob, { name: "fromkit", template: "alice/kit" }); | |
| 90 | expect(made.status).toBe(201); | |
| 91 | const parent = JSON.parse(await readFile(join(dir, "children", `fake-${placed}`, "parent.json"), "utf8")); | |
| 92 | expect(parent.template).toMatchObject({ id: "alice/kit", repo: "alice/kit" }); | |
| 93 | expect(parent.forgeCode?.upstream).toBe("alice/kit"); | |
| 94 | }); | |
| 95 | ||
| 96 | test("an unmarked repository is refused, and the refusal says which", async () => { | |
| 97 | const made = await spawn(bob, { name: "fromplain", template: "alice/plain" }); | |
| 98 | expect(made.status).toBe(422); | |
| 99 | expect(made.message).toContain(`template: ${templateNotMarked("alice/plain")}`); | |
| 100 | }); | |
| 101 | ||
| 102 | test("a private template the maker cannot read is refused", async () => { | |
| 103 | const made = await spawn(bob, { name: "fromsecret", template: "alice/secret" }); | |
| 104 | expect(made.status).toBe(422); | |
| 105 | expect(made.message).toContain(`template: ${templateNotReadable("alice/secret")}`); | |
| 106 | }); | |
| 107 | ||
| 108 | test("a private template the maker can read gives a child repository that is not public", async () => { | |
| 109 | const made = await spawn(alice, { name: "fromsecretok", template: "alice/secret" }); | |
| 110 | expect(made.status).toBe(201); | |
| 111 | const child = createApp({ dataDir: join(dir, "children", `fake-${placed}`) }); | |
| 112 | try { | |
| 113 | const repo = getRepo(child.db, "fromsecretok", FORGE_CODE_NAME); | |
| 114 | expect(repo).toBeDefined(); | |
| 115 | expect(repo?.visibility).toBe("private"); | |
| 116 | } finally { | |
| 117 | child.close(); | |
| 118 | } | |
| 119 | }); | |
| 120 | ||
| 121 | test("a public template stays public in the child", async () => { | |
| 122 | const made = await spawn(bob, { name: "frompubkid", template: "alice/kit" }); | |
| 123 | expect(made.status).toBe(201); | |
| 124 | const child = createApp({ dataDir: join(dir, "children", `fake-${placed}`) }); | |
| 125 | try { | |
| 126 | expect(getRepo(child.db, "frompubkid", FORGE_CODE_NAME)?.visibility).toBe("public"); | |
| 127 | } finally { | |
| 128 | child.close(); | |
| 129 | } | |
| 130 | }); | |
| 131 | ||
| 132 | test("a name that is no repository is refused as unreadable", async () => { | |
| 133 | const made = await spawn(bob, { name: "fromnone", template: "alice/none" }); | |
| 134 | expect(made.status).toBe(422); | |
| 135 | expect(made.message).toContain("template: "); | |
| 136 | }); | |
| 137 | ||
| 138 | test("the New forge page lists only template repositories, in one select", async () => { | |
| 139 | { | |
| 140 | const cookie = `forge_session=${createSession(app.db, bob.id).token}`; | |
| 141 | const html = await (await fetch(`${servers.url}/forges/new`, { headers: { cookie } })).text(); | |
| 142 | expect(html.match(/<select[^>]*name="template"/g)?.length).toBe(1); | |
| 143 | expect(html).toContain('value="alice/kit"'); | |
| 144 | expect(html).not.toContain('value="alice/plain"'); | |
| 145 | expect(html).not.toContain('value="alice/secret"'); | |
| 146 | } | |
| 147 | }); | |
| 148 | }); |
test/tui-newforge.test.ts +40 −2
| @@ -6,8 +6,9 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | ||
| 6 | 6 | import { mkdtemp, readdir, rm } from "node:fs/promises"; |
| 7 | 7 | import { tmpdir } from "node:os"; |
| 8 | 8 | import { join } from "node:path"; |
| 9 | import { createRepo } from "../src/actions/repos.ts"; | |
| 9 | import { createRepo, updateRepoSettings } from "../src/actions/repos.ts"; | |
| 10 | 10 | import { createApp, type App } from "../src/app.ts"; |
| 11 | import { getRepo } from "../src/core/repos.ts"; | |
| 11 | 12 | import { createUser, type User } from "../src/core/users.ts"; |
| 12 | 13 | import { usePlacement, useProbe } from "../src/spawn/door.ts"; |
| 13 | 14 | import { hostedPlacement } from "../src/spawn/placement.ts"; |
| @@ -57,6 +58,15 @@ beforeAll(async () => { | ||
| 57 | 58 | bob = await mk("bob", false); |
| 58 | 59 | const repo = await createRepo(app, admin, { name: "bakery", visibility: "public" }); |
| 59 | 60 | if (!repo.ok) throw new Error("repo"); |
| 61 | // Template repositories: one bob may read, one unmarked, one marked but private to alice. | |
| 62 | for (const [name, visibility] of [["kit", "public"], ["plain", "public"], ["secret", "private"]] as const) { | |
| 63 | const made = await createRepo(app, admin, { name, visibility }); | |
| 64 | if (!made.ok) throw new Error(name); | |
| 65 | } | |
| 66 | for (const name of ["kit", "secret"]) { | |
| 67 | const marked = await updateRepoSettings(app, admin, getRepo(app.db, "alice", name)!, { template: true }); | |
| 68 | if (!marked.ok) throw new Error("mark"); | |
| 69 | } | |
| 60 | 70 | useProbe(app, () => async () => true); |
| 61 | 71 | usePlacement(app, hostedPlacement({ host: "forge.test" })); |
| 62 | 72 | }); |
| @@ -228,11 +238,39 @@ describe("the new forge screen", () => { | ||
| 228 | 238 | expect(tui.screen.toText()).toContain("Template: Starter app."); |
| 229 | 239 | })); |
| 230 | 240 | |
| 241 | test("right past starter chooses a readable template repository; unmarked and unreadable ones are not offered", () => | |
| 242 | withScreen(bob, async ({ tui, terminal }) => { | |
| 243 | terminal.feed("tuikit" + "\t".repeat(10)); | |
| 244 | await settleApp(tui); | |
| 245 | const seen: string[] = [tui.screen.toText()]; | |
| 246 | for (let i = 0; i < 4; i++) { | |
| 247 | terminal.feed("\x1b[C"); // right arrow | |
| 248 | await settleApp(tui); | |
| 249 | seen.push(tui.screen.toText()); | |
| 250 | } | |
| 251 | // blank, starter, then alice/kit with that repository's sentence, then round again. | |
| 252 | expect(seen[1]).toContain("A server, a page, tests and a forge.json"); | |
| 253 | expect(seen[2]).toContain("alice/kit"); | |
| 254 | expect(seen[2]).toContain("The code and apps of that repository."); | |
| 255 | expect(seen[3]).toContain("Only the apps you fork"); | |
| 256 | for (const text of seen) { | |
| 257 | expect(text).not.toContain("alice/plain"); | |
| 258 | expect(text).not.toContain("alice/secret"); | |
| 259 | } | |
| 260 | })); | |
| 261 | ||
| 262 | test("a typed owner/name gets the repository sentence", () => | |
| 263 | withScreen(bob, async ({ tui, terminal }) => { | |
| 264 | terminal.feed("tuityped" + "\t".repeat(10) + "alice/kit"); | |
| 265 | await settleApp(tui); | |
| 266 | expect(tui.screen.toText()).toContain("The code and apps of that repository."); | |
| 267 | })); | |
| 268 | ||
| 231 | 269 | test("an unknown template is refused beside the field", () => |
| 232 | 270 | withScreen(admin, async ({ tui, terminal }) => { |
| 233 | 271 | terminal.feed("tuitpl" + "\t".repeat(10) + "nope\x10"); |
| 234 | 272 | await settleApp(tui); |
| 235 | expect(tui.screen.toText()).toContain("template must be blank or starter"); | |
| 273 | expect(tui.screen.toText()).toContain("template must be blank, starter or the owner/name of a template repository"); | |
| 236 | 274 | })); |
| 237 | 275 | |
| 238 | 276 | test("an unknown size is refused beside the field", () => |
HIGH: visibility stays "public" for the child's forge repo even when the template is private (the maker can read it, per the spawn check). That leaks a private repo's code to everyone. Copy the template's visibility (or force private) when
templateis set, and add a test.