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

A forge made from a template remembers which template and commit, and settings shows it as one line #13064

Merged opened this

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

Merged

scout/forge:scout/13038-a-forge-made-from-a-template-remembers-w → main 9 commits fork 6 threads · 6 unresolved

  • Merged. scout/13038-a-forge-made-from-a-template-remembers-w was merged into main as 5520683.

Review

Sign in to review this change.
12 files changed +379 −37
docs/features/README.md +1
@@ -37,6 +37,7 @@ Read with the guide page [What a forge is](../guide-what-a-forge-is.md).
3737 - [Template mark](repo-template.md)
3838 - [Who changed a setting, and when](setting-history.md)
3939 - [A new forge can start from a template repository](new-forge-template.md)
40 - [Made from: the template a forge came from](made-from.md)
4041 - [The explorer's sorts](explore.md)
4142 - [The feed pages by cursor](feed-cursor.md)
4243 - [The fork tree](fork-tree.md)
docs/features/made-from.md added +9
@@ -0,0 +1,9 @@
1 # Made from (#13038)
2
3 A forge made from a template repository remembers which one and at what commit. The record is the `template` entry of its `parent.json` (`{ id, repo, tip }`, written when it is made); a forge made without a template repository, or before this was kept, has none and says nothing.
4
5 - **Settings:** `/settings` has a `Made from` row, `<owner>/<name> at <short sha>`, in the same list as the Plan row.
6 - **Terminal:** the palette entry *Made from* (`src/tui/screens/madefrom.ts`, offered only to a signed-in person and only when the record exists; a guest is told nothing) prints `Made from <template> at <short sha>`.
7 - **Parent's read:** `GET /api/v1/forge` returns `madeFrom: { template, at }` (the full commit) only when the caller shows the parent's secret; anyone else, or a wrong secret, gets no `madeFrom`.
8 - **MCP:** the `forges` tool's rows (admin) carry `madeFrom` (`{ template, at }` or null), read from the record the parent wrote; no new tool.
9 - **Try it:** make a forge from a template repository, open `/settings`.
src/actions/spawn.ts +44 −12
@@ -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 {
@@ -335,12 +350,14 @@ async function make(
335350 // A retry of an unfinished child is a new attempt: its failure has a start.
336351 app.bus.append({ kind: "forge.spawn.started", payload: { ...(deps.drill === true ? { drill: 1 } : {}) } });
337352 } else {
338 // A paid plan is held to its own count, never the free one; the free plan keeps today's per-person limits.
353 // A paid plan is held to its own count, never the free one; the free plan keeps today's
354 // per-person limits.
339355 const chosen = plan.plan === undefined ? undefined : getPlan(app.db, plan.plan);
340356 if (plan.plan !== undefined && chosen === undefined)
341357 return err({ kind: "invalid", field: "plan", reason: `${plan.plan} is not a plan this forge offers` });
342358 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.
359 // A redeemed gift code (`actions/codes.ts`) or a paid order (`actions/order.ts`) is what
360 // lends this plan: it asks no admin.
344361 } else if (chosen !== undefined && chosen.key !== FREE) {
345362 if (owner === undefined) return err({ kind: "refused", reason: "plan", message: `the ${chosen.name} plan is for a signed-in person; sign in first` });
346363 if (!owner.isAdmin) return err({ kind: "refused", reason: "plan", message: PAID_PLAN_ADMIN_ONLY(chosen.name) });
@@ -559,6 +576,9 @@ async function copyInto(
559576 // the forge does not name its code repository (`forgeRepo`).
560577 const forgeCode = await forkForgeCode(app, child, org.username, plan.followMode ?? DEFAULT_MODE, fromRepo);
561578 if (!forgeCode.ok) return err(forgeCode.error);
579 // The commit a template repository was read at, kept with the template (#13038).
580 if (fromRepo !== undefined && forgeCode.value !== undefined && forgeCode.value.tip !== "")
581 templateMark = { id: fromRepo, repo: fromRepo, tip: forgeCode.value.tip };
562582
563583 for (const b of plan.briefs) {
564584 // The jobs it declares travel with it (#8907).
@@ -724,7 +744,8 @@ async function startFresh(
724744 * undefined when it has none yet (or the child's database is not there).
725745 */
726746 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.
747 // The child's database is asked off this thread (`spawn/child_db.ts`); only the sealed row comes
748 // back.
728749 const row = await childSubscription(dir, STARTER_KEY);
729750 if (row === undefined) return undefined;
730751 try {
@@ -786,12 +807,17 @@ export async function reissueClaimFor(
786807 }
787808 }
788809
789 /** What this forge shows a child it made to learn its private facts; undefined for an older child. */
810 /**
811 * What this forge shows a child it made to learn its private facts; undefined for an older child.
812 */
790813 export async function statusTokenOf(app: App, name: string): Promise<string | undefined> {
791814 return (await readLedger(app, name))?.statusToken;
792815 }
793816
794 /** The key a child of this forge signs heartbeats with; undefined for a name this forge did not make. */
817 /**
818 * The key a child of this forge signs heartbeats with; undefined for a name this forge did not
819 * make.
820 */
795821 export async function beatKeyOf(app: App, name: string): Promise<string | undefined> {
796822 return (await readLedger(app, name))?.beatKey;
797823 }
@@ -815,7 +841,10 @@ export interface Child {
815841 readonly placementNote: string | null;
816842 /** Where its move into a cell of its own stands, when one was ever tried (`spawn/where.ts`). */
817843 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. */
844 /**
845 * The person who made it (their id here); absent for a stranger's or a ledger from before it was
846 * kept.
847 */
819848 readonly ownerId?: string;
820849 }
821850
@@ -852,7 +881,10 @@ export async function listChildren(app: App): Promise<Child[]> {
852881 return ledgers.flatMap((ledger) => (ledger ? [childOf(app, ledger)] : []));
853882 }
854883
855 /** `listChildren`, read at once: for a terminal command that draws in the same turn (one small file per child). */
884 /**
885 * `listChildren`, read at once: for a terminal command that draws in the same turn (one small file
886 * per child).
887 */
856888 export function listChildrenNow(app: App): Child[] {
857889 const dir = join(app.config.dataDir, "spawn");
858890 let files: string[];
src/contract/openapi/routes/getApiV1Forge.ts +1 −1
@@ -1,3 +1,3 @@
11 import type { Route } from "../shared.ts";
22
3 export const route: Route = { method: "get", path: "/api/v1/forge", summary: "A spawned forge's word about itself: { claimed, lastActivityAt, link? }; lastActivityAt and link ({ state, revokedAt, usedAt }) are null or absent unless the parent's secret is sent", auth: false, role: "anonymous", refusals: { not_found: "404: this forge was not spawned" } };
3 export const route: Route = { method: "get", path: "/api/v1/forge", summary: "A spawned forge's word about itself: { claimed, lastActivityAt, link? }; lastActivityAt, link ({ state, revokedAt, usedAt }) are null or absent, as is madeFrom ({ template, at }), unless the parent's secret is sent", auth: false, role: "anonymous", refusals: { not_found: "404: this forge was not spawned" } };
src/http/mcp/tools/forges.ts +1 −1
@@ -12,7 +12,7 @@ import { good, bad, type Tool } from "../shared.ts";
1212
1313 export const tool: Tool = {
1414 name: "forges",
15 doc: "an admin's list of the forges sent from here: name, address, whom for, apps, claimed, stage (sent/opened/signed in/last tell; resend true when unopened 3 days: claim_link), last activity (a person or the crew, never a heartbeat), who claimed it and when, what it costs to keep (keepBytes, use, credit), archive (why it is proposed for archive), reachable, size, use; `{ forge, plan?, dryRun? }` reads a forge's plan (small|medium|large, status, source, changes) or, with `plan`, grants it by hand; `{ forge, sandbox: true }` reads what moving a forge out of this forge's own process into a sandbox would meet (hooks and command-running config keys by name, size) and with `dryRun: false` moves it, proven and put back on any failure (`acknowledge: true` when it was held for what its repositories hold); each forge carries `placement` and `where`; gift codes: `codes` true lists, `code` {plan, uses?, note?, expires?} makes (shown once), `revoke` id; planned unless `dryRun` is false; `archive` a name or names stops each, writes its data and ledger as one file to the backup destination, then removes it; `restore` a name brings an archived one back; `kind` refused lists the last 20 refused first asks",
15 doc: "an admin's list of the forges sent from here: name, address, whom for, apps, claimed, stage (sent/opened/signed in/last tell; resend true when unopened 3 days: claim_link), last activity (a person or the crew, never a heartbeat), who claimed it and when, what it costs to keep (keepBytes, use, credit), archive (why it is proposed for archive), reachable, size, use, madeFrom; `{ forge, plan?, dryRun? }` reads a forge's plan (small|medium|large, status, source, changes) or, with `plan`, grants it by hand; `{ forge, sandbox: true }` reads what moving a forge out of this forge's own process into a sandbox would meet (hooks and command-running config keys by name, size) and with `dryRun: false` moves it, proven and put back on any failure (`acknowledge: true` when it was held for what its repositories hold); each forge carries `placement` and `where`; gift codes: `codes` true lists, `code` {plan, uses?, note?, expires?} makes (shown once), `revoke` id; planned unless `dryRun` is false; `archive` a name or names stops each, writes its data and ledger as one file to the backup destination, then removes it; `restore` a name brings an archived one back; `kind` refused lists the last 20 refused first asks",
1616 description:
1717 "Forges sent from here (admin; a stage says when to resend), or one forge's plan to read or grant.",
1818 inputSchema: { type: "object", properties: { kind: { type: "string", enum: ["refused"] }, forge: { type: "string" }, plan: { type: "string" }, codes: { type: "boolean" }, code: { type: "object" }, revoke: { type: "string" }, archive: { type: ["string", "array"], items: { type: "string" } }, restore: { type: "string" }, sandbox: { type: "boolean" }, acknowledge: { type: "boolean" }, dryRun: { type: "boolean" } } },
src/spawn/clients.ts +61 −15
@@ -5,8 +5,8 @@
55 * small answer (`forgeState`, `GET /api/v1/forge`) that holds nothing else.
66 * Claimed is anyone's to know; when anything last happened is the parent's
77 * alone, for it tells when private work goes on: the parent shows a secret
8 * kept in its ledger, and the child checks it against the hash it holds. A child that does not answer in time reads "unknown": the
9 * list never waits on, or fails for, one forge that is down.
8 * kept in its ledger, and the child checks it against the hash it holds. A child that does not
9 * answer in time reads "unknown": the list never waits on, or fails for, one forge that is down.
1010 */
1111
1212 import { liveChildDisk, readMountinfo, type ChildDisk } from "./disk_mount.ts";
@@ -36,6 +36,7 @@ import { readNotices } from "./archive.ts";
3636 import { billTo, personReading } from "./person_activity.ts";
3737 import { archiveProposal, type ArchiveProposal } from "./archive_proposal.ts";
3838 import { appLinkLines, type AppLinkLine } from "./app_links.ts";
39 import { madeFromOf, type MadeFrom } from "./template_record.ts";
3940 import { NO_KEY_HELD, NO_KEY_HOST_LINE } from "../crew/no_key.ts";
4041
4142 /** What a spawned forge says about itself to anyone: nothing more. */
@@ -44,6 +45,11 @@ export interface ForgeState {
4445 readonly lastActivityAt: string | null;
4546 /** The claim link's state; only the parent's secret unlocks it. Absent from an older child. */
4647 readonly link?: LinkInfo | null;
48 /**
49 * The template repository and commit it was made from (#13038); only the parent's secret
50 * unlocks it, absent when it has none.
51 */
52 readonly madeFrom?: MadeFrom;
4753 }
4854
4955 /** One row of the client list; `claimed` is null when the child did not answer. */
@@ -52,7 +58,10 @@ export interface ClientRow {
5258 readonly url: string;
5359 readonly for: string | null;
5460 readonly apps: readonly string[];
55 /** Whether the child still follows each app it was sent (`spawn/app_links.ts`); empty when it was sent none. */
61 /**
62 * Whether the child still follows each app it was sent (`spawn/app_links.ts`); empty when it was
63 * sent none.
64 */
5665 readonly appLinks?: readonly AppLinkLine[];
5766 readonly sentAt: string | null;
5867 /** False while the child is still being made (a resumed spawn finishes it). */
@@ -78,21 +87,35 @@ export interface ClientRow {
7887 readonly keepBytes?: number | null;
7988 /** Why it is proposed for archive, when it is (`spawn/archive_proposal.ts`). */
8089 readonly archive?: ArchiveProposal | null;
90 /** The template repository and commit it was made from (#13038); null when none. */
91 readonly madeFrom?: MadeFrom | null;
8192 /** When its claimant was told it may be archived, ISO; null when not. */
8293 readonly noticedAt?: string | null;
83 /** Whether its process is running now; a sleeping forge costs nothing and wakes on its next request. */
94 /**
95 * Whether its process is running now; a sleeping forge costs nothing and wakes on its next
96 * request.
97 */
8498 readonly awake?: boolean;
8599 /** Why the host stopped it, while that explains its state (spawn/stopped.ts); a sentence. */
86100 readonly stopped?: string | null;
87101 /** The apps this parent runs for the child; null when it runs none here. */
88102 readonly running: ChildAppsSummary | null;
89 /** What a visitor got from its public addresses when last asked (`spawn/reach.ts`); null before it was. */
103 /**
104 * What a visitor got from its public addresses when last asked (`spawn/reach.ts`); null before it
105 * was.
106 */
90107 readonly reach: ChildReach | null;
91 /** The claim link's state (open, used, ended) and when it was taken back; null when the child did not say. */
108 /**
109 * The claim link's state (open, used, ended) and when it was taken back; null when the child did
110 * not say.
111 */
92112 readonly link: LinkInfo | null;
93113 /** Why this forge needs its owner now; null when it does not. */
94114 readonly attention: Attention | null;
95 /** Where the sent link stands, in four plain states; null while it is being made or the child did not answer. */
115 /**
116 * Where the sent link stands, in four plain states; null while it is being made or the child did
117 * not answer.
118 */
96119 readonly stage: Stage | null;
97120 /** Dollars the child's crew spent today, from its last heartbeat; null when it has not said. */
98121 readonly spendTodayUsd: number | null;
@@ -102,7 +125,10 @@ export interface ClientRow {
102125 readonly month?: MonthSum | LedgerBroken | null;
103126 /** The child's forge cap in dollars; null when none or unsaid. */
104127 readonly ceilingUsd: number | null;
105 /** The dollars this forge lends it on its own model credential, and what it has spent; null when none is lent. */
128 /**
129 * The dollars this forge lends it on its own model credential, and what it has spent; null when
130 * none is lent.
131 */
106132 readonly creditCapUsd?: number | null;
107133 readonly creditSpentUsd?: number | null;
108134 /** `cell` (a process of its own, sandboxed) or `hosted` (inside this forge's own process). */
@@ -116,7 +142,10 @@ export interface ClientRow {
116142 readonly size: Size;
117143 /** What it uses against that size: its cell's reading, or "shared" when it is hosted here. */
118144 readonly use: ForgeUse;
119 /** Whether its data is a filesystem of its own, and that filesystem's size (`spawn/disk_mount.ts`). */
145 /**
146 * Whether its data is a filesystem of its own, and that filesystem's size
147 * (`spawn/disk_mount.ts`).
148 */
120149 readonly disk: ChildDisk;
121150 /** When its last heartbeat reached this forge, ISO; null when none has. */
122151 readonly lastHeartbeatAt: string | null;
@@ -182,7 +211,13 @@ export async function forgeState(
182211 announceSandboxed(app);
183212 // What a person did, never what the forge did by itself (`person_activity.ts`).
184213 const last = { at: personReading(app.db).lastAt };
185 return { claimed, lastActivityAt: last?.at ?? null, link: linkOf(app.db) };
214 const madeFrom = madeFromOf(app.config.dataDir);
215 return {
216 claimed,
217 lastActivityAt: last?.at ?? null,
218 link: linkOf(app.db),
219 ...(madeFrom === undefined ? {} : { madeFrom }),
220 };
186221 }
187222
188223 const LINK_STATES: readonly LinkState[] = ["open", "used", "ended"];
@@ -268,7 +303,8 @@ export async function clientRows(app: App, options: { probe?: boolean } = {}): P
268303 const states = await Promise.all(
269304 children.map((c) => {
270305 const last = known?.get(c.name);
271 // Not asking (a clock's pass, which must not wake a sleeping forge): what each last said, or nothing.
306 // Not asking (a clock's pass, which must not wake a sleeping forge): what each last said, or
307 // nothing.
272308 if (!probing) return last?.state;
273309 if (last === undefined) return ask(app, c);
274310 if (now - last.at > FRESH_MS) void ask(app, c);
@@ -320,6 +356,8 @@ export async function clientRows(app: App, options: { probe?: boolean } = {}): P
320356 disk: liveChildDisk(app.config.dataDir, c.bodyId, mountinfo),
321357 lastHeartbeatAt: beats[i] === undefined ? null : new Date(beats[i]!.receivedAt).toISOString(),
322358 link: states[i]?.link ?? null,
359 // Read from the record this forge wrote when it made the child, never from the child's word.
360 madeFrom: madeFromOf(childDirOf(app, c.bodyId)) ?? null,
323361 nextStep: nextStepOf(states[i]?.claimed ?? null, beats[i]?.beat),
324362 })),
325363 now,
@@ -419,7 +457,8 @@ export const servedMemoryMiB = (app: App): number | undefined => heldMemory.get(
419457 const building = new WeakMap<App, Promise<ClientRow[]>>();
420458 /**
421459 * The list a page serves is looked at again in the background when it is older than `ms`. At 0
422 * (the suite's setting) a read waits for a fresh one: a test changes a forge and reads the list at once.
460 * (the suite's setting) a read waits for a fresh one: a test changes a forge and reads the list at
461 * once.
423462 */
424463 export const servedWindow = { ms: 15_000 };
425464
@@ -525,7 +564,8 @@ export const STALE_WORDS = "Not opened in 3 days";
525564 /**
526565 * Sent, opened, signed in, told: read from what is already kept (the
527566 * ledger's send time, the link's spent time, the claim, the last tell in the
528 * child's heartbeat). The heartbeat carries only the latest tell, so the last stage says "Last tell", never "First".
567 * child's heartbeat). The heartbeat carries only the latest tell, so the last stage says "Last
568 * tell", never "First".
529569 */
530570 export function stageOf(r: Omit<ClientRow, "attention" | "stage">, now: number): Stage | null {
531571 if (!r.made || r.claimed === null) return null;
@@ -607,7 +647,10 @@ export function claimState(r: ClientRow): keyof typeof CLAIM_WORDS {
607647 return r.claimed === null ? "unknown" : r.claimed ? "yes" : "no";
608648 }
609649
610 /** What the recipient will see first, while they have not claimed it; null once they have (the page and the terminal share it). */
650 /**
651 * What the recipient will see first, while they have not claimed it; null once they have (the page
652 * and the terminal share it).
653 */
611654 export function firstScreenOf(r: ClientRow): string | null {
612655 return claimState(r) === "no" ? firstScreenLine(r.apps) : null;
613656 }
@@ -648,7 +691,10 @@ export function spendWords(r: ClientRow): { words: string; warn: boolean } | nul
648691 /** What the host reads of a child whose crew cannot start; null when it can. */
649692 export const crewHeldWords = (r: Pick<ClientRow, "crewHeld">): string | null => (r.crewHeld === NO_KEY_HELD ? NO_KEY_HOST_LINE : null);
650693
651 /** "grace until 2026-11-18" for a forge whose payment is late, as /forges and the terminal say it; null otherwise. */
694 /**
695 * "grace until 2026-11-18" for a forge whose payment is late, as /forges and the terminal say it;
696 * null otherwise.
697 */
652698 export function graceWords(r: Pick<ClientRow, "graceUntil">): string | null {
653699 return r.graceUntil === undefined ? null : `grace until ${new Date(r.graceUntil).toISOString().slice(0, 10)}`;
654700 }
src/spawn/template_birth.ts +1
@@ -20,6 +20,7 @@ import { freshName } from "./plan.ts";
2020 export interface TemplateMark {
2121 readonly id: string;
2222 readonly repo?: string;
23 /** The commit a template repository was read at (#13038). */
2324 readonly tip?: string;
2425 }
2526
src/spawn/template_record.ts added +46
@@ -0,0 +1,46 @@
1 /**
2 * What a forge was made from (#13038): the template repository and the commit it was read at,
3 * kept in the spawn record (`parent.json`, `template: { id, repo, tip }`). A forge made without a
4 * template repository, or before this was kept, has none: nothing is guessed.
5 */
6
7 import { readFileSync } from "node:fs";
8 import { join } from "node:path";
9
10 export interface MadeFrom {
11 /** The template, as `owner/name`. */
12 readonly template: string;
13 /** The commit it was read at, in full. */
14 readonly at: string;
15 }
16
17 const REPO = /^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;
18 const SHA = /^[0-9a-f]{40,64}$/;
19
20 /**
21 * The record's `template` entry, validated; undefined unless it names both a repository and a
22 * commit.
23 */
24 export function madeFromDoc(doc: unknown): MadeFrom | undefined {
25 if (typeof doc !== "object" || doc === null) return undefined;
26 const t = (doc as Record<string, unknown>)["template"];
27 if (typeof t !== "object" || t === null) return undefined;
28 const { repo, tip: at } = t as Record<string, unknown>;
29 return typeof repo === "string" && REPO.test(repo) && typeof at === "string" && SHA.test(at)
30 ? { template: repo, at }
31 : undefined;
32 }
33
34 /** This forge's template record, read from its data directory; undefined when it has none. */
35 export function madeFromOf(dataDir: string): MadeFrom | undefined {
36 try {
37 return madeFromDoc(JSON.parse(readFileSync(join(dataDir, "parent.json"), "utf8")));
38 } catch {
39 return undefined;
40 }
41 }
42
43 /** What a row says after its `Made from` label: `<template> at <short sha>`. */
44 export function madeFromLine(m: MadeFrom): string {
45 return `${m.template} at ${m.at.slice(0, 7)}`;
46 }

Both doors: add the terminal screen in src/tui/ that prints this line, plus docs/features/<name>.md.

src/tui/screens/entries.ts +5 −1
@@ -57,6 +57,7 @@ import { entry as claimLink } from "./claim_link.ts";
5757 import { entry as invites } from "./invites.ts";
5858 import { entry as billingLinks } from "./billinglinks.ts";
5959 import { entry as planRow } from "./planrow.ts";
60 import { entry as madeFrom } from "./madefrom.ts";
6061 import { entry as cores } from "./cores.ts";
6162 import { entry as limits } from "./limits.ts";
6263 import { entry as plans } from "./plans.ts";
@@ -189,6 +190,7 @@ export const ENTRIES: readonly PaletteEntry[] = [
189190 invites,
190191 billingLinks,
191192 planRow,
193 madeFrom,
192194 cores,
193195 claimStart,
194196 claimLink,
@@ -225,7 +227,9 @@ export const ENTRIES: readonly PaletteEntry[] = [
225227 newIssue,
226228 ];
227229
228 /** Put each entry the session is offered into `commands`, after the command it names or at the end. */
230 /**
231 * Put each entry the session is offered into `commands`, after the command it names or at the end.
232 */
229233 export function addEntries(commands: Command[], session: Session, ctx: Ctx): void {
230234 const placed = new Map<string, number>();
231235 for (const e of ENTRIES) {
src/tui/screens/madefrom.ts added +44
@@ -0,0 +1,44 @@
1 /**
2 * Where this forge came from, in the terminal (#13038): the settings page's `Made from` row, from
3 * the same record (`madeFromOf`) and the same words (`madeFromLine`).
4 */
5
6 import { madeFromLine, madeFromOf } from "../../spawn/template_record.ts";
7 import type { Ctx, Screen } from "../app/app.ts";
8 import { style } from "../term/style.ts";
9 import { truncate } from "../term/width.ts";
10 import type { Session } from "../session.ts";
11 import type { PaletteEntry } from "./entries.ts";
12
13 /** `Made from <template> at <short sha>`; undefined when no template repository made this forge. */
14 export function madeFromScreenLine(dataDir: string): string | undefined {
15 const made = madeFromOf(dataDir);
16 return made === undefined ? undefined : `Made from ${madeFromLine(made)}`;
17 }
18
19 export function madeFromScreen(f: Session, ctx: Ctx): Screen {
20 return {
21 title: "Made from",
22 keys: [],
23 render(area, s) {
24 // The settings page's identity: a guest is told nothing (a template may be private).
25 const text = !f.signedIn
26 ? "Sign in to see what this forge was made from."
27 : (madeFromScreenLine(f.app.config.dataDir) ?? "This forge was made from no template repository.");
28 s.text(area.x, area.y, truncate(text, area.w), style(ctx.theme.c.fg, ctx.theme.c.bg), area.x + area.w);
29 },
30 key: () => false,
31 };
32 }
33
34 /**
35 * Offered to a signed-in person, as the settings row is, and only on a forge that has the record.
36 */
37 export const entry: PaletteEntry = {
outdated

Offered to every session, including a guest. The settings row needs a signed-in user, and a template can be a private repository. Gate this on the same identity as the page (a guest sees nothing private).

38 id: "made-from",
39 title: "Made from",
40 hint: "the template and commit this forge was made from",
41 after: ["plan-row"],
42 offered: (session) => session.signedIn && madeFromOf(session.app.config.dataDir) !== undefined,
43 run: (session, ctx) => ctx.push(madeFromScreen(session, ctx)),
44 };
src/web/pages/account.ts +24 −7
@@ -85,6 +85,7 @@ import { STOPPED_ONE, myShells, stopIdleShells, stopShell, stoppedIdleSays } fro
8585 import { DOTFILES_ERRORS, dotfilesRepoOf, setDotfilesRepo } from "../../machines/dotfiles.ts";
8686 import { billsBlock } from "./bills.ts";
8787 import { everydayLine } from "./everyday.ts";
88 import { madeFromLine, madeFromOf } from "../../spawn/template_record.ts";
8889 import { passkeyJs } from "../passkey-client.ts";
8990 import { THEME_NAMES, THEMES, type ThemeName } from "../../design/themes.ts";
9091
@@ -247,7 +248,10 @@ function edgeLinkView(ctx: Ctx): Html {
247248 );
248249 }
249250
250 /** The parent forge: linked as its host, or not, with Link (a round trip through the parent) and Unlink. */
251 /**
252 * The parent forge: linked as its host, or not, with Link (a round trip through the parent) and
253 * Unlink.
254 */
251255 function parentLinkView(ctx: Ctx): Html {
252256 const issuer = parentIssuerOf(ctx.app.config);
253257 if (issuer === undefined) return html``;
@@ -339,7 +343,8 @@ export async function resendVerifyLink(ctx: Ctx): Promise<Response> {
339343 const form = await readForm(ctx);
340344 if (form instanceof Response) return form;
341345 const sent = await resendVerification(ctx.app, ctx.auth.user);
342 // No mail: said in the reader's terms, with the page that verifies when they are an admin, and who can when they are not (`kernel/blocked.ts`).
346 // No mail: said in the reader's terms, with the page that verifies when they are an admin, and
347 // who can when they are not (`kernel/blocked.ts`).
343348 if (!sent.ok && sent.error === "no_mail" && ctx.auth.user !== undefined) {
344349 return flashTo(ctx, "/settings", blockedFlash(noMailBlocked(ctx.app, ctx.auth.user), "success"));
345350 }
@@ -452,7 +457,10 @@ function profileView(ctx: Ctx, values: ProfileForm): Html {
452457 /** A reading the cell may not give: a dash, never a zero that says "idle". */
453458 const reading = (n: number | null, unit: string): string => (n === null ? "–" : `${n}${unit}`);
454459
455 /** The machine shells this person holds and last held (#10544). Read only; the live row says its few facts in a `dl`. */
460 /**
461 * The machine shells this person holds and last held (#10544). Read only; the live row says its few
462 * facts in a `dl`.
463 */
456464 export function shellsView(ctx: Ctx, user: User): Html {
457465 const shells = myShells(ctx.app, user.id);
458466 if (shells.length === 0) return html`<p class="muted" id="shells">You have opened no shell on a machine yet.</p>`;
@@ -489,7 +497,10 @@ export function shellsView(ctx: Ctx, user: User): Html {
489497 </ul>`;
490498 }
491499
492 /** The gallery's own rules, sent with its page only: every other page's stylesheet stays without them. */
500 /**
501 * The gallery's own rules, sent with its page only: every other page's stylesheet stays without
502 * them.
503 */
493504 const galleryCss = /* css */ `
494505 .theme-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin-top: 12px; }
495506 @media (min-width: 720px) { .theme-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); } }
@@ -521,7 +532,8 @@ function themeCard(value: string, label: string, kind: string, looks: readonly T
521532 </button>`;
522533 }
523534
524 // GET /settings/appearance — every theme, to pick by looking. A visitor's too: the choice is a cookie.
535 // GET /settings/appearance — every theme, to pick by looking. A visitor's too: the choice is a
536 // cookie.
525537 export function appearancePage(ctx: Ctx): Response {
526538 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
527539 const body = block(
@@ -579,7 +591,11 @@ export function accountPage(ctx: Ctx): Response {
579591 const notify = timePhase(ctx.request, "notify", () => notifyView(ctx));
580592 const rendering = performance.now();
581593 const admin = user.isAdmin === true;
582 const plan = planRow(ctx.app.config.dataDir, parentIssuerOf(ctx.app.config), admin, coresRow(admin, coresLine()));
594 const made = madeFromOf(ctx.app.config.dataDir);
595 const madeRow = made === undefined ? null : html`<div class="status-row"><dt>Made from</dt><dd>${madeFromLine(made)}</dd></div>`;
596 const plan =
597 planRow(ctx.app.config.dataDir, parentIssuerOf(ctx.app.config), admin, html`${madeRow}${coresRow(admin, coresLine())}`) ??
598 (madeRow === null ? null : html`<dl class="status-rows">${madeRow}</dl>`);
583599 const response = accountShell(
584600 ctx,
585601 "profile",
@@ -783,7 +799,8 @@ export function sessionsCard(
783799 export function connectCard(ctx: Ctx, token: string | undefined): Html {
784800 const url = publicOrigin(ctx.app.config.url, ctx.url.origin);
785801 const env = `FORGE_URL=${url} FORGE_TOKEN=${token ?? "<token>"}`;
786 // The plugin marketplace is the forge's configured source, offered only while anyone can clone it.
802 // The plugin marketplace is the forge's configured source, offered only while anyone can clone
803 // it.
787804 const repo = offeredPluginRepo(ctx.app.db, ctx.app.config.forgeRepo, UPSTREAM_REPO);
788805 const market = repo !== undefined;
789806 const clone = copyField("connect-claude", `${env} claude --plugin-dir plugins/claude-code`, "Terminal agent command", "Copy command");
test/spawn-template-record.test.ts added +142
@@ -0,0 +1,142 @@
1 /**
2 * A forge made from a template repository remembers which and at what commit (#13038): recorded
3 * in the spawn record, shown as one line on its settings page, returned by the parent's read
4 * and printed by the terminal, and left out when there is no record.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { childDirOf } from "../src/actions/spawn.ts";
12 import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts";
13 import { usePlacement, useProbe } from "../src/spawn/door.ts";
14 import { entry as madeFromEntry, madeFromScreenLine } from "../src/tui/screens/madefrom.ts";
15 import { Session } from "../src/tui/forge.ts";
16 import type { User } from "../src/core/users.ts";
17 import { madeFromDoc, madeFromLine, madeFromOf } from "../src/spawn/template_record.ts";
18 import { createToken } from "../src/core/tokens.ts";
19 import { createUser } from "../src/core/users.ts";
20 import { createOrg } from "../src/core/orgs.ts";
21 import { sha256 } from "../src/kernel/hash.ts";
22 import { repoDir } from "../src/git/repos.ts";
23 import { runGit } from "../src/git/env.ts";
24 import { serve, type Servers } from "../src/http/server.ts";
25 import { ok } from "../src/kernel/result.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27
28 quietLogs();
29
30 describe("a forge remembers its template", () => {
31 let dataDir: string;
32 let app: App;
33 let servers: Servers;
34 let base: string;
35 let rw: string;
36 let sha = "";
37 let alice: User;
38
39 const auth = { authorization: "" };
40 const secret = "a-parent-secret-of-some-length";
41 const forgeRead = async (shown?: string) =>
42 (await (await fetch(`${base}/api/v1/forge`, { headers: shown === undefined ? {} : { "x-forge-parent": shown } })).json()) as any;
43
44 beforeAll(async () => {
45 dataDir = await mkdtemp(join(tmpdir(), "forge-spawn-template-record-"));
46 app = createApp({ dataDir, port: 0 });
47 servers = await serve(app);
48 base = servers.url;
49 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
50 if (!a.ok) throw new Error("user");
51 alice = a.value;
52 rw = createToken(app.db, a.value.id, "rw", "rw").token;
53 auth.authorization = `Bearer ${rw}`;
54 const kit = await createRepo(app, a.value, { name: "kit", visibility: "public", description: "" });
55 if (!kit.ok) throw new Error("repo");
56 await commitToBranch(app, a.value, kit.value, { message: "seed", files: [{ path: "a.txt", content: "a" }] });
57 const marked = await updateRepoSettings(app, a.value, kit.value, { template: true });
58 if (!marked.ok) throw new Error("mark");
59 const head = await runGit(["rev-parse", "HEAD"], { cwd: repoDir(app.reposRoot, "alice", "kit") });
60 if (!head.ok) throw new Error("head");
61 sha = head.value.trim();
62 const org = createOrg(app.db, "kid-org", a.value.id, { allowReserved: true });
63 if (!org.ok) throw new Error("org");
64 useProbe(app, () => async () => true);
65 usePlacement(app, {
66 place: async (plan) => ok({ url: `https://${plan.name}.fake.test`, bodyId: `fake-${plan.name}` }),
67 retire: async () => ok(),
68 });
69 }, 30_000);
70
71 afterAll(async () => {
72 servers.stop();
73 app.close();
74 await rm(dataDir, { recursive: true, force: true });
75 });
76
77 test("recorded: the spawn record names the template and the commit it was read at", async () => {
78 const made = await fetch(`${base}/api/v1/forges`, {
79 method: "POST",
80 headers: { "content-type": "application/json", ...auth },
81 body: JSON.stringify({ name: "kid", template: "alice/kit", dryRun: false }),
82 });
83 expect(made.status).toBe(201);
84 const body = (await made.json()) as any;
85 const parent = await Bun.file(join(childDirOf(app, body.bodyId), "parent.json")).json();
86 expect(parent.template).toEqual({ id: "alice/kit", repo: "alice/kit", tip: sha });
87 expect(madeFromOf(childDirOf(app, body.bodyId))).toEqual({ template: "alice/kit", at: sha });
88 }, 60_000);
89
90 test("the MCP forges read carries madeFrom on the spawned forge's row, no new tool", async () => {
91 const res = await fetch(`${base}/mcp`, {
92 method: "POST",
93 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", ...auth },
94 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "forges", arguments: {} } }),
95 });
96 const j = (await res.json()) as any;
97 const rows = JSON.parse(String(j.result.content[0].text)).forges as any[];
98 expect(rows.find((r) => r.name === "kid")?.madeFrom).toEqual({ template: "alice/kit", at: sha });
99 }, 30_000);
100
101 const record = (template: unknown) =>
102 Bun.write(join(dataDir, "parent.json"), JSON.stringify({ org: "kid-org", statusHash: sha256(secret), template }));
103
104 test("shown: a dl row on settings", async () => {
105 await record({ id: "alice/kit", repo: "alice/kit", tip: sha });
106 const page = await (await fetch(`${base}/settings`, { headers: auth })).text();
107 expect(page).toContain(`<dt>Made from</dt><dd>alice/kit at ${sha.slice(0, 7)}</dd>`);
108 expect(page).not.toContain('<p class="muted small">alice/kit');
109 expect(madeFromLine({ template: "alice/kit", at: sha })).toBe(`alice/kit at ${sha.slice(0, 7)}`);
110 });
111
112 test("the forge read gives madeFrom to the parent's secret only", async () => {
113 await record({ id: "alice/kit", repo: "alice/kit", tip: sha });
114 expect((await forgeRead(secret)).madeFrom).toEqual({ template: "alice/kit", at: sha });
115 expect((await forgeRead()).madeFrom).toBeUndefined();
116 expect((await forgeRead("not-the-secret")).madeFrom).toBeUndefined();
117 });
118
119 test("the terminal screen prints the same fact", async () => {
120 await record({ id: "alice/kit", repo: "alice/kit", tip: sha });
121 expect(madeFromScreenLine(dataDir)).toBe(`Made from alice/kit at ${sha.slice(0, 7)}`);
122 });
123
124 test("the terminal entry is a signed-in person's, as the settings row is: a guest is not offered it", async () => {
125 await record({ id: "alice/kit", repo: "alice/kit", tip: sha });
126 const who = (user?: User) => ({ sshUsername: user?.username ?? "git", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user });
127 expect(madeFromEntry.offered(new Session(app, who(alice)))).toBe(true);
128 expect(madeFromEntry.offered(new Session(app, who()))).toBe(false);
129 });
130
131 test("omitted: no record, a built-in template, or a malformed one says nothing", async () => {
132 expect(madeFromDoc({})).toBeUndefined();
133 expect(madeFromDoc({ template: { id: "starter" } })).toBeUndefined();
134 expect(madeFromDoc({ template: { id: "a/b", repo: "a/b" } })).toBeUndefined();
135 expect(madeFromDoc({ template: { repo: "a/b", tip: "nothex" } })).toBeUndefined();
136 await record({ id: "starter" });
137 const page = await (await fetch(`${base}/settings`, { headers: auth })).text();
138 expect(page).not.toContain("Made from");
139 expect((await forgeRead(secret)).madeFrom).toBeUndefined();
140 expect(madeFromScreenLine(dataDir)).toBeUndefined();
141 });
142 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs