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
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/13643-making-a-forge-offers-a-workshop-size-th → main 14 commits fork 5 threads · 5 unresolved
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`; | ||
| 127 | 127 | | `forge` | — | How is my forge? What needs you, recommended; `apply` takes them | 297 | |
| 128 | 128 | | `forge_proposals` | — | What this forge proposed to its parent; `reachable` false if it is silent | 245 | |
| 129 | 129 | | `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 | | |
| 131 | 131 | | `fork` | — | Fork a repository into your account; for a guest, a copy to send changes back from | 232 | |
| 132 | 132 | | `fork_tree` | — | The fork tree around a repo: ancestors, siblings and descendants you may read | 440 | |
| 133 | 133 | | `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`; | ||
| 212 | 212 | | `sever` | — | Unlink a spawned forge from its parent, or an app from the repository it came from | 225 | |
| 213 | 213 | | `share` | — | Share a feed item: no `to` tells the app's crew and owners, else followers; budgeted | 283 | |
| 214 | 214 | | `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 | | |
| 216 | 216 | | `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 | | |
| 218 | 218 | | `spend` | — | Report what your session spent outside forge runs: who, model, tokens or dollars, issue | 470 | |
| 219 | 219 | | `ssh_keys` | `list`, `add`, `remove` | Your SSH keys; add: key, remove: id | 250 | |
| 220 | 220 | | `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 ( | ||
| 11 | 11 | **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". |
| 12 | 12 | |
| 13 | 13 | 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 @@ | ||
| 1 | 1 | /** |
| 2 | 2 | * 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`. | |
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | 9 | import type { App } from "../app.ts"; |
| @@ -18,6 +18,7 @@ import { isStripeKey, stripeClient, type StripeError } from "../billing/stripe.t | ||
| 18 | 18 | import { publicOrigin } from "../core/public_origin.ts"; |
| 19 | 19 | import { holdValues } from "../kernel/log.ts"; |
| 20 | 20 | import { listChildrenNow } from "./spawn.ts"; |
| 21 | import { BILLING_SIZES } from "../settings/billing.ts"; | |
| 21 | 22 | import { parseSize } from "../spawn/sizes.ts"; |
| 22 | 23 | |
| 23 | 24 | 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 | ||
| 75 | 76 | const child = typeof forge === "string" ? listChildrenNow(app).find((c) => c.name === forge) : undefined; |
| 76 | 77 | if (!child) return err("no_such_forge"); |
| 77 | 78 | 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"); | |
| 79 | 81 | const from = entitlementOf(app.db, child.name, child.size); |
| 80 | 82 | return ok({ from, to: { forge: child.name, plan: size.value, status: "active", source: "granted" } }); |
| 81 | 83 | } |
| @@ -155,8 +157,8 @@ export function saveSigningSecret(app: App, actor: User | undefined, secret: unk | ||
| 155 | 157 | } |
| 156 | 158 | |
| 157 | 159 | /** |
| 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. | |
| 160 | 162 | */ |
| 161 | 163 | export async function disconnectStripe(app: App, actor: User | undefined, fetchFn: typeof fetch = fetch): Promise<Result<true, BillingError | StripeWords>> { |
| 162 | 164 | const who = admin(actor); |
src/actions/proposals.ts +3 −1
| @@ -40,7 +40,9 @@ function errorWords(e: unknown): string { | ||
| 40 | 40 | return typeof m === "string" ? m : "it was refused"; |
| 41 | 41 | } |
| 42 | 42 | |
| 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 | */ | |
| 44 | 46 | function mine( |
| 45 | 47 | app: App, |
| 46 | 48 | actor: User | undefined, |
src/core/dep_standing.ts +4 −1
| @@ -286,7 +286,10 @@ export function blockerByTitle( | ||
| 286 | 286 | 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.` }; |
| 287 | 287 | } |
| 288 | 288 | |
| 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 | */ | |
| 290 | 293 | export function chainLines(s: Standing): string[] { |
| 291 | 294 | const row = (lead: string, n: StandingNode): string => |
| 292 | 295 | `${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([ | ||
| 121 | 121 | "forge.restored", |
| 122 | 122 | "forge.archive_noticed", |
| 123 | 123 | "forge.stopped", |
| 124 | "forge.resized", | |
| 124 | 125 | // A forge's own one line to its people: it runs in a sandbox now (`spawn/sandboxed.ts`). It names |
| 125 | 126 | // nothing. |
| 126 | 127 | "forge.sandboxed", |
src/crew/autonomy.ts +21 −12
| @@ -394,7 +394,9 @@ function meanRunUsd(db: App["db"], repoId: string): number { | ||
| 394 | 394 | ); |
| 395 | 395 | } |
| 396 | 396 | |
| 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 | */ | |
| 398 | 400 | export type TickPicks = ReadonlyMap<string, ReadonlySet<string>>; |
| 399 | 401 | |
| 400 | 402 | /** |
| @@ -649,10 +651,10 @@ export function startable( | ||
| 649 | 651 | |
| 650 | 652 | /** |
| 651 | 653 | * 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. | |
| 656 | 658 | * |
| 657 | 659 | * A hand-over is owed one pass, not one a minute: it asks only while it is |
| 658 | 660 | * newer than the last planning run. That one pass is owed even by a planner |
| @@ -1008,7 +1010,10 @@ export function parkForBreaker( | ||
| 1008 | 1010 | return true; |
| 1009 | 1011 | } |
| 1010 | 1012 | |
| 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 | */ | |
| 1012 | 1017 | export function parkedCount(app: App, repo: Repo, issueId: string): number { |
| 1013 | 1018 | return countParks(app.db, repo, issueId); |
| 1014 | 1019 | } |
| @@ -1305,7 +1310,8 @@ export async function autonomyTick( | ||
| 1305 | 1310 | sweep: (app: App, repo: Repo) => Promise<number> = sweepGreen, |
| 1306 | 1311 | ): Promise<void> { |
| 1307 | 1312 | 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. | |
| 1309 | 1315 | try { |
| 1310 | 1316 | sweepStranded(app, now); |
| 1311 | 1317 | } catch (error) { |
| @@ -1336,7 +1342,8 @@ export async function autonomyTick( | ||
| 1336 | 1342 | // the next batch is formed, not at its gate (#6611). |
| 1337 | 1343 | pruneLine(app, repo); |
| 1338 | 1344 | 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). | |
| 1340 | 1347 | await breathe(); |
| 1341 | 1348 | // First of all: a slot freed goes to an approved pull that no longer |
| 1342 | 1349 | // merges, before a changes-requested one or a new issue (#3682). |
| @@ -1432,7 +1439,8 @@ export async function autonomyTick( | ||
| 1432 | 1439 | // The standing reserve the planner keeps: startable/target (#3237). |
| 1433 | 1440 | reserve: reserveWords(reserveOf(held.startable.length, status.slots)), |
| 1434 | 1441 | 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). | |
| 1436 | 1444 | passed: passedWords(pickFilter(app, current, held.startable, now).passed), |
| 1437 | 1445 | // The files 5 or more open pulls touch, which no new build starts on (#5934). |
| 1438 | 1446 | ...(held.by.hot_file.length === 0 ? {} : { hot: hotWords(hotFiles(current.id)) }), |
| @@ -1448,8 +1456,8 @@ export async function autonomyTick( | ||
| 1448 | 1456 | idle: idleBuilders(activeNow, crewNow), |
| 1449 | 1457 | ...(governor === undefined ? {} : { governor }), |
| 1450 | 1458 | // 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). | |
| 1453 | 1461 | ...finishFields(finishing.moves, readConflictLane(app.db), finishing.open), |
| 1454 | 1462 | ...(requested.length === 0 |
| 1455 | 1463 | ? {} |
| @@ -2256,7 +2264,8 @@ async function admit( | ||
| 2256 | 2264 | if (!again) addComment(app, by, repo, getIssueById(app.db, pull.id) ?? pull, clashSaid(red.comment, together)); |
| 2257 | 2265 | // A red that reproduces on the re-gate is the code's: only then is it the doctor's to hold. |
| 2258 | 2266 | 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. | |
| 2260 | 2269 | else noteRed(app, repo, pull, red, baseOid, together); |
| 2261 | 2270 | }, |
| 2262 | 2271 | }); |
src/crew/held.ts +16 −4
| @@ -98,7 +98,10 @@ export interface Held { | ||
| 98 | 98 | readonly by: Readonly<Record<HoldName, readonly Issue[]>>; |
| 99 | 99 | /** Of the `hot_file` ones, those an admin's hold keeps: issue number to the hold that does. */ |
| 100 | 100 | 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 | */ | |
| 102 | 105 | readonly relieving: ReadonlyMap<number, { path: string; by: number }>; |
| 103 | 106 | /** Of the `twin` ones: issue number to the twin that holds the same work. */ |
| 104 | 107 | readonly twins: ReadonlyMap<number, Twin>; |
| @@ -110,7 +113,10 @@ export interface LastRun { | ||
| 110 | 113 | readonly created_at: string; |
| 111 | 114 | } |
| 112 | 115 | |
| 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 | */ | |
| 114 | 120 | export function lastAgentRuns(app: App, ids: readonly string[]): Map<string, LastRun> { |
| 115 | 121 | const out = new Map<string, LastRun>(); |
| 116 | 122 | const CHUNK = 400; |
| @@ -415,7 +421,10 @@ export function mapHolds( | ||
| 415 | 421 | return { holds, startable: held.startable.map((r) => r.issue.number) }; |
| 416 | 422 | } |
| 417 | 423 | |
| 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 | */ | |
| 419 | 428 | export function admits(app: App, repo: Repo, scope: { sealed?: true; sealedBy?: string }) { |
| 420 | 429 | if (scope.sealed === true) return () => true; |
| 421 | 430 | return (n: number): boolean => { |
| @@ -424,7 +433,10 @@ export function admits(app: App, repo: Repo, scope: { sealed?: true; sealedBy?: | ||
| 424 | 433 | }; |
| 425 | 434 | } |
| 426 | 435 | |
| 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 | */ | |
| 428 | 440 | export const mapHeldReuse = { ms: process.env["NODE_ENV"] === "test" ? 0 : 5_000 }; |
| 429 | 441 | const mapHeldKept = new WeakMap<App, Map<string, { at: number; holds: ReturnType<typeof mapHolds> }>>(); |
| 430 | 442 |
src/flow/alarms.ts +4 −1
| @@ -51,7 +51,10 @@ export const FORGE_BROKEN: ReadonlySet<FiredAlarm["key"]> = new Set(["red_main", | ||
| 51 | 51 | export function firedAlarms( |
| 52 | 52 | db: Database, |
| 53 | 53 | 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 | */ | |
| 55 | 58 | opts: { readonly dataDir: string | null; readonly publicOnly?: boolean; readonly ceilingUsd?: number | null }, |
| 56 | 59 | ): FiredAlarm[] { |
| 57 | 60 | const out: FiredAlarm[] = []; |
src/flow/lanes_read.ts +51 −16
| @@ -52,14 +52,19 @@ export const MOVED_MS = 30 * 60_000; | ||
| 52 | 52 | export const SLOW_MS = 30_000; |
| 53 | 53 | |
| 54 | 54 | 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 | */ | |
| 56 | 58 | readonly key: string; |
| 57 | 59 | readonly repoId: string; |
| 58 | 60 | readonly kind: "issue" | "pull" | "main" | "deploy"; |
| 59 | 61 | readonly number: number | null; |
| 60 | 62 | readonly title: string; |
| 61 | 63 | 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 | */ | |
| 63 | 68 | readonly who: string; |
| 64 | 69 | /** When it entered this lane. */ |
| 65 | 70 | readonly since: string; |
| @@ -71,7 +76,10 @@ export interface LaneItem { | ||
| 71 | 76 | readonly position: number | null; |
| 72 | 77 | /** When its worker last said it was alive; null when it does not say. */ |
| 73 | 78 | 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 | */ | |
| 75 | 83 | readonly issueId: string | null; |
| 76 | 84 | /** When the issue or pull was opened; null where there is none. */ |
| 77 | 85 | readonly born: string | null; |
| @@ -95,7 +103,10 @@ export interface StripPart { | ||
| 95 | 103 | readonly usedPct: number; |
| 96 | 104 | readonly mayUsePct: number; |
| 97 | 105 | } | 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 | */ | |
| 99 | 110 | readonly weekSpendUsd: number; |
| 100 | 111 | readonly ceilingUsd: number | null; |
| 101 | 112 | readonly needs: readonly { readonly says: string; readonly href: string }[]; |
| @@ -117,7 +128,10 @@ export interface LanePicture { | ||
| 117 | 128 | readonly asks: Readonly<Record<string, AsksWaiting>>; |
| 118 | 129 | /** The home's figures; null until the slow part has been read. */ |
| 119 | 130 | 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 | */ | |
| 121 | 135 | readonly idle: IdleReason | null; |
| 122 | 136 | } |
| 123 | 137 | |
| @@ -223,7 +237,10 @@ function item( | ||
| 223 | 237 | }; |
| 224 | 238 | } |
| 225 | 239 | |
| 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 | */ | |
| 227 | 244 | function runRows( |
| 228 | 245 | db: Database, |
| 229 | 246 | kind: "agent" | "check", |
| @@ -342,9 +359,10 @@ interface Deploy { | ||
| 342 | 359 | /** |
| 343 | 360 | * Production deploys going live now and those that went live in the last 24 |
| 344 | 361 | * 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. | |
| 348 | 366 | */ |
| 349 | 367 | function deploys( |
| 350 | 368 | db: Database, |
| @@ -473,12 +491,14 @@ function live(db: Database, dayAgo: string): LaneRead { | ||
| 473 | 491 | const { rows, total } = deploys(db, dayAgo); |
| 474 | 492 | const seen = new Set<string>(); |
| 475 | 493 | 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. | |
| 477 | 496 | for (const d of rows) { |
| 478 | 497 | if (items.length >= LANE_ITEMS + 3) break; |
| 479 | 498 | const going = d.state === "queued" || d.state === "running"; |
| 480 | 499 | 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. | |
| 482 | 502 | const key = `i-${change?.id ?? d.id}`; |
| 483 | 503 | if (seen.has(key)) continue; |
| 484 | 504 | seen.add(key); |
| @@ -515,7 +535,10 @@ export interface Fast { | ||
| 515 | 535 | readonly working: ReadonlySet<string>; |
| 516 | 536 | } |
| 517 | 537 | |
| 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 | */ | |
| 519 | 542 | export function readFast(db: Database, now: Date): Fast { |
| 520 | 543 | const iso = now.toISOString(); |
| 521 | 544 | const week = new Date(now.getTime() - 7 * 86_400_000).toISOString(); |
| @@ -596,7 +619,10 @@ export function withWaits( | ||
| 596 | 619 | } |
| 597 | 620 | |
| 598 | 621 | 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 | */ | |
| 600 | 626 | readonly asked: readonly LaneItem[]; |
| 601 | 627 | readonly askedTotal: number; |
| 602 | 628 | readonly strip: StripPart; |
| @@ -706,7 +732,10 @@ export function readSlow( | ||
| 706 | 732 | }; |
| 707 | 733 | } |
| 708 | 734 | |
| 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 | */ | |
| 710 | 739 | function idleOf(db: Database, dataDir: string, now: Date): IdleReason | null { |
| 711 | 740 | try { |
| 712 | 741 | return idleReason({ db, config: { dataDir } } as unknown as App, now); |
| @@ -715,7 +744,10 @@ function idleOf(db: Database, dataDir: string, now: Date): IdleReason | null { | ||
| 715 | 744 | } |
| 716 | 745 | } |
| 717 | 746 | |
| 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 | */ | |
| 719 | 751 | function asksOf(db: Database, viewers: readonly string[], now: Date): Record<string, AsksWaiting> { |
| 720 | 752 | const out: Record<string, AsksWaiting> = {}; |
| 721 | 753 | for (const id of viewers) { |
| @@ -730,7 +762,10 @@ function asksOf(db: Database, viewers: readonly string[], now: Date): Record<str | ||
| 730 | 762 | return out; |
| 731 | 763 | } |
| 732 | 764 | |
| 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 | */ | |
| 734 | 769 | function versionOf(read: LaneRead): string { |
| 735 | 770 | return Bun.hash( |
| 736 | 771 | JSON.stringify([ |
src/http/mcp/tools/forges.ts +12 −5
| @@ -9,19 +9,20 @@ import { archiveForge, archivedForges, restoreForge } from "../../../spawn/archi | ||
| 9 | 9 | import { CHILD_NAME } from "../../../spawn/placement.ts"; |
| 10 | 10 | import { checkMove } from "../../../spawn/move_check.ts"; |
| 11 | 11 | import { moveToCell } from "../../../spawn/move_cell.ts"; |
| 12 | import { resizeForge } from "../../../spawn/manage.ts"; | |
| 12 | 13 | import { good, bad, type Tool } from "../shared.ts"; |
| 13 | 14 | |
| 14 | 15 | const sentSays = (n: number) => (n === 0 ? "This forge has sent no forges yet." : `${n} forge${n === 1 ? "" : "s"} sent from here.`); |
| 15 | 16 | |
| 16 | 17 | export const tool: Tool = { |
| 17 | 18 | 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", | |
| 19 | 20 | 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" } } }, | |
| 22 | 23 | writes: true, |
| 23 | 24 | dryByDefault: true, |
| 24 | readsWithout: ["forge", "plan", "code", "revoke", "archive", "restore"], | |
| 25 | readsWithout: ["forge", "plan", "size", "code", "revoke", "archive", "restore"], | |
| 25 | 26 | async run(ctx, user, args) { |
| 26 | 27 | if (!user.isAdmin) |
| 27 | 28 | return bad("forbidden", "only an admin of this forge sees the forges it sent"); |
| @@ -64,7 +65,7 @@ export const tool: Tool = { | ||
| 64 | 65 | if (!CHILD_NAME.test(name)) return bad("invalid", "restore names an archived forge"); |
| 65 | 66 | 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) }); |
| 66 | 67 | 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); | |
| 68 | 69 | } |
| 69 | 70 | const names = (Array.isArray(args["archive"]) ? args["archive"] : [args["archive"]]).map(String); |
| 70 | 71 | 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 = { | ||
| 85 | 86 | const done = await moveToCell(ctx.app, forge, { by: "admin", acknowledge: args["acknowledge"] === true, actorId: user.id }); |
| 86 | 87 | return done.ok ? good(done) : bad(done.kind, done.says); |
| 87 | 88 | } |
| 89 | if (args["forge"] !== undefined && args["size"] !== undefined) { | |
| 90 | const live = args["dryRun"] === false; | |
| 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 | } | |
| 88 | 95 | if (args["forge"] !== undefined || args["plan"] !== undefined) { |
| 89 | 96 | const refuse = (e: string) => (e === "not_found" ? bad("not_found", "Not found.") : bad("invalid", BILLING_WORDS[e as keyof typeof BILLING_WORDS] ?? e)); |
| 90 | 97 | if (args["plan"] === undefined) { |
src/http/mcp/tools/sizes.ts +2 −2
| @@ -3,9 +3,9 @@ import { good, type Tool } from "../shared.ts"; | ||
| 3 | 3 | |
| 4 | 4 | export const tool: Tool = { |
| 5 | 5 | 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", | |
| 7 | 7 | 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.", | |
| 9 | 9 | inputSchema: { type: "object", properties: {} }, |
| 10 | 10 | writes: false, |
| 11 | 11 | run: () => good(sizesView()), |
src/http/mcp/tools/spawn.ts +1 −1
| @@ -36,7 +36,7 @@ export const tool: Tool = { | ||
| 36 | 36 | }, |
| 37 | 37 | size: { |
| 38 | 38 | type: "string", |
| 39 | enum: ["small", "medium", "large"], | |
| 39 | enum: ["small", "medium", "large", "xlarge"], | |
| 40 | 40 | 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 |
||
| 41 | 41 | }, |
| 42 | 42 | plan: { |
src/http/route_marks.ts +1
| @@ -228,6 +228,7 @@ export const ROUTES: Readonly<Record<string, Mark>> = { | ||
| 228 | 228 | "/forges/:name/undo-link": "admin", |
| 229 | 229 | "/forges/:name/stop": "admin", |
| 230 | 230 | "/forges/:name/sandbox": "admin", |
| 231 | "/forges/:name/size": "admin", | |
| 231 | 232 | "/forges/:name/reach/allow": "admin", |
| 232 | 233 | "/forges/:name/reach/later": "admin", |
| 233 | 234 | "/forges/:name/reach/revoke": "admin", |
src/http/server.ts +2 −1
| @@ -320,7 +320,7 @@ import { claimFragmentPage, claimOptions, claimRenew, claimSubmit, welcomePage, | ||
| 320 | 320 | import { firstAdminOptions, firstAdminPage, firstAdminSubmit } from "../web/pages/first-admin.ts"; |
| 321 | 321 | import { familyPage } from "../web/pages/family.ts"; |
| 322 | 322 | 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"; | |
| 324 | 324 | import { billDownload } from "./api/forge_bill.ts"; |
| 325 | 325 | import { forgesRefusedPage } from "../web/pages/forges-refused.ts"; |
| 326 | 326 | import { forgeReachAllow, forgeReachLater, forgeReachRevoke } from "../web/pages/hosted-forges.ts"; |
| @@ -967,6 +967,7 @@ export function buildRouter(): Router<Handler> { | ||
| 967 | 967 | router.add("POST", "/forges/:name/reach/later", forgeReachLater); |
| 968 | 968 | router.add("POST", "/forges/:name/reach/revoke", forgeReachRevoke); |
| 969 | 969 | router.add("POST", "/forges/:name/own-code", forgeOwnCodeSubmit); |
| 970 | router.add("POST", "/forges/:name/size", forgeSizeSubmit); | |
| 970 | 971 | router.add("GET", "/forges/:name/remove", forgeRemoveConfirm); |
| 971 | 972 | router.add("POST", "/forges/:name/remove", forgeRemoveSubmit); |
| 972 | 973 | router.add("GET", "/forges/:name/ready", forgeReady); |
src/snapshot/sealed_store.ts +30 −8
| @@ -34,7 +34,10 @@ export const SEALED_PREFIX = "sealed/"; | ||
| 34 | 34 | const MAGIC = Buffer.from("FSO1"); |
| 35 | 35 | const IV_BYTES = 12; |
| 36 | 36 | 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 | */ | |
| 38 | 41 | export const LANE_HEADER = `${SEALED_PREFIX}lane.json`; |
| 39 | 42 | const SALT_BYTES = 16; |
| 40 | 43 | const SALT_HEX = /^[0-9a-f]{32}$/; |
| @@ -49,7 +52,10 @@ export interface SealKeys { | ||
| 49 | 52 | readonly mac: Buffer; |
| 50 | 53 | } |
| 51 | 54 | |
| 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 | */ | |
| 53 | 59 | export function sealKeys(passphrase: string, salt: Uint8Array): Promise<SealKeys> { |
| 54 | 60 | return new Promise((resolve, reject) => { |
| 55 | 61 | scrypt(passphrase, salt, 64, SCRYPT, (error, k) => { |
| @@ -59,7 +65,10 @@ export function sealKeys(passphrase: string, salt: Uint8Array): Promise<SealKeys | ||
| 59 | 65 | }); |
| 60 | 66 | } |
| 61 | 67 | |
| 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 | */ | |
| 63 | 72 | const checkOf = (keys: SealKeys): string => createHmac("sha256", keys.mac).update("forge off-site lane header").digest("hex"); |
| 64 | 73 | |
| 65 | 74 | /** 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 | ||
| 103 | 112 | return Buffer.concat([MAGIC, iv, cipher.update(plain), cipher.final(), cipher.getAuthTag()]); |
| 104 | 113 | } |
| 105 | 114 | |
| 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 | */ | |
| 107 | 119 | export function openBody(keys: SealKeys, sealed: Uint8Array, key: string): Uint8Array { |
| 108 | 120 | const b = Buffer.from(sealed.buffer, sealed.byteOffset, sealed.byteLength); |
| 109 | 121 | 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 { | ||
| 130 | 142 | } |
| 131 | 143 | |
| 132 | 144 | 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 | */ | |
| 134 | 149 | readonly create?: boolean; |
| 135 | 150 | } |
| 136 | 151 | |
| 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 | */ | |
| 138 | 156 | export function sealedStore(inner: Store, passphrase: string, options: SealedOptions = {}): Store { |
| 139 | 157 | 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. | |
| 141 | 160 | const keys = (): Promise<SealKeys> => |
| 142 | 161 | (pending ??= laneKeys(inner, passphrase, options.create ?? true).catch((error: unknown) => { |
| 143 | 162 | pending = undefined; |
| @@ -183,7 +202,10 @@ function over(inner: Store, keys: () => Promise<SealKeys>): Store { | ||
| 183 | 202 | return bounded === undefined ? store : { ...store, bounded: (leftMs) => over(bounded.call(inner, leftMs), keys) }; |
| 184 | 203 | } |
| 185 | 204 | |
| 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 | */ | |
| 187 | 209 | export function refusingStore(where: string, reason: string): Store { |
| 188 | 210 | const no = async (): Promise<never> => { |
| 189 | 211 | throw new Error(reason); |
src/snapshot/snapshot.ts +7 −2
| @@ -184,7 +184,10 @@ export interface Progress { | ||
| 184 | 184 | readonly etaMs?: number; |
| 185 | 185 | } |
| 186 | 186 | |
| 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 | */ | |
| 188 | 191 | export function progressFacts(p: Progress): { label: string; value: string }[] { |
| 189 | 192 | const rows: { label: string; value: string }[] = []; |
| 190 | 193 | 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 }[] { | ||
| 194 | 197 | return rows; |
| 195 | 198 | } |
| 196 | 199 | |
| 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 | */ | |
| 198 | 203 | export function progressWords(p: Progress): string { |
| 199 | 204 | const parts = [`${fmtBytes(p.bytes)} sent`]; |
| 200 | 205 | 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"; | ||
| 13 | 13 | import { restoreClaim, revokeClaim, spawnedOrg } from "./claim.ts"; |
| 14 | 14 | import { forgetHeard } from "./clients.ts"; |
| 15 | 15 | 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"; | |
| 16 | 19 | import { retireBody } from "./door.ts"; |
| 17 | import { sleepChild } from "./host.ts"; | |
| 18 | 20 | import { CHILD_NAME } from "./placement.ts"; |
| 19 | 21 | import { switchOwnCode } from "./own_code.ts"; |
| 20 | 22 | |
| @@ -96,3 +98,25 @@ export async function ownCode(app: App, name: string, on: boolean): Promise<Mana | ||
| 96 | 98 | if (switched.ok) await sleepChild(app, name); |
| 97 | 99 | return switched; |
| 98 | 100 | } |
| 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
|
||
| 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 | ||
| 184 | 184 | } |
| 185 | 185 | } |
| 186 | 186 | 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. | |
| 188 | 189 | const tell = repo !== undefined && link.mode === "tell-me" && state.error === "" && state.parentTip !== "" && |
| 189 | 190 | (state.behind ?? 0) > 0 && state.parentTip !== state.toldTip; |
| 190 | 191 | if (tell) state = { ...state, toldTip: state.parentTip }; |
src/tui/screens/forges.ts +34 −2
| @@ -16,7 +16,7 @@ import { clientRows } from "../../spawn/clients.ts"; | ||
| 16 | 16 | import { diskWords } from "../../spawn/disk_mount.ts"; |
| 17 | 17 | import { archiveForge, archivedForges, destinationWords, restoreForge } from "../../spawn/archive.ts"; |
| 18 | 18 | 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"; | |
| 20 | 20 | import { moveToCell } from "../../spawn/move_cell.ts"; |
| 21 | 21 | import { readOwnCode } from "../../spawn/own_code.ts"; |
| 22 | 22 | import type { App } from "../../app.ts"; |
| @@ -165,6 +165,37 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses | ||
| 165 | 165 | }), |
| 166 | 166 | ); |
| 167 | 167 | }; |
| 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 | }; | |
| 168 | 199 | // "Send a new link" on a row not yet claimed: the page's preview and confirm (`offerNewLink`). |
| 169 | 200 | const newLink = (): void => { |
| 170 | 201 | if (session === undefined || session.user?.isAdmin !== true) return; |
| @@ -174,7 +205,7 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses | ||
| 174 | 205 | }; |
| 175 | 206 | const screen: Screen = { |
| 176 | 207 | 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")], | |
| 178 | 209 | render(area, s) { |
| 179 | 210 | const c = ctx.theme.c; |
| 180 | 211 | 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 | ||
| 219 | 250 | }), |
| 220 | 251 | ); |
| 221 | 252 | } else if (e.key === "m") sandboxOne(); |
| 253 | else if (e.key === "w") raiseOne(); | |
| 222 | 254 | else if (e.key === "x" && session !== undefined) |
| 223 | 255 | choose("Remove which forge?", (name) => |
| 224 | 256 | ctx.push( |
src/tui/screens/resilience.ts +17 −5
| @@ -66,7 +66,10 @@ export function resilienceLines(dataDir: string): string[] { | ||
| 66 | 66 | /** How many of a nightly job's last lines the output dialog shows. */ |
| 67 | 67 | export const OUTPUT_TAIL = 12; |
| 68 | 68 | |
| 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 | */ | |
| 70 | 73 | export function nightlyOutputLines(dataDir: string): string[] { |
| 71 | 74 | const said = nightlyLines(dataDir); |
| 72 | 75 | return JOBS.flatMap((job, i) => { |
| @@ -103,7 +106,10 @@ export function mirrorLine(f: Session): string { | ||
| 103 | 106 | return where === undefined ? "Mirror: none." : `Mirror: ${where}`; |
| 104 | 107 | } |
| 105 | 108 | |
| 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 | */ | |
| 107 | 113 | export function verdictLines(f: Session): string[] { |
| 108 | 114 | const v = backupVerdict(f.app.config.dataDir, lastDrill(f.app.db)); |
| 109 | 115 | const mark = v.state === "red" ? "RED" : v.state === "unknown" ? "unknown" : "ok"; |
| @@ -157,7 +163,9 @@ export function resilienceScreen(f: Session, ctx: Ctx): Screen { | ||
| 157 | 163 | const refusedAll = "Where snapshots go is a forge admin's."; |
| 158 | 164 | // The actions refuse anyone else too; the keys are not offered to them. |
| 159 | 165 | 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 | */ | |
| 161 | 169 | let snapshots: string[] | "unreadable" | undefined; |
| 162 | 170 | let asking: Asking | undefined; |
| 163 | 171 | // 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 { | ||
| 291 | 299 | const out: string[] = []; |
| 292 | 300 | if (asking !== undefined) out.push(QUESTION[asking], ""); |
| 293 | 301 | 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. | |
| 295 | 304 | if (note !== "") out.push(...wrap(note, INNER), ""); |
| 296 | 305 | out.push(...wrap(backupsLine(f.app).says, INNER), ...verdictLines(f), ""); |
| 297 | 306 | 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 { | ||
| 380 | 389 | return screen; |
| 381 | 390 | } |
| 382 | 391 | |
| 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 | */ | |
| 384 | 396 | export const entry: PaletteEntry = { |
| 385 | 397 | id: "resilience", |
| 386 | 398 | title: "Resilience", |
src/web/pages/billing.ts +1 −2
| @@ -16,7 +16,6 @@ import { CODE_ERRORS, makeCode, readCodes, revoke, type CodeError } from "../../ | ||
| 16 | 16 | import { publicOrigin } from "../../core/public_origin.ts"; |
| 17 | 17 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| 18 | 18 | import type { Ctx } from "../../http/context.ts"; |
| 19 | import { SIZES } from "../../spawn/sizes.ts"; | |
| 20 | 19 | import { BILLING_SIZES, getPortalUrl, PORTAL_WORDS, parseBillingLinks } from "../../settings/billing.ts"; |
| 21 | 20 | import { getPlans } from "../../settings/plans.ts"; |
| 22 | 21 | import { changeBillingLinks, changePortalUrl, readBillingLinks } from "../../actions/signup.ts"; |
| @@ -196,7 +195,7 @@ function billingView(ctx: Ctx, shown?: Shown, values: Record<string, string> = { | ||
| 196 | 195 | <span class="mono">${f.forge}</span> |
| 197 | 196 | <span class="muted small">${f.status} · ${f.source}${lapseWords(lapseFor(ctx.app.db, f.forge))}</span> |
| 198 | 197 | <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>`)} | |
| 200 | 199 | </select> |
| 201 | 200 | ${btn("Review change")} |
| 202 | 201 | </form> |
src/web/pages/forges.ts +27 −2
| @@ -22,7 +22,8 @@ import { noRoom } from "../../spawn/door.ts"; | ||
| 22 | 22 | import { sizeWords, useWords } from "../../spawn/usage.ts"; |
| 23 | 23 | import { diskWords } from "../../spawn/disk_mount.ts"; |
| 24 | 24 | 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"; | |
| 26 | 27 | import { readOwnCode } from "../../spawn/own_code.ts"; |
| 27 | 28 | import { moveToCell } from "../../spawn/move_cell.ts"; |
| 28 | 29 | import { sealedAt } from "../../spawn/sealed.ts"; |
| @@ -72,6 +73,8 @@ function seenWords(seen: Seen): Html { | ||
| 72 | 73 | return html`<span data-seen data-opened="${seen.opened ? "yes" : "no"}">${parts.map((p, i) => (i === 0 ? p : html` · ${p}`))}</span>`; |
| 73 | 74 | } |
| 74 | 75 | |
| 76 | const XLARGE_SAYS = `${sizeWords("xlarge")}. ${sizesView().sizes.find((x) => x.size === "xlarge")?.says ?? ""}`; | |
| 77 | ||
| 75 | 78 | export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = false): Html { |
| 76 | 79 | const state = claimState(r); |
| 77 | 80 | const seen = seenOf(r); |
| @@ -155,6 +158,11 @@ export function forgeRow(r: ClientRow, now: number, reach?: ForgeReach, bill = f | ||
| 155 | 158 | : "Closes it here, starts it in a sandbox of its own, proves its data is intact; puts it back if anything fails", |
| 156 | 159 | })} |
| 157 | 160 | </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>` | |
| 158 | 166 | : null}${r.made |
| 159 | 167 | ? 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> |
| 160 | 168 | ${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 { | ||
| 436 | 444 | restored: html`The link for <strong>${name}</strong> is open again.`, |
| 437 | 445 | refused: html`The link for <strong>${name}</strong> did not change: it was not open, or the minute is over.`, |
| 438 | 446 | }[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>`; | |
| 440 | 453 | } |
| 441 | 454 | |
| 442 | 455 | // 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> { | ||
| 602 | 615 | dropServed(ctx.app); |
| 603 | 616 | return redirect(`/forges?code=${done.ok ? want : "refused"}&forge=${encodeURIComponent(name)}#forge-code`); |
| 604 | 617 | } |
| 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", () => { | ||
| 97 | 97 | const landingBefore = await (await get("/live/lane?s=landing", owner)).text(); |
| 98 | 98 | expect(titles(before, "checks")).not.toContain("Pasted links keep their address"); |
| 99 | 99 | 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 | |
| 101 | 102 | const pull = seed.pulls["a2"]!; |
| 102 | 103 | app.db.run("UPDATE review SET state = 'commented' WHERE issue_id = ?1", [pull]); |
| 103 | 104 | startCheck(app, pull, seed.repos.glue.id); |
| @@ -258,7 +259,8 @@ describe("nothing on the new home polls", () => { | ||
| 258 | 259 | const text = readFileSync(join(import.meta.dir, "..", file), "utf8"); |
| 259 | 260 | expect(text).not.toMatch(/setInterval\s*\(/); |
| 260 | 261 | 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 | |
| 262 | 264 | expect((text.match(/setTimeout\s*\(/g) ?? []).length).toBe(file === "src/flow/lanes.ts" ? 2 : 0); |
| 263 | 265 | } |
| 264 | 266 | }); |
| @@ -289,7 +291,8 @@ describe("before the first reading, a page never reads on the thread", () => { | ||
| 289 | 291 | expect(html).toContain("Reading the hosted forges"); |
| 290 | 292 | for (const lane of LANES) expect(html).toContain(`id="lane-${lane}"`); |
| 291 | 293 | 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 | |
| 293 | 296 | const lane = await (await fetch(`${srv.url}/live/lane?s=building`, { headers: { cookie } })).text(); |
| 294 | 297 | expect(lane).toContain("A cost ledger per delivery"); |
| 295 | 298 | 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 | */ | |
| 2 | 5 | import { Database } from "bun:sqlite"; |
| 3 | 6 | import { bugTables, reachTables } from "./helpers/reach-tables.ts"; |
| 4 | 7 | import { NO_REACH, readReach } from "../src/flow/reach.ts"; |
test/no-alarm-banner.test.ts +7 −3
| @@ -71,7 +71,9 @@ interface World { | ||
| 71 | 71 | readonly cookie: string; |
| 72 | 72 | } |
| 73 | 73 | |
| 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 | */ | |
| 75 | 77 | async function world(spent: number): Promise<World> { |
| 76 | 78 | const root = mkdtempSync(join(tmpdir(), "forge-no-alarm-banner-")); |
| 77 | 79 | const app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge", crewCeilingUsd: 1 }); |
| @@ -89,7 +91,8 @@ async function world(spent: number): Promise<World> { | ||
| 89 | 91 | mkdirSync(join(root, "snapshot"), { recursive: true }); |
| 90 | 92 | const long = new Date(Date.now() - 72 * 3_600_000).toISOString(); |
| 91 | 93 | 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. | |
| 93 | 96 | const bug = openIssue(app, made.value, repo.value, { title: "The page is blank" }); |
| 94 | 97 | if (!bug.ok) throw new Error(String(bug.error)); |
| 95 | 98 | 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", | ||
| 209 | 212 | expect(offenders("/", `<main id="main">${banner}<h1>Home</h1></main>`)).toHaveLength(1); |
| 210 | 213 | expect(offenders("/", '<p role="alert">Disk is low</p>')).toHaveLength(1); |
| 211 | 214 | 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. | |
| 213 | 217 | expect(offenders("/", '<p class="small"><a href="/flow">No off-box backup has landed. The snapshot failed: the bucket refused</a></p>')).toEqual([]); |
| 214 | 218 | 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([]); |
| 215 | 219 | expect(offenders("/", '<span class="menu-item" aria-disabled="true" title="this host'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", () => { | ||
| 213 | 213 | expect(cut).toHaveLength(4); |
| 214 | 214 | expect(cut[3]![1]).toBe("+7 more (see /forges)"); |
| 215 | 215 | }); |
| 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 | }); |
new above
offline
Dead check:
user.isAdminis already enforced at the top ofrun. Remove it. Also a missing forge returnsinvalidhere, notnot_found; keep it consistent with the other branches.