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

Making a forge offers a workshop size: the CPUs and memory a crew's forge needs, named with its reason #13655

Merged opened this

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

Merged

scout/forge:scout/13643-making-a-forge-offers-a-workshop-size-th → main 14 commits fork 5 threads · 5 unresolved

  • Merged. scout/13643-making-a-forge-offers-a-workshop-size-th was merged into main as a674c2b.

Review

Sign in to review this change.
28 files changed +477 −84
docs/MCP.md +3 −3
@@ -127,7 +127,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
127127 | `forge` | — | How is my forge? What needs you, recommended; `apply` takes them | 297 |
128128 | `forge_proposals` | — | What this forge proposed to its parent; `reachable` false if it is silent | 245 |
129129 | `forge_view` | — | The forge as one picture: counts, apps, runs with stations, health | 282 |
130 | `forges` | `refused`, `clients` | Forges sent from here (admin), the client list, or one forge's plan | 610 |
130 | `forges` | `refused`, `clients` | Forges sent from here (admin), clients, a forge's plan or size | 630 |
131131 | `fork` | — | Fork a repository into your account; for a guest, a copy to send changes back from | 232 |
132132 | `fork_tree` | — | The fork tree around a repo: ancestors, siblings and descendants you may read | 440 |
133133 | `forks` | `chain` | A repo's forks you may see, paged by limit and cursor (next_cursor), each with commits ahead and behind | 480 |
@@ -212,9 +212,9 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
212212 | `sever` | — | Unlink a spawned forge from its parent, or an app from the repository it came from | 225 |
213213 | `share` | — | Share a feed item: no `to` tells the app's crew and owners, else followers; budgeted | 283 |
214214 | `signup` | — | Sign-ups: open (default); invite lets in only a person with an open invite link; closed refuses every new account | 324 |
215 | `sizes` | — | A child forge's sizes: small, medium and large, each with CPU, memory and disk | 196 |
215 | `sizes` | — | Child forge sizes up to xlarge: CPU, memory, disk | 167 |
216216 | `snapshot_now` | — | Take a snapshot now, as Backups does (admin) | 133 |
217 | `spawn` | — | Spawn a child forge | 1203 |
217 | `spawn` | — | Spawn a child forge | 1212 |
218218 | `spend` | — | Report what your session spent outside forge runs: who, model, tokens or dollars, issue | 470 |
219219 | `ssh_keys` | `list`, `add`, `remove` | Your SSH keys; add: key, remove: id | 250 |
220220 | `steer` | — | Say a word to one crew run by its id | 224 |
docs/features/forge-size-use.md +2
@@ -11,3 +11,5 @@ The parent passes the size and the cgroup directory in the child's environment (
1111 **A parent** lists every finished child under "Child forges", each name a link to the child, with its size and its use against it, read the same way as on `/forges`. A hosted child reads "shared with this forge" and a stopped cell reads "not running".
1212
1313 Both are visible only to the forge's owner (`canSeeMemory`, the same check as the memory block and the terminal entry). Anyone else who opens /system gets neither.
14
15 **Raising to xlarge.** A forge admin presses "Raise to xlarge" on a forge's row on /forges (16 CPUs, 32 GiB from the next start; receipted as `forge.resized`). In the terminal, `w` on "Forges you sent" does the same after a plan and a confirm; the MCP `forges` tool plans it with `{ forge, size: "xlarge" }` and makes it with `dryRun: false` and an admin token. A raise only goes up, and a forge already at xlarge shows no button.
src/actions/billing.ts +9 −7
@@ -1,9 +1,9 @@
11 /**
22 * Billing as a forge admin reaches it (#11134): every forge's plan, and the
3 * hand grant that is the only way a plan changes (no payment processor). Never an agent: a crew that could
4 * grant itself a plan would decide its own limits. Each grant is kept in
5 * `entitlement_change` and put on the event outbox (`billing.plan`), so it
6 * shows in the audit trail. Anyone else is told `not_found`.
3 * hand grant that is the only way a plan changes (no payment processor). Never an agent: a crew
4 * that could grant itself a plan would decide its own limits. Each grant is kept in
5 * `entitlement_change` and put on the event outbox (`billing.plan`), so it shows in the audit
6 * trail. Anyone else is told `not_found`.
77 */
88
99 import type { App } from "../app.ts";
@@ -18,6 +18,7 @@ import { isStripeKey, stripeClient, type StripeError } from "../billing/stripe.t
1818 import { publicOrigin } from "../core/public_origin.ts";
1919 import { holdValues } from "../kernel/log.ts";
2020 import { listChildrenNow } from "./spawn.ts";
21 import { BILLING_SIZES } from "../settings/billing.ts";
2122 import { parseSize } from "../spawn/sizes.ts";
2223
2324 export type BillingError = "not_found" | "no_such_forge" | "bad_plan";
@@ -75,7 +76,8 @@ export function planGrant(app: App, actor: User | undefined, forge: unknown, pla
7576 const child = typeof forge === "string" ? listChildrenNow(app).find((c) => c.name === forge) : undefined;
7677 if (!child) return err("no_such_forge");
7778 const size = parseSize(plan);
78 if (!size.ok) return err("bad_plan");
79 // xlarge is a size a forge is raised to (`spawn/manage.ts`), never a plan that is paid for.
80 if (!size.ok || !(BILLING_SIZES as readonly string[]).includes(size.value)) return err("bad_plan");
7981 const from = entitlementOf(app.db, child.name, child.size);
8082 return ok({ from, to: { forge: child.name, plan: size.value, status: "active", source: "granted" } });
8183 }
@@ -155,8 +157,8 @@ export function saveSigningSecret(app: App, actor: User | undefined, secret: unk
155157 }
156158
157159 /**
158 * Remove the webhook endpoint and the sealed key and secret; the key and secret go even when Stripe cannot be reached,
159 * and `left_at_stripe` says the endpoint is still there.
160 * Remove the webhook endpoint and the sealed key and secret; the key and secret go even when Stripe
161 * cannot be reached, and `left_at_stripe` says the endpoint is still there.
160162 */
161163 export async function disconnectStripe(app: App, actor: User | undefined, fetchFn: typeof fetch = fetch): Promise<Result<true, BillingError | StripeWords>> {
162164 const who = admin(actor);
src/actions/proposals.ts +3 −1
@@ -40,7 +40,9 @@ function errorWords(e: unknown): string {
4040 return typeof m === "string" ? m : "it was refused";
4141 }
4242
43 /** The proposal and its repository, when this person is who it asks and it is in one of `states`. */
43 /**
44 * The proposal and its repository, when this person is who it asks and it is in one of `states`.
45 */
4446 function mine(
4547 app: App,
4648 actor: User | undefined,
src/core/dep_standing.ts +4 −1
@@ -286,7 +286,10 @@ export function blockerByTitle(
286286 return { says: `${found.length > 5 ? "More than five" : found.length} issues match "${wanted}": ${found.slice(0, 5).map((i) => `#${i.number}`).join(", ")}. Type the number.` };
287287 }
288288
289 /** The chain as plain lines for the terminal: what it waits for (furthest back first), then what waits for it. */
289 /**
290 * The chain as plain lines for the terminal: what it waits for (furthest back first), then what
291 * waits for it.
292 */
290293 export function chainLines(s: Standing): string[] {
291294 const row = (lead: string, n: StandingNode): string =>
292295 `${lead} #${n.number} ${n.title} - ${n.word}${n.holding ? " · holding this" : ""}${n.next === "" ? "" : ` · next: ${n.next}`}`;
src/core/event_audience.ts +1
@@ -121,6 +121,7 @@ const READER_KINDS: ReadonlySet<string> = new Set([
121121 "forge.restored",
122122 "forge.archive_noticed",
123123 "forge.stopped",
124 "forge.resized",
124125 // A forge's own one line to its people: it runs in a sandbox now (`spawn/sandboxed.ts`). It names
125126 // nothing.
126127 "forge.sandboxed",
src/crew/autonomy.ts +21 −12
@@ -394,7 +394,9 @@ function meanRunUsd(db: App["db"], repoId: string): number {
394394 );
395395 }
396396
397 /** The issues each repository picked in this tick, by repository id: their runs may not show yet. */
397 /**
398 * The issues each repository picked in this tick, by repository id: their runs may not show yet.
399 */
398400 export type TickPicks = ReadonlyMap<string, ReadonlySet<string>>;
399401
400402 /**
@@ -649,10 +651,10 @@ export function startable(
649651
650652 /**
651653 * Give the planner the direction when the reserve is due a pass — down to
652 * half of two startable issues per builder slot (`reserve.ts`) — or when the crew has handed it an issue it parked twice,
653 * and no planning run is in flight, and the last one is old enough.
654 * Returns whether a planning run was set up. Planning runs alongside
655 * building: the builders are never waited for.
654 * half of two startable issues per builder slot (`reserve.ts`) — or when the crew has handed it an
655 * issue it parked twice, and no planning run is in flight, and the last one is old enough. Returns
656 * whether a planning run was set up. Planning runs alongside building: the builders are never
657 * waited for.
656658 *
657659 * A hand-over is owed one pass, not one a minute: it asks only while it is
658660 * newer than the last planning run. That one pass is owed even by a planner
@@ -1008,7 +1010,10 @@ export function parkForBreaker(
10081010 return true;
10091011 }
10101012
1011 /** How many times the crew has parked this issue since a person who directs it last spoke (`parks.ts`). */
1013 /**
1014 * How many times the crew has parked this issue since a person who directs it last spoke
1015 * (`parks.ts`).
1016 */
10121017 export function parkedCount(app: App, repo: Repo, issueId: string): number {
10131018 return countParks(app.db, repo, issueId);
10141019 }
@@ -1305,7 +1310,8 @@ export async function autonomyTick(
13051310 sweep: (app: App, repo: Repo) => Promise<number> = sweepGreen,
13061311 ): Promise<void> {
13071312 if (crewOffInPreview()) return;
1308 // A pull a person holds with changes requested goes back to its builder after a day of silence, in any repository.
1313 // A pull a person holds with changes requested goes back to its builder after a day of silence,
1314 // in any repository.
13091315 try {
13101316 sweepStranded(app, now);
13111317 } catch (error) {
@@ -1336,7 +1342,8 @@ export async function autonomyTick(
13361342 // the next batch is formed, not at its gate (#6611).
13371343 pruneLine(app, repo);
13381344 void startSweep(app, repo, sweep);
1339 // Each pass below is one slice of the thread: a request waiting is served between them (#8848).
1345 // Each pass below is one slice of the thread: a request waiting is served between them
1346 // (#8848).
13401347 await breathe();
13411348 // First of all: a slot freed goes to an approved pull that no longer
13421349 // merges, before a changes-requested one or a new issue (#3682).
@@ -1432,7 +1439,8 @@ export async function autonomyTick(
14321439 // The standing reserve the planner keeps: startable/target (#3237).
14331440 reserve: reserveWords(reserveOf(held.startable.length, status.slots)),
14341441 held: heldWords(held),
1435 // What the picker passes over among the startable, so no ready issue goes unexplained (#8924).
1442 // What the picker passes over among the startable, so no ready issue goes unexplained
1443 // (#8924).
14361444 passed: passedWords(pickFilter(app, current, held.startable, now).passed),
14371445 // The files 5 or more open pulls touch, which no new build starts on (#5934).
14381446 ...(held.by.hot_file.length === 0 ? {} : { hot: hotWords(hotFiles(current.id)) }),
@@ -1448,8 +1456,8 @@ export async function autonomyTick(
14481456 idle: idleBuilders(activeNow, crewNow),
14491457 ...(governor === undefined ? {} : { governor }),
14501458 // Approved conflicted pulls: queued, in flight, and why each other is
1451 // skipped (#3682, #6237), or "0 candidates of N open" (#6263); and the lane for rebases: conflicted N,
1452 // rebasing M, room R (#6140).
1459 // skipped (#3682, #6237), or "0 candidates of N open" (#6263); and the lane for rebases:
1460 // conflicted N, rebasing M, room R (#6140).
14531461 ...finishFields(finishing.moves, readConflictLane(app.db), finishing.open),
14541462 ...(requested.length === 0
14551463 ? {}
@@ -2256,7 +2264,8 @@ async function admit(
22562264 if (!again) addComment(app, by, repo, getIssueById(app.db, pull.id) ?? pull, clashSaid(red.comment, together));
22572265 // A red that reproduces on the re-gate is the code's: only then is it the doctor's to hold.
22582266 if (again) treatRed(app, repo, by, pull, red, baseOid);
2259 // Red only on top of pulls that landed first: no single culprit yet, so the class is recorded and the re-gate alone decides.
2267 // Red only on top of pulls that landed first: no single culprit yet, so the class is recorded
2268 // and the re-gate alone decides.
22602269 else noteRed(app, repo, pull, red, baseOid, together);
22612270 },
22622271 });
src/crew/held.ts +16 −4
@@ -98,7 +98,10 @@ export interface Held {
9898 readonly by: Readonly<Record<HoldName, readonly Issue[]>>;
9999 /** Of the `hot_file` ones, those an admin's hold keeps: issue number to the hold that does. */
100100 readonly pinned: ReadonlyMap<number, FileHold>;
101 /** Of the `hot_file` ones, those that wait because another issue already relieves the same path: issue number to that path and issue. */
101 /**
102 * Of the `hot_file` ones, those that wait because another issue already relieves the same path:
103 * issue number to that path and issue.
104 */
102105 readonly relieving: ReadonlyMap<number, { path: string; by: number }>;
103106 /** Of the `twin` ones: issue number to the twin that holds the same work. */
104107 readonly twins: ReadonlyMap<number, Twin>;
@@ -110,7 +113,10 @@ export interface LastRun {
110113 readonly created_at: string;
111114 }
112115
113 /** The newest agent run of each of `ids` in a few reads, not one per issue; an issue never run is absent. */
116 /**
117 * The newest agent run of each of `ids` in a few reads, not one per issue; an issue never run is
118 * absent.
119 */
114120 export function lastAgentRuns(app: App, ids: readonly string[]): Map<string, LastRun> {
115121 const out = new Map<string, LastRun>();
116122 const CHUNK = 400;
@@ -415,7 +421,10 @@ export function mapHolds(
415421 return { holds, startable: held.startable.map((r) => r.issue.number) };
416422 }
417423
418 /** The pulls a viewer of `scope` may see: all with the sealed scope, else the unsealed and their own. */
424 /**
425 * The pulls a viewer of `scope` may see: all with the sealed scope, else the unsealed and their
426 * own.
427 */
419428 export function admits(app: App, repo: Repo, scope: { sealed?: true; sealedBy?: string }) {
420429 if (scope.sealed === true) return () => true;
421430 return (n: number): boolean => {
@@ -424,7 +433,10 @@ export function admits(app: App, repo: Repo, scope: { sealed?: true; sealedBy?:
424433 };
425434 }
426435
427 /** How long a viewer's map holds are reused by the next reader of the same repository. Off under `bun test`. */
436 /**
437 * How long a viewer's map holds are reused by the next reader of the same repository. Off under
438 * `bun test`.
439 */
428440 export const mapHeldReuse = { ms: process.env["NODE_ENV"] === "test" ? 0 : 5_000 };
429441 const mapHeldKept = new WeakMap<App, Map<string, { at: number; holds: ReturnType<typeof mapHolds> }>>();
430442
src/flow/alarms.ts +4 −1
@@ -51,7 +51,10 @@ export const FORGE_BROKEN: ReadonlySet<FiredAlarm["key"]> = new Set(["red_main",
5151 export function firedAlarms(
5252 db: Database,
5353 now: Date,
54 /** `dataDir` is required so a caller cannot forget it and lose the backup alarm; `null` says there is none to read (a unit over a bare db). */
54 /**
55 * `dataDir` is required so a caller cannot forget it and lose the backup alarm; `null` says there
56 * is none to read (a unit over a bare db).
57 */
5558 opts: { readonly dataDir: string | null; readonly publicOnly?: boolean; readonly ceilingUsd?: number | null },
5659 ): FiredAlarm[] {
5760 const out: FiredAlarm[] = [];
src/flow/lanes_read.ts +51 −16
@@ -52,14 +52,19 @@ export const MOVED_MS = 30 * 60_000;
5252 export const SLOW_MS = 30_000;
5353
5454 export interface LaneItem {
55 /** Stable across lanes: the same change keeps its key as it moves, so the page can move its tile. */
55 /**
56 * Stable across lanes: the same change keeps its key as it moves, so the page can move its tile.
57 */
5658 readonly key: string;
5759 readonly repoId: string;
5860 readonly kind: "issue" | "pull" | "main" | "deploy";
5961 readonly number: number | null;
6062 readonly title: string;
6163 readonly sealed: boolean;
62 /** Who has it: the crew member, the reviewer, the person who asked or merged. Empty when no one does. */
64 /**
65 * Who has it: the crew member, the reviewer, the person who asked or merged. Empty when no one
66 * does.
67 */
6368 readonly who: string;
6469 /** When it entered this lane. */
6570 readonly since: string;
@@ -71,7 +76,10 @@ export interface LaneItem {
7176 readonly position: number | null;
7277 /** When its worker last said it was alive; null when it does not say. */
7378 readonly beat: string | null;
74 /** The issue or pull this is, for an action over it (`fleet/verbs.ts`); null for a check of main and a deploy. */
79 /**
80 * The issue or pull this is, for an action over it (`fleet/verbs.ts`); null for a check of main
81 * and a deploy.
82 */
7583 readonly issueId: string | null;
7684 /** When the issue or pull was opened; null where there is none. */
7785 readonly born: string | null;
@@ -95,7 +103,10 @@ export interface StripPart {
95103 readonly usedPct: number;
96104 readonly mayUsePct: number;
97105 } | null;
98 /** The crew's spend over seven days at list price, for the forge's own estimate when the provider has not reported. */
106 /**
107 * The crew's spend over seven days at list price, for the forge's own estimate when the provider
108 * has not reported.
109 */
99110 readonly weekSpendUsd: number;
100111 readonly ceilingUsd: number | null;
101112 readonly needs: readonly { readonly says: string; readonly href: string }[];
@@ -117,7 +128,10 @@ export interface LanePicture {
117128 readonly asks: Readonly<Record<string, AsksWaiting>>;
118129 /** The home's figures; null until the slow part has been read. */
119130 readonly figures: Figures | null;
120 /** Why no builder is starting anything, when something names it (the day's ceiling, no subscription with room, nothing ready); null otherwise. */
131 /**
132 * Why no builder is starting anything, when something names it (the day's ceiling, no
133 * subscription with room, nothing ready); null otherwise.
134 */
121135 readonly idle: IdleReason | null;
122136 }
123137
@@ -223,7 +237,10 @@ function item(
223237 };
224238 }
225239
226 /** Runs of one kind in flight, running first and then by age; a queued run paused on a limit is not waiting for a worker. */
240 /**
241 * Runs of one kind in flight, running first and then by age; a queued run paused on a limit is not
242 * waiting for a worker.
243 */
227244 function runRows(
228245 db: Database,
229246 kind: "agent" | "check",
@@ -342,9 +359,10 @@ interface Deploy {
342359 /**
343360 * Production deploys going live now and those that went live in the last 24
344361 * hours, newest first. Only the ids and times come from the run table, and
345 * only through its own two small indexes (`run_live`, `run_queue`), named (`INDEXED BY`) because the planner picks `run_kind_state` and walks every deploy: the
346 * deploy ledger (`deploy_pull`) is never counted or sorted, because a deploy
347 * lists every change it carries and production's holds ten million rows.
362 * only through its own two small indexes (`run_live`, `run_queue`), named (`INDEXED BY`) because
363 * the planner picks `run_kind_state` and walks every deploy: the deploy ledger (`deploy_pull`) is
364 * never counted or sorted, because a deploy lists every change it carries and production's holds
365 * ten million rows.
348366 */
349367 function deploys(
350368 db: Database,
@@ -473,12 +491,14 @@ function live(db: Database, dayAgo: string): LaneRead {
473491 const { rows, total } = deploys(db, dayAgo);
474492 const seen = new Set<string>();
475493 const items: LaneItem[] = [];
476 // Enough to list; the carried-change lookup is a few rows each, so it is bounded to what a lane draws.
494 // Enough to list; the carried-change lookup is a few rows each, so it is bounded to what a lane
495 // draws.
477496 for (const d of rows) {
478497 if (items.length >= LANE_ITEMS + 3) break;
479498 const going = d.state === "queued" || d.state === "running";
480499 const change = carried(db, d.repo_id, d.at);
481 // A tile is the change it put live, keyed as the change (so Landing's tile arrives here); a deploy that names none is keyed by itself.
500 // A tile is the change it put live, keyed as the change (so Landing's tile arrives here); a
501 // deploy that names none is keyed by itself.
482502 const key = `i-${change?.id ?? d.id}`;
483503 if (seen.has(key)) continue;
484504 seen.add(key);
@@ -515,7 +535,10 @@ export interface Fast {
515535 readonly working: ReadonlySet<string>;
516536 }
517537
518 /** The fast part: running and queued work, approved and merged pulls, deploys. A few indexed reads, each bounded. */
538 /**
539 * The fast part: running and queued work, approved and merged pulls, deploys. A few indexed reads,
540 * each bounded.
541 */
519542 export function readFast(db: Database, now: Date): Fast {
520543 const iso = now.toISOString();
521544 const week = new Date(now.getTime() - 7 * 86_400_000).toISOString();
@@ -596,7 +619,10 @@ export function withWaits(
596619 }
597620
598621 export interface Slow {
599 /** The crew's next asks in its own order, a few more than a lane draws so a build starting leaves the lane full. */
622 /**
623 * The crew's next asks in its own order, a few more than a lane draws so a build starting leaves
624 * the lane full.
625 */
600626 readonly asked: readonly LaneItem[];
601627 readonly askedTotal: number;
602628 readonly strip: StripPart;
@@ -706,7 +732,10 @@ export function readSlow(
706732 };
707733 }
708734
709 /** Why the builders sit idle, from the same module the dispatcher is asked in; `app` is the database and the data directory, the two things it reads. */
735 /**
736 * Why the builders sit idle, from the same module the dispatcher is asked in; `app` is the database
737 * and the data directory, the two things it reads.
738 */
710739 function idleOf(db: Database, dataDir: string, now: Date): IdleReason | null {
711740 try {
712741 return idleReason({ db, config: { dataDir } } as unknown as App, now);
@@ -715,7 +744,10 @@ function idleOf(db: Database, dataDir: string, now: Date): IdleReason | null {
715744 }
716745 }
717746
718 /** What waits on each viewer: the same set `/review` draws (`reviewSetOf`), counted per person the worker was told of. */
747 /**
748 * What waits on each viewer: the same set `/review` draws (`reviewSetOf`), counted per person the
749 * worker was told of.
750 */
719751 function asksOf(db: Database, viewers: readonly string[], now: Date): Record<string, AsksWaiting> {
720752 const out: Record<string, AsksWaiting> = {};
721753 for (const id of viewers) {
@@ -730,7 +762,10 @@ function asksOf(db: Database, viewers: readonly string[], now: Date): Record<str
730762 return out;
731763 }
732764
733 /** A short hash of what a lane shows: its items without the heartbeat, which moves every few seconds and is no change. */
765 /**
766 * A short hash of what a lane shows: its items without the heartbeat, which moves every few seconds
767 * and is no change.
768 */
734769 function versionOf(read: LaneRead): string {
735770 return Bun.hash(
736771 JSON.stringify([
src/http/mcp/tools/forges.ts +12 −5
@@ -9,19 +9,20 @@ import { archiveForge, archivedForges, restoreForge } from "../../../spawn/archi
99 import { CHILD_NAME } from "../../../spawn/placement.ts";
1010 import { checkMove } from "../../../spawn/move_check.ts";
1111 import { moveToCell } from "../../../spawn/move_cell.ts";
12 import { resizeForge } from "../../../spawn/manage.ts";
1213 import { good, bad, type Tool } from "../shared.ts";
1314
1415 const sentSays = (n: number) => (n === 0 ? "This forge has sent no forges yet." : `${n} forge${n === 1 ? "" : "s"} sent from here.`);
1516
1617 export const tool: Tool = {
1718 name: "forges",
18 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, keep cost, archive reason, reachable, size, use, madeFrom; `{ forge, plan?, dryRun? }` reads a forge's plan (small|medium|large) 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, command-running keys, 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; `kind` clients lists each client in the page's words",
19 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, keep cost, archive reason, reachable, size, use, madeFrom; `{ forge, plan?, dryRun? }` reads a forge's plan (small|medium|large) or, with `plan`, grants it by hand; `size` workshop raises a forge; `{ forge, sandbox: true }` reads what moving a forge out of this forge's own process into a sandbox would meet (hooks, command-running keys, 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; `kind` clients lists each client in the page's words",
1920 description:
20 "Forges sent from here (admin), the client list, or one forge's plan.",
21 inputSchema: { type: "object", properties: { kind: { type: "string", enum: ["refused", "clients"] }, 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" } } },
21 "Forges sent from here (admin), clients, a forge's plan or size.",
22 inputSchema: { type: "object", properties: { kind: { type: "string", enum: ["refused", "clients"] }, 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" }, size: { type: "string" }, acknowledge: { type: "boolean" }, dryRun: { type: "boolean" } } },
2223 writes: true,
2324 dryByDefault: true,
24 readsWithout: ["forge", "plan", "code", "revoke", "archive", "restore"],
25 readsWithout: ["forge", "plan", "size", "code", "revoke", "archive", "restore"],
2526 async run(ctx, user, args) {
2627 if (!user.isAdmin)
2728 return bad("forbidden", "only an admin of this forge sees the forges it sent");
@@ -64,7 +65,7 @@ export const tool: Tool = {
6465 if (!CHILD_NAME.test(name)) return bad("invalid", "restore names an archived forge");
6566 if (!live) return good({ says: `This would restore ${name} from its archive under the same name; nothing changed. Send dryRun: false to do it.`, archived: archivedForges(ctx.app) });
6667 const done = await restoreForge(ctx.app, name, { actorId: user.id });
67 return done.ok ? good({ says: done.says }) : bad("invalid", done.says);
68 return done.ok ? good({ says: done.says }) : bad(done.says.startsWith("no forge named") ? "not_found" : "invalid", done.says);
6869 }
6970 const names = (Array.isArray(args["archive"]) ? args["archive"] : [args["archive"]]).map(String);
7071 if (names.length === 0 || names.length > 5 || !names.every((n) => CHILD_NAME.test(n))) return bad("invalid", "archive names one to five forges");
@@ -85,6 +86,12 @@ export const tool: Tool = {
8586 const done = await moveToCell(ctx.app, forge, { by: "admin", acknowledge: args["acknowledge"] === true, actorId: user.id });
8687 return done.ok ? good(done) : bad(done.kind, done.says);
8788 }
89 if (args["forge"] !== undefined && args["size"] !== undefined) {
90 const live = args["dryRun"] === false;
outdated

Dead check: user.isAdmin is already enforced at the top of run. Remove it. Also a missing forge returns invalid here, not not_found; keep it consistent with the other branches.

91 if (live && !scopeAllows(ctx.auth.scope ?? "ro", "admin")) return bad("forbidden", "raising a forge's size needs an admin token");
92 const done = await resizeForge(ctx.app, user.id, String(args["forge"]), args["size"], !live);
93 return done.ok ? good({ says: done.says }) : bad(done.says.startsWith("no forge named") ? "not_found" : "invalid", done.says);
94 }
8895 if (args["forge"] !== undefined || args["plan"] !== undefined) {
8996 const refuse = (e: string) => (e === "not_found" ? bad("not_found", "Not found.") : bad("invalid", BILLING_WORDS[e as keyof typeof BILLING_WORDS] ?? e));
9097 if (args["plan"] === undefined) {
src/http/mcp/tools/sizes.ts +2 −2
@@ -3,9 +3,9 @@ import { good, type Tool } from "../shared.ts";
33
44 export const tool: Tool = {
55 name: "sizes",
6 doc: "what a child forge's sizes mean: small, medium and large, each with CPU, memory and disk",
6 doc: "what a child forge's sizes mean: small, medium, large and xlarge, each with CPU, memory and disk",
77 description:
8 "A child forge's sizes: small, medium and large, each with CPU, memory and disk.",
8 "Child forge sizes up to xlarge: CPU, memory, disk.",
99 inputSchema: { type: "object", properties: {} },
1010 writes: false,
1111 run: () => good(sizesView()),
src/http/mcp/tools/spawn.ts +1 −1
@@ -36,7 +36,7 @@ export const tool: Tool = {
3636 },
3737 size: {
3838 type: "string",
39 enum: ["small", "medium", "large"],
39 enum: ["small", "medium", "large", "xlarge"],
4040 description: "Recorded only.",

Box 1: the workshop is offered here with no line on what it is for. Say it in the same words as sizesView.

4141 },
4242 plan: {
src/http/route_marks.ts +1
@@ -228,6 +228,7 @@ export const ROUTES: Readonly<Record<string, Mark>> = {
228228 "/forges/:name/undo-link": "admin",
229229 "/forges/:name/stop": "admin",
230230 "/forges/:name/sandbox": "admin",
231 "/forges/:name/size": "admin",
231232 "/forges/:name/reach/allow": "admin",
232233 "/forges/:name/reach/later": "admin",
233234 "/forges/:name/reach/revoke": "admin",
src/http/server.ts +2 −1
@@ -320,7 +320,7 @@ import { claimFragmentPage, claimOptions, claimRenew, claimSubmit, welcomePage,
320320 import { firstAdminOptions, firstAdminPage, firstAdminSubmit } from "../web/pages/first-admin.ts";
321321 import { familyPage } from "../web/pages/family.ts";
322322 import { forgeLinkForm, forgeLinkRevoke, forgeLinkSubmit, forgeLinkUndo, forgeArchiveConfirm, forgeArchiveSubmit, forgeRestoreSubmit, forgeRemoveConfirm, forgeRemoveSubmit, forgeStopSubmit,
323 forgeOwnCodeSubmit, forgeSandboxSubmit, forgesPage } from "../web/pages/forges.ts";
323 forgeOwnCodeSubmit, forgeSizeSubmit, forgeSandboxSubmit, forgesPage } from "../web/pages/forges.ts";
324324 import { billDownload } from "./api/forge_bill.ts";
325325 import { forgesRefusedPage } from "../web/pages/forges-refused.ts";
326326 import { forgeReachAllow, forgeReachLater, forgeReachRevoke } from "../web/pages/hosted-forges.ts";
@@ -967,6 +967,7 @@ export function buildRouter(): Router<Handler> {
967967 router.add("POST", "/forges/:name/reach/later", forgeReachLater);
968968 router.add("POST", "/forges/:name/reach/revoke", forgeReachRevoke);
969969 router.add("POST", "/forges/:name/own-code", forgeOwnCodeSubmit);
970 router.add("POST", "/forges/:name/size", forgeSizeSubmit);
970971 router.add("GET", "/forges/:name/remove", forgeRemoveConfirm);
971972 router.add("POST", "/forges/:name/remove", forgeRemoveSubmit);
972973 router.add("GET", "/forges/:name/ready", forgeReady);
src/snapshot/sealed_store.ts +30 −8
@@ -34,7 +34,10 @@ export const SEALED_PREFIX = "sealed/";
3434 const MAGIC = Buffer.from("FSO1");
3535 const IV_BYTES = 12;
3636 const TAG_BYTES = 16;
37 /** The lane's header, beside the sealed objects and unsealed: the salt and a check value, never the key. */
37 /**
38 * The lane's header, beside the sealed objects and unsealed: the salt and a check value, never the
39 * key.
40 */
3841 export const LANE_HEADER = `${SEALED_PREFIX}lane.json`;
3942 const SALT_BYTES = 16;
4043 const SALT_HEX = /^[0-9a-f]{32}$/;
@@ -49,7 +52,10 @@ export interface SealKeys {
4952 readonly mac: Buffer;
5053 }
5154
52 /** The two keys a passphrase gives under a lane's salt: one seals bodies, one hides names. One scrypt, about 100 ms, off the main thread. */
55 /**
56 * The two keys a passphrase gives under a lane's salt: one seals bodies, one hides names. One
57 * scrypt, about 100 ms, off the main thread.
58 */
5359 export function sealKeys(passphrase: string, salt: Uint8Array): Promise<SealKeys> {
5460 return new Promise((resolve, reject) => {
5561 scrypt(passphrase, salt, 64, SCRYPT, (error, k) => {
@@ -59,7 +65,10 @@ export function sealKeys(passphrase: string, salt: Uint8Array): Promise<SealKeys
5965 });
6066 }
6167
62 /** What the header keeps to tell the right passphrase from a wrong one; an HMAC, so it gives no shortcut past scrypt. */
68 /**
69 * What the header keeps to tell the right passphrase from a wrong one; an HMAC, so it gives no
70 * shortcut past scrypt.
71 */
6372 const checkOf = (keys: SealKeys): string => createHmac("sha256", keys.mac).update("forge off-site lane header").digest("hex");
6473
6574 /** A header's salt and check, or a sentence when the object is not one the lane wrote. */
@@ -103,7 +112,10 @@ export function sealBody(keys: SealKeys, body: Uint8Array | string): Uint8Array
103112 return Buffer.concat([MAGIC, iv, cipher.update(plain), cipher.final(), cipher.getAuthTag()]);
104113 }
105114
106 /** The plain body; throws, naming the key, when the passphrase is wrong or the object is not one the lane sealed. */
115 /**
116 * The plain body; throws, naming the key, when the passphrase is wrong or the object is not one the
117 * lane sealed.
118 */
107119 export function openBody(keys: SealKeys, sealed: Uint8Array, key: string): Uint8Array {
108120 const b = Buffer.from(sealed.buffer, sealed.byteOffset, sealed.byteLength);
109121 if (b.length < MAGIC.length + IV_BYTES + TAG_BYTES || !b.subarray(0, MAGIC.length).equals(MAGIC))
@@ -130,14 +142,21 @@ export function hiddenKey(keys: SealKeys, key: string): string {
130142 }
131143
132144 export interface SealedOptions {
133 /** Whether a lane with no header yet starts one (the mirror pass); a restore reads, so it does not. */
145 /**
146 * Whether a lane with no header yet starts one (the mirror pass); a restore reads, so it does
147 * not.
148 */
134149 readonly create?: boolean;
135150 }
136151
137 /** `inner`, every object sealed under `passphrase` and named so a path never shows. The keys are derived on first use. */
152 /**
153 * `inner`, every object sealed under `passphrase` and named so a path never shows. The keys are
154 * derived on first use.
155 */
138156 export function sealedStore(inner: Store, passphrase: string, options: SealedOptions = {}): Store {
139157 let pending: Promise<SealKeys> | undefined;
140 // One derivation for the store and every bounded view of it; a failed read of the header is tried again next time.
158 // One derivation for the store and every bounded view of it; a failed read of the header is tried
159 // again next time.
141160 const keys = (): Promise<SealKeys> =>
142161 (pending ??= laneKeys(inner, passphrase, options.create ?? true).catch((error: unknown) => {
143162 pending = undefined;
@@ -183,7 +202,10 @@ function over(inner: Store, keys: () => Promise<SealKeys>): Store {
183202 return bounded === undefined ? store : { ...store, bounded: (leftMs) => over(bounded.call(inner, leftMs), keys) };
184203 }
185204
186 /** A lane that may not write: every call fails with `reason`, so the board says why and nothing leaves unsealed. */
205 /**
206 * A lane that may not write: every call fails with `reason`, so the board says why and nothing
207 * leaves unsealed.
208 */
187209 export function refusingStore(where: string, reason: string): Store {
188210 const no = async (): Promise<never> => {
189211 throw new Error(reason);
src/snapshot/snapshot.ts +7 −2
@@ -184,7 +184,10 @@ export interface Progress {
184184 readonly etaMs?: number;
185185 }
186186
187 /** What a page shows beside "N objects, X so far": one label and value each; parts not known are left out. */
187 /**
188 * What a page shows beside "N objects, X so far": one label and value each; parts not known are
189 * left out.
190 */
188191 export function progressFacts(p: Progress): { label: string; value: string }[] {
189192 const rows: { label: string; value: string }[] = [];
190193 if (p.already !== undefined && p.seen !== undefined && p.seen > 0) rows.push({ label: "Already there", value: `${p.already} of ${p.seen} chunks` });
@@ -194,7 +197,9 @@ export function progressFacts(p: Progress): { label: string; value: string }[] {
194197 return rows;
195198 }
196199
197 /** Progress as a short sentence for the log and the terminal: what is sent, what is left, how long. */
200 /**
201 * Progress as a short sentence for the log and the terminal: what is sent, what is left, how long.
202 */
198203 export function progressWords(p: Progress): string {
199204 const parts = [`${fmtBytes(p.bytes)} sent`];
200205 if (p.toGoBytes !== undefined) parts.push(`${fmtBytes(p.toGoBytes)} left`);
src/spawn/manage.ts +25 −1
@@ -13,8 +13,10 @@ import { revokeChildFollowTokens } from "../core/proposal_token.ts";
1313 import { restoreClaim, revokeClaim, spawnedOrg } from "./claim.ts";
1414 import { forgetHeard } from "./clients.ts";
1515 import { forgetForge } from "../core/child_reach.ts";
16 import { noteLedger, sleepChild } from "./host.ts";
17 import { resizeRefusal } from "./quota.ts";
18 import { isSize, SIZE_ORDER, SIZES, type Size } from "./sizes.ts";
1619 import { retireBody } from "./door.ts";
17 import { sleepChild } from "./host.ts";
1820 import { CHILD_NAME } from "./placement.ts";
1921 import { switchOwnCode } from "./own_code.ts";
2022
@@ -96,3 +98,25 @@ export async function ownCode(app: App, name: string, on: boolean): Promise<Mana
9698 if (switched.ok) await sleepChild(app, name);
9799 return switched;
98100 }
101
102 /**
103 * Raise a forge to a larger size (xlarge, for a crew that builds the forge itself): the
104 * site admin's, receipted as `forge.resized`. Only upward; a host without the room for it says so
105 * and nothing changes. `dryRun` says what would happen. A running cell is put to sleep so its next
106 * visitor wakes it with the new CPUs and memory.
107 */
108 export async function resizeForge(app: App, actorId: string, name: string, to: unknown, dryRun = false): Promise<Managed> {
109 const child = await find(app, name);
110 if (child === undefined) return { ok: false, says: `no forge named ${name}` };
111 if (!isSize(to)) return { ok: false, says: `size must be ${SIZE_ORDER.join(", ")}` };
112 if (SIZE_ORDER.indexOf(to) <= SIZE_ORDER.indexOf(child.size)) return { ok: false, says: `${name} is ${child.size} already; a size is only raised` };
113 const room = resizeRefusal(app.config.dataDir, child.size, to);
114 if (room !== undefined) return { ok: false, says: `${name} stays ${child.size}: ${room}` };
115 const l = SIZES[to];
outdated

tellPlan is the billing plan notice; the workshop is deliberately not a plan. Confirm what it sends on a resize, and drop it if it tells the forge a plan changed.

116 const words = `${l.cpu} CPUs and ${l.memoryMiB / 1024} GiB of memory`;
117 if (dryRun) return { ok: true, says: `${name} would go from ${child.size} to ${to}: ${words}. Nothing changed.` };
118 noteLedger(app, name, () => ({ size: to as Size }));
119 app.bus.append({ kind: "forge.resized", actorId, payload: { name, from: child.size, to } });
120 await sleepChild(app, name);
121 return { ok: true, says: `${name} is raised from ${child.size} to ${to}: ${words} from its next start` };
122 }
src/spawn/upstream.ts +2 −1
@@ -184,7 +184,8 @@ async function run(app: App, options: { remote?: string; now?: number }): Promis
184184 }
185185 }
186186 const repo = getRepo(app.db, o, n);
187 // Remember the tip before the card, so a crash between them can lose a card but never repeat one.
187 // Remember the tip before the card, so a crash between them can lose a card but never repeat
188 // one.
188189 const tell = repo !== undefined && link.mode === "tell-me" && state.error === "" && state.parentTip !== "" &&
189190 (state.behind ?? 0) > 0 && state.parentTip !== state.toldTip;
190191 if (tell) state = { ...state, toldTip: state.parentTip };
src/tui/screens/forges.ts +34 −2
@@ -16,7 +16,7 @@ import { clientRows } from "../../spawn/clients.ts";
1616 import { diskWords } from "../../spawn/disk_mount.ts";
1717 import { archiveForge, archivedForges, destinationWords, restoreForge } from "../../spawn/archive.ts";
1818 import { claimedWords, keepWords } from "../../spawn/keep_words.ts";
19 import { changeLink, ownCode, removeForge, stopForge } from "../../spawn/manage.ts";
19 import { changeLink, ownCode, removeForge, resizeForge, stopForge } from "../../spawn/manage.ts";
2020 import { moveToCell } from "../../spawn/move_cell.ts";
2121 import { readOwnCode } from "../../spawn/own_code.ts";
2222 import type { App } from "../../app.ts";
@@ -165,6 +165,37 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
165165 }),
166166 );
167167 };
168 // The page's "Raise to xlarge", through the same action (`resizeForge`): an admin's, after
169 // reading what it would do.
170 const raiseOne = (): void => {
171 const user = session?.user;
172 if (session === undefined || user?.isAdmin !== true) return;
173 const items = rows.filter((r) => r.made && r.size !== "xlarge").map((r) => ({ id: r.name, label: r.name, hint: r.size }));
174 if (items.length === 0) return ctx.toast("No forge can be raised to xlarge");
175 ctx.push(
176 pickerScreen(ctx, screen, {
177 title: "Raise which forge to xlarge?",
178 items,
179 onPick: (ids) => {
180 const name = ids[0];
181 if (name === undefined) return;
182 void resizeForge(session.app, user.id, name, "xlarge", true).then((plan) => {
183 if (!plan.ok) return ctx.toast(plan.says, "danger");
184 ctx.push(
185 confirmScreen(ctx, screen, {
186 title: `Raise ${name}?`,
187 body: [plan.says.replace(" Nothing changed.", ""), "It is put to sleep and starts with the new size."],
188 actions: [{ label: "Raise it" }, { label: "Leave it" }],
189 onChoose: (i) => {
190 if (i === 0) void resizeForge(session.app, user.id, name, "xlarge").then((done) => ctx.toast(done.says, done.ok ? "success" : "danger"));
191 },
192 }),
193 );
194 });
195 },
196 }),
197 );
198 };
168199 // "Send a new link" on a row not yet claimed: the page's preview and confirm (`offerNewLink`).
169200 const newLink = (): void => {
170201 if (session === undefined || session.user?.isAdmin !== true) return;
@@ -174,7 +205,7 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
174205 };
175206 const screen: Screen = {
176207 title: "Forges you sent",
177 keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["esc"], "close")],
208 keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["w"], "raise to xlarge"), binding(["esc"], "close")],
178209 render(area, s) {
179210 const c = ctx.theme.c;
180211 const w = Math.min(100, Math.max(30, area.w - 6));
@@ -219,6 +250,7 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
219250 }),
220251 );
221252 } else if (e.key === "m") sandboxOne();
253 else if (e.key === "w") raiseOne();
222254 else if (e.key === "x" && session !== undefined)
223255 choose("Remove which forge?", (name) =>
224256 ctx.push(
src/tui/screens/resilience.ts +17 −5
@@ -66,7 +66,10 @@ export function resilienceLines(dataDir: string): string[] {
6666 /** How many of a nightly job's last lines the output dialog shows. */
6767 export const OUTPUT_TAIL = 12;
6868
69 /** Each nightly job's line and the tail of its newest output, as /resilience/nightly/<job> shows it whole. */
69 /**
70 * Each nightly job's line and the tail of its newest output, as /resilience/nightly/<job> shows it
71 * whole.
72 */
7073 export function nightlyOutputLines(dataDir: string): string[] {
7174 const said = nightlyLines(dataDir);
7275 return JOBS.flatMap((job, i) => {
@@ -103,7 +106,10 @@ export function mirrorLine(f: Session): string {
103106 return where === undefined ? "Mirror: none." : `Mirror: ${where}`;
104107 }
105108
106 /** The bucket's verdict, as home and the MCP's `backups` say it: the line, each lane's newest, what is wrong. */
109 /**
110 * The bucket's verdict, as home and the MCP's `backups` say it: the line, each lane's newest, what
111 * is wrong.
112 */
107113 export function verdictLines(f: Session): string[] {
108114 const v = backupVerdict(f.app.config.dataDir, lastDrill(f.app.db));
109115 const mark = v.state === "red" ? "RED" : v.state === "unknown" ? "unknown" : "ok";
@@ -157,7 +163,9 @@ export function resilienceScreen(f: Session, ctx: Ctx): Screen {
157163 const refusedAll = "Where snapshots go is a forge admin's.";
158164 // The actions refuse anyone else too; the keys are not offered to them.
159165 const mayAct = (): boolean => f.user?.isAdmin === true;
160 /** The newest snapshots, `unreadable` when the store could not be listed; undefined until read. */
166 /**
167 * The newest snapshots, `unreadable` when the store could not be listed; undefined until read.
168 */
161169 let snapshots: string[] | "unreadable" | undefined;
162170 let asking: Asking | undefined;
163171 // While an action runs, `n`, `l` and `r` are ignored: a second would queue behind it.
@@ -291,7 +299,8 @@ export function resilienceScreen(f: Session, ctx: Ctx): Screen {
291299 const out: string[] = [];
292300 if (asking !== undefined) out.push(QUESTION[asking], "");
293301 else if (said !== "") out.push(...wrap(said, INNER), "");
294 // A refusal or a result of a change stays up here too, above where a prompt opens over the middle.
302 // A refusal or a result of a change stays up here too, above where a prompt opens over the
303 // middle.
295304 if (note !== "") out.push(...wrap(note, INNER), "");
296305 out.push(...wrap(backupsLine(f.app).says, INNER), ...verdictLines(f), "");
297306 for (const line of nightlyLines(f.app.config.dataDir)) out.push(...wrap(line, INNER));
@@ -380,7 +389,10 @@ export function resilienceScreen(f: Session, ctx: Ctx): Screen {
380389 return screen;
381390 }
382391
383 /** Where snapshots go and each THREATS.md protection's standing, as /resilience says it: a site admin's; a person admin sets or forgets the destination and the mirror here. */
392 /**
393 * Where snapshots go and each THREATS.md protection's standing, as /resilience says it: a site
394 * admin's; a person admin sets or forgets the destination and the mirror here.
395 */
384396 export const entry: PaletteEntry = {
385397 id: "resilience",
386398 title: "Resilience",
src/web/pages/billing.ts +1 −2
@@ -16,7 +16,6 @@ import { CODE_ERRORS, makeCode, readCodes, revoke, type CodeError } from "../../
1616 import { publicOrigin } from "../../core/public_origin.ts";
1717 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1818 import type { Ctx } from "../../http/context.ts";
19 import { SIZES } from "../../spawn/sizes.ts";
2019 import { BILLING_SIZES, getPortalUrl, PORTAL_WORDS, parseBillingLinks } from "../../settings/billing.ts";
2120 import { getPlans } from "../../settings/plans.ts";
2221 import { changeBillingLinks, changePortalUrl, readBillingLinks } from "../../actions/signup.ts";
@@ -196,7 +195,7 @@ function billingView(ctx: Ctx, shown?: Shown, values: Record<string, string> = {
196195 <span class="mono">${f.forge}</span>
197196 <span class="muted small">${f.status} · ${f.source}${lapseWords(lapseFor(ctx.app.db, f.forge))}</span>
198197 <select class="input" name="plan" aria-label="Plan for ${f.forge}">
199 ${Object.keys(SIZES).map((p) => html`<option value="${p}" ${p === f.plan ? html`selected` : null}>${p}</option>`)}
198 ${BILLING_SIZES.map((p) => html`<option value="${p}" ${p === f.plan ? html`selected` : null}>${p}</option>`)}
200199 </select>
201200 ${btn("Review change")}
202201 </form>
src/web/pages/forges.ts +27 −2
@@ -22,7 +22,8 @@ import { noRoom } from "../../spawn/door.ts";
2222 import { sizeWords, useWords } from "../../spawn/usage.ts";
2323 import { diskWords } from "../../spawn/disk_mount.ts";
2424 import { listChildren } from "../../actions/spawn.ts";
25 import { ownCode, removeForge, stopForge, type Managed } from "../../spawn/manage.ts";
25 import { ownCode, removeForge, resizeForge, stopForge, type Managed } from "../../spawn/manage.ts";
26 import { sizesView } from "../../spawn/sizes.ts";
2627 import { readOwnCode } from "../../spawn/own_code.ts";
2728 import { moveToCell } from "../../spawn/move_cell.ts";
2829 import { sealedAt } from "../../spawn/sealed.ts";
@@ -72,6 +73,8 @@ function seenWords(seen: Seen): Html {
7273 return html`<span data-seen data-opened="${seen.opened ? "yes" : "no"}">${parts.map((p, i) => (i === 0 ? p : html` · ${p}`))}</span>`;
7374 }
7475
76 const XLARGE_SAYS = `${sizeWords("xlarge")}. ${sizesView().sizes.find((x) => x.size === "xlarge")?.says ?? ""}`;
77
7578 export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = false): Html {
7679 const state = claimState(r);
7780 const seen = seenOf(r);
@@ -155,6 +158,11 @@ export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = f
155158 : "Closes it here, starts it in a sandbox of its own, proves its data is intact; puts it back if anything fails",
156159 })}
157160 </form>`
161 : null}${r.made && r.size !== "xlarge"
162 ? html`<form method="post" action="/forges/${r.name}/size" class="inline">
163 <input type="hidden" name="size" value="xlarge" />
164 ${btn("Raise to xlarge", { size: "sm", title: XLARGE_SAYS })}
165 </form>`
158166 : null}${r.made
159167 ? html`<form method="post" action="/forges/${r.name}/stop" class="inline">${btn("Stop", { size: "sm", title: "Put it to sleep now; its next visitor wakes it" })}</form>
160168 ${btn("Archive", { href: `/forges/archive?name=${r.name}`, size: "sm", title: "Saves its data and ledger as one file to the backup destination, then removes it; Restore brings it back" })}
@@ -436,7 +444,12 @@ function receipt(ctx: Ctx, rows: readonly ClientRow[]): Html | null {
436444 restored: html`The link for <strong>${name}</strong> is open again.`,
437445 refused: html`The link for <strong>${name}</strong> did not change: it was not open, or the minute is over.`,
438446 }[ctx.url.searchParams.get("link") ?? ""];
439 return says === undefined ? null : html`<p role="status" class="muted" data-receipt>${says}</p>`;
447 if (says === undefined) {
448 const sized = ctx.url.searchParams.get("size");
449 if (sized !== "raised" && sized !== "refused") return null;
450 return html`<p role="status" class="muted" data-receipt>${name} ${sized === "raised" ? "is raised to the xlarge size from its next start." : "keeps its size: the host has no room for the xlarge size, or it is that size already."}</p>`;
451 }
452 return html`<p role="status" class="muted" data-receipt>${says}</p>`;
440453 }
441454
442455 // POST /forges/:name/revoke-link and /undo-link — take the link back, or bring it back for a
@@ -602,3 +615,15 @@ export async function forgeOwnCodeSubmit(ctx: Ctx): Promise<Response> {
602615 dropServed(ctx.app);
603616 return redirect(`/forges?code=${done.ok ? want : "refused"}&forge=${encodeURIComponent(name)}#forge-code`);
604617 }
618
619 // POST /forges/:name/size — raise a forge to a larger size (xlarge); a receipt on the list.
620 export async function forgeSizeSubmit(ctx: Ctx): Promise<Response> {
621 const user = ctx.auth.user;
622 if (!user?.isAdmin) return notFoundPage(ctx);
623 const form = await readForm(ctx, "admin");
624 if (form instanceof Response) return form;
625 const name = ctx.params["name"] ?? "";
626 const done = await resizeForge(ctx.app, user.id, name, form.get("size"));
627 dropServed(ctx.app);
628 return redirect(`/forges?size=${done.ok ? "raised" : "refused"}&forge=${encodeURIComponent(name)}`);
629 }
test/home-flow.test.ts +6 −3
@@ -97,7 +97,8 @@ describe("the new home draws every lane", () => {
9797 const landingBefore = await (await get("/live/lane?s=landing", owner)).text();
9898 expect(titles(before, "checks")).not.toContain("Pasted links keep their address");
9999 expect(titles(landingBefore, "landing")).toContain("Pasted links keep their address");
100 // the crew starts the checks on an approved pull: its approval is superseded by new work, a check begins
100 // the crew starts the checks on an approved pull: its approval is superseded by new work, a
101 // check begins
101102 const pull = seed.pulls["a2"]!;
102103 app.db.run("UPDATE review SET state = 'commented' WHERE issue_id = ?1", [pull]);
103104 startCheck(app, pull, seed.repos.glue.id);
@@ -258,7 +259,8 @@ describe("nothing on the new home polls", () => {
258259 const text = readFileSync(join(import.meta.dir, "..", file), "utf8");
259260 expect(text).not.toMatch(/setInterval\s*\(/);
260261 expect(text).not.toMatch(/requestAnimationFrame/);
261 // the picture's two one-shots (a pause, a deadline on one worker job) are the only timers, and they hold nothing
262 // the picture's two one-shots (a pause, a deadline on one worker job) are the only timers,
263 // and they hold nothing
262264 expect((text.match(/setTimeout\s*\(/g) ?? []).length).toBe(file === "src/flow/lanes.ts" ? 2 : 0);
263265 }
264266 });
@@ -289,7 +291,8 @@ describe("before the first reading, a page never reads on the thread", () => {
289291 expect(html).toContain("Reading the hosted forges");
290292 for (const lane of LANES) expect(html).toContain(`id="lane-${lane}"`);
291293 expect(html).not.toContain("A cost ledger per delivery");
292 // its script fills each region from the region's own address: the lane waits for the worker, off the thread
294 // its script fills each region from the region's own address: the lane waits for the worker,
295 // off the thread
293296 const lane = await (await fetch(`${srv.url}/live/lane?s=building`, { headers: { cookie } })).text();
294297 expect(lane).toContain("A cost ledger per delivery");
295298 expect(lane).not.toContain("data-reading");
test/home-kpi-row.test.ts +4 −1
@@ -1,4 +1,7 @@
1 /** Home's figures row (#2871): the tiles, their links, studio words only, a sparkline of 24 points and one of 30 days of visitors (#3186). */
1 /**
2 * Home's figures row (#2871): the tiles, their links, studio words only, a sparkline of 24 points
3 * and one of 30 days of visitors (#3186).
4 */
25 import { Database } from "bun:sqlite";
36 import { bugTables, reachTables } from "./helpers/reach-tables.ts";
47 import { NO_REACH, readReach } from "../src/flow/reach.ts";
test/no-alarm-banner.test.ts +7 −3
@@ -71,7 +71,9 @@ interface World {
7171 readonly cookie: string;
7272 }
7373
74 /** A forge in an alarm state; `spent` is the crew's spend today, in dollars, against a $1 ceiling. */
74 /**
75 * A forge in an alarm state; `spent` is the crew's spend today, in dollars, against a $1 ceiling.
76 */
7577 async function world(spent: number): Promise<World> {
7678 const root = mkdtempSync(join(tmpdir(), "forge-no-alarm-banner-"));
7779 const app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge", crewCeilingUsd: 1 });
@@ -89,7 +91,8 @@ async function world(spent: number): Promise<World> {
8991 mkdirSync(join(root, "snapshot"), { recursive: true });
9092 const long = new Date(Date.now() - 72 * 3_600_000).toISOString();
9193 writeFileSync(join(root, "snapshot", "state.json"), JSON.stringify({ at: long, failingSince: long, error: "the bucket refused" }));
92 // A bug past its 48 h clock, in a repository that runs itself and has started no run: the bug-clock and idle-crew alarms.
94 // A bug past its 48 h clock, in a repository that runs itself and has started no run: the
95 // bug-clock and idle-crew alarms.
9396 const bug = openIssue(app, made.value, repo.value, { title: "The page is blank" });
9497 if (!bug.ok) throw new Error(String(bug.error));
9598 const label = createLabel(app.db, repo.value.id, "bug", "d73a4a");
@@ -209,7 +212,8 @@ test("the detector names a banner and passes the lines the forge really draws",
209212 expect(offenders("/", `<main id="main">${banner}<h1>Home</h1></main>`)).toHaveLength(1);
210213 expect(offenders("/", '<p role="alert">Disk is low</p>')).toHaveLength(1);
211214 expect(offenders("/", '<div class="stack banner">x</div>')).toHaveLength(1);
212 // Markup copied from the rendered pages: the home alarm line, the board's need, the menu item that carries the disk.
215 // Markup copied from the rendered pages: the home alarm line, the board's need, the menu item
216 // that carries the disk.
213217 expect(offenders("/", '<p class="small"><a href="/flow">No off-box backup has landed. The snapshot failed: the bucket refused</a></p>')).toEqual([]);
214218 expect(offenders("/board", '<li><a data-need id="sentinel" href="/trevato/forge/issues"><span class="dot" data-tone="attn"></span> The sentinel has 1 open finding</a></li>')).toEqual([]);
215219 expect(offenders("/", '<span class="menu-item" aria-disabled="true" title="this host&#39;s disk has 0.0% free">New forge</span>')).toEqual([]);
test/tui-forges.test.ts +24
@@ -213,3 +213,27 @@ test("a list taller than the card ends with how many are cut off", () => {
213213 expect(cut).toHaveLength(4);
214214 expect(cut[3]![1]).toBe("+7 more (see /forges)");
215215 });
216
217 describe("w raises a forge to xlarge", () => {
218 test("it is a key of the screen, an admin's, and with no forge to raise it says so", async () => {
219 const dataDir = await mkdtemp(join(tmpdir(), "forge-tui-xlarge-"));
220 const forge = createApp({ dataDir, port: 0 });
221 const made = await createUser(forge.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
222 if (!made.ok) throw new Error(made.error);
223 const terminal = headlessTerminal(140, 32);
224 const { app } = createForgeApp(forge, { sshUsername: "t", remoteAddress: "127.0.0.1", user: getUserByName(forge.db, "alice")! }, { terminal, exitHooks: false });
225 app.start();
226 const key = (k: string, ctrl = false) => app.dispatch({ type: "key", key: k, ctrl, alt: false, shift: false });
227 key("k", true);
228 for (const ch of "Forges you sent") key(ch);
229 await settleApp(app);
230 key("enter");
231 await settleApp(app);
232 key("w");
233 await settleApp(app);
234 expect(app.screen.toText()).toContain("No forge can be raised to xlarge");
235 app.stop();
236 forge.close();
237 await rm(dataDir, { recursive: true, force: true });
238 });
239 });
test/xlarge-size.test.ts added +161
@@ -0,0 +1,161 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { createToken } from "../src/core/tokens.ts";
7 import { createUser, getUserByName } from "../src/core/users.ts";
8 import { planGrant } from "../src/actions/billing.ts";
9 import { serve, type Servers } from "../src/http/server.ts";
10 import { tool as spawnTool } from "../src/http/mcp/tools/spawn.ts";
11 import { resizeForge } from "../src/spawn/manage.ts";
12 import { resizeRefusal } from "../src/spawn/quota.ts";
13 import { cellLimits } from "../src/spawn/cell.ts";
14 import { parseSize, SIZES, sizesView, nextSize } from "../src/spawn/sizes.ts";
15 import { adminCookie } from "./helpers/admin.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 describe("the xlarge size", () => {
21 test("a forge made with it gets its CPUs and memory", () => {
22 expect(cellLimits("xlarge")).toEqual({ cpus: 16, memoryMiB: 32768, diskMiB: 81920 });
23 expect(SIZES.xlarge.cpu).toBeGreaterThan(SIZES.large.cpu);
24 });
25
26 test("it is parsed, offered with a line on what it is for, and never reached on its own", () => {
27 expect(parseSize("xlarge")).toEqual({ ok: true, value: "xlarge" });
28 const says = sizesView().sizes.find((s) => s.size === "xlarge")?.says;
29 expect(says).toContain("as big as the forge itself");
30 expect(nextSize("large")).toBeUndefined();
31 expect(nextSize("xlarge")).toBeUndefined();
32 expect(nextSize("medium")).toBe("large");
33 });
34
35 test("the make-a-forge tool takes it; the sizes tool says what it is for", () => {
36 const props = spawnTool.inputSchema["properties"] as Record<string, { enum?: string[]; description?: string }>;
37 expect(props["size"]?.enum).toContain("xlarge");
38 expect(JSON.stringify(sizesView())).toContain("as big as the forge itself");
39 });
40
41 test("the host's limits can refuse a raise", () => {
42 const dir = mkdtempSync(join(tmpdir(), "xlarge-quota-"));
43 try {
44 expect(resizeRefusal(dir, "small", "xlarge", { FORGE_CHILD_MEMORY_MIB: "1024" })).toBeDefined();
45 expect(resizeRefusal(dir, "small", "xlarge", {})).toBeUndefined();
46 } finally {
47 rmSync(dir, { recursive: true, force: true });
48 }
49 });
50 });
51
52 describe("raising a forge to xlarge", () => {
53 let dataDir: string;
54 let app: App;
55 let servers: Servers;
56 let cookie = "";
57 let u1 = "";
58 let rw = "";
59 let admin = "";
60 let bobCookie = "";
61 const ledger = (name: string, size: string) => writeFileSync(join(dataDir, "spawn", `${name}.json`), JSON.stringify({ name, bodyId: `h-${name}`, done: true, placement: "hosted", size }));
62 const sizeOf = (name: string) => (JSON.parse(readFileSync(join(dataDir, "spawn", `${name}.json`), "utf8")) as { size: string }).size;
63 const events = () => app.db.query("SELECT payload FROM event WHERE kind = 'forge.resized'").all() as { payload: string }[];
64 const mcp = async (tok: string, args: object) => {
65 const res = await fetch(`${servers.url}/mcp`, {
66 method: "POST",
67 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${tok}` },
68 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "forges", arguments: args } }),
69 });
70 const j = (await res.json()) as any;
71 return { error: j.result?.isError === true, text: String(j.result?.content?.[0]?.text ?? JSON.stringify(j)) };
72 };
73 const post = (name: string, c: string, size = "xlarge", origin = servers.url) =>
74 fetch(`${servers.url}/forges/${name}/size`, { method: "POST", redirect: "manual", headers: { cookie: c, origin, "content-type": "application/x-www-form-urlencoded" }, body: `size=${size}` });
75
76 beforeAll(async () => {
77 dataDir = mkdtempSync(join(tmpdir(), "xlarge-"));
78 app = createApp({ dataDir, port: 0 });
79 servers = await serve(app);
80 cookie = await adminCookie(app, { username: "alice", email: "[email protected]" });
81 u1 = getUserByName(app.db, "alice")?.id ?? "";
82 const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
83 if (!bob.ok) throw new Error(bob.error);
84 bobCookie = `forge_session=${(await import("../src/core/sessions.ts")).createSession(app.db, bob.value.id).token}`;
85 rw = createToken(app.db, u1, "rw", "rw").token;
86 admin = createToken(app.db, u1, "adm", "admin").token;
87 mkdirSync(join(dataDir, "spawn"), { recursive: true });
88 for (const n of ["kid", "kid2", "kid3", "kid4"]) ledger(n, "small");
89 });
90 afterAll(async () => {
91 await servers.stop?.();
92 app.close();
93 rmSync(dataDir, { recursive: true, force: true });
94 });
95
96 test("a dry run changes nothing; the real one is receipted and only upward", async () => {
97 const planned = await resizeForge(app, u1, "kid", "xlarge", true);
98 expect(planned.ok).toBe(true);
99 expect(events()).toHaveLength(0);
100 expect(sizeOf("kid")).toBe("small");
101 const done = await resizeForge(app, u1, "kid", "xlarge");
102 expect(done.ok).toBe(true);
103 expect(sizeOf("kid")).toBe("xlarge");
104 expect(JSON.parse(events()[0]!.payload)).toEqual({ name: "kid", from: "small", to: "xlarge" });
105 expect((await resizeForge(app, u1, "kid", "xlarge")).ok).toBe(false);
106 expect((await resizeForge(app, u1, "kid", "small")).ok).toBe(false);
107 expect((await resizeForge(app, u1, "kid2", "huge")).ok).toBe(false);
108 expect((await resizeForge(app, u1, "nobody", "xlarge")).ok).toBe(false);
109 });
110
111 test("a resize is no plan change: it is never granted as a plan, and the forge is told no plan", () => {
112 const user = getUserByName(app.db, "alice")!;
113 const planned = planGrant(app, user, "kid2", "xlarge");
114 expect(planned.ok).toBe(false);
115 expect(planGrant(app, user, "kid2", "medium").ok).toBe(true);
116 });
117
118 test("the page's button: an admin's, from this origin only, receipted on the list", async () => {
119 expect((await post("kid2", bobCookie)).status).toBe(403);
120 expect(sizeOf("kid2")).toBe("small");
121 expect((await post("kid2", cookie, "xlarge", "https://evil.example")).status).toBe(403);
122 expect(sizeOf("kid2")).toBe("small");
123 const ok = await post("kid2", cookie);
124 expect(ok.status).toBe(303);
125 expect(ok.headers.get("location")).toBe("/forges?size=raised&forge=kid2");
126 expect(sizeOf("kid2")).toBe("xlarge");
127 const again = await post("kid2", cookie);
128 expect(again.headers.get("location")).toBe("/forges?size=refused&forge=kid2");
129 const bad = await post("kid3", cookie, "huge");
130 expect(bad.headers.get("location")).toBe("/forges?size=refused&forge=kid3");
131 expect(sizeOf("kid3")).toBe("small");
132 const page = await (await fetch(`${servers.url}/forges?size=raised&forge=kid2`, { headers: { cookie } })).text();
133 expect(page).toContain("kid2 is raised to the xlarge size");
134 expect(page).toContain('action="/forges/kid3/size"');
135 expect(page).not.toContain('action="/forges/kid2/size"');
136 });
137
138 test("the MCP tool: a plan by default, a live raise needs an admin token, a missing forge is not found", async () => {
139 const planned = await mcp(rw, { forge: "kid4", size: "xlarge" });
140 expect(planned.error).toBe(false);
141 expect(planned.text).toContain("Nothing changed");
142 expect(sizeOf("kid4")).toBe("small");
143 const live = await mcp(rw, { forge: "kid4", size: "xlarge", dryRun: false });
144 expect(live.error).toBe(true);
145 expect(sizeOf("kid4")).toBe("small");
146 const done = await mcp(admin, { forge: "kid4", size: "xlarge", dryRun: false });
147 expect(done.error).toBe(false);
148 expect(sizeOf("kid4")).toBe("xlarge");
149 const gone = await mcp(admin, { forge: "nobody", size: "xlarge" });
150 expect(gone.error).toBe(true);
151 expect(gone.text).toContain("not_found");
152 });
153
154 test("a person who is no admin is refused by the tool", async () => {
155 const bob = getUserByName(app.db, "bob")!;
156 const t = createToken(app.db, bob.id, "b", "admin").token;
157 const res = await mcp(t, { forge: "kid3", size: "xlarge", dryRun: false });
158 expect(res.error).toBe(true);
159 expect(sizeOf("kid3")).toBe("small");
160 });
161 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs