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

One rule says what looks like a secret, and the config form never holds one #17739

opened this

Merged 10h 7m ago, live in production

sold/leaf-editor-2 → main 0 commits

  • Merged. sold/leaf-editor-2 was merged into main as 7b1aa0a.

Review

Sign in to review this change.
219 files changed +4566 −474
AGENTS.md +1
@@ -109,3 +109,4 @@ A pull that adds a page (`src/web/pages/*.ts`), an MCP tool (`src/http/mcp/tools
109109 `src/spawn/routes.ts`: `tables`, per data directory, the router's table of forges moved to another machine (#16859), read once from `routes.json` and kept by `setRoute`, the only writer (a rename of the whole file); at most one entry per moved forge, gone on restart (the file is the state). `src/spawn/machines.ts`: `registered`, the machines declared by `FORGE_MACHINES` (or put by a test), made on first read, and each process machine's `running` process groups by forge name; at most one per forge, gone on restart. `src/spawn/move_machine.ts`: `busy`, the forges being moved now, so a second ask is refused; gone when the move ends. The terminal door is `g` on the Forges screen (`src/tui/screens/forges.ts`; `planMove`/`moveToMachine` give the page, the MCP `forges` tool and the terminal the same words).
110110
111111 A new route of the studio's own router (`buildRouter`, `src/http/server.ts`) is added in the module of its concept under `src/http/routes/`, named for that one concept (`talk`, `accounts`, `repo_issues`, `git_http`…), never in `server.ts`, which only mounts them; `buildRouter` is the one list, so a new module is mounted there and `bun scripts/lazy-lists.ts` writes its route list (a test fails for a route module nothing mounts, #17036). The router matches in insertion order, so a literal route goes above the `/:owner…` ones: literal-path modules are called first, `repo_*` the `/:owner/:name` ones, and the few modules whose place is not obvious say why in their header (`repo_display`, `repo_api`, `migrate`). Smart-HTTP access (`withGitAccess`, `asStranger`) is `src/http/git_access.ts`.
112 `src/games/store.ts`: `players`, per database, the ids of everyone with a grant on a game box, read once per 30 s (`PLAYERS_MS`) so the top bar's Games costs no query a page; `grant`, the one writer, drops it; at most one id per person granted, gone on restart (the rows are `game_grant`).
docs/CONTRACT.md +2 −2
@@ -249,8 +249,8 @@ Two more places the table reaches, so it is never only a page:
249249 ## Agent doors beside the table
250250
251251 - `GET /<owner>/<repo>/pulls/<n>/check.txt` is a pull's latest check as plain
252 text (line 1 `pending`, `green` or `red`; line 2 `head: <oid>`; on red the
253 log tail where the log door allows it). It is in the OpenAPI description and
252 text (line 1 `pending`, `green` or `red`; line 2 `head: <oid>`; on red what
253 failed, then the log tail, where the log door allows it). It is in the OpenAPI description and
254254 in `/llms.txt`; `test/openapi-check-txt.test.ts` keeps the three in step.
255255
256256 ## What is not here yet
docs/SNAPSHOT.md +7 −2
@@ -91,6 +91,10 @@ and `sentMb` put, `heldBefore` already there.
9191 A restore returns each file byte for byte (`test/drop-backup.test.ts`). A
9292 large Drop makes the night longer by the time it takes to read and hash it;
9393 only chunks the store lacks are sent.
94 - The plugin jars people uploaded for their game servers (`games/jars/<id>.jar`),
95 kept nowhere else. A restore names each jar the database lists whose file did
96 not come back, or is of another size (`test/jar-backup.test.ts`). A snapshot
97 from before 2026-12-02 holds none of them.
9498 - The crew's run logs, a day's worth to a few bundles
9599 (`runs/<day>[-n].ndjson`, cut at 4 MB of logs), in the order the logs were
96100 last written: a bundle once full is the same bytes in every later
@@ -99,8 +103,9 @@ and `sentMb` put, `heldBefore` already there.
99103 with its size, hash and chunks, `sent` (what this snapshot itself put),
100104 and `key`: `wrapped` or `none` (older snapshots: `raw`).
101105
102 What stays out is what a boot or a deploy rebuilds: clones, checks,
103 pictures, previews.
106 Everything else under the data directory stays out. Most of it is what a boot
107 or a deploy rebuilds: clones, checks, pictures of pages, previews. Some is not:
108 [backup-left-out.md](features/backup-left-out.md) lists it.
104109
105110 ## Is a snapshot encrypted before it leaves?
106111
docs/design/areas/shell.md +2 −1
@@ -3,8 +3,9 @@
33 The chrome every page sits in: a skip link, the sticky top bar with the wordmark, the main column and the footer, drawn by `page()` in `src/web/layout.ts` (the top bar by `topbar()`, its search by `searchBar()`, the footer by `footer()`); a page hands over its body and never draws the frame itself. Rules live in `src/web/style/base.ts`, the search field's and the crumbs' narrow-screen rule in `src/web/style/components.ts`.
44
55 - `.skip` — the "Skip to content" link, first in the document and hidden above the top until it has keyboard focus.
6 - `.topbar` — the `<header role="banner">` across the top of every page: wordmark, crumbs, then the tools.
6 - `.topbar` — the `<header role="banner">` across the top of every page: wordmark, areas, crumbs, then the tools.
77 - `.wordmark` — the forge's name and mark, linking home (`g h`); the mark turns on hover. Also written by the board's own header in `src/web/pages/board.ts`.
8 - `.areas` — the top bar's `<nav aria-label="Areas">`, after the wordmark: Apps, Games, Infrastructure and Explore, the `GO_PAGES` rows marked `area` (`src/web/go_pages.ts`), each viewer only those they may use, Games first for a person with a game grant and no repository of their own (`playsOnly`), the current one by weight (`aria-current`). Games needs a grant on a box (`seesAnyBox`, one read per 30 s a process). From 720px the links are in the bar, and up to 1199px the search field gives way to its icon. Under 720px they are the bar's first line, 44px and pinned with it, on every page with a bar: a repository's, a visitor's and one that passes `tools` too. `--areas-h` adds those 44px to `--topbar-h`, so what sticks or scrolls under the bar follows. A page with tabs of its own shows them under the bar as before.
89 - `.topbar-tools` — the top bar's right-hand group (search, Asks, the new and user menus): one row that may shrink but never wraps, its bare `a.small` links 44px tall.
910 - `.topbar-search` — the top bar's search form: an icon, a borderless input and its `/` key hint in one bordered pill, the border taking the accent on focus. Shown from 720px; below that the icon button carries search.
1011 - `.hide-lg` — shown under 720px, hidden from 720px: the narrow-screen stand-in for something `.hide-sm` shows on wide screens (the search icon button beside `.topbar-search`).
docs/design/attention-budget.json +3 −3
@@ -115,16 +115,16 @@
115115 },
116116 "settings": {
117117 "390": {
118 "words": 148,
118 "words": 149,
119119 "blocks": 32,
120120 "colours": 1
121121 },
122122 "1280": {
123 "words": 148,
123 "words": 149,
124124 "blocks": 32,
125125 "colours": 1
126126 },
127 "note": "146 words since #13308 (2026-11-15, Settings \u203a Connected agents): its side-nav entry added two words to the 144 main had; 147 since the forge dataset (Settings \u203a Dataset), one word; 148 since the Tables page (#6002), one word."
127 "note": "146 words since #13308 (2026-11-15, Settings \u203a Connected agents): its side-nav entry added two words to the 144 main had; 147 since the forge dataset (Settings \u203a Dataset), one word; 148 since the Tables page (#6002), one word; 149 since Settings \u203a Infrastructure, one word: an admin looked for the cloud bill here and found no way to it."
128128 },
129129 "search": {
130130 "390": {
docs/design/plan.md +1 −1
@@ -23,5 +23,5 @@ Each item is one filed issue, small enough for one run; items 4–9 wait for the
2323 `chain`): one line each on why it is a page; retire or turn into board panels.
2424 10. **#2697 Tokenise `style/content.ts`** — 23 colours, 31 sizes; the largest debt.
2525 11. **#2698 Tokenise `style/components.ts`, `studio/home.ts`, `pages/looks.ts`, `pages/site.ts`.**
26 12. **#2699 Top bar diet** — at most search, New, and the user menu on the left of the fold.
26 12. **#2699 Top bar diet** — replaced: the top bar names the areas (docs/design/areas/shell.md).
2727 13. **#2700 Class rule against DESIGN.md §5** — done: 13 classes no page drew are gone, the other 505 page-local ones are registered in DESIGN.md §5d, and the check reads §5 rather than the baseline. Items 4–12 retire §5d entries as they redo each page.
docs/design/size-budget/board.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/board",
3 "js": 30208,
3 "js": 30464,
44 "css": 52992
55 }
docs/design/size-budget/changelog.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/changelog",
3 "js": 30720,
3 "js": 30976,
44 "css": 52992
55 }
docs/design/size-budget/claim.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/claim",
3 "js": 28160,
3 "js": 28416,
44 "css": 52992
55 }
docs/design/size-budget/explore.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/explore",
3 "js": 25344,
3 "js": 25600,
44 "css": 52992
55 }
docs/design/size-budget/fleet.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/fleet",
3 "js": 25344,
3 "js": 25600,
44 "css": 52992
55 }
docs/design/size-budget/forges-new.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/forges/new",
3 "js": 25344,
3 "js": 25600,
44 "css": 52992
55 }
docs/design/size-budget/home.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/",
3 "js": 25600,
3 "js": 25856,
44 "css": 52992
55 }
docs/design/size-budget/maintenance.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/maintenance",
3 "js": 25344,
3 "js": 25600,
44 "css": 52992
55 }
docs/design/size-budget/map.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/map",
3 "js": 32768,
3 "js": 33024,
44 "css": 54784
55 }
docs/design/size-budget/owner-name-next.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/:owner/:name/next",
3 "js": 27392,
3 "js": 27648,
44 "css": 53504
55 }
docs/design/size-budget/owner-name-space.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/:owner/:name/space",
3 "js": 34304,
3 "js": 34560,
44 "css": 54272
55 }
docs/design/size-budget/pricing.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/pricing",
3 "js": 25344,
3 "js": 25600,
44 "css": 52992
55 }
docs/design/size-budget/system.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/system",
3 "js": 27392,
3 "js": 27648,
44 "css": 52992
55 }
docs/design/size-budget/templates.json +1 −1
@@ -1,5 +1,5 @@
11 {
22 "page": "/templates",
3 "js": 25344,
3 "js": 25600,
44 "css": 52992
55 }
docs/features/backup-left-out.md added +52
@@ -0,0 +1,52 @@
1 ---
2 topic: Backups and moving
3 row: What is in no backup
4 ---
5 # What is in no backup
6
7 The nightly snapshot takes a fixed list from the data directory (`src/snapshot/snapshot.ts`,
8 [SNAPSHOT.md](../SNAPSHOT.md), "What a snapshot holds"). A folder that is not on the list is in no
9 snapshot. This page lists those that hold something a boot or a deploy does not make again, as the
10 code writes them.
11
12 ## Kept nowhere else
13
14 | Under the data directory | What it is | Written by |
15 | --- | --- | --- |
16 | `conversation-files/` | Files and images people attached to a Talk message | `src/core/conversation_files.ts` |
17 | `note-pictures/` | The picture sent with a note from the forge button | `src/core/note_pictures.ts` |
18 | `changes/` | Each app's ordered change stream, one SQLite file an app | `src/apps/changes.ts` |
19 | `machines/` | Each person's own directory on a repository's machines | `src/machines/shell.ts` |
20 | `recipes/` | Forge configurations a person saved by name | `src/spawn/recipes.ts` |
21 | `claude-config/` | The agent's own session files for conversations, unless the operator named another directory | `src/crew/conversation.ts` |
22 | `secret.key.old` | The key before the last change of key, while there is one | `src/kernel/secret.ts` |
23 | `edge/signing.pem` | The key that signs the files the edge serves. A boot without it makes a new one, with a new public key | `src/cloud/edge.ts` |
24 | `dataset/salt` | The secret that names people in the dataset. An export without it makes a new one, so the names change | `src/actions/dataset.ts` |
25 | `archive/` | The record of each archived hosted forge: which store holds its copy, and the copy's hash | `src/spawn/archive.ts` |
26 | `routes.json` | Which machine holds a hosted forge that is not on this one | `src/spawn/routes.ts` |
27 | `access/`, `perf/`, `nightly/` | The access log (14 days), the performance log, each nightly job's last output | `src/http/access_log.ts`, `src/perf/kept_log.ts`, `src/nightly/output.ts` |
28
29 ## In the bucket, or only here
30
31 With `S3_*` set these are written to the bucket, beside the snapshots and not inside them. Without
32 it they are folders under the data directory, and in no backup.
33
34 | Without a bucket | What it is | Written by |
35 | --- | --- | --- |
36 | `look-blobs/` | Pictures a person attached as looks | `src/looks/archive.ts` |
37 | `run-archive/` | Finished run logs. The snapshot takes `runs/`, and a log the store holds leaves `runs/` about a day after it was last written | `src/runs/archive.ts` |
38 | `large-blobs/` | Copies of big git blobs; git keeps its own, and the bundles hold it | `src/blob/large.ts` |
39
40 ## Covered another way
41
42 - `ledger/`, this forge's cost ledger: its lines are committed to the `ledger` branch of the forge's
43 own repository, at most once an hour, and that repository is in the snapshot. With no such
44 repository (`FORGE_LEDGER_REPO`, or the forge's own), the ledger is in no backup. A hosted forge's
45 `ledger/` is in the snapshot itself.
46 - `carts/`: a page saved from a build at a fixed commit. Capture makes it again while the build
47 still runs.
48 - `app-backups/`: sealed copies of an app's production data. The data is in the snapshot; the sealed
49 copies are not.
50
51 This list was read from the code on 2026-12-02 and is not checked by a test. It names what was found
52 to matter; folders that hold clones, caches, checks and last-seen states are not listed.
docs/features/config-form.md +37
@@ -72,6 +72,43 @@ difference is the save: they are patched, not rewritten.
7272 one most of the file uses. A file that mixes two indents loses the rarer one
7373 in that document.
7474
75 ## Secrets
76
77 One rule says what looks like a secret: `src/core/secret_text.ts`. The form
78 (`src/web/render/config-secrets.ts`, web and terminal), its diff, the read-only view, the `.env` and
79 `.ini` views, a game server's environment and plugin files, and a pinned
80 forge's config all ask it.
81
82 - **Where:** the key (`api-key`, `dbPassword`, `SSH_KEY`), a list under it, the
83 names under `passwords:`, `tokens:`, `secrets:` or `credentials:`, the
84 `value:` beside a `name: DB_PASSWORD`, `DB_PASSWORD=…` as a list item, a
85 password inside a URL and a private key block.
86 - **Showing fails closed.** Under a password every value is hidden. Under
87 another secret's key all are, but a flag and an amount (`max-tokens: 4096`,
88 `token-limit: 30`). An empty value and a `${NAME}` are shown.
89 - **Refusing fails open.** A flag and a number of up to three digits may be
90 saved under a secret's key.
91 - **In the form** such a value is `‹kept: /its/pointer›`, in the field and in
92 the document the page carries. A save puts the file's own value back. The
93 diff shows `‹hidden›`.
94 - **Refused:** a new secret in the clear, and a kept one moved to a key that
95 would show it. If the file changed since it was opened, a form that keeps a
96 secret has to be opened again: its place may be another's now.
97 - **What this is not:** access control. Git still holds the value, and the
98 source view, the raw file and **Edit as text** still show it. Seal it and
99 change it.
100 - **An alias under a secret's key** (`token: *t`) keeps the file from the form,
101 since its anchor stands under a key that would show it. Edit it as text. As
102 with every file the form cannot hold, the terminal checks no schema on it.
103
104 **Edit as text** masks nothing, on the web or in the terminal. A save that
105 adds what looks like a secret to a config file (`addedSecrets`: the text's
106 secrets after it, less those before, by key and value) is stopped once. It
107 names the key and offers **This is not a secret**; ticked, the save goes
108 through. A `*.pem` or `*.secret` file is asked about whole. Values are in no
109 message. Code is not asked: `password: string` is a type there. A change
110 proposed to another forge is asked the same way.
111
75112 ### The two vendored libraries
76113
77114 Neither is a dependency in `package.json`: each is one bundled file under
docs/features/contribute-token.md +2
@@ -27,3 +27,5 @@ or the MCP `start` tool with `action: "contribute"` (same arguments). The answer
2727 **The push opens the pull (#12013).** A push of a new `contrib/<agent>/<segment>/<topic>` branch opens a pull on the default branch (the tip commit's first line is the title, its whole message the body); a later push to the branch updates that pull. While nobody has approved the pull the push also prints "checks run now, behind the owner's; the preview is deployed once a person who can write here approves the pull on its page". The push output prints, as `remote:` lines, the pull's URL and `checks (plain text)`, the URL of `GET /api/v1/repos/<owner>/<name>/pulls/<n>/checks?format=text` (`state:`, `head:`, `required:`). Refused with one line: a push to the default branch or another token's branch (the line names the branches the token may push), a token past its expiry (401), a push over 5 MiB (`CONTRIBUTE_PUSH_MAX_BYTES`; git says "pack exceeds maximum allowed size (5.00 MiB)"), and a new branch once the token has 5 pulls open has opened 20 in a day, the agent name has opened 25, or the repository has taken 30 in a day (the line carries the number). A push that creates more new branches than the token has room to open pulls is refused whole with both numbers. Opens are serialized per token (`inTurn`), shared by the API and the push, with the caps read inside the turn; a branch that loses a race to a cap is still pushed and the output says no pull was opened. Code: `src/actions/contribute_push.ts`; test: `test/contribute-push.test.ts`.
2828
2929 **Reading its own check.** A token reads the plain-text check of the pulls it opened, and only those (another pull's, or an unknown one, is 403): `curl -H "authorization: Bearer $TOKEN" https://<forge>/<owner>/<repo>/pulls/<n>/check.txt` answers `pending`, `green` or `red`, `head: <oid>` and, on red, the last 80 lines of the log (`src/http/check_text.ts`). Add `?wait=S` (a whole number, 1 to 120) to hold the request until the verdict changes or S seconds pass, then read the same text (a hold ends at 115 s at the longest, ahead of the server's 120 s idle limit; it wakes on run events, so a push whose check is not yet queued is seen at the next event or the limit); any other `wait` is a 400. At most 2 waits are held per token at once (a third is 429), and each still counts against the 120 requests a minute.
30
31 **The checks read's `state` (#17705).** `GET …/pulls/<n>/checks` (JSON and `?format=text`) answers the state merging reads (`checkSummaryOf`, `src/core/runs.ts`): the newest run of each kind at the head, a failed one first, then one still to come. A deploy that ends after a red or running check never hides it; `run` is the run that decided, and `runs` lists every run.
docs/features/file-env.md +1 −1
@@ -6,7 +6,7 @@ row: A `.env.example` opens as the variables an app needs
66
77 A file named exactly `.env.example`, `.env.sample` or `.env.template` opens as a table instead of raw text: **name**, **example value** and the **comment** written above the line. Source is one tap away (`?view=source`). A plain `.env` (or `.env.local`, `.env.production`) is never drawn this way and keeps the source view.
88
9 - **Value:** shown as written, quotes removed; `—` when empty. A name ending `_KEY`, `_SECRET` or `_TOKEN`, or containing `PASSWORD`, shows `•••` instead of its value, even in an example file.
9 - **Value:** shown as written, quotes removed; `—` when empty. A value whose name looks like a secret (`secretSetting`, `src/core/secret_text.ts`) is shown as `‹hidden›`.
1010 - **Comment:** the `#` lines directly above a variable, plus an inline ` # note`. `export ` is allowed; `#` inside quotes or a URL fragment is part of the value.
1111 - **Groups:** a `#` block followed by a blank line is a group heading; the variables below it sit under it.
1212 - **Cap:** at most 500 variables, then one line `N more not shown`. Files over 1 MB keep Source. A file with no variable shows Source with the reason.
docs/features/file-ini-rtf-xml.md +1 −1
@@ -6,7 +6,7 @@ row: `.ini`/`.properties`, `.rtf` and `.xml` files open readable
66
77 Each opens as a drawn view instead of raw text. Source is one tap away (`?view=source`).
88
9 - **`.ini` and `.properties`:** one table per `[section]` with a key and value per row; comments dropped, properties continuation lines joined. A value whose key ends in key, secret, token or password is shown as `•••`. 500 settings, then `more not shown`. A file with no settings, or over 1 MB, opens as text.
9 - **`.ini` and `.properties`:** one table per `[section]` with a key and value per row; comments dropped, properties continuation lines joined. A value whose key looks like a secret (`secretSetting`, `src/core/secret_text.ts`) is shown as `‹hidden›`. 500 settings, then `more not shown`. A file with no settings, or over 1 MB, opens as text.
1010 - **`.rtf`:** its text as paragraphs, formatting dropped. Font and colour tables, pictures, headers, footers and other destinations are skipped; nothing embedded is fetched or run. 100,000 characters, then a note. A `.rtf` not starting with `{\rtf` is plain text. Over 5 MB opens as text.
1111 - **`.xml`:** the element tree with attributes and leaf text. Prolog, comments, processing instructions and the doctype are skipped and no entity is expanded (only the five named ones and numeric references are decoded). 1,000 elements, 24 levels deep, then `more elements not shown`; at most 100,000 elements are read, a file with more is counted as that many. Indented with a small step per level and wrapped, so a deep tree fits a phone. JUnit, OPML and feed files keep their own views. Over 5 MB opens as text.
1212 - A file's bytes must agree with its name; the media route still sends all three as `application/octet-stream`. Every value is escaped, drawn on the server; no script, no dependency.
docs/features/fleet.md +1 −1
@@ -9,7 +9,7 @@ Before a fleet operation acts, see the rows its query line selects. There are fo
99 **On the web:** `GET /fleet?q=<query line>&sort=<column>` (`src/web/pages/fleet.ts`), linked from the fleet graph as "Rows".
1010
1111 - The page shows a row count and a table.
12 - Click a column header to sort by it, and click again to reverse. This works through `?sort=<column>` and `?sort=-<column>` links, so no JavaScript is needed.
12 - Click a column header to sort by it, and click again to reverse. This works through `?sort=<column>` and `?sort=-<column>` links, so no JavaScript is needed. A cell that is empty or not known is last both ways.
1313 - A line that does not parse shows its reason beside the field, with status 200, and selects nothing.
1414
1515 **Acting on the rows (web):** under the table, a signed-in person picks a verb for the kind and a value, and chooses Preview (`src/web/pages/fleet-ops.ts`, `src/web/fleet-act.ts`).
docs/features/forge-archive.md +1 −1
@@ -11,7 +11,7 @@ For the host (a site admin). `/forges` answers "is this forge in use?" and lets
1111 - **A person last did something here**: a sign-in, a token used (a push), an account made by the claim, an issue, a comment, a run a person started. Never a heartbeat, telemetry, the engine's own ticks or what the crew did by itself. The host reads it from the forge's own tables, so a sleeping forge and one on older code answer alike (`src/spawn/person_activity.ts`, asked through `src/spawn/child_db.ts`).
1212 - **Claimed by** who, and when.
1313 - **What it costs to keep**: its data directory's size, its memory while awake, the credit it has spent.
14 - Sort with the links above the list: needs you first, quietest first, most recent activity, costliest to keep (`?sort=quiet|recent|cost`).
14 - Sort with the links above the list: needs you first, quietest first, most recent activity, costliest to keep (`?sort=quiet|recent|cost`). A size not measured yet comes after every measured one.
1515
1616 ## Archive and Restore
1717
docs/features/game-box.md +2 −1
@@ -12,8 +12,9 @@ and nothing appears at the provider unexplained. It never ends on its own: it is
1212 experiment.
1313
1414 - **Plan one (agents):** `infra` with `{ action: "plan", want: { game: true, where: "digitalocean/main@digitalocean:nyc3:s-4vcpu-8gb", repo: "you/mc-network", name?: "mc", host?: "mc.trevato.dev" } }`, then `apply` its id. The plan says "Start a 4 vCPU, 8 GB game box in New York running you/mc-network's compose file" and waits for the address and the DNS record, not for an https answer. The web and terminal doors are `/games` and the Games screen. `repo` is always named. One box a compose file: a second box on a file another box runs is refused, because a change to one would change both.
15 - **The boot config's size:** a cloud takes only so much (DigitalOcean 64 KiB, Hetzner 32 KiB; OVHcloud names no limit, so its own error is shown). The plan, a deploy, a restore, an update, a rollback and a new claim link measure the real one first and refuse one that is over, in a sentence with the size and the limit, before anything is made or deleted (`src/cloud/boot_size.ts`).
1516 - **The machine:** Ubuntu with Docker and its compose plugin (Ubuntu's packages, data on the box's volume), 4 GB of swap for the JVMs, and a firewall that lets in only 25565/tcp (Java) and 19132/udp (Bedrock, through Geyser on the proxy): no SSH, no web, no backend port. A cloud firewall the forge makes on request opens only the web ports, so a game box should not be given one. Password and root logins are off and updates are on, as on a forge.
16 - **The agent:** `/opt/forge-game/agent.sh` (`src/games/agent.sh`) under systemd (`forge-game-agent`). Every 5 s it POSTs the services, their CPU and memory, new log lines, command results and the host to `/api/v1/games/agent/sync`, and does what the answer asks: writes `compose.yml` and the answer's `.env` beside it (only that name: `FORWARDING_SECRET` and an `RCON_<SERVICE>` for every service; any other name is ignored and logged, so nothing can land on the agent's own files), runs `docker compose -p game --project-directory /opt/forge-game up -d --remove-orphans` when they change, and runs queued commands (rcon through `docker compose exec -T <service> rcon-cli -- <text>`, by service name, or restart, stop, start, pull, recreate). Nothing dials in to the box; a failed sync is tried again in 5 s, forever.
17 - **The agent:** `/opt/forge-game/agent.sh` (`src/games/agent.sh`) under systemd (`forge-game-agent`). The boot config does not carry it, for size: `fetch.sh` gets it from the forge with the box's token and checks its sha256. The boot repeats that every 5 s without end, before it mounts the volume or installs Docker, and each failed try prints its HTTP code on the console. A box that was rebooted before its first sync: replace it; the volume is kept. Every 5 s it POSTs the services, their CPU and memory, new log lines, command results and the host to `/api/v1/games/agent/sync`, and does what the answer asks: writes `compose.yml` and the answer's `.env` beside it (only that name: `FORWARDING_SECRET` and an `RCON_<SERVICE>` for every service; any other name is ignored and logged, so nothing can land on the agent's own files), runs `docker compose -p game --project-directory /opt/forge-game up -d --remove-orphans` when they change, and runs queued commands (rcon through `docker compose exec -T <service> rcon-cli -- <text>`, by service name, or restart, stop, start, pull, recreate). Nothing dials in to the box; a failed sync is tried again in 5 s, forever.
1718 - **When it is up but not playing:** the boot installs Docker, its compose plugin and jq in `runcmd`, each apt call waiting up to ten minutes for the lock a first boot's unattended upgrade holds, three tries (a `packages:` list failed on that lock and left box `mc` with no jq). Its last step, `agent.sh --boot-report`, posts cloud-init's status to the sync once. An agent missing jq or docker still posts `{"agent":1,"boot":"missing jq: <cloud-init status>"}`, built by hand with curl, every 30 s until they are there. The forge keeps that word until a full sync clears it, and `/games` and the terminal's Games say "Box is up but missing jq: …".
1819 - **Never blind:** compose up, pull and the power verbs run in a background job queue, one at a time, output to `.up.log`; the agent keeps syncing every 5 s whatever runs, and a failed up is not retried for the same compose. Every sync carries `diag`, about 8 KB: the job (label, since, running, last exit) and the tail of `.up.log`, `docker ps -a` and `docker images` (bounded), the agent's and Docker's journal, cloud-init's status, `df -h /`, where Docker's data root is mounted and whether the volume is, and the versions. The whole diag runs within one deadline (8 s; every docker read in a sync is capped at 5 s), and over it the sync carries `{"note":"diag ran over 8 s"}`, so a docker that hangs never holds the sync. A job interrupted under the agent (a stale pid with no exit status, or a pid that is now another program's, by its command line) is queued again, never marked failed. The forge keeps the latest (16 KB at most). The box's owner (and forge admins) read it whole; anyone else who may see one of its services reads only what it is doing ("Applying since …", "N of M running"), naming no container, image, error or journal. For the owner, `/games/<box>` has a Box section of plain lines ("Pulling …", "compose up failed: <its last error line>", "Docker's data is on the root disk, not the volume", "The volume is not mounted at …") over a folded run log of the raw tails; the terminal's Games shows the top line (`b` there opens the box: the same plain lines and raw tails) and the MCP games tool's `list` up to three.
1920 - **The proxy's own jars:** a compose file that mounts `./jars:/forge-jars:ro` in the proxy and names the files in its `PLUGINS` comes with `jars: [{ name, url, sha256 }]` in the same answer. The agent fetches each into `/opt/forge-game/jars` and checks its sha256 before the up; one that is missing or wrong holds back the proxy alone. An up that succeeds does not prove that the plugin loaded: read the proxy's log for that. Every full sync's body says `"jars": true`, which an agent from before this does not.
docs/features/game-plugin-config.md added +19
@@ -0,0 +1,19 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: Game plugin config
4 ---
5 # Game plugin config
6
7 A plugin's settings (`plugins/Hub/config.yml`, a mod's `config/…`) are files the repository holds,
8 so a change is a commit, previewed first and undone by a revert (#17699).
9
10 - **Where a file is kept:** a top-level `configs:` entry of the box's compose file, `content:` inline, mounted where the image copies from at start: `/plugins/<Plugin>/…` on a server image (copied to `/data/plugins`), `/config/plugins/<Plugin>/…` on the proxy (copied to `/server`), `/config/…` for a mod's. The forge already ships Paper's seeds and AutoStopper's config this way, so nothing new is written into a container and the box fetches nothing. Inline `content:` needs Compose 2.23.1 or newer on the box. A file is at most 64 KiB, as it sits in the compose file a person reads.
11 - **Use it, on the page:** `/games/<box>/<service>/config` (the service's page links to it, under "Plugin config") lists each plugin's files with their text (secrets hidden) and the place each has in the compose file. Type a path (`plugins/Hub/config.yml`) and the text, or pick a file's Edit, and Preview: the diff, the restart and who is online come first, and "Commit and restart" commits on the commit it was previewed on (a changed network refuses it: preview again). "Preview removing it" and a file's Revert plan the same way. Reading needs a viewer's grant, writing an operator's, as on the service's page, and every write is same-origin (`src/web/pages/games_config.ts`).
12 - **Use it, in the terminal:** `f` on a service's screen (`src/tui/screens/game_config.ts`): `j` and `k` pick a file, `e` edits it in a text box (ctrl+d previews, esc leaves), `a` adds one by its path, `d` previews removing it, `r` previews undoing its last change; `y` commits the preview shown, `n` drops it.
13 - **Use it (agents):** the games MCP tool, `plugin_config` with `box` and `service` lists each plugin's files (secrets hidden, each with its place in the compose file); `plugin_config_set` with `path` and `content` (omit `content` to remove) and `plugin_config_revert` with `path` plan first and commit with `dryRun: false`, on the commit they were planned on. The preview has the diff, says the server should restart on the box's next check-in and who is online.
14 - **The repository wins:** the service gets `SYNC_SKIP_NEWER_IN_DESTINATION=false`, so at every start (also after a crash) the image replaces the server's copy of a file the repository holds when they differ. The copy deletes nothing: a file removed from the repository stays on the server, and the plan says so. A file only the box has is left alone.
15 - **Why a commit should restart the server, and what is not yet proven:** compose does not recreate a container whose `content:` changed (measured for the sleepers' AutoStopper config, `src/games/sleep.ts`) and does recreate one whose environment changed (the same measurement). A changed label is expected to recreate it too, since compose hashes the whole service, so each commit also sets the service's `forge.config` label to a hash of its files. **That the label does it, that the image reads an inline `content:` mount at start and that `SYNC_SKIP_NEWER_IN_DESTINATION=false` makes it replace the server's copy have not been tried on a real container.** The plan and the page therefore say "should restart", and what a person sees after the first commit on a box is the test: if the file is not in `/data/plugins` after the next check-in, `power` `recreate` on the service does it by hand, and the how-to is to be corrected.
16 - **Compose reads `${…}` in `content:`:** the forge writes a literal `$` as `$$`, and reads it back as `$`.
17 - **Secrets:** a key that names one (`api-key`, `dbPassword`), a file that is one (`forwarding.secret`, a private key block) and a value written out are refused, and so is a password inside a URL under any key (`mysql://user:pass@host/db`, `jdbc:…;password=…`, `?token=…`); the page and the plan name the line, never the value. Write `${CFG_NAME}` in the file instead: the images fill it from the container's environment while copying (yml, json, toml, properties), and the value belongs in the box's sealed `.env`.
18
19 What the box holds is not read back: the agent sends no config files, so the page cannot say a server's copy differs from the repository's. That needs the agent to send `files: [{ service, path, sha256, text? }]` in each sync, and is a pull of its own.
docs/features/games.md +2 −1
@@ -8,6 +8,7 @@ A **game box** is a VM on your own cloud running Docker and `forge-game-agent`,
88
99 ## Where
1010
11 - **In the navigation:** Games is in the top bar, at `g p` (`g P` inside a repository), in Cmd/Ctrl K and in the terminal's palette, for a forge admin and anyone with a grant on a box. With no box, an admin's `/games` has Start a game box: it asks Talk for a plan, which builds nothing until approved. In the terminal `n` on an empty Games screen sends the same words.
1112 - **Web:** `/games` lists the boxes you may see; `/games/<box>` is the network, one row a service with Start, Stop and Restart; `/games/<box>/<service>` is the console (a live log over SSE in the game's own colours: the agent and the sync route turn each colour escape into its § code before they drop every other escape, and the page draws § codes through the one renderer, with Raw for the lines as kept; an RCON input whose answer shows inline, with the service's earlier commands on up and down; a crash found in the log leads in one line, "Crashed: Fabric could not load the mods: Install fabric-api", with the crash folded under it and a Share on mclo.gs button that says it publishes the log where anyone with the link can read it, and posts only on that click), the environment editor (commits `games: <service> env: <keys>`), the settings ([Game settings](game-settings.md)) and its mods or plugins (Modrinth, below; Upload jar for `PLUGINS`). Pages: `src/web/pages/games.ts`.
1213 - **Terminal:** the Games screen (`src/tui/screens/games.ts`): each service, `s`, `x`, `r`; `enter` opens its console and env, `c` there its settings, and `m` its mods (`/` search, `a` install, `u` update all, `d` remove, then `y` commits the preview shown); a service's console reads its log with the colour codes gone, a crash first in one line, and `:`'s prompt walks earlier commands with up and down.
1314 - **MCP:** `games` (admin-listed): `list`, `console`, `power`, `env`, `config`, `config_set`, and `mods`, `mods_search`, `mods_install`, `mods_update`, `mods_remove` (each change planned first; `dryRun: false` commits), with the same grants.
@@ -109,7 +110,7 @@ The token a box boots with is spent at its first sync: the box makes its own, se
109110
110111 The Velocity forwarding secret (`forwarding.env`) and an RCON password a service (`rcon-<service>.env`) are generated once, sealed like every forge secret and sent only in the sync's `env`, never committed. A box token is shown once and stored hashed. An uploaded jar is kept by the forge at `/games/jar/<id>/<name>`; the compose a box gets carries it signed for 6 hours, and only for the box that uploaded it. A jar must be a `.jar` (a zip), at most 64 MiB, and a box keeps at most 20 jars and 256 MiB.
111112
112 The environment editor refuses a key that looks like a secret (`PASSWORD`, `SECRET`, `TOKEN`, `KEY` in its name): a secret belongs in the sealed `.env` the forge writes to the box, never in the repository. An env or plugin change is a commit by the person who asks, so it needs write access to the compose repository; without it the forge says to ask the repository's owner.
113 The environment editor refuses a key that looks like a secret (the one rule, `secretKey` in `src/core/secret_text.ts`): a secret belongs in the sealed `.env` the forge writes to the box, never in the repository. An env or plugin change is a commit by the person who asks, so it needs write access to the compose repository; without it the forge says to ask the repository's owner.
113114
114115 A plugin or jar runs code on the game server; give operator only to people you trust.
115116
docs/features/go-jumps.md +11 −5
@@ -9,15 +9,21 @@ Press `g`, then a letter within one second, from any page outside a field. Modif
99 | Keys | Page | Who |
1010 |---|---|---|
1111 | `g h` | Home | everyone |
12 | `g a` | Apps | everyone |
13 | `g p` | Games | admins, and anyone with a grant on a game box |
14 | `g i` | Infrastructure | admins |
1215 | `g e` | Explore | everyone |
13 | `g f` | Flow | signed in |
14 | `g q` | Asks | signed in |
1516 | `g t` | Talk | signed in |
16 | `g s` | System | admins |
17 | `g n` | Next up | signed in |
18 | `g f` | Flow | admins |
19 | `g b` | Boards | admins |
20 | `g y` | System | admins |
21
22 Inside a repository `g p`, `g i` and `g b` are its pull requests, issues and branches, so Games, Infrastructure and Boards are `g P`, `g I` and `g B` there. `?` lists them that way.
1723
1824 - A page the viewer cannot open does nothing (no error, no redirect to sign-in): the script only knows the pages for the viewer's level.
1925 - The table is `GO_PAGES` in `src/web/go_pages.ts`, the same list as the `:` prompt and Cmd/Ctrl K. A page gets a jump by giving it a `key` there; a test refuses a letter used twice. `?` lists the jumps the viewer has, read from that table.
20 - `g h`, `g q` and `g t` are the chords the top bar already wore (its hover hints show them), so they now work from anywhere and the sheet names them like the rest.
26 - `g h` and `g t` are the chords the top bar already wore (its hover hints show them), so they now work from anywhere and the sheet names them like the rest.
2127 - Test: `test/keys-goto.test.ts` runs the real keys script against a fake document: stranger and user, the 1 s timeout, Ctrl/Meta, and a field.
2228
23 **Terminal:** no screen binds `g` for an action of its own any more (each moved to a letter of its verb, and the old `g` says where it went until 2026-12-15, `docs/features/keymap.md`). Lists still take `g` as their top until the terminal's own `g` jumps arrive and take `g g` for the top.
29 **Terminal:** `g` opens the same places, areas first (`src/tui/app/which.ts`): Games and Infrastructure are screens (`src/tui/screens/games.ts`, `src/tui/screens/infra.ts`), Apps and Explore give their web address. `g g` is the top of a list.
docs/features/hosted-backup.md +2 −2
@@ -14,10 +14,10 @@ Each forge this one hosts goes into the nightly snapshot (#13819), under `childr
1414 | Its key, wrapped under `FORGE_SNAPSHOT_PASSPHRASE` | `secret.key.wrapped` (without a passphrase the key stays home) |
1515 | Every app's production data | alongside |
1616 | This forge's own record of it | `ledger.json` |
17 | Its history: run logs, drop, cost ledger, `parent.json`, `plan.json` | `runs/`, `drop/`, `ledger/`, alongside |
17 | Its history: run logs, drop, cost ledger, uploaded plugin jars, `parent.json`, `plan.json` | `runs/`, `drop/`, `ledger/`, `games/jars/`, alongside |
1818 | What the host holds of it: credit and spend, the own-code switch | `parent/credit.json`, `parent/own-code.json`; `--forge` puts them back under `<data>/credit` and `<data>/own-code` |
1919
20 `parent/credit.json` holds the forge's `tokenHash`; it is backed up like everything else and is covered by the same encryption: a snapshot kept on a sealed lane is sealed chunk by chunk, this file with the rest. Files are opened without following a link and only if regular; a link, a pipe, a file that changed while it was copied, or history past the 512 MiB cap on `runs/`, `drop/` and `ledger/` together is left out and named in the manifest's `omitted` list (first 100, `omittedTotal` counts all). A restore refuses a `parent/` entry it has no place for.
20 `parent/credit.json` holds the forge's `tokenHash`; it is backed up like everything else and is covered by the same encryption: a snapshot kept on a sealed lane is sealed chunk by chunk, this file with the rest. Files are opened without following a link and only if regular; a link, a pipe, a file that changed while it was copied, or history past the 512 MiB cap on `runs/`, `drop/`, `ledger/` and `games/jars/` together is left out and named in the manifest's `omitted` list (first 100, `omittedTotal` counts all). A restore refuses a `parent/` entry it has no place for.
2121
2222 Chunks are shared with the rest of the snapshot, so a forge unchanged since last night sends nothing. A forge that cannot be read is named in the manifest's `hosted` list and the log; the snapshot goes on without it.
2323
docs/features/infra.md +3 −1
@@ -9,6 +9,8 @@ What runs on your own cloud, what it's for, what it costs, and when it ends; and
99
1010 ## Where
1111
12 - **From an app:** its page's "Run it on its own machine" (admins) opens `/infra/build?app=owner/name` with the app chosen, for running the app itself, with no end; nothing is built until Build.
13 - **Getting there:** the top bar, the account menu, the settings sidebar under Connections, and a link on Cloud accounts, Connect a cloud, Deploy to and Forges you sent; admins only, like the page.
1214 - **Web:** `/infra` (`src/web/pages/infra.ts`, routes in `src/http/infra_routes.ts`). Each account's month against its ceiling, one sentence a line ("$13.00 of $50 a month on DigitalOcean"); a line for anything the hourly watch found at a provider that the forge did not make, linking that account's row on Cloud accounts; then each machine that bills, grouped by its experiment's question or by its app, with where it runs in plain words, its monthly cost and when it ends, Keep 7 more days and End now beside it; End now shows only where something exists at the provider (`existsAtProvider` in `src/cloud/billing.ts`, the same test Retire on Pinned forges uses), so a first deploy that made nothing offers none. What ended in the last 30 days, and anything retired that still bills, stays under a quiet **Ended** disclosure, each in the shared billing sentence with its day: "retired Mon 30 Nov; nothing bills", or "…; its kept disk still bills $1.00 a month" with a link to delete it on Pinned forges; older ones that bill nothing are one line with their count. A dead row (a first deploy that failed and left nothing at its provider) says "nothing exists at DigitalOcean; clear this row", with Clear this row through the confirm (`clearPinned`, event `pinned.cleared`). Build something opens the compose form: an app, a place (the cheapest two in each city, each a row of at least 44px; a filter of city, provider or size words narrows the whole catalog on the server, `/infra/live?part=places`, so the page never carries it; one that cannot be ordered is listed, dimmed, with why), what it is for (a new question, a running experiment, or running the app itself), and when it ends (1, 3, 7 or 30 days; no end only for an app). The plan tray sits at the foot of the form.
1315 - **Terminal:** the Infrastructure screen (`src/tui/screens/infra.ts`, after Cloud accounts in the palette, and `I` on the Cloud accounts screen). What ended is listed after what runs, each in its billing sentence. `n` composes one question at a time and shows the plan with Build; `l` looks at the DNS records against Cloudflare now; `m` makes one (type, name, host, what it points to, a port for SRV, then the plan with Make the record); `u` removes the selected record after a confirm; `+` keeps the selected machine 7 more days; `x` ends it now after a confirm (only where something exists at its provider), and `c` clears a dead row after a confirm. A build's steps lead the list as they happen.
1416 - **API:** `GET /api/v1/admin/infra` (`?plan=<id>` adds a build's steps), `POST /api/v1/admin/infra/plan`, `POST /api/v1/admin/infra/apply` (202). Keep is `POST /api/v1/admin/pinned/:name/keep`.
@@ -60,7 +62,7 @@ Build runs in the background and appends `infra.applied` (the wants and each ste
6062
6163 ## As code (#17075, read-only so far)
6264
63 An app's repo may hold `infra.json` at its root on the main branch: `{"version": 1, "machines": [{"name", "account", "place", "host"?}]}`. Every machine in it runs that app, so a file cannot name another repo's machines. The schema is closed (an unknown key is refused), capped at 64 KiB and 50 machines, and every problem is said with its path (`src/cloud/infra_file.ts`). `/infra` shows an **As code** block per file: what applying it would add, change or remove, or that a name is blocked because another app runs it, which is never applied (only this app's running machines are ever removed); nothing is applied. The terminal's Infrastructure screen lists the same (`src/tui/screens/infra.ts`), `GET /api/v1/admin/infra/code` returns it, and the `infra` tool's `code` action says it. Reading is `src/cloud/infra_read.ts`: apps are read in parallel and a (repo, tip) already read is served from memory. Not yet: a lifetime in the file (the diff cannot compare it), the page writing the file as a commit, and reconciling on merge to main.
65 An app's repo may hold `infra.json` at its root on the main branch: `{"version": 1, "machines": [{"name", "account", "place", "host"?}]}`. Every machine in it runs that app, so a file cannot name another repo's machines. The schema is closed (an unknown key is refused), capped at 64 KiB and 50 machines, and every problem is said with its path (`src/cloud/infra_file.ts`). `/infra` shows an **As code** block per file: what applying it would add or change, that a name is blocked because another app runs it, and which of this app's machines are in no file; nothing is applied, and a machine the file does not name is left alone. The file is compared with the forge's own record, not with the cloud, so a file with no difference says "as the forge recorded it": a machine resized in the cloud's console still reads so. The terminal's Infrastructure screen lists the same (`src/tui/screens/infra.ts`), `GET /api/v1/admin/infra/code` returns it, and the `infra` tool's `code` action says it. Reading is `src/cloud/infra_read.ts`: apps are read in parallel and a (repo, tip) already read is served from memory. Not yet: a lifetime in the file (the diff cannot compare it), the page writing the file as a commit, and reconciling on merge to main.
6466
6567 ## A database (#17074)
6668
docs/features/keymap.md +2 −2
@@ -29,7 +29,7 @@ The owner, after the bridge: "tying together all the keybinds is really what im
2929
3030 ## Go and scopes
3131
32 `g` and a letter is a destination in the scope the page is in (`keymap.ts` `GO`, one table): inside a repository `g c` code, `g i` issues, `g p` pulls, `g r` runs, `g m` map, `g l` log (commits), `g b` branches, `g k` forks, `g s` settings; elsewhere `g h` home, `g e` explore, `g f` flow, `g t` Talk, `g n` next up, `g y` system, `g b` boards. A forge place a repository shadows is `g` and the capital there (`g B` boards), or `Space g`, or Cmd/Ctrl K. The chords that moved say where they went until 2026-12-15 when they would now do nothing (`g a`: the map is `g m`; `g s` outside a repository: System is `g y`).
32 `g` and a letter is a destination in the scope the page is in (`keymap.ts` `GO`, one table): inside a repository `g c` code, `g i` issues, `g p` pulls, `g r` runs, `g m` map, `g l` log (commits), `g b` branches, `g k` forks, `g s` settings; elsewhere `g h` home, `g a` Apps, `g p` Games, `g i` Infrastructure, `g e` explore, `g f` flow, `g t` Talk, `g n` next up, `g y` system, `g b` boards. A forge place a repository shadows is `g` and the capital there (`g B` boards, `g P` Games, `g I` Infrastructure), or `Space g`, or Cmd/Ctrl K. The chords that moved say where they went until 2026-12-15 when they would now do nothing (`g s` outside a repository: System is `g y`).
3333
3434 ## The terminal gives up g
3535
@@ -53,7 +53,7 @@ The web and the terminal answer the same tree, `g` table and `v`. The counts (`3
5353 The terminal reads the same tables (`src/tui/app/which.ts`):
5454
5555 - **`Space`, a group, a leaf.** A verb presses its key on the screen, so `Space p m` and `m` are one act. A place opens its palette command. What only a web page does (a settings page with no screen, copying a link) says so.
56 - **`g` and a letter** opens a forge place by its palette command (`g h` home, `g f` flow, `g t` Talk, `g y` System, `g b` boards, `g n` next up). **`g g`** is the top of a list, as `Home` is; `G` is still the end.
56 - **`g` and a letter** opens a forge place by its palette command (`g h` home, `g a` Apps, `g p` Games, `g i` Infrastructure, `g f` flow, `g t` Talk, `g y` System, `g b` boards, `g n` next up). **`g g`** is the top of a list, as `Home` is; `G` is still the end.
5757 - **The panel** of next keys sits at the foot while a chord is open. Escape or Backspace goes up a level, and a key that is nothing says so.
5858 - **Space is the leader only off a control.** A form's checkbox, a picker's tick and the git stage (lazygit-style) keep their Space; `test/keymap-terminal.test.ts` lists them.
5959 - **Space moved elsewhere:**
docs/features/living-home.md +1 −1
@@ -51,6 +51,6 @@ Each card says which of the three it is. The planner's standing direction is nev
5151
5252 **An ask ends.** One nobody touches for seven days is closed by the forge as dropped (`src/crew/ask_days.ts`, on the parked pulls' five-minute pass). The receipt is one comment that says why and how to undo it, posted by the forge as the repository's autonomy account (whoever turned its crew on), not written by a person; a repository with no one named closes nothing. **Reopen** on the issue brings it back as it was, and its seven days start again from that change; any word on it starts them again too. If the closed ask held up other work, that work is a plan to confirm where plans need a person (the Autonomy knob's ask), an ask with seven days of its own; on go it is simply the crew's.
5353
54 **With nothing to answer** the lane says "Nothing needs you." and is quiet.
54 **With nothing to answer** the lane says "Nothing needs you." and is quiet. A person who may see a game box, is not an admin and owns no repository gets one link after it, "Your games"; nobody else's home changes.
5555
5656 The terminal's home shows the same lane for the same person (`src/tui/screens/asks_lines.ts`): `Asked:` and the lane's words, the first four asks with what each asks, then the crew's one line.
docs/features/palette-rows.md +3 −1
@@ -10,9 +10,11 @@ Filtered on the server before the list exists (`src/web/palette_rows.ts`, `palet
1010
1111 Terminal: the palette itself is a web surface, but its app actions have their door. On an app's deploys screen (`src/tui/screens/deploys.ts`) a writer presses `D` to redeploy production and `S` to stop it, each after a one-line confirm, through the same `redeployEnv` and `stopEnv`; a stopped production offers only `D`, a reader neither. That is the terminal side of "Redeploy" and "Stop" here, gated the same way.
1212
13 **Plain words find an area.** An area's row carries search words (`words` in `src/web/go_pages.ts`), matched and never shown: Apps is `deploy app site`; Games `minecraft server players`; Infrastructure `cloud cost spend bill infra machine server aws deploy`. A word counts from its third letter, as a whole word or the start of one (`wordsHit`, `src/web/palette.ts`), a little under a title that says the same. So "server" shows Games and Infrastructure, each only to a person who may open it. The `:` prompt, the search page ("Go to Games") and the terminal's palette read the same words.
14
1315 The cap of eight apps: two rows an app, so at most sixteen rows, about one screen of the list; the page lists thirty repositories and a palette is a short list, not a table.
1416
15 Tests: `test/palette-rows.test.ts`.
17 Tests: `test/palette-rows.test.ts`, `test/areas.test.ts`.
1618
1719 ## A search that matches nothing sends nothing (#17647)
1820
docs/features/pull-pane.md +1 −1
@@ -8,7 +8,7 @@ A pull says where it stands in one sentence, with what shows it and at most thre
88
99 - **One reader:** `src/flow/pull_pane.ts` (`pullPane`, `paneOf`) reads the facts the flow already trusts: who acts next (`nextOfPull`, which carries a hold), the head's check and its place in the queue, the crew's unfinished run on the pull, and whether production has served since a merge.
1010 - **Three doors, one sentence:** the pull page (both tabs, under the title, `src/web/studio/pane.ts`), the terminal's pull screen, and the peek card that a link to a pull shows on hover. Each prints the same sentence.
11 - **States:** draft, held, conflict, building, checking, red, changes asked, a person decides, waits for a review, ready, merged, closed. `test/pull-pane.test.ts` holds each one's sentence, verbs and evidence.
11 - **States:** draft, held, conflict, building, checking, red, changes asked, a person decides, waits for a review, ready, merged, closed. Ready also shows, with Merge and Close, when a green pull has no queue to land it (the repository's autonomy is off, #16452): the Next line reads "a person lands it". `test/pull-pane.test.ts` holds each one's sentence, verbs and evidence.
1212 - **Verbs** go through the doors the acts already have:
1313 - a run's stop and queue again post to the run's routes;
1414 - update and close post to the pull's routes;
docs/features/reviews-off-lands-on-green.md +2 −2
@@ -4,7 +4,7 @@ row: Reviews are something an owner turns on
44 ---
55 # Reviews are something an owner turns on (#11666)
66
7 A green pull in an app whose owner has **not** asked for reviews, and where no reviewer is seated, lands by itself. No review is sent and nothing waits for one.
7 A green pull in an app whose owner has **not** asked for reviews, and where no reviewer is seated, lands by itself where the app's autonomy is on. No review is sent and nothing waits for one. Where autonomy is off no queue lands anything: the pull reads "green, reviews are off: a person lands it" and a person merges it.
88
99 **This changes the default.** Before, a green agent pull with no reviewer seated waited for a person forever. Now, with **Require review** off (the default) and no reviewer on the crew, it lands once its check passes. A new forge's first app has reviews off, so its first change goes live on green. An owner who wants a second look before anything lands turns reviews on, as below.
1010
@@ -17,7 +17,7 @@ Either one keeps every agent pull waiting for an approving review:
1717
1818 ## What still stops a pull with reviews off
1919
20 A conflict, a red check, a hold, the access wall, and a `changes requested` verdict on the head. Only the wait for a review is gone. The pull's page, the terminal and the MCP `pull` tool read "Next: queue, green, reviews are off: it lands".
20 A conflict, a red check, a hold, the access wall, and a `changes requested` verdict on the head. Only the wait for a review is gone. The pull's page, the terminal and the MCP `pull` tool read "Next: queue, green, reviews are off: it lands" where autonomy is on, and "Next: person, green, reviews are off: a person lands it" where it is off (#16452).
2121
2222 ## One rule
2323
docs/features/run-logs.md +4
@@ -14,6 +14,10 @@ A run writes its log to a file under the forge's data. Once the run is finished,
1414
1515 Every one of these asks first whether the run is in this repository and the viewer may read its log; only then is an evicted log fetched back from the store, so a run id from another repository or a hidden log never reaches the store. A run still in progress is never archived or restored.
1616
17 ## The line that says why
18
19 When a run fails, the forge keeps the one line that says why (`findingsOf` in `src/logs/findings.ts`): the failing test its check named, at that test's own `(fail)` line; else the line the run's verdict quotes; else, for a deploy or an agent's run, the last line that states an error. The feed's post says it and links to it. `GET …/check.txt` says up to five failing tests with the end of each one's output, above the last 80 lines. A word in passing (`0 failed`, a passing test named for an error) is never taken for it.
20
1721 ## When the store is down
1822
1923 A log that fails to archive stays local and the next sweep tries again. The seven-day prune never removes the log of a finished run the store does not hold, and one sweep runs at a time.
docs/features/terminal-workspace-kinds.md +1 −1
@@ -4,7 +4,7 @@ row: Notebooks, JSON Lines and logs in the terminal
44 ---
55 # Notebooks, JSON Lines and logs in the terminal
66
7 The SSH workspace opens `.ipynb`, `.jsonl`/`.ndjson` and `.log`/`.ansi` files the way the blob page does, from the same parsers (`parseNotebook` in `src/web/render/notebook.ts`, `parseJsonl`, `ansiLines`, `logLevel` in `src/web/render/log.ts`). Drawing lives in `src/tui/screens/workspace_kinds.ts`.
7 The SSH workspace opens `.ipynb`, `.jsonl`/`.ndjson` and `.log`/`.ansi` files the way the blob page does, from the same parsers (`parseNotebook` in `src/web/render/notebook.ts`, `parseJsonl`, `ansiLines`, `logLevel` in `src/logs/level.ts`). Drawing lives in `src/tui/screens/workspace_kinds.ts`.
88
99 - **Notebook**: cells in order. Markdown keeps its source lines (headings bold), code is dimmed as `In [n]: …`, outputs are text, errors are red, images say `[image output not shown]`. Nothing is run.
1010 - **JSON Lines**: a table, one row per object; a bad line is a row that names its line number.
scripts/restore-drill.ts +2 −1
@@ -22,7 +22,7 @@ import { bootRestored } from "../src/snapshot/boot.ts";
2222 import { resolveSnapshots } from "../src/snapshot/destination.ts";
2323 import { offsiteFromEnv } from "../src/snapshot/mirror.ts";
2424 import { publicCounts, type PublicCounts } from "../src/snapshot/public_counts.ts";
25 import { restoreSnapshot } from "../src/snapshot/restore.ts";
25 import { jarLines, restoreSnapshot } from "../src/snapshot/restore.ts";
2626 import { listSnapshots } from "../src/snapshot/snapshot.ts";
2727 import { PREVIEW_ADMIN } from "../src/spawn/preview-looks.ts";
2828
@@ -98,6 +98,7 @@ async function main(): Promise<number> {
9898 });
9999 console.log(`restored ${done.files} files and ${done.repos} repositories, key ${done.key}, ${seconds()}s`);
100100 if (done.sealedMissing.length > 0) console.log(`sealed values to set again: ${done.sealedMissing.length}`);
101 for (const line of jarLines(done.jarsMissing)) console.log(line);
101102
102103 let restored: PublicCounts | undefined;
103104 const booted = await bootRestored(args.dataDir, BOOT_MS, undefined, async (base) => {
scripts/standby-restore.ts +2
@@ -16,6 +16,7 @@
1616 */
1717 import { resolve } from "node:path";
1818 import { resolveSnapshots } from "../src/snapshot/destination.ts";
19 import { jarLines } from "../src/snapshot/restore.ts";
1920 import { restoreStandby } from "../src/snapshot/standby.ts";
2021
2122 async function main(args: readonly string[]): Promise<number> {
@@ -38,6 +39,7 @@ async function main(args: readonly string[]): Promise<number> {
3839 try {
3940 const done = await restoreStandby(store, snapshot, dataDir, process.env["FORGE_SNAPSHOT_PASSPHRASE"] || undefined);
4041 console.log(`restored ${done.name}: ${done.restored.files} files, ${done.repos} repositories, key ${done.restored.key}`);
42 for (const line of jarLines(done.restored.jarsMissing)) console.log(line);
4143 if (done.problems.length > 0) {
4244 for (const p of done.problems) console.error(`standby-restore: ${p}`);
4345 return 1;
src/actions/edit_words.ts +9
@@ -11,6 +11,15 @@ export function changedSinceWords(path: string, branch: string, gone: boolean):
1111 return `${path} ${gone ? "was removed from" : "changed on"} ${branch} since you opened it. Nothing was saved; your text is kept.`;
1212 }
1313
14 /** The box that lets a save past `secretAddedWords`, on the web and in the terminal. */
15 export const NOT_A_SECRET = "This is not a secret";
16
17 /** A save that would add what looks like a secret (`addedSecrets`), stopped once. Names only, never a value. */
18 export function secretAddedWords(names: readonly string[]): string {
19 const more = names.length > 3 ? ` and ${names.length - 3} more` : "";
20 return `${names.slice(0, 3).join(", ")}${more} ${names.length === 1 ? "looks" : "look"} like a secret, and git keeps it. Nothing was saved; your text is kept. Take it out, or tick “${NOT_A_SECRET}”.`;
21 }
22
1423 export function editMessage(kind: string): string {
1524 switch (kind) {
1625 case "storage_limit":
src/actions/infra.ts +1 −1
@@ -660,7 +660,7 @@ function fixOf(r: Refusal, wants: readonly Want[]): { why: string; href: string;
660660 }
661661
662662 /** What a plan of no wants reads: nothing at all. */
663 const NOTHING: Reads = { besideBox: () => undefined, firewalls: () => false, account: () => undefined, price: () => undefined, closed: () => undefined, host: () => "", dnsAuto: false, experiment: () => undefined, where: () => undefined };
663 const NOTHING: Reads = { besideBox: () => undefined, boots: () => undefined, firewalls: () => false, account: () => undefined, price: () => undefined, closed: () => undefined, host: () => "", dnsAuto: false, experiment: () => undefined, where: () => undefined };
664664
665665 /** Plan a compose against what exists now. */
666666 export async function planCompose(app: App, actor: User | undefined, c: Compose, choices?: ComposeChoices): Promise<Result<Planned, string>> {
src/actions/pinned.ts +16 −15
@@ -68,8 +68,8 @@ import { markStep, watchOf, type WatchTimes } from "../core/pinned_watch.ts";
6868 import { LIFETIME_DAYS, MAX_LIFETIME_DAYS } from "./pinned_lifetime.ts";
6969 export { LIFETIME_DAYS, MAX_LIFETIME_DAYS };
7070
71 /** Swapped in tests; the real forge always uses `fetch`, and asks DNS for a name's A records. */
72 export const net: { fetch: Fetch; probe: Fetch; resolve: (host: string) => Promise<string[]> } = {
71 /** Swapped in tests; the real forge always uses `fetch`, asks DNS for a name's A records, and holds a boot config to its cloud's own limit. */
72 export const net: { fetch: Fetch; probe: Fetch; resolve: (host: string) => Promise<string[]>; bootLimit?: number | undefined } = {
7373 fetch: (u, i) => fetch(u, { ...i, signal: boundedSignal(i?.signal) }),
7474 probe: (u, i) => fetch(u, { ...i, signal: boundedSignal(i?.signal) }),
7575 resolve: (host) => resolve4(host).catch(() => []),
@@ -235,7 +235,7 @@ function hostFor(app: App, name: string, raw: string): Result<string, string> {
235235 /**
236236 * A new code with its hash and deadline; the code leaves this module only inside an `IssuedClaim`.
237237 */
238 function newClaim(now = Date.now()): { code: string; hash: string; expires: string } {
238 export function newClaim(now = Date.now()): { code: string; hash: string; expires: string } {
239239 return { ...newFirstAdminCode(), expires: new Date(now + FIRST_ADMIN_SEED_TTL_MS).toISOString() };
240240 }
241241
@@ -345,7 +345,7 @@ export function fileForge(app: App, actor: User | undefined, name: string): Prom
345345 const project = projectOf(app, p);
346346 if (project === "") return Promise.resolve(err("Its cloud account names no project: set one on Settings → Cloud first."));
347347 if (p.remote === "" || p.volume === "") return Promise.resolve(err("This forge has no machine and volume to file yet."));
348 return withCloud(app, who.value, p, "file", (f, token) => fileIn(capped(app, p.name, driverOf(p.target)), f, token, p, project)).then((r) => (r.ok ? ok(`${name} is filed in the project "${project}".`) : r));
348 return withCloud(app, who.value, p, "file", (f, token) => fileIn(capped(app, p.name, driverOf(p.target), net.bootLimit), f, token, p, project)).then((r) => (r.ok ? ok(`${name} is filed in the project "${project}".`) : r));
349349 }
350350
351351 /** Open the account's token and run `go` with a gated fetch; the token never leaves this scope. */
@@ -457,16 +457,16 @@ export type DeployInput = {
457457 };
458458
459459 /**
460 * The row a machine is made from: a game box's carries its boot (`games/boot.ts`) with a token made
461 * now, so each machine made for it (a create or a replace) has its own and ends the one before.
460 * The row as its new machine boots it, for `provision` and `replace` to ask when they make one: a game
461 * box's carries its boot (`games/boot.ts`) with a token made then, which ends the one before. Made any
462 * earlier, a refusal would cut off the box that runs. A row and a games store that disagree boot
463 * nothing, and are refused here, before anything is asked of the cloud.
462464 */
463 function bootRow(app: App, p: Pinned): Pinned & { game?: GameBoot } {
465 function bootOf(app: App, p: Pinned): () => Pinned & { game?: GameBoot } {
464466 const box = boxNamed(app.db, p.name);
465 // The row says what it boots; a row and a games store that disagree boot nothing.
466467 if ((box !== undefined) !== (p.boots === "game")) throw new Error(`${p.name} is ${box === undefined ? "a game box with no row in the games store" : "a game box's name, and its machine is not one"}`);
467 if (box === undefined) return p;
468 const token = rotateGameBoxToken(app.db, box.id);
469 return { ...p, game: { forgeUrl: (app.config.url ?? "").replace(/\/+$/, ""), token } };
468 if (box === undefined) return () => p;
469 return () => ({ ...p, game: { forgeUrl: (app.config.url ?? "").replace(/\/+$/, ""), token: rotateGameBoxToken(app.db, box.id) } });
470470 }
471471
472472 export async function deployPinned(app: App, actor: User | undefined, input: DeployInput): Promise<Result<Issued, string>> {
@@ -540,7 +540,8 @@ async function deployAs(app: App, who: Who, input: DeployInput): Promise<Result<
540540 const made = await create(
541541 app, who, p, "deploy",
542542 (f, token) =>
543 provision(capped(app, p.name, driverOf(p.target)), f, token, bootRow(app, getPinned(app.db, p.name)!), {
543 provision(capped(app, p.name, driverOf(p.target), net.bootLimit), f, token, getPinned(app.db, p.name)!, {
544 boot: bootOf(app, getPinned(app.db, p.name)!),
544545 ...(old?.volume ? { have: old.volume } : {}),
545546 ...(restore === undefined ? {} : { from: restore }),
546547 project: projectOf(app, p),
@@ -589,7 +590,7 @@ async function changeNow(
589590 if (!ours.ok) return ours;
590591 // Asked of the cloud before the pin moves: what cannot be ordered, or would pass the account's
591592 // ceiling, is refused while the row and the running machine still agree, and nothing is recorded.
592 const fits = await withCloud(app, who.value, before, kind, () => orderable(capped(app, before.name, driverOf(before.target)), before));
593 const fits = await withCloud(app, who.value, before, kind, () => orderable(capped(app, before.name, driverOf(before.target), net.bootLimit), before, { ...before, ...to.value }));
593594 if (!fits.ok) return fits;
594595 if (!same) {
595596 const c = recordChange(app.db, before, kind, to.value, who.value.by);
@@ -598,7 +599,7 @@ async function changeNow(
598599 const after = getPinned(app.db, name)!;
599600 const done = await create(
600601 app, who.value, after, kind,
601 (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, bootRow(app, after), { project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who.value, name) }),
602 (f, token) => replace(capped(app, after.name, driverOf(after.target), net.bootLimit), f, token, after, { boot: bootOf(app, after), project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who.value, name) }),
602603 (m) => setRemote(app.db, name, { ...m, address: "", state: "running" }),
603604 true,
604605 );
@@ -675,7 +676,7 @@ async function claimNow(app: App, who: Who, name: string, input: { host?: string
675676 const after: Pinned = { ...getPinned(app.db, name)!, claimHash: claim.hash, claimExpires: claim.expires };
676677 const done = await create(
677678 app, who, after, "claim",
678 (f, token) => replace(capped(app, after.name, driverOf(after.target)), f, token, bootRow(app, after), { project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who, name) }),
679 (f, token) => replace(capped(app, after.name, driverOf(after.target), net.bootLimit), f, token, after, { boot: bootOf(app, after), project: projectOf(app, after), onDeleted: () => setRemote(app.db, name, { remote: "", address: "" }), onUnfiled: unfiled(app, who, name) }),
679680 (m) => {
680681 setClaim(app.db, name, { hash: claim.hash, expires: claim.expires });
681682 setRemote(app.db, name, { ...m, address: "", state: "running" });
src/actions/runs.ts +8 −4
@@ -44,7 +44,8 @@ import { err, ok, type Result } from "../kernel/result.ts";
4444 import { restoreRunLog } from "../runs/archive.ts";
4545 import { readRunLog, readRunLogTail, runLogPath } from "../runs/log.ts";
4646 import { shownStates, type ShownState } from "../runs/state.ts";
47 import { firstErrorLine } from "../runs/error_line.ts";
47 import { findingsOf } from "../logs/findings.ts";
48 import { clip } from "../text/clip.ts";
4849 import { cancelledBy } from "../runs/cancelled.ts";
4950 import { requireReader, requireWriter, type AccessError } from "./access.ts";
5051 import { deskForRun } from "../crew/desk_posts.ts";
@@ -95,15 +96,18 @@ export function announceRun(app: App, run: Run, actorId?: string): void {
9596 });
9697 }
9798
99 /** The most of that line a run keeps. */
100 export const ERROR_LINE_MAX = 120;
101
98102 /**
99103 * What a failed run's public event may say of it: the number of the pull or
100 * issue it was for. The first error line of its log is a log line, so it is
104 * issue it was for. The line that says why it failed is a log line, so it is
101105 * kept with the run (`setRunErrorLine`), once, and never put on the event.
102106 */
103107 function failureOf(app: App, run: Run): Record<string, unknown> {
104108 if (run.state !== "failed") return {};
105 const found = firstErrorLine(readRunLog(app.config.dataDir, run.id).lines);
106 if (found !== undefined) setRunErrorLine(app.db, run.id, found.text, found.at);
109 const found = findingsOf(run, readRunLog(app.config.dataDir, run.id).lines)[0];
110 if (found !== undefined) setRunErrorLine(app.db, run.id, clip(found.says, ERROR_LINE_MAX), found.line ?? 0);
107111 const subject = run.issueId === null ? undefined : getIssueById(app.db, run.issueId);
108112 return subject === undefined ? {} : { subject: subject.number };
109113 }
src/apps/feature.ts +1 −1
@@ -33,7 +33,7 @@ export const SETTING_TYPES: readonly SettingType[] = ["bool", "int", "string", "
3333
3434 /** The labels the forge's own menus use: a feature may not borrow one. */
3535 const BUILT_IN_MENU_LABELS = [
36 "your profile", "repositories", "apps", "notes", "talk", "explore", "packs", "displays", "map", "features",
36 "your profile", "repositories", "apps", "games", "infrastructure", "notes", "talk", "explore", "packs", "displays", "map", "features",
3737 "new app", "new repository", "new issue", "new organization", "migrate", "settings", "access tokens", "ssh keys",
3838 "origins", "boards", "crew", "system memory", "help", "sign out", "log out", "sign in", "admin", "administration",
3939 "access codes", "computer keys", "connected accounts", "jump to anywhere",
src/cloud/boot_ascii.ts +6
@@ -18,6 +18,12 @@ export function yamlString(value: string): string {
1818 return out;
1919 }
2020
21 /**
22 * A row that has no boot config to build yet (no name to be served on, no https forge to answer to):
23 * its deploy refuses it in words of its own, so a plan that only measures the config passes it by.
24 */
25 export class NoBootConfig extends Error {}
26
2127 /**
2228 * The one door every driver's user-data goes through: refused, in plain words, when anything in it
2329 * is not ASCII, so a byte a cloud reads as another never reaches cloud-init.
src/cloud/boot_size.ts added +23
@@ -0,0 +1,23 @@
1 /**
2 * Whether the boot config a machine would really get fits what its cloud takes of one. Asked where a
3 * place and a ceiling are (`capped`), before the first thing is made or deleted: a replace deletes the
4 * machine that runs before it asks for the next, so a config the cloud refuses would leave none.
5 */
6
7 import type { App } from "../app.ts";
8 import type { Booted, Driver } from "./machine.ts";
9
10 /** A game box's row boots with a token made at the last moment: one of the same length stands in for it. */
11 const STAND_IN = `fgb_${"0".repeat(43)}`;
12
13 /** The row as its machine boots it, a game box's with its forge's address and a stand-in token. */
14 const asBooted = (app: App, p: Booted): Booted =>
15 p.boots === "game" && p.game === undefined ? { ...p, game: { forgeUrl: (app.config.url ?? "").replace(/\/+$/, ""), token: STAND_IN } } : p;
16
17 /** Why `p`'s boot config is refused: its size, the limit, and that nothing was touched; undefined when it fits or the cloud names no limit. */
18 export function bootRefusal(app: App, d: Driver, p: Booted & { readonly volume?: string; readonly remote?: string }, limit: number | undefined = d.boot.limit): string | undefined {
19 // Built also where no limit is known: a config that cannot be built is refused while the old machine runs.
20 const bytes = Buffer.byteLength(d.boot.of(asBooted(app, p), p.volume || "1"), "utf8");
21 if (limit === undefined || bytes <= limit) return undefined;
22 return `${p.name}'s boot config is ${bytes} bytes, and ${new URL(d.api).host} takes at most ${limit}. Nothing was made or deleted${p.remote ? `, and ${p.name} keeps running` : ""}.`;
23 }
src/cloud/ceiling.ts +22 −3
@@ -15,6 +15,7 @@
1515 * bill is the truth.
1616 */
1717
18 import { bootRefusal } from "./boot_size.ts";
1819 import type { Database } from "bun:sqlite";
1920 import type { App } from "../app.ts";
2021 import { getCloudAccount } from "../core/cloud_account.ts";
@@ -237,7 +238,25 @@ export function refusalOf(s: Standing): string | undefined {
237238 );
238239 }
239240
240 /** The driver, held to the account's ceiling: its `admit` checks before the first thing is made. */
241 export function capped(app: App, name: string, d: Driver): Driver {
242 return { ...d, admit: () => admit(app, name) };
241 /** Refuse a boot config over its cloud's limit (`bootRefusal`), in those words, before anything is made or deleted. */
242 function bootFits(app: App, d: Driver, p: Parameters<typeof bootRefusal>[2], limit?: number): void {
243 const no = bootRefusal(app, d, p, limit);
244 if (no !== undefined) throw new CeilingRefusal(no);
245 }
246
247 /** The driver, held to the account's ceiling and its cloud's boot size: its `admit` checks before the first thing is made. `limit` is the cloud's own unless given. */
248 export function capped(app: App, name: string, d: Driver, limit?: number): Driver {
249 return {
250 ...d,
251 // The cloud's own refusal first, in its words. The place and the price are the row's as recorded; the size is of what would boot.
252 admit: (p, next = p) => {
253 try {
254 d.admit?.(p, next);
255 } catch (e) {
256 throw new CeilingRefusal(e instanceof Error ? e.message : String(e));
257 }
258 admit(app, name);
259 bootFits(app, d, next, limit);
260 },
261 };
243262 }
src/cloud/droplet.ts +2
@@ -41,6 +41,8 @@ const tagged = (x: any, tag: (t: string) => boolean): boolean => Array.isArray(x
4141 export const digitalocean: Driver = {
4242 api: "https://api.digitalocean.com/v2",
4343 firewall: digitaloceanFirewall,
44 // "may not exceed 64 KiB" (DigitalOcean's OpenAPI, droplet_create, read 2026-12-02).
45 boot: { limit: 64 * 1024, of: (p) => bootConfig(p) },
4446 async createVolume(call, p, snapshot) {
4547 // From a snapshot the volume keeps the filesystem it holds: DigitalOcean refuses to format one.
4648 const v = await call("POST", "/volumes", {
src/cloud/hetzner.ts +2
@@ -37,6 +37,8 @@ const foundIn = (list: unknown): Found[] =>
3737 export const hetzner: Driver = {
3838 api: "https://api.hetzner.cloud/v1",
3939 firewall: hetznerFirewall,
40 // "limited to 32KiB" (Hetzner's cloud API spec, create a server, read 2026-12-02).
41 boot: { limit: 32 * 1024, of: (p, volume) => bootConfig(p, volume) },
4042 async createVolume(call, p) {
4143 const v = await call("POST", "/volumes", { name: volumeName(p.name), location: p.datacenter, size: 10, format: "ext4", automount: false, labels: { "forge-pinned": "true", forge: p.name } });
4244 return String(v.volume?.id ?? "");
src/cloud/infra_file.ts +12 −10
@@ -1,7 +1,7 @@
11 /**
22 * `infra.json` (#17075, phase 4 of #16696): what an app's repo says should run on its owner's own
3 * cloud, and how that differs from what runs. This is the schema and the diff, both pure; reading
4 * the file out of a repo is `cloud/infra_read.ts`.
3 * cloud, and how that differs from what the forge recorded. This is the schema and the diff, both
4 * pure; reading the file out of a repo is `cloud/infra_read.ts`.
55 *
66 * { "version": 1, "machines": [ { "name": "shop-1", "account": "digitalocean/main",
77 * "place": "digitalocean:fra1:s-1vcpu-1gb", "host": "shop.example.com" } ] }
@@ -31,7 +31,7 @@ export interface Declared {
3131 readonly host: string;
3232 }
3333
34 /** What the forge has of a machine, as the diff compares it. */
34 /** What the forge recorded of a machine, as the diff compares it: its own row, not the cloud's answer. */
3535 export interface Existing {
3636 readonly name: string;
3737 readonly app: string;
@@ -42,9 +42,10 @@ export interface Existing {
4242 }
4343
4444 /**
45 * `blocked` is a declared machine that cannot be made as written; it is never something to apply.
45 * `blocked` is a declared machine that cannot be made as written, and `unfiled` one the file does not
46 * name; neither is ever something to apply.
4647 */
47 type ChangeKind = "add" | "change" | "remove" | "same" | "blocked";
48 type ChangeKind = "add" | "change" | "unfiled" | "same" | "blocked";
4849
4950 export interface Change {
5051 readonly kind: ChangeKind;
@@ -102,9 +103,10 @@ export function parseInfra(text: string): Result<Declared[], string[]> {
102103
103104 /**
104105 * What applying the file would change, for one app: a machine declared and not there is added; one
105 * there with another account, place or host is changed; one of this app's that is running and no
106 * longer declared is removed; the rest is the same. Retired machines are not "there". Read-only:
107 * nothing here makes or ends anything.
106 * recorded with another account, place or host is changed; one of this app's that the file does not
107 * name is in no file, and is left alone: a file never ends what it did not name. The rest is as the
108 * forge recorded it, which the cloud was not asked about. Retired machines are not "there".
109 * Read-only: nothing here makes or ends anything.
108110 */
109111 export function diffOf(app: string, declared: readonly Declared[], have: readonly Existing[]): Change[] {
110112 const live = new Map(have.filter((h) => h.state !== "retired").map((h) => [h.name, h]));
@@ -121,10 +123,10 @@ export function diffOf(app: string, declared: readonly Declared[], have: readonl
121123 h.place !== d.place ? `place ${h.place} → ${d.place}` : "",
122124 d.host !== "" && h.host !== d.host ? `host ${h.host} → ${d.host}` : "",
123125 ].filter(Boolean);
124 out.push(moved.length === 0 ? { kind: "same", name: d.name, says: `${d.name} is as declared` } : { kind: "change", name: d.name, says: `change ${d.name}: ${moved.join(", ")}` });
126 out.push(moved.length === 0 ? { kind: "same", name: d.name, says: `${d.name} is as the forge recorded it` } : { kind: "change", name: d.name, says: `change ${d.name}: ${moved.join(", ")}` });
125127 }
126128 }
127129 const names = new Set(declared.map((d) => d.name));
128 for (const h of live.values()) if (h.app === app && !names.has(h.name)) out.push({ kind: "remove", name: h.name, says: `remove ${h.name}: it runs but ${INFRA_FILE} does not declare it` });
130 for (const h of live.values()) if (h.app === app && !names.has(h.name)) out.push({ kind: "unfiled", name: h.name, says: `${h.name} is in no file` });
129131 return out;
130132 }
src/cloud/infra_read.ts +3 −3
@@ -1,5 +1,5 @@
11 /**
2 * `infra.json` against what runs (#17075, #16696 phase 4), read-only: for each app whose repo holds
2 * `infra.json` against what the forge recorded (#17075, #16696 phase 4), read-only: for each app whose repo holds
33 * the file at its main branch, what the file declares and what applying it would change. Pure
44 * parsing and diffing is `cloud/infra_file.ts`; this reads the repos and the pinned rows. Every
55 * door shows these: the /infra page, the terminal screen, `GET /api/v1/admin/infra/code` and the
@@ -30,9 +30,9 @@ export interface CodeFile {
3030 }
3131
3232 function codeSays(changes: readonly Change[]): string {
33 if (changes.every((c) => c.kind === "same")) return "matches what runs";
33 if (changes.every((c) => c.kind === "same")) return "as the forge recorded it";
3434 const n = (k: Change["kind"]): number => changes.filter((c) => c.kind === k).length;
35 return countLine([[n("add"), "to add"], [n("change"), "to change"], [n("remove"), "to remove"], [n("blocked"), "blocked"]]);
35 return countLine([[n("add"), "to add"], [n("change"), "to change"], [n("blocked"), "blocked"], [n("unfiled"), "in no file"]]);
3636 }
3737
3838 /** What one blob at one tip parsed to: kept per (repo, tip), so an unchanged tip costs no read. */
src/cloud/machine.ts +21 −14
@@ -19,7 +19,7 @@
1919 */
2020
2121 import type { ProviderView } from "./provider_detail.ts";
22 import { asciiBoot, yamlString } from "./boot_ascii.ts";
22 import { asciiBoot, NoBootConfig, yamlString } from "./boot_ascii.ts";
2323 import { BUN_PIN } from "../kernel/bun_pin.ts";
2424 import type { Fetch } from "./providers.ts";
2525 import { firstAdminSeed, readSeed } from "../core/first_admin.ts";
@@ -62,7 +62,7 @@ export type Booted = Pick<Pinned, "name" | "source" | "version" | "config" | "ho
6262 * this one starts from that commit by default.
6363 */
6464 export function servedEnv(p: Booted): Record<string, string> {
65 if (!validHost(p.host)) throw new Error("this forge has no name to be served on");
65 if (!validHost(p.host)) throw new NoBootConfig("this forge has no name to be served on");
6666 const seed = p.claimHash === "" ? "" : firstAdminSeed(p.claimHash, p.claimExpires);
6767 if (seed !== "" && readSeed(seed) === undefined) throw new Error("this forge's claim is not a hash and a deadline");
6868 return {
@@ -201,9 +201,15 @@ export interface Driver {
201201 signed?(f: Fetch, token: string): Call;
202202 /**
203203 * Refuse a place that may not be ordered, by throwing in words shown as they are: called before
204 * the first thing is made or deleted (`ceiling.ts` sets it).
204 * the first thing is made or deleted (`ceiling.ts` sets it). `next` is the row as it would boot,
205 * where that is not `p` (an update asked before its pin moves).
205206 */
206 admit?(p: Pinned): void;
207 admit?(p: Pinned, next?: Pinned): void;
208 /**
209 * What a machine boots from here, and the most bytes the cloud takes of it, where its API spec gives a
210 * number (`boot_size.ts` asks before anything is made or deleted).
211 */
212 readonly boot: { readonly limit?: number; of(p: Booted, volume: string): string };
207213 /**
208214 * Make the data volume; `snapshot` (a volume snapshot's id at this cloud) restores it from one.
209215 */
@@ -301,11 +307,11 @@ const ID = /^[A-Za-z0-9-]{1,64}$/;
301307
302308 /**
303309 * Volume first, then the machine that mounts it. A volume a failed earlier try
304 * made (`have`) is reused; a new one is recorded through `onVolume` before the
310 * made (`have`) is reused; `boot` is as `machineOf` has it; a new one is recorded through `onVolume` before the
305311 * machine is asked for. Returns the ids to keep.
306312 */
307313 export async function provision(
308 d: Driver, f: Fetch, token: string, p: Pinned, hooks: { have?: string; project?: string; from?: Restore; onVolume(id: string): void; onUnfiled?(why: string): void },
314 d: Driver, f: Fetch, token: string, p: Pinned, hooks: { have?: string; project?: string; from?: Restore; boot?(): Pinned; onVolume(id: string): void; onUnfiled?(why: string): void },
309315 ): Promise<{ remote: string; volume: string }> {
310316 const call = caller(d, f, token);
311317 d.admit?.(p);
@@ -319,7 +325,7 @@ export async function provision(
319325 if (!VOLUME.test(volume)) throw new Error(`${new URL(d.api).host} made no volume`);
320326 hooks.onVolume(volume);
321327 }
322 const remote = await machineOf(d, call, p, volume, hooks.from?.what === "machine" ? hooks.from.id : undefined);
328 const remote = await machineOf(d, call, p, volume, hooks.boot, hooks.from?.what === "machine" ? hooks.from.id : undefined);
323329 await file(d, call, project, remote, volume, hooks.onUnfiled);
324330 return { remote, volume };
325331 }
@@ -336,11 +342,12 @@ const found = async (ask: Promise<string>): Promise<string> => {
336342 /**
337343 * One forge, one machine: the machine already made for it is adopted, and one is created only when
338344 * the provider has none. An answer with no usable id is an error, and the machine it made is found
339 * by name on the next try.
345 * by name on the next try. `boot` gives the row as the new machine boots it, and is asked only when
346 * one is really made: a token made there is never made for a machine that runs already.
340347 */
341 async function machineOf(d: Driver, call: Call, p: Pinned, volume: string, image?: string): Promise<string> {
348 async function machineOf(d: Driver, call: Call, p: Pinned, volume: string, boot?: () => Pinned, image?: string): Promise<string> {
342349 const have = await found(d.findMachine(call, p));
343 const remote = have !== "" ? have : await d.createMachine(call, p, volume, image);
350 const remote = have !== "" ? have : await d.createMachine(call, boot?.() ?? p, volume, image);
344351 if (!ID.test(remote)) throw new Error(`${new URL(d.api).host} made no machine the forge can name`);
345352 return remote;
346353 }
@@ -382,7 +389,7 @@ export async function fileIn(d: Driver, f: Fetch, token: string, p: Pinned, name
382389 * does not delete twice.
383390 */
384391 export async function replace(
385 d: Driver, f: Fetch, token: string, p: Pinned, hooks: { project?: string; onDeleted(): void; onUnfiled?(why: string): void },
392 d: Driver, f: Fetch, token: string, p: Pinned, hooks: { project?: string; boot?(): Pinned; onDeleted(): void; onUnfiled?(why: string): void },
386393 ): Promise<{ remote: string }> {
387394 if (p.volume === "") throw new Error("this forge has no volume to keep");
388395 if (p.remote !== "" && !ID.test(p.remote)) throw new Error("this forge has no machine to replace");
@@ -398,7 +405,7 @@ export async function replace(
398405 hooks.onDeleted();
399406 await untilFree(d, call, p.volume);
400407 }
401 const remote = await machineOf(d, call, p, p.volume);
408 const remote = await machineOf(d, call, p, p.volume, hooks.boot);
402409 await file(d, call, project, remote, p.volume, hooks.onUnfiled);
403410 return { remote };
404411 }
@@ -424,8 +431,8 @@ async function untilFree(d: Driver, call: Call, volume: string): Promise<void> {
424431 * is where a place that cannot be ordered, or a ceiling (`ceiling.ts`), refuses. Asked before a
425432 * change is recorded, so a refusal leaves the row and the machine agreeing.
426433 */
427 export async function orderable(d: Driver, p: Pinned): Promise<void> {
428 d.admit?.(p);
434 export async function orderable(d: Driver, p: Pinned, next?: Pinned): Promise<void> {
435 d.admit?.(p, next);
429436 }
430437
431438 /** What a volume's id may look like on the way into a path: DigitalOcean's are UUIDs, Hetzner's numbers. */
src/cloud/ovh.ts +2
@@ -44,6 +44,8 @@ const q = encodeURIComponent;
4444
4545 export const ovh: Driver = {
4646 api: "https://api.us.ovhcloud.com/1.0",
47 // No limit: OVHcloud's API names none (cloud.json, read 2026-12-02), so one it refuses is told in its own words.
48 boot: { of: (p, volume) => bootConfig(p, volume) },
4749 signed(f, token) {
4850 const o = ovhParts(token);
4951 if (!o) throw new Error("the OVHcloud US credential is not APPLICATION_KEY:APPLICATION_SECRET:CONSUMER_KEY:PROJECT_ID");
src/cloud/plan.ts +24 −2
@@ -30,7 +30,7 @@
3030
3131 import type { App } from "../app.ts";
3232 import { dropRecord, putRecord } from "../actions/dns_record.ts";
33 import { besideNew, clearPinned, deployPinned, firewallPinned, LIFETIME_DAYS, LIFETIME_WORDS, MAX_LIFETIME_DAYS, retirePinned } from "../actions/pinned.ts";
33 import { besideNew, clearPinned, deployPinned, firewallPinned, net, newClaim, ownCode, LIFETIME_DAYS, LIFETIME_WORDS, MAX_LIFETIME_DAYS, retirePinned } from "../actions/pinned.ts";
3434 import { stuckWords, WATCH } from "../actions/pinned_watch.ts";
3535 import { bindDatabase, createDatabase, ONLY_DIGITALOCEAN, pollDatabase } from "../actions/database.ts";
3636 import { getRepo } from "../core/repos.ts";
@@ -45,7 +45,9 @@ import { err, ok, type Result } from "../kernel/result.ts";
4545 import { COMPOSE_AT, sameFile } from "../games/compose_file.ts";
4646 import { getBaseDomain } from "../settings/pinned_domain.ts";
4747 import { DNS_TTL, specKey, specWords, specWordsOf, type DnsSpec, type DnsType } from "./dns_record.ts";
48 import { firewallCloud } from "./drivers.ts";
48 import { NoBootConfig } from "./boot_ascii.ts";
49 import { bootRefusal } from "./boot_size.ts";
50 import { driverOf, firewallCloud } from "./drivers.ts";
4951 import { NO_FIREWALL } from "./firewall.ts";
5052 import { accountCents, priced, refusalOf, rowCents } from "./ceiling.ts";
5153 import { attachMachine, beginExperiment, EXPERIMENT_WORDS, experiments } from "./experiments.ts";
@@ -237,6 +239,8 @@ export interface Reads {
237239 experiment(id: string): { readonly state: "running" | "done"; readonly question: string } | undefined;
238240 /** Why a new game box `name` may not run the compose file in `repo` (`besideBox`); undefined when it may. */
239241 besideBox(name: string, repo: string): string | undefined;
242 /** Why the machine this want makes could not be booted at its cloud (`bootRefusal`); undefined when it could. */
243 boots(w: MachineWant, host: string): string | undefined;
240244 /** What a database want needs read; absent, no database can be planned. */
241245 readonly database?: DatabaseReads | undefined;
242246 }
@@ -536,6 +540,11 @@ export function plan(
536540 }
537541 files.set(file, w.name);
538542 }
543 const unbootable = make ? reads.boots(w, host) : undefined;
544 if (unbootable !== undefined) {
545 refuse(w.name, unbootable, w.account);
546 continue;
547 }
539548 if (make) {
540549 const price = reads.price(w.place);
541550 const counted = h?.cents ?? 0;
@@ -1078,6 +1087,19 @@ export function readInfra(app: App): { have: Have[]; reads: Reads; databases: Da
10781087 closed: (place) => prices.closed(place),
10791088 host: (name, asked) => asked.trim().toLowerCase() || (base === "" ? "" : `${name}.${base}`),
10801089 firewalls: firewallCloud,
1090 // The row as the deploy of this want makes it (`deployAs`): the code it would run, a new claim, and no settings.
1091 boots: (w, host) => {
1092 const code = ownCode(app, { source: w.source, version: w.version ?? "" });
1093 if (!code.ok) return undefined; // the deploy refuses it in those words, and there is no config to measure
1094 const claim = newClaim();
1095 try {
1096 const row = { name: w.name, ...code.value, config: {}, host, claimHash: claim.hash, claimExpires: claim.expires, boots: w.boots ?? "forge" };
1097 return bootRefusal(app, driverOf(providerOf(w.account)), row, net.bootLimit);
1098 } catch (e) {
1099 if (e instanceof NoBootConfig) return undefined;
1100 return `${w.name}'s boot config could not be built: ${e instanceof Error ? e.message.slice(0, 200) : "failed"}`;
1101 }
1102 },
10811103 besideBox: (name, repo) => besideNew(db, name, repo),
10821104 dnsAuto: listCloudAccounts(db).some((a) => a.provider === "cloudflare" && a.writeAllowed),
10831105 where: (place) => {
src/cloud/service_boot.ts +2 −2
@@ -8,7 +8,7 @@
88
99 import { INSTALL } from "../games/boot.ts";
1010 import { validHost } from "../core/pinned.ts";
11 import { yamlString } from "./boot_ascii.ts";
11 import { NoBootConfig, yamlString } from "./boot_ascii.ts";
1212 import { hardenFiles, mount, proxyCommands, proxyStore, PUBLIC_PORTS } from "./harden.ts";
1313
1414 /** What the machine answers on its own name. */
@@ -30,7 +30,7 @@ const closed = (tool: string, address: string): string =>
3030 /** The cloud-config of a services machine answering on `host`, its volume at `dataDir`; `early` is the cloud's own mount. */
3131 export function serviceBootConfig(host: string, dataDir: string, early: readonly string[] = []): string {
3232 const dir = mount(dataDir);
33 if (!validHost(host)) throw new Error("this machine has no name to be served on");
33 if (!validHost(host)) throw new NoBootConfig("this machine has no name to be served on");
3434 const needsVolume = `[Unit]\nRequiresMountsFor=${dir}\nAssertPathIsMountPoint=${dir}\n`;
3535 const docker = `${needsVolume}[Service]\nExecStartPost=/bin/sh -c '${closed("iptables", "169.254.169.254/32")}'\nExecStartPost=/bin/sh -c '${closed("ip6tables", "fd00:ec2::254/128")} || [ ! -s /proc/net/if_inet6 ]'\n`;
3636 const file = (path: string, content: string): string => ` - path: ${path}\n permissions: "0644"\n content: ${yamlString(content)}`;
src/contract/openapi/routes/getApiV1AdminInfraCode.ts +1 −1
@@ -4,7 +4,7 @@ export const route: Route = {
44 method: "get",
55 path: "/api/v1/admin/infra/code",
66 summary: "Each app's infra.json from its repo's main branch, checked",
7 detail: "Read from the root of each app's repo main branch, read-only: each file's problems as rows and its difference from what runs; nothing is changed",
7 detail: "Read from the root of each app's repo main branch, read-only: each file's problems as rows and its difference from what the forge recorded; nothing is changed",
88 auth: true,
99 role: "admin",
1010 refusals: {
src/contract/openapi/routes/getOwnerNamePullsNumberCheckTxt.ts +1 −1
@@ -6,7 +6,7 @@ export const route: Route = {
66 summary:
77 "A pull's latest check as `text/plain`, for a script",
88 detail:
9 "A pull's latest check as `text/plain`, for a script: line 1 is `pending`, `green` or `red`, line 2 is `head: <oid>`; on red a blank line and the last 80 log lines follow, only where the run-log door would show that reader the log. Anonymous on a public repository. It differs from `/api/v1/repos/{owner}/{name}/pulls/{number}/checks?format=text` (`state:`, `head:`, `required:` lines, no log tail, state words `none`/`ok`/`failed`): this answers the one word to branch on, plus the failing tail",
9 "A pull's latest check as `text/plain`, for a script: line 1 is `pending`, `green` or `red`, line 2 is `head: <oid>`; on red a blank line, what failed (each failing test with the end of its output), a blank line and the last 80 log lines follow, only where the run-log door would show that reader the log. Anonymous on a public repository. It differs from `/api/v1/repos/{owner}/{name}/pulls/{number}/checks?format=text` (`state:`, `head:`, `required:` lines, no log tail, state words `none`/`ok`/`failed`): this answers the one word to branch on, plus the failing tail",
1010 auth: false,
1111 role: "anonymous",
1212 refuses: [404],
src/core/empty_words.ts +5 −1
@@ -96,13 +96,17 @@ const TABLE = {
9696 appFlags: { sentence: NO_FLAG, reason: `Add a ${FLAGS_FILE} to the repository to declare one.` },
9797 appRegistry: { sentence: "Nothing installed from the registry.", reason: "An item is noted here when it is installed." },
9898 regValues: { sentence: "No values." },
99 gameBoxes: { sentence: "Nothing runs here yet.", reason: "A game box is a machine on your cloud running a compose project; an admin makes one from Infra." },
99 gameBoxes: { sentence: "Nothing runs here yet.", reason: "A game box is a machine on your cloud running a compose project; an admin starts one." },
100100 gameServices: { sentence: "Nothing has reported yet.", reason: "The box shows its services once its agent first syncs." },
101101 gamePlugins: { sentence: "Nothing is installed.", reason: "Search Modrinth below, or upload a jar." },
102102 cloudResources: { sentence: "No cloud account is attached.", reason: "Attach one and the forge reads what it holds and what it costs." },
103 gamePluginConfigs: { sentence: "No plugin config file is kept in the repository yet.", reason: "Add one below: it is a commit to the compose file." },
103104 gameSnapshots: { sentence: "No snapshot yet.", reason: "One is taken before every import or restore." },
104105 } as const satisfies Readonly<Record<string, EmptyWords>>;
105106
107 /** What Start a game box asks Talk, from the page and the terminal: `infra` plans one free, and the forge asks before it builds. */
108 export const START_BOX = "Start a game box on my cloud: plan it, show me the places and what each costs a month, and build nothing until I say so.";
109
106110 export type EmptyKind = keyof typeof TABLE;
107111
108112 export const EMPTY_WORDS: Readonly<Record<EmptyKind, EmptyWords>> = TABLE;
src/core/pinned.ts +2 −2
@@ -8,6 +8,7 @@
88 import type { Database } from "bun:sqlite";
99 import { id as newId } from "../kernel/id.ts";
1010 import { err, ok, type Result } from "../kernel/result.ts";
11 import { secretKey } from "./secret_text.ts";
1112
1213 /**
1314 * What a machine boots (#17625): a forge, a game box (Docker and the game agent, `games/boot.ts`),
@@ -109,7 +110,6 @@ export const BOOT_NAMES: readonly string[] = [
109110 "FORGE_URL", "FORGE_HOST", "FORGE_BIND", "FORGE_TRUSTED_PROXIES", "FORGE_SSH_PORT", "FORGE_FIRST_ADMIN_SEED", "FORGE_CREW_SANDBOX", "FORGE_DATA", "FORGE_APP_DATA",
110111 "FORGE_REPO", "FORGE_UPSTREAM", "FORGE_COMMIT", "FORGE_RELEASE_KEEPER", "FORGE_SELF_SWAP",
111112 ];
112 const SECRETISH = /SECRET|TOKEN|PASSWORD|PASSWD|PASSPHRASE|PRIVATE|CREDENTIAL|COOKIE|AUTH(?!OR)|API_?KEY|ACCESS_?KEY|(?:^|_)KEYS?(?:_|$)/;
113113 // A name that steers the dynamic loader, the runtime, the path or the shell of the process it is
114114 // set for is never a setting: it is the unit's environment, and a forge that runs as itself must
115115 // not be told to load someone's library. The service's own HOME, USER and PATH come from systemd.
@@ -139,7 +139,7 @@ export function checkConfig(raw: unknown): Result<Record<string, string>, string
139139 if (!KEY.test(k)) return err(`config name ${k.slice(0, 20)} is capitals, digits and underscores`);
140140 if (BOOT_NAMES.includes(k)) return err(`${k} is set by the deploy itself (the forge's name, listener, claim, sandbox and data); it is not a setting`);
141141 if (STEERING.test(k)) return err(`${k} steers the loader, the runtime or the path of the process; it is not a setting`);
142 if (SECRETISH.test(k)) return err(`${k} looks like a secret; secrets are sealed in cloud accounts, never in config`);
142 if (secretKey(k)) return err(`${k} looks like a secret; secrets are sealed in cloud accounts, never in config`);
143143 if (typeof v !== "string" || !VALUE.test(v)) return err(`config ${k} is plain text of letters, digits and . , : / @ + = - _`);
144144 out[k] = v;
145145 }
src/core/runs.ts +9 −1
@@ -1398,6 +1398,11 @@ function summaryOf(verdict: readonly Run[]): CheckSummary {
13981398 : { state: "none", run: null };
13991399 }
14001400
1401 /** `checkSummary` over runs already read at one head, newest first (`checksForHead`). */
1402 export function checkSummaryOf(runs: readonly Run[]): CheckSummary {
1403 return summaryOf(newestOfEachKind(runs));
1404 }
1405
14011406 export function checkSummary(
14021407 db: Database,
14031408 issueId: string,
@@ -1995,7 +2000,10 @@ export function listRunning(
19952000 }));
19962001 }
19972002
1998 /** Keep a finished run's first error line (see `runs/error_line.ts`) beside it. */
2003 /**
2004 * Keep the line that says why a finished run failed (`logs/findings.ts`) beside it; `at` is 0 when
2005 * its log does not hold it.
2006 */
19992007 export function setRunErrorLine(db: Database, runId: string, text: string, at: number): void {
20002008 db.query("UPDATE run SET error_line = ?2, error_at = ?3 WHERE id = ?1").run(runId, text, at);
20012009 }
src/core/secret_text.ts added +239
@@ -0,0 +1,239 @@
1 /**
2 * The one rule for what looks like a secret in a config file: by its key, and in its text.
3 * Everything that shows or commits a config value asks here (the config form and its diff, the
4 * `.env` and `.ini` views, a game server's environment and plugin files, a pinned forge's config).
5 * It is display, not access control: git still holds what was committed. Pure, and linear in the
6 * text's length.
7 */
8
9 export const MASK = "‹hidden›";
10
11 const SECRET_WORDS = new Set(["password", "passwd", "passphrase", "pass", "pwd", "pin", "secret", "secrets", "token", "tokens", "apikey", "credential", "credentials", "webhook", "pem", "keystore"]);
12 const KEY_WORDS = "api|private|access|auth|secret|signing|encryption|license|ssh|ssl|tls|master|client|session|deploy|server|host|bot|rcon|admin|user|account|storage|service";
13 const KEY_PAIR = new RegExp(`^(?:${KEY_WORDS})$`);
14 /** Inside a word too, as words run together in lower case are written: `dbpassword`, `clientsecret`, `authtoken`. */
15 const ANYWHERE = new RegExp(`passw(?:or)?d|passphrase|api[_-]?key|secret(?!ar)|credential|tokens?(?![a-z])|(?:${KEY_WORDS})keys?(?![a-z])`, "i");
16 /** An environment variable's name (all capitals) says it in more ways: `SSH_KEY`, `OAUTH`, `COOKIE`. */
17 const ENV_NAME = /^[A-Z][A-Z0-9_]*$/;
18 const ENV_SECRET = /SECRET|TOKEN|PASSWORD|PASSWD|PASSPHRASE|PRIVATE|CREDENTIAL|COOKIE|AUTH(?!OR)|KEY/;
19 /** Words that only contain KEY. */
20 const NOT_KEY = /MONKEY|DONKEY|TURKEY|HOCKEY|JOCKEY|HOTKEY|KEYBOARD|KEYPAD|KEYFRAME|KEYWORD/g;
21 /** Keys that hold several secrets by name: `passwords: { alice: … }`. */
22 const SEVERAL = /^(?:passwords|tokens|secrets|credentials)$|[._-](?:passwords|tokens|secrets|credentials)$/i;
23 /** A key whose whole value is one password, whatever it looks like. */
24 const PASSWORD_LAST = /passw(?:or)?ds?[\W_\d]*$|passphrases?[\W_\d]*$|pwd[\W_\d]*$/i;
25 const PASS_WORD = new Set(["pass", "pin"]);
26 /** Words that make a number beside a secret's word an amount: `max-tokens`, `token-limit`, `password-length`. */
27 const AMOUNT = new Set("max min limit limits count length size ttl expiry expires expiration timeout lifetime total per budget usage used age rotation refresh days hours minutes seconds interval attempts retries port version rounds".split(" "));
28
29 const words = (name: string): string[] => name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
30
31 /** Whether a key (`api-key`, `dbPassword`, `SSH_KEY`) or a file's name names a secret. */
32 export function secretKey(key: string): boolean {
33 if (ANYWHERE.test(key) || SEVERAL.test(key) || (ENV_NAME.test(key) && ENV_SECRET.test(key.replace(NOT_KEY, "")))) return true;
34 const w = words(key);
35 return w.some((x, i) => SECRET_WORDS.has(x) || (x === "key" && i > 0 && KEY_PAIR.test(w[i - 1]!)));
36 }
37
38 /** The same in a file of settings (`.env`, `.ini`, `.properties`), where a last word `key` is one too. */
39 export const secretSetting = (key: string): boolean => secretKey(key) || words(key).at(-1) === "key";
40
41 /** Whether a key holds several secrets, each under a name of its own. */
42 export const severalSecrets = (key: string): boolean => SEVERAL.test(key);
43
44 const PLACEHOLDER = /^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/;
45 const FLAG = /^(?:null|~|true|false|none)$/i;
46 const NUMBER = /^-?\d+(?:\.\d+)?$/;
47 export const PRIVATE_BLOCK = /-----BEGIN [A-Z ]*PRIVATE KEY-----/;
48
49 /**
50 * Whether `v` under the secret's key `key` may not be shown. Showing fails closed: under a password
51 * every value counts, and under another secret all but a flag and an amount (`max-tokens: 4096`).
52 */
53 export function hiddenValue(key: string, v: string): boolean {
54 if (v === "" || v === MASK || PLACEHOLDER.test(v)) return false;
55 const w = words(key);
56 if (PASSWORD_LAST.test(key) || PASS_WORD.has((w.findLast((x) => !/^\d+$/.test(x)) ?? "").replace(/\d+$/, ""))) return true;
57 return !FLAG.test(v) && !(NUMBER.test(v) && w.some((x) => AMOUNT.has(x)));
58 }
59
60 /** Whether `v` under `key` is refused as a secret in the clear. Refusing fails open: a flag and a short number pass. */
61 export const literalSecret = (key: string, v: string): boolean => hiddenValue(key, v) && !FLAG.test(v) && !/^-?(?:\d{1,3}|\d+\.\d+)$/.test(v);
62
63 /** A value as a line writes it, without its comment, comma, anchor, tag and quotes. */
64 const bare = (raw: string): string => {
65 const v = raw.trim().replace(/^(?:[&!]\S*\s+)+/, "");
66 return (v.startsWith("#") ? "" : v.replace(/\s#.*$/, "")).trim().replace(/,$/, "").trim().replace(/^["']|["']$/g, "");
67 };
68
69 const URL_PASSWORD = /([a-z][a-z0-9+.-]{0,30}:\/\/[^\s/:@"']{0,256}:)([^\s/@"']+)(@)/gi;
70 const URL_PARAM = /([?&;])([A-Za-z0-9_.-]+)=([^&;\s"']+)/g;
71
72 /** A line with a password inside a URL (`scheme://user:pass@host`, `?password=…`) replaced by MASK. */
73 export const maskUrl = (line: string): string =>
74 line
75 .replace(URL_PASSWORD, (all, head: string, pass: string, at: string) => (hiddenValue("password", pass) ? `${head}${MASK}${at}` : all))
76 .replace(URL_PARAM, (all, sep: string, name: string, value: string) => (secretKey(name) && hiddenValue(name, value) ? `${sep}${name}=${MASK}` : all));
77
78 const ASSIGN = /^(\s*(?:[#;!]+\s*)?(?:-\s+)?(?:export\s+)?["']?)([A-Za-z0-9_.-]+)(["']?\s*[:=]\s*)(.*)$/;
79 const INLINE = /([A-Za-z0-9_.-]{1,64})["']?\s{0,3}[:=]\s{0,3}/g;
80 const indentOf = (line: string): number => line.length - line.trimStart().length;
81
82 /** Where the value that starts at `from` ends, in a line of braces or brackets. */
83 function inlineEnd(line: string, from: number): number {
84 const q = line[from];
85 let depth = 0;
86 for (let i = q === '"' || q === "'" ? from + 1 : from; i < line.length; i++) {
87 const c = line[i]!;
88 if (q === '"' || q === "'") {
89 if (c === "\\" && q === '"') i++;
90 else if (c === q) return i + 1;
91 } else if (c === "[" || c === "{") depth++;
92 else if (c === "]" || c === "}") {
93 if (depth === 0) return i;
94 depth--;
95 } else if (c === "," && depth === 0) return i;
96 }
97 return line.length;
98 }
99
100 /** Told each secret in the clear, a text at a time: its key and the value as written. */
101 type Found = (key: string, value: string) => void;
102
103 /** Secrets written inside one line's braces or brackets: `db: { user: a, password: b }`. */
104 function inline(line: string, found: Found): string {
105 if (!/[{[]|"\s*,\s*"/.test(line)) return line;
106 let out = "";
107 let at = 0;
108 INLINE.lastIndex = 0;
109 for (let m = INLINE.exec(line); m !== null; m = INLINE.exec(line)) {
110 const from = m.index + m[0].length;
111 if (!secretKey(m[1]!)) continue;
112 // A map under a key for one secret is read key by key; its end is not looked for, or nested ones cost their square.
113 if (line[from] === "{" && !severalSecrets(m[1]!)) continue;
114 const end = inlineEnd(line, from);
115 const raw = line.slice(from, end);
116 if (/^[[{]/.test(raw) ? /[^\s[\]{},]/.test(raw) : hiddenValue(m[1]!, bare(raw))) {
117 if (/^[[{]/.test(raw) || literalSecret(m[1]!, bare(raw))) found(m[1]!, bare(raw));
118 out += line.slice(at, from) + MASK;
119 at = end;
120 }
121 INLINE.lastIndex = Math.max(end, from);
122 }
123 return out + line.slice(at);
124 }
125
126 /** What the lines after a secret's key are: until when, and whether they are its text whole. */
127 type Open = { readonly key: string; readonly indent: number; readonly until: "indent" | "]" | "}" | '"""' | "'''" | '"' | "'"; readonly whole: boolean };
128
129 const closes = (line: string, until: Open["until"]): boolean => (until === '"' ? /(?:^|[^\\])"/.test(line) : line.includes(until));
130
131 /** What follows a secret's key when its value goes on past the line. */
132 function opens(key: string, indent: number, raw: string): Open | undefined {
133 const v = raw.trim().replace(/^(?:[&!]\S*(?:\s+|$))+/, "");
134 const base = { key, indent };
135 if (/^[|>][0-9+-]*(?:\s+#.*)?$/.test(v)) return { ...base, until: "indent", whole: true };
136 if (v === "" || v.startsWith("#")) return { ...base, until: "indent", whole: false };
137 for (const q of ['"""', "'''", '"', "'"] as const)
138 if (v.startsWith(q)) return closes(v.slice(q.length), q) ? undefined : { ...base, until: q, whole: true };
139 if (v.startsWith("[") && !v.includes("]")) return { ...base, until: "]", whole: true };
140 if (v.startsWith("{") && !v.includes("}") && severalSecrets(key)) return { ...base, until: "}", whole: true };
141 return undefined;
142 }
143
144 /** Walk the text's lines: each one as it may be shown, and each secret's key as it is found. */
145 function scan(text: string, found: Found, placeholders: boolean): string[] {
146 let open: Open | undefined;
147 let table: string | undefined;
148 let pem = false;
149 return text.split("\n").map((line) => {
150 if (pem || PRIVATE_BLOCK.test(line)) {
151 pem = !/-----END [A-Z ]*PRIVATE KEY-----/.test(line);
152 return `${line.slice(0, indentOf(line))}${MASK}`;
153 }
154 if (open !== undefined) {
155 const o = open;
156 const hide = (value = line.trim()): string => {
157 if (o.whole || literalSecret(o.key, value)) found(o.key, value);
158 return `${line.slice(0, indentOf(line))}${/^\s*-\s/.test(line) ? "- " : ""}${MASK}`;
159 };
160 if (o.until !== "indent") {
161 if (closes(line, o.until)) open = undefined;
162 return /^[\s\]},]*$/.test(line) ? line : hide();
163 }
164 if (line.trim() === "") return line;
165 const item = /^\s*-(?:\s|$)/.test(line);
166 if (indentOf(line) > o.indent || (!o.whole && item && indentOf(line) === o.indent)) {
167 if (o.whole) return hide();
168 const child = ASSIGN.exec(line);
169 if (child === null) {
170 const v = bare(line.replace(/^\s*-\s*/, ""));
171 return hiddenValue(o.key, v) && !/^[\s\]},]*$/.test(line) ? hide(v) : line;
172 }
173 // A map under a key for one secret is read key by key.
174 if (severalSecrets(o.key) && !item && hiddenValue(o.key, bare(child[4]!))) return hide(bare(child[4]!));
175 } else open = undefined;
176 }
177 const t = line.trim();
178 const deep = t.startsWith("[[") ? 2 : 1;
179 if (t.startsWith("[") && t.endsWith("]") && /^[\w."' -]+$/.test(t.slice(deep, -deep))) {
180 const name = t.slice(deep, -deep).split(".").at(-1)!.replace(/["' ]/g, "");
181 table = severalSecrets(name) ? name : undefined;
182 return line;
183 }
184 const m = ASSIGN.exec(line);
185 const key = m === null ? undefined : secretKey(m[2]!) ? m[2]! : table;
186 if (m === null || key === undefined) return inline(maskUrl(line), found);
187 const raw = m[4]!;
188 // A commented-out value is hidden, and is no reason to refuse a text.
189 const note = /^\s*[#;!]/.test(line) ? () => {} : found;
190 const next = note === found ? opens(key, indentOf(line), raw) : undefined;
191 if (next !== undefined) {
192 open = next;
193 if (next.until === "indent") return line;
194 found(key, bare(raw));
195 return `${m[1]!}${m[2]!}${m[3]!}${MASK}`;
196 }
197 if (raw.startsWith("{") && !severalSecrets(key)) return inline(maskUrl(line), found);
198 const v = bare(raw);
199 const list = /^[[{]/.test(v);
200 if (list ? /[^\s[\]{},]/.test(v) : hiddenValue(key, v)) {
201 if (list || literalSecret(key, v)) note(key, v);
202 } else if (!(placeholders && PLACEHOLDER.test(v))) return inline(maskUrl(line), found);
203 return `${m[1]!}${m[2]!}${m[3]!}${MASK}`;
204 });
205 }
206
207 /** The text with each secret value replaced by MASK; `placeholders` hides `${NAME}` ones too (for a diff). */
208 export const hideSecrets = (text: string, placeholders = false): string => scan(text, () => {}, placeholders).join("\n");
209
210 /** The keys whose values are secrets written out in the text (a placeholder is not one). */
211 export function secretLiterals(text: string): string[] {
212 const keys = new Set<string>();
213 scan(text, (k) => keys.add(k), false);
214 return [...keys];
215 }
216
217 const CONFIG_FILE = /\.(?:jsonc?|ya?ml|toml|properties|ini|cfg|conf|env|tfvars)$|(?:^|\/)\.env[^/]*$/i;
218 const WHOLE_SECRET = /\.(?:pem|secret)$/i;
219
220 /**
221 * What looks like a secret in `after` and was not in `before`, by name, never by value: a config
222 * file's keys, or the file itself when it is a secret as a whole (`*.pem`, `*.secret`). Code is not
223 * asked: `password: string` is a type there.
224 */
225 export function addedSecrets(path: string, before: string, after: string): string[] {
226 const file = path.slice(path.lastIndexOf("/") + 1);
227 if (before === after) return [];
228 if (WHOLE_SECRET.test(path)) return after.trim() === "" ? [] : [file];
229 if (!CONFIG_FILE.test(path)) return [];
230 const all = (text: string): Map<string, string> => {
231 const out = new Map<string, string>();
232 scan(text, (k, v) => out.set(`${k}\0${v}`, k), false);
233 for (const l of text.split("\n")) if (maskUrl(l) !== l) out.set(`\0${l.trim()}`, "a password in a URL");
234 if (PRIVATE_BLOCK.test(text)) out.set("\0", "a private key");
235 return out;
236 };
237 const had = all(before);
238 return [...new Set([...all(after)].filter(([id]) => !had.has(id)).map(([, k]) => `${k} in ${file}`))];
239 }
src/crew/dispatch.ts +6 −2
@@ -158,7 +158,7 @@ import {
158158 type Pause,
159159 } from "./runner.ts";
160160 import { steerRun } from "./steer.ts";
161 import { STALE_AFTER_MS } from "../runs/lease.ts";
161 import { STALE_AFTER_MS, heldRuns } from "../runs/lease.ts";
162162 import { stoppedMark } from "../spawn/stopped.ts";
163163 import { abortAgentRun } from "./running.ts";
164164 import { background, during } from "../perf/jobs.ts";
@@ -1604,8 +1604,12 @@ export function interruptionBackoffMs(n: number): number {
16041604 * forge that fell and was back within the lease sees its runs lapse later.
16051605 */
16061606 export function requeueInterrupted(app: App): void {
1607 // A run this process holds is alive here: its lease looks lapsed only when this process's own
1608 // loop stalled (#17708, which made #17706 and #17707 for one issue). Its worker finishes or fails
1609 // it.
1610 const mine = heldRuns(app.db);
16071611 for (const run of listActive(app.db, "agent")) {
1608 if (run.state !== "running" || !leaseLapsed(run, STALE_AFTER_MS)) continue;
1612 if (run.state !== "running" || mine.has(run.id) || !leaseLapsed(run, STALE_AFTER_MS)) continue;
16091613 if (stoppedForMemory(app, run)) {
16101614 // The host stopped this forge for memory: the run is queued again once; a run stopped that
16111615 // way twice would only stop it again, so it fails with the reason.
src/fleet/columns.ts +5 −1
@@ -53,7 +53,10 @@ export function readSort(kind: FleetKind, text: string | null): Sort | undefined
5353 /** The sort as `?sort=` writes it. */
5454 export const sortText = (sort: Sort): string => `${sort.descending ? "-" : ""}${sort.key}`;
5555
56 /** The rows in the sort's order; a copy, the input is left alone. Ties keep their order. */
56 /**
57 * The rows in the sort's order; a copy, the input is left alone. Ties keep their order, and a cell
58 * that is empty or not known is last whichever way the sort runs.
59 */
5760 export function sortRows(rows: readonly FleetRow[], sort: Sort | undefined): FleetRow[] {
5861 const out = [...rows];
5962 if (sort === undefined) return out;
@@ -61,6 +64,7 @@ export function sortRows(rows: readonly FleetRow[], sort: Sort | undefined): Fle
6164 out.sort((a, b) => {
6265 const x = a[sort.key] ?? "";
6366 const y = b[sort.key] ?? "";
67 if (x === "" || y === "") return Number(x === "") - Number(y === "");
6468 const by =
6569 typeof x === "number" && typeof y === "number"
6670 ? x - y
src/flow/landing_line.ts +9 −1
@@ -9,6 +9,7 @@
99
1010 import type { Database } from "bun:sqlite";
1111 import { etaSays, landingEta } from "./landing_eta.ts";
12 import { noQueueLands } from "./next_actor.ts";
1213 import { median } from "./pipeline.ts";
1314
1415 const HOUR_MS = 3_600_000;
@@ -19,7 +20,10 @@ export interface LandingLine {
1920 readonly says: string;
2021 }
2122
22 /** The pull's estimate, or null when it is not an open, approved, unlanded pull. */
23 /**
24 * The pull's estimate, or null when it is not an open, approved, unlanded pull or no queue lands
25 * here.
26 */
2327 export function landingLine(
2428 db: Database,
2529 pull: { readonly id: string; readonly number: number; readonly state: string; readonly mergedAt: string | null },
@@ -28,6 +32,10 @@ export function landingLine(
2832 ): LandingLine | null {
2933 if (pull.state !== "open" || pull.mergedAt !== null) return null;
3034 // Open approved pulls, each by its latest approval with no changes-requested after it.
35 // No queue lands here, so there is no place in one to say: the pull's Next line says a person
36 // does (#16452).
37 const repo = db.query<{ autonomy: string; autonomyBy: string | null }, [string]>("SELECT autonomy, autonomy_by AS autonomyBy FROM repo WHERE id = ?1").get(repoId);
38 if (repo === null || noQueueLands(repo)) return null;
3139 const approved = db
3240 .query<{ id: string; number: number; at: string }, [string]>(
3341 `SELECT i.id AS id, i.number AS number, a.at AS at
src/flow/next_actor.ts +31 −5
@@ -25,6 +25,11 @@ export interface Next {
2525 * Set when a reviewer's asked-for changes on this head are the reason (the pane's own state too).
2626 */
2727 readonly changes?: true;
28 /**
29 * Set when it is ready and only a person's merge lands it (`personLands`): the pane still offers
30 * Merge.
31 */
32 readonly lands?: true;
2833 }
2934
3035 export interface NextInput {
@@ -45,6 +50,17 @@ export interface NextInput {
4550 readonly firstChange?: boolean;
4651 /** Who asked for changes on this head, and which review (`blockingReviewWords`). */
4752 readonly askedBy?: string | null;
53 /**
54 * No merge queue lands here: the repository's autonomy is not `autonomous` (or no one
55 * turned it on), so `land_admit.ts` answers `off` and a green pull waits for a person to
56 * land it (#16452). Unset reads as a queue that lands.
57 */
58 readonly personLands?: boolean;
59 }
60
61 /** No merge queue lands in this repository: `land_admit.ts` answers `off` (#16452). */
62 export function noQueueLands(repo: { readonly autonomy: string; readonly autonomyBy: string | null }): boolean {
63 return repo.autonomy !== "autonomous" || repo.autonomyBy === null;
4864 }
4965
5066 const WAITING = {
@@ -60,7 +76,10 @@ export function nextActor(i: NextInput): Next {
6076 if (i.conflicted) return { who: "builder", why: "it conflicts with its base" };
6177 if (i.changesRequested > 0 && i.firstChange === true && i.check !== "failed") {
6278 if (i.wall != null && i.wall.length > 0) return { who: "person", why: wallAsk(i.wall) };
63 if (i.check === "ok") return { who: "queue", why: "green, the app's first change: it lands" };
79 if (i.check === "ok")
80 return i.personLands === true
81 ? { who: "person", why: "green, the app's first change: a person lands it", lands: true }
82 : { who: "queue", why: "green, the app's first change: it lands" };
6483 return { who: "queue", why: WAITING[i.check] };
6584 }
6685 if (i.changesRequested > 0)
@@ -68,11 +87,17 @@ export function nextActor(i: NextInput): Next {
6887 if (i.check === "failed") return { who: "builder", why: "its check is red" };
6988 if (i.wall != null && i.wall.length > 0) return { who: "person", why: wallAsk(i.wall) };
7089 if (i.approvals > 0) {
71 if (i.check === "ok") return { who: "queue", why: "approved and green" };
90 if (i.check === "ok")
91 return i.personLands === true
92 ? { who: "person", why: "approved and green: a person lands it", lands: true }
93 : { who: "queue", why: "approved and green" };
7294 return { who: "queue", why: `approved, ${WAITING[i.check]}` };
7395 }
7496 if (i.reviewOff === true) {
75 if (i.check === "ok") return { who: "queue", why: "green, reviews are off: it lands" };
97 if (i.check === "ok")
98 return i.personLands === true
99 ? { who: "person", why: "green, reviews are off: a person lands it", lands: true }
100 : { who: "queue", why: "green, reviews are off: it lands" };
76101 return { who: "queue", why: i.check === "none" ? "no check yet" : WAITING[i.check] };
77102 }
78103 return {
@@ -96,8 +121,8 @@ export function nextOfPull(
96121 db: Database,
97122 pull: Pull,
98123 live: { readonly headOid: string; readonly conflicts: number },
99 /** The pull's repository; without one, reviews count as asked for. */
100 repo: Pick<Repo, "id" | "requireReview"> | undefined,
124 /** The pull's repository; without one, reviews count as asked for and a queue as landing. */
125 repo: Pick<Repo, "id" | "requireReview" | "autonomy" | "autonomyBy"> | undefined,
101126 /** The head's check, when the caller already read it for `live.headOid`. */
102127 known?: CheckSummary,
103128 ): Next | null {
@@ -115,6 +140,7 @@ export function nextOfPull(
115140 wall: wallWords(db, pull.id, live.headOid),
116141 askedBy: reviews.changesRequested > 0 ? blockingReviewWords(db, pull.id, live.headOid) : null,
117142 firstChange: reviews.changesRequested > 0 && repo !== undefined && isFirstChange(db, repo, pull),
143 personLands: repo !== undefined && noQueueLands(repo),
118144 },
119145 () => repo !== undefined && reviewsOff(db, repo),
120146 );
src/flow/pull_pane.ts +3 −1
@@ -132,6 +132,8 @@ export function paneOf(f: PaneFacts): Pane {
132132 };
133133 if (n === null) return { state: "waits", tone: undefined, sentence: "Waiting", verbs: [], evidence: [] };
134134 const green = c.state === "ok" ? "Green" : c.state === "cancelled" ? "Its check was cancelled" : "No check yet";
135 // Ready, and no queue lands it here (autonomy is off, #16452): the person merges.
136 if (n.lands === true) return { state: "ready", tone: "success", sentence: cap(n.why), verbs: ["merge", "close"], evidence: [] };
135137 if (n.who === "person") return { state: "decide", tone: "attn", sentence: cap(n.why), verbs: [], evidence: [] };
136138 if (n.who === "queue")
137139 return {
@@ -154,7 +156,7 @@ export function paneOf(f: PaneFacts): Pane {
154156 */
155157 export function pullPane(
156158 db: Database,
157 repo: Pick<Repo, "id" | "requireReview" | "defaultBranch">,
159 repo: Pick<Repo, "id" | "requireReview" | "defaultBranch" | "autonomy" | "autonomyBy">,
158160 pull: Pull,
159161 live: { readonly headOid: string; readonly conflicts: readonly string[] },
160162 now: Date = new Date(),
src/flow/waits_for.ts +1 −1
@@ -22,7 +22,7 @@ import { nextOfPull, type Next } from "./next_actor.ts";
2222 */
2323 export function pullWaitsFor(
2424 db: Database,
25 repo: Pick<Repo, "id" | "requireReview">,
25 repo: Pick<Repo, "id" | "requireReview" | "autonomy" | "autonomyBy">,
2626 pull: Pull,
2727 live: { readonly headOid: string; readonly conflicts: number },
2828 now: Date = new Date(),
src/games/boot.ts +10 −6
@@ -3,14 +3,17 @@
33 * with, where a pinned forge's is `cloud/machine.ts` `bootConfig`. What hardens it is the same as a
44 * forge's (no password or root login, updates, `harden.ts`); then a firewall that lets in only the
55 * game's port (25565/tcp; no SSH, as a forge has none), swap for the JVMs, Docker with its compose
6 * plugin (Ubuntu's own packages) keeping its data on the box's volume, and the agent (`agent.sh`) under systemd. The token
6 * plugin (Ubuntu's own packages) keeping its data on the box's volume, and the agent (`agent.sh`) under systemd. The agent
7 * is fetched from the forge (`fetch.sh`), not carried: it alone is over a cloud's limit on a boot config. Nothing after
8 * the fetch runs without it: it mounts the volume, and Docker installed before that would put new worlds on the root disk. The token
79 * is in one place only: `/opt/forge-game/agent.env`, mode 600, which the unit reads. The boot's is spent at
810 * the first sync: the box makes its own and keeps it there (`agent.sh`).
911 */
1012
1113 import agentScript from "./agent.sh" with { type: "text" };
14 import fetchScript from "./fetch.sh" with { type: "text" };
1215 import { hardenFiles } from "../cloud/harden.ts";
13 import { yamlString } from "../cloud/boot_ascii.ts";
16 import { NoBootConfig, yamlString } from "../cloud/boot_ascii.ts";
1417
1518 /** The Java port a game box opens to the world: Velocity's, in front of every backend. */
1619 export const GAME_PORT = 25565;
@@ -59,8 +62,8 @@ export const INSTALL =
5962
6063 /** The cloud-config for a game box whose volume is mounted at `dataDir`. */
6164 export function gameBootConfig(g: GameBoot, dataDir: string): string {
62 const url = new URL(g.forgeUrl);
63 if (url.protocol !== "https:" && url.hostname !== "127.0.0.1" && url.hostname !== "localhost") throw new Error("a game box answers to its forge over https");
65 const url = URL.canParse(g.forgeUrl) ? new URL(g.forgeUrl) : undefined;
66 if (url === undefined || (url.protocol !== "https:" && url.hostname !== "127.0.0.1" && url.hostname !== "localhost")) throw new NoBootConfig("a game box answers to its forge over https");
6467 if (!TOKEN.test(g.token)) throw new Error("that is not a game box token");
6568 if (!/^\/[A-Za-z0-9/_.-]+$/.test(dataDir)) throw new Error("the volume's mount is not a plain path");
6669 const env = `FORGE_URL=${url.origin}\nFORGE_GAME_TOKEN=${g.token}\nFORGE_GAME_DATA=${dataDir}\n`;
@@ -72,9 +75,9 @@ write_files:
7275 - path: ${GAME_DIR}/agent.env
7376 permissions: "0600"
7477 content: ${yamlString(env)}
75 - path: ${GAME_DIR}/agent.sh
78 - path: ${GAME_DIR}/fetch.sh
7679 permissions: "0755"
77 content: ${yamlString(AGENT_SH)}
80 content: ${yamlString(fetchScript)}
7881 - path: /etc/systemd/system/forge-game-agent.service
7982 permissions: "0644"
8083 content: ${yamlString(AGENT_UNIT)}
@@ -89,6 +92,7 @@ runcmd:
8992 - ufw allow ${BEDROCK_PORT}/udp
9093 - ufw --force enable
9194 - fallocate -l ${SWAP_GIB}G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile && echo '/swapfile none swap sw 0 0' >> /etc/fstab
95 - ${yamlString(`until bash ${GAME_DIR}/fetch.sh; do sleep 5; done`)}
9296 - ${yamlString(`bash ${GAME_DIR}/agent.sh --mount-volume`)}
9397 - mkdir -p ${dataDir}/docker
9498 - ${yamlString(INSTALL)}
src/games/compose.ts +15 −4
@@ -8,6 +8,7 @@
88 import type { App } from "../app.ts";
99 import { commitToBranch } from "../actions/repos.ts";
1010 import { canWrite, getRepo } from "../core/repos.ts";
11 import { secretKey } from "../core/secret_text.ts";
1112 import type { User } from "../core/users.ts";
1213 import { runGit } from "../git/env.ts";
1314 import { repoDir } from "../git/repos.ts";
@@ -28,6 +29,19 @@ export async function readCompose(app: App, box: GameBox): Promise<Compose | und
2829 return text === undefined ? undefined : { sha: sha.value.trim(), text };
2930 }
3031
32 /** The folder the compose file is in, with its trailing slash ("" at the repository's root). */
33 export function composeDir(box: Pick<GameBox, "path">): string {
34 return box.path.includes("/") ? box.path.slice(0, box.path.lastIndexOf("/") + 1) : "";
35 }
36
37 /** The commits at `sha` that changed the compose file, newest first (at most `limit`). */
38 export async function composeHistory(app: App, box: GameBox, sha: string, limit: number): Promise<string[]> {
39 const cwd = boxRepoDir(app, box);
40 if (cwd === undefined) return [];
41 const out = await runGit(["log", `-${String(limit)}`, "--format=%H", sha, "--", box.path], { cwd });
42 return out.ok ? out.value.split("\n").filter((l) => /^[0-9a-f]{40}$/.test(l)) : [];
43 }
44
3145 /** The box's compose repository on disk; undefined when it is gone. */
3246 function boxRepoDir(app: App, box: GameBox): string | undefined {
3347 const [owner = "", name = ""] = box.repo.split("/");
@@ -247,9 +261,6 @@ export function setTopEntry(text: string, section: string, name: string, block:
247261 return lines.join("\n");
248262 }
249263
250 /** A key that names a secret: it belongs in the sealed `.env` the forge writes, never in the repository. */
251 export const SECRET_KEY = /PASSWORD|SECRET|TOKEN|KEY/i;
252
253264 /** A file of the box's repository at `sha` (the compose file's commit); undefined when missing. */
254265 export async function readRepoFile(app: App, box: GameBox, sha: string, path: string): Promise<string | undefined> {
255266 const cwd = boxRepoDir(app, box);
@@ -266,7 +277,7 @@ export async function commitServiceEnv(
266277 service: string,
267278 values: Record<string, string | null>,
268279 ): Promise<{ ok: true; sha: string } | { ok: false; error: string }> {
269 const secret = Object.keys(values).find((k) => SECRET_KEY.test(k));
280 const secret = Object.keys(values).find((k) => secretKey(k));
270281 if (secret !== undefined)
271282 return {
272283 ok: false,
src/games/fetch.sh added +18
@@ -0,0 +1,18 @@
1 #!/bin/bash
2 # One try at fetching the game agent from the forge this box answers to: a cloud's boot config has a size
3 # limit that the agent is over. The boot repeats it until it works. A script whose sha256 is not the one
4 # the forge names is not kept. The token goes to curl in a file, never on a command line.
5 set -u
6 D="${FORGE_GAME_DIR:-/opt/forge-game}"
7 . "$D/agent.env"
8 umask 077
9 printf 'Authorization: Bearer %s\n' "$FORGE_GAME_TOKEN" >"$D/.fetch.auth"
10 code="$(curl -sS -m 60 -H "@$D/.fetch.auth" -D "$D/.fetch.head" -o "$D/agent.sh.fetched" -w '%{http_code}' "${FORGE_URL%/}/api/v1/games/agent/script")"
11 want="$(tr -d '\r' <"$D/.fetch.head" 2>/dev/null | sed -n 's/^[Xx]-[Aa]gent-[Ss]ha: //p' | tail -n 1)"
12 got="$(sha256sum "$D/agent.sh.fetched" 2>/dev/null | cut -d' ' -f1)"
13 if [ "$code" = 200 ] && [ -n "$want" ] && [ "$got" = "$want" ] && bash -n "$D/agent.sh.fetched"; then
14 chmod 755 "$D/agent.sh.fetched" && mv "$D/agent.sh.fetched" "$D/agent.sh" && rm -f "$D/.fetch.auth" "$D/.fetch.head" && exit 0
15 fi
16 rm -f "$D/.fetch.auth" "$D/.fetch.head" "$D/agent.sh.fetched"
17 echo "forge-game-fetch: HTTP ${code:-000}, no agent from the forge; nothing is mounted or installed until it answers" >&2
18 exit 1
src/games/gist.ts +9 −4
@@ -9,7 +9,7 @@ import type { Database } from "bun:sqlite";
99 import { isIP } from "node:net";
1010 import { isPublicAddress } from "../apps/egress.ts";
1111 import { peopleOf } from "./people.ts";
12 import type { GameService } from "./store.ts";
12 import { commandOf, type GameService } from "./store.ts";
1313
1414 const POWER = ["start", "stop", "restart", "recreate", "pull"] as const;
1515 type Power = (typeof POWER)[number];
@@ -30,13 +30,18 @@ function ago(iso: string, now: number): string {
3030 */
3131 export function powerNow(db: Database, boxId: string, service: string, now = Date.now()): string | undefined {
3232 const r = db
33 .query<{ kind: string; created_at: string; handed_at: string; done_at: string; ok: number | null; output: string }, [string, string]>(
34 "SELECT kind, created_at, handed_at, done_at, ok, output FROM game_command WHERE box_id = ?1 AND service = ?2 AND kind IN ('start', 'stop', 'restart', 'recreate', 'pull') ORDER BY created_at DESC LIMIT 1",
33 .query<{ id: string; kind: string; created_at: string; handed_at: string; done_at: string; ok: number | null; output: string }, [string, string]>(
34 "SELECT id, kind, created_at, handed_at, done_at, ok, output FROM game_command WHERE box_id = ?1 AND service = ?2 AND kind IN ('start', 'stop', 'restart', 'recreate', 'pull') ORDER BY created_at DESC LIMIT 1",
3535 )
3636 .get(boxId, service);
3737 if (r === null) return undefined;
3838 const kind = r.kind as Power;
39 if (r.done_at === "") return `${DOING[kind]}: asked ${ago(r.created_at, now)}${r.handed_at === "" ? "" : ", the server has it"}`;
39 if (r.done_at === "") {
40 // Whether the box answered is `commandOf`'s rule, so this line and the command's own row agree.
41 const c = commandOf(db, r.id, now);
42 const unanswered = c?.done === true && c.ok === null;
43 return `${DOING[kind]}: asked ${ago(r.created_at, now)}${r.handed_at === "" ? "" : unanswered ? ", no answer came back" : ", the server has it"}`;
44 }
4045 if (now - Date.parse(r.done_at) > 600_000) return undefined;
4146 return r.ok === 0 ? `${kind[0]!.toUpperCase()}${kind.slice(1)} failed${r.output === "" ? "" : `: ${r.output.split("\n")[0]}`}` : DID[kind];
4247 }
src/games/jars.ts added +37
@@ -0,0 +1,37 @@
1 /**
2 * Where plugin jars people uploaded are kept, and which of them a data directory lacks. A jar is
3 * a row in `game_jar` and a file under `<data>/games/jars`; the snapshot carries both, and a
4 * restore says which rows came back without their file.
5 */
6 import { Database } from "bun:sqlite";
7 import { existsSync, statSync } from "node:fs";
8 import { join } from "node:path";
9
10 /** Under the data directory, and under the same name in a snapshot. */
11 export const JARS_DIR = "games/jars";
12
13 /** The jars the database at `dataDir` names whose file is missing or of another size, in words. */
14 export function jarsMissing(dataDir: string): string[] {
15 let db: Database | undefined;
16 try {
17 db = new Database(join(dataDir, "forge.db"), { readonly: true });
18 // A database from before jars names none.
19 if (db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'game_jar'").get() === null) return [];
20 return db
21 .query<{ id: string; name: string; bytes: number; box: string | null }, []>(
22 "SELECT j.id AS id, j.name AS name, j.bytes AS bytes, b.name AS box FROM game_jar j LEFT JOIN game_box b ON b.id = j.box_id ORDER BY b.name, j.name, j.id",
23 )
24 .all()
25 .flatMap((j) => {
26 const file = join(dataDir, JARS_DIR, `${j.id}.jar`);
27 const of = `${j.name} (${j.box === null ? "a box that is gone" : `box ${j.box}`})`;
28 if (!existsSync(file)) return [`${of}: no file`];
29 const size = statSync(file).size;
30 return size === j.bytes ? [] : [`${of}: ${size} bytes, not ${j.bytes}`];
31 });
32 } catch (error) {
33 return [`the jars could not be checked: ${error instanceof Error ? error.message : String(error)}`];
34 } finally {
35 db?.close();
36 }
37 }
src/games/mods.ts +2 −3
@@ -18,7 +18,7 @@
1818
1919 import type { App } from "../app.ts";
2020 import type { User } from "../core/users.ts";
21 import { commitCompose, pluginUrls, readCompose, readRepoFile, serviceEnv, setServiceEnv } from "./compose.ts";
21 import { commitCompose, composeDir, pluginUrls, readCompose, readRepoFile, serviceEnv, setServiceEnv } from "./compose.ts";
2222 import { byVersion, latestRelease, newestPack, packUpdate, readPack, resolve, targetOf, updates, type Locked, type LockedPack, type Result, type Target, type Version } from "./modrinth.ts";
2323 import { AUTOSTOPPER } from "./sleep.ts";
2424 import type { GameBox } from "./store.ts";
@@ -54,8 +54,7 @@ export interface Plan {
5454
5555 /** The lockfile's path for a service, beside the compose file. */
5656 export function lockPath(box: GameBox, service: string): string {
57 const dir = box.path.includes("/") ? box.path.slice(0, box.path.lastIndexOf("/") + 1) : "";
58 return `${dir}modrinth/${service}.lock.json`;
57 return `${composeDir(box)}modrinth/${service}.lock.json`;
5958 }
6059
6160 const split = (v: string | undefined): string[] => (v ?? "").split(/[\s,]+/).filter(Boolean);
src/games/plugin_config.ts added +320
@@ -0,0 +1,320 @@
1 /**
2 * A game server's plugin config files (forge games, #17699): the files are the truth, and the truth
3 * is the network's repository. Each file is a top-level `configs:` entry of the compose file the
4 * box already follows (`content:` inline), mounted into the service where its image copies from at
5 * start: `/plugins/<Plugin>/…` for a server image (the image copies `/plugins` to `/data/plugins`),
6 * `/config/plugins/<Plugin>/…` for the proxy image (it copies `/config` to `/server`), `/config/…`
7 * for a mod's. The forge already ships its Paper seeds and AutoStopper's config this way
8 * (`settings.ts`, `sleep.ts`), so no new way to write into a container and nothing new for the box
9 * to fetch. The reasons it is not a folder beside the compose file: that needs the box's agent to
10 * fetch it, and a large file is the one thing this costs the compose file a person reads.
11 *
12 * The repository wins: with SYNC_SKIP_NEWER_IN_DESTINATION=false (server images) the image replaces
13 * the server's copy of a file whenever the two differ, at every start, also after a crash. Nothing
14 * is replaced unseen: a change is previewed with its diff, the restart, and who is online. A file
15 * only the box has is left alone, and the copy deletes nothing, so a file removed here stays on the
16 * server. What the box holds is not read back yet (the agent sends no files), so no drift is shown.
17 *
18 * Compose does not recreate a container for changed `content:` (measured, `sleep.ts`), and does
19 * for a changed environment or label (the label is expected from how compose hashes a service, and
20 * not yet tried on a box), so each commit also sets the service's `forge.config` label to a hash of
21 * its files. Compose reads `${…}` inside `content:` itself: a literal `$` is written `$$`, and a
22 * `${CFG_NAME}` placeholder (the image fills it from the container's environment while copying)
23 * is written `$${CFG_NAME}`, so compose leaves it be.
24 *
25 * A secret is never shown and never committed: a key that names one (`api-key`, `dbPassword`), a
26 * file that is one (`forwarding.secret`, a private key block) is refused with where it belongs
27 * instead. The box's copy holds a filled placeholder, so what the box sends back is hidden alike.
28 *
29 * Replaceable by deletion: a file is named `{repo, branch, path, at}` (the compose file and a
30 * pointer into it, never a path on the box), the one lookup of mounts is `configMounts`, a commit
31 * goes through `commitCompose` with `expectTip`, and a plugin has one place to configure it.
32 */
33
34 import type { App } from "../app.ts";
35 import { hideSecrets, MASK, maskUrl, PRIVATE_BLOCK, secretKey, secretLiterals } from "../core/secret_text.ts";
36 import type { User } from "../core/users.ts";
37 import { lineDiff, type DiffLine } from "../web/render/json-doc.ts";
38 import { commitCompose, composeHistory, readCompose, readRepoFile, setServiceEnv, setServiceLabels, setServiceListItem, setTopEntry } from "./compose.ts";
39 import type { Result } from "./modrinth.ts";
40 import { peopleOf } from "./people.ts";
41 import type { GameBox } from "./store.ts";
42
43 /** Where a file lives: the compose file and a pointer into it. */
44 export interface ConfigRef {
45 readonly repo: string;
46 readonly branch: string;
47 /** The compose file's path in the repository. */
48 readonly path: string;
49 /** Where in it: `configs.<name>.content`. */
50 readonly at: string;
51 }
52
53 export interface ConfigFile {
54 /** Relative to the server's root: plugins/Hub/config.yml. */
55 readonly file: string;
56 /** The plugin it belongs to (the folder under plugins/), or "config". */
57 readonly plugin: string;
58 readonly ref: ConfigRef;
59 /** The repository's text with secret values hidden. */
60 readonly text: string;
61 }
62
63 /** A change, previewed. */
64 export interface ConfigPlan {
65 readonly file: string;
66 readonly lines: readonly string[];
67 readonly diff: readonly DiffLine[];
68 /** One sentence: that the server restarts, and who is on it. */
69 readonly restart: string;
70 /** The commit it was previewed on: it commits on that or not at all. */
71 readonly sha: string;
72 readonly message: string;
73 readonly done: string;
74 /** The file's new text; null removes it. */
75 readonly content: string | null;
76 }
77
78 /** A mount the forge wrote: a config file of a service, read out of the compose text. */
79 export interface ConfigMount {
80 readonly name: string;
81 readonly file: string;
82 readonly target: string;
83 readonly content: string;
84 }
85
86 export const MAX_BYTES = 64 * 1024;
87 const BIG_LINES = 150;
88 const SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9 _.+-]{0,63}$/;
89 const EXTENSION = /\.(ya?ml|json|properties|toml|conf|cfg|txt)$/i;
90 /** The Paper files `settings.ts` owns. */
91 const SETTINGS_OWN = new Set(["config/paper-global.yml", "config/paper-world-defaults.yml"]);
92
93 /**
94 * Why `file` is no config file of a server (relative to its root: plugins/Hub/config.yml);
95 * undefined when it is one.
96 */
97 export function fileProblem(file: string): string | undefined {
98 const parts = file.split("/");
99 if (parts.length < 2 || parts.length > 8 || (parts[0] !== "plugins" && parts[0] !== "config"))
100 return "A config file is under plugins/<Plugin>/ or config/, for example plugins/Hub/config.yml.";
101 if (!parts.every((p) => SEGMENT.test(p) && !p.includes("..")))
102 return "A config file's path is plain names: letters, digits, spaces and _ . + - only, no .. and none starting with a dot.";
103 if (!EXTENSION.test(file)) return "A config file ends in .yml, .yaml, .json, .properties, .toml, .conf, .cfg or .txt.";
104 if (SETTINGS_OWN.has(file)) return `${file} is Paper's, and is changed with the server's settings.`;
105 return undefined;
106 }
107
108 const pluginOf = (file: string): string => (file.startsWith("plugins/") ? file.split("/")[1]! : "config");
109
110 // ---- secrets ----
111
112 /** Whether the file as a whole is a secret, by its name or its text. */
113 export const secretFile = (file: string, text: string): boolean => secretKey(file.slice(file.lastIndexOf("/") + 1)) || PRIVATE_BLOCK.test(text);
114
115 const WHERE = "the image fills a `${CFG_NAME}` placeholder from the server's environment at start; the value belongs in the box's sealed .env, named in the file and never written in it";
116
117 /** The lines (from 1) that carry a password inside a URL, under any key. */
118 const urlSecretLines = (text: string): number[] => text.split("\n").flatMap((l, n) => (maskUrl(l) === l ? [] : [n + 1]));
119
120 /** Why `text` may not be committed as `file`; undefined when it may. */
121 function textProblem(file: string, text: string): string | undefined {
122 // The image fills only `${CFG_…}`: another placeholder would reach the plugin as written.
123 const strict = text.replace(/\$\{(?!CFG_[A-Za-z0-9_]+\})/g, "$.{");
124 if (text.includes("\0")) return "A config file is text; this one has a NUL byte.";
125 if (new TextEncoder().encode(text).length > MAX_BYTES)
126 return `A config file here is at most ${String(MAX_BYTES / 1024)} KiB, because it lives in the compose file a person reads.`;
127 if (text.includes(MASK))
128 return `This text still has ${MASK} where a secret was hidden; committing it would write that over the real value. Put a \${CFG_NAME} placeholder there.`;
129 if (secretFile(file, text)) return `${file} is a secret as a whole, and the repository is no place for one: keep it on the box (a secret file is named in git, never held there).`;
130 const keys = secretLiterals(strict);
131 if (keys.length > 0)
132 return `${keys.join(", ")} looks like a secret, and the repository is no place for one. Write \${CFG_${keys[0]!.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}} in the file: ${WHERE}.`;
133 const urls = urlSecretLines(strict);
134 if (urls.length > 0)
135 return `Line ${urls.slice(0, 3).join(", ")} has a password or token inside a URL (scheme://user:pass@host, ?password=…), and the repository is no place for one. Write \${CFG_NAME} there: ${WHERE}.`;
136 return undefined;
137 }
138
139 // ---- the compose text: the one place mounts are read and written ----
140
141 const isProxy = (image: string): boolean => /mc-proxy|bungeecord|velocity/i.test(image);
142
143 /** Where a file is mounted in a service: what its image copies from at start. */
144 const targetOf = (file: string, proxy: boolean): string => (proxy ? `/config/${file}` : `/${file}`);
145 const fileOf = (target: string, proxy: boolean): string => (proxy ? target.replace(/^\/config\//, "") : target.slice(1));
146
147 const owned = (service: string): string => `${service.replace(/[^A-Za-z0-9_]/g, "_")}_cfg_`;
148 const hash = (text: string, n = 64): string => new Bun.CryptoHasher("sha256").update(text).digest("hex").slice(0, n);
149 /** A config's name in the compose file: unique to its service and file. */
150 const nameOf = (service: string, file: string): string => `${owned(service)}${file.replace(/[^A-Za-z0-9]+/g, "_").toLowerCase().slice(0, 40)}_${hash(file, 6)}`;
151
152 interface Doc {
153 services?: Record<string, { image?: unknown; configs?: unknown }>;
154 configs?: Record<string, { content?: unknown }>;
155 }
156
157 function parse(text: string): Doc {
158 try {
159 return (Bun.YAML.parse(text) as Doc | null) ?? {};
160 } catch {
161 return {};
162 }
163 }
164
165 /** The config files of a service the forge wrote into its compose text, as mounted. Pure. */
166 export function configMounts(text: string, service: string): ConfigMount[] {
167 const doc = parse(text);
168 const proxy = isProxy(String(doc.services?.[service]?.image ?? ""));
169 const mounts = doc.services?.[service]?.configs;
170 if (!Array.isArray(mounts)) return [];
171 const out: ConfigMount[] = [];
172 for (const m of mounts) {
173 if (m === null || typeof m !== "object") continue;
174 const { source, target } = m as { source?: unknown; target?: unknown };
175 if (typeof source !== "string" || typeof target !== "string" || !source.startsWith(owned(service))) continue;
176 const content = doc.configs?.[source]?.content;
177 const file = fileOf(target, proxy);
178 if (typeof content === "string" && fileProblem(file) === undefined) out.push({ name: source, file, target, content: content.replaceAll("$$", "$") });
179 }
180 return out.sort((a, b) => a.file.localeCompare(b.file));
181 }
182
183 /** A hash of a service's config files: the label that makes compose recreate the container. */
184 export const configHash = (mounts: readonly ConfigMount[]): string => hash(mounts.map((m) => `${m.file}\0${m.content}`).join("\0\0"), 16);
185
186 /** A `content:` block's lines: literal, its newline kept as the text has it. */
187 function block(content: string): string[] {
188 const body = content.replaceAll("$", "$$$$").replace(/\n$/, "").split("\n");
189 const first = body.find((l) => l.trim() !== "") ?? "";
190 const keep = content.endsWith("\n") ? "" : "-";
191 return ["# Written by the forge's plugin config editor.", `content: |${/^\s/.test(first) ? "2" : ""}${keep}`, ...body.map((l) => ` ${l}`)];
192 }
193
194 /**
195 * The compose text with `file` of `service` set to `content` (null removes it), its label and env
196 * following.
197 */
198 export function withConfig(text: string, service: string, file: string, content: string | null): string {
199 const image = String(parse(text).services?.[service]?.image ?? "");
200 const proxy = isProxy(image);
201 const name = nameOf(service, file);
202 let out = setTopEntry(text, "configs", name, content === null ? null : block(content));
203 out = setServiceListItem(out, service, "configs", `source: ${name}`, content === null ? null : [`- source: ${name}`, ` target: ${targetOf(file, proxy)}`]);
204 const mounts = configMounts(out, service);
205 out = setServiceLabels(out, service, { "forge.config": mounts.length === 0 ? null : configHash(mounts) });
206 if (mounts.length > 0)
207 out = setServiceEnv(out, service, { REPLACE_ENV_VARIABLES: "true", ...(proxy ? {} : { SYNC_SKIP_NEWER_IN_DESTINATION: "false" }) });
208 // The edit is textual; the file must still say what was meant, or nothing is committed.
209 const placed = configMounts(out, service).find((m) => m.file === file);
210 if (content === null ? placed !== undefined : placed?.content !== content) throw new Error(`${file} could not be placed in the compose file; nothing was committed.`);
211 return out;
212 }
213
214 // ---- reading ----
215
216 /** A plugin's files together: one place to configure it. */
217 export interface PluginConfigs {
218 readonly plugin: string;
219 readonly files: readonly ConfigFile[];
220 }
221
222 /**
223 * A service's config files as the compose file holds them at the branch's tip, grouped by plugin.
224 * Secret values are hidden in every text.
225 */
226 export async function configsOf(app: App, box: GameBox, service: string): Promise<Result<{ sha: string; plugins: PluginConfigs[] }>> {
227 const compose = await readCompose(app, box);
228 if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` };
229 const files: ConfigFile[] = configMounts(compose.text, service).map((m) => ({
230 file: m.file,
231 plugin: pluginOf(m.file),
232 ref: { repo: box.repo, branch: box.branch, path: box.path, at: `configs.${m.name}.content` },
233 text: hideSecrets(m.content),
234 }));
235 const plugins = [...new Set(files.map((f) => f.plugin))].sort().map((plugin) => ({ plugin, files: files.filter((f) => f.plugin === plugin) }));
236 return { ok: true, value: { sha: compose.sha, plugins } };
237 }
238
239 // ---- planning and committing ----
240
241 const count = (n: number, one: string, many: string): string => `${String(n)} ${n === 1 ? one : many}`;
242
243 /** The sentence before a commit: the server restarts to read the file, and who is on it. */
244 export function restartWords(app: App, box: GameBox, service: string): string {
245 const { online } = peopleOf(app.db, box.id, service);
246 const who =
247 online.length === 0
248 ? "nobody is online"
249 : `${count(online.length, "player is", "players are")} online (${online.slice(0, 5).map((p) => p.name).join(", ")}${online.length > 5 ? ", …" : ""}) and will be disconnected`;
250 return `${service} should restart on the box's next check-in to read it (the image copies config only at start); ${who}.`;
251 }
252
253 /**
254 * Preview `content` (null removes the file) as `file` on a service: the diff, the restart, who is
255 * online, and the refusal when a secret is in it.
256 */
257 export async function planConfig(app: App, box: GameBox, service: string, file: string, content: string | null): Promise<Result<ConfigPlan>> {
258 const text = content === null ? null : content.replaceAll("\r\n", "\n").replace(/\n*$/, "\n");
259 const bad = fileProblem(file) ?? (text === null ? undefined : textProblem(file, text));
260 if (bad !== undefined) return { ok: false, error: bad };
261 const compose = await readCompose(app, box);
262 if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` };
263 const before = configMounts(compose.text, service).find((m) => m.file === file)?.content;
264 if (before === undefined && text === null) return { ok: false, error: `${file} is not in the repository; there is nothing to remove.` };
265 if (before === text) return { ok: false, error: `${file} already says that.` };
266 try {
267 withConfig(compose.text, service, file, text);
268 } catch (e) {
269 return { ok: false, error: e instanceof Error ? e.message : String(e) };
270 }
271 const diff = lineDiff(hideSecrets(before ?? "", true), hideSecrets(text ?? "", true));
272 const added = diff.filter((l) => l.op === "+").length;
273 const removed = diff.filter((l) => l.op === "-").length;
274 const lines = [
275 text === null
276 ? `Removes ${file} from the repository (${count(removed, "line", "lines")})`
277 : before === undefined
278 ? `Adds ${file} to the repository (${count(added, "line", "lines")}), in the compose file under configs:`
279 : `Changes ${file}: ${count(added, "line", "lines")} added, ${count(removed, "line", "lines")} removed`,
280 `Mounted in ${service} where its image copies from at start; the repository's file wins over the server's copy`,
281 "Compose does not recreate a container for changed file text, so the commit also changes the label forge.config, which should make compose recreate it",
282 ];
283 if (text !== null && text.split("\n").length > BIG_LINES) lines.push(`This file is ${count(text.split("\n").length, "line", "lines")} of the compose file a person reads`);
284 if (text !== null && /\$\{CFG_/.test(text)) lines.push("A ${CFG_…} placeholder is filled from the server's environment at start; its value is not in this file");
285 if (text === null) lines.push("The image deletes nothing: the server keeps its copy of the file until it is removed there");
286 lines.push("A revert of the commit puts the file back as it was");
287 const message = `games: ${service} config: ${text === null ? "remove" : before === undefined ? "add" : "change"} ${file}`;
288 return { ok: true, value: { file, lines, diff, restart: restartWords(app, box, service), sha: compose.sha, message, done: `${file} is saved`, content: text } };
289 }
290
291 /**
292 * The plan that undoes the file's last change: its text as it was before, from the compose file's
293 * history.
294 */
295 export async function planRevertConfig(app: App, box: GameBox, service: string, file: string): Promise<Result<ConfigPlan>> {
296 const bad = fileProblem(file);
297 if (bad !== undefined) return { ok: false, error: bad };
298 const compose = await readCompose(app, box);
299 if (compose === undefined) return { ok: false, error: `No ${box.path} on ${box.repo}@${box.branch}.` };
300 const now = configMounts(compose.text, service).find((m) => m.file === file)?.content;
301 for (const c of await composeHistory(app, box, compose.sha, 40)) {
302 const old = await readRepoFile(app, box, c, box.path);
303 const was = old === undefined ? undefined : configMounts(old, service).find((m) => m.file === file)?.content;
304 if (was === now) continue;
305 const planned = await planConfig(app, box, service, file, was ?? null);
306 return planned.ok ? { ok: true, value: { ...planned.value, message: `games: ${service} config: revert ${file}` } } : planned;
307 }
308 return { ok: false, error: `${file} has no earlier version to go back to.` };
309 }
310
311 /** Commit a plan on the commit it was planned on. */
312 export async function commitConfig(app: App, user: User, box: GameBox, service: string, plan: ConfigPlan): Promise<Result<string>> {
313 const done = await commitCompose(app, user, box, {
314 message: plan.message,
315 what: `${service} config`,
316 edit: (text) => withConfig(text, service, plan.file, plan.content),
317 expectTip: plan.sha,
318 });
319 return done.ok ? { ok: true, value: done.sha } : done;
320 }
src/games/store.ts +27 −1
@@ -8,6 +8,7 @@
88 */
99
1010 import type { Database } from "bun:sqlite";
11 import { JARS_DIR } from "./jars.ts";
1112 import { COMPOSE_AT, sameFile, type ComposeFile } from "./compose_file.ts";
1213 import { keptDiag, readDiag, type Diag } from "./diag.ts";
1314 import { outcomeOf } from "./outcome.ts";
@@ -281,7 +282,32 @@ export function seesBox(db: Database, user: User | undefined, boxId: string): bo
281282 return db.query("SELECT 1 FROM game_grant WHERE box_id = ?1 AND user_id = ?2").get(boxId, user.id) !== null;
282283 }
283284
285 /** How long who holds a grant is believed: another process's grant shows within this. */
286 export const PLAYERS_MS = 30_000;
287 /** Everyone with a grant on any box, per database; `grant`, the one writer, drops it. */
288 const players = new WeakMap<Database, { readonly at: number; readonly ids: ReadonlySet<string> }>();
289
290 /**
291 * Whether `user` may see any game box: a forge admin, or anyone with a grant. The top bar asks on
292 * every page, so it is one read per {@link PLAYERS_MS}, never one a page.
293 */
294 export function seesAnyBox(db: Database, user: User | undefined, now = Date.now()): boolean {
295 if (user === undefined) return false;
296 if (user.isAdmin) return true;
297 let held = players.get(db);
298 if (held === undefined || now - held.at >= PLAYERS_MS) {
299 const rows = db.query<{ user_id: string }, []>("SELECT DISTINCT user_id FROM game_grant").all();
300 held = { at: now, ids: new Set(rows.map((r) => r.user_id)) };
301 players.set(db, held);
302 }
303 return held.ids.has(user.id);
304 }
305
306 /** A person here for a game box alone: a grant, no repository of their own (`owns` counts them), not an admin. */
307 export const herePlaying = (db: Database, user: User | undefined, owns: () => number): boolean => user?.isAdmin === false && seesAnyBox(db, user) && owns() === 0;
308
284309 export function grant(db: Database, boxId: string, userId: string, role: Role | "none", service = ""): void {
310 players.delete(db);
285311 if (role === "none") db.query("DELETE FROM game_grant WHERE box_id = ?1 AND user_id = ?2 AND service = ?3").run(boxId, userId, service);
286312 else
287313 db.query(
@@ -453,7 +479,7 @@ export function envFiles(app: App, box: GameBox, compose: string, services: read
453479 export const JAR_URL_MS = 6 * 3_600_000;
454480
455481 export function jarPath(app: App, jarId: string): string {
456 return `${app.config.dataDir}/games/jars/${jarId}.jar`;
482 return `${app.config.dataDir}/${JARS_DIR}/${jarId}.jar`;
457483 }
458484
459485 /** What one box keeps: jars, and their bytes together; one jar is at most `JAR_MAX_BYTES`. */
src/http/api.ts +7 −3
@@ -242,6 +242,7 @@ import { isCrew, type Agent } from "../core/agents.ts";
242242 import { listApps, type AppRecord } from "../core/apps.ts";
243243 import {
244244 checksForHead,
245 checkSummaryOf,
245246 getRun,
246247 isTerminal,
247248 RUN_STATES,
@@ -3670,19 +3671,22 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
36703671 const oid = await pullHeadOid(ctx, found.repo, found.pull);
36713672 return { head: oid, runs: checksForHead(ctx.app.db, found.pull.id, oid) };
36723673 });
3673 const latest = runs[0];
3674 // The rule merging uses (`verdictForHead`): a failed or running check at the head is never
3675 // hidden by a deploy that ended after it (#17705). `runs` keeps every run.
3676 const summary = checkSummaryOf(runs);
3677 const latest = summary.run ?? undefined;
36743678 // With no run, the reason: a bare "none" does not say whether to wait, approve or add a
36753679 // check.
36763680 const why = latest === undefined ? await whyNoCheck(ctx.app, found.repo, found.pull, head) : undefined;
36773681 // `?format=text`: three plain lines, the URL a contribute push prints.
36783682 if (ctx.url.searchParams.get("format") === "text")
3679 return new Response(`state: ${latest?.state ?? "none"}\nhead: ${head}\nrequired: ${found.repo.requireChecks ? "yes" : "no"}\n${why === undefined ? "" : `why: ${why}\n`}`, {
3683 return new Response(`state: ${summary.state}\nhead: ${head}\nrequired: ${found.repo.requireChecks ? "yes" : "no"}\n${why === undefined ? "" : `why: ${why}\n`}`, {
36803684 headers: { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" },
36813685 });
36823686 return timePhase(ctx.request, "render", () =>
36833687 json({
36843688 head,
3685 state: latest?.state ?? "none",
3689 state: summary.state,
36863690 required: found.repo.requireChecks,
36873691 ...(why === undefined ? {} : { why }),
36883692 run: latest ?? null,
src/http/api/admin.ts +1 −1
@@ -144,7 +144,7 @@ export function adminRoutes(router: Router<Handler>): void {
144144 return json({ ...seen.value, ...(plan === null ? {} : { build: buildOf(ctx.app, ctx.auth.user, plan) ?? null }) });
145145 });
146146
147 // infra.json in each app's repo against what runs (#17075): what applying it would change.
147 // infra.json in each app's repo against what the forge recorded (#17075): what applying it would change.
148148 // Read-only.
149149 router.add("GET", "/api/v1/admin/infra/code", async (ctx) => {
150150 const denied = accountAdmin(ctx, "ro");
src/http/check_text.ts +11 −3
@@ -1,8 +1,10 @@
11 /**
22 * GET /:owner/:name/pulls/:number/check.txt — a pull's latest check as plain
33 * text, for a script or an agent. Line 1 is pending, green or red; line 2 is
4 * `head: <oid>`; on red, a blank line and the last 80 lines of the log, but
5 * only when the log door (`runLog`) would show that reader the log.
4 * `head: <oid>`; on red, a blank line, what failed (`logs/findings.ts`: each
5 * failing test with the end of its own output), a blank line, and the last 80
6 * lines of the log, but only when the log door (`runLog`) would show that
7 * reader the log.
68 *
79 * `?wait=S` (S in 1..120) holds the request until the latest check's verdict
810 * differs from the one it began with, or S seconds pass, then answers the same
@@ -16,6 +18,7 @@
1618 import { getRepoRun, runLog } from "../actions/runs.ts";
1719 import { restoreRunLog } from "../runs/archive.ts";
1820 import { readRunLogTail } from "../runs/log.ts";
21 import { findingsOf } from "../logs/findings.ts";
1922 import { checkSummary } from "../core/runs.ts";
2023 import { loadPull } from "./api.ts";
2124 import type { Ctx } from "./context.ts";
@@ -162,7 +165,12 @@ async function tailRead(
162165 const log = await runLog(ctx.app, ctx.auth.user, v.repo, run.id, TAIL_MAX);
163166 lines = log.ok && !log.value.logHidden ? log.value.lines : [];
164167 }
165 return lines.slice(-TAIL_MAX);
168 if (lines.length === 0) return [];
169 const tail = lines.slice(-TAIL_MAX);
170 // What failed first: the tail is often the tally or a teardown, far below it. One the tail
171 // already shows with nothing to add is not said twice.
172 const why = findingsOf(run, tail).filter((f) => f.detail.length > 0 || !tail.some((l) => l.trim() === f.says));
173 return why.length === 0 ? tail : [...why.flatMap((f) => [f.says, ...f.detail]), "", ...tail];
166174 }
167175
168176 async function read(ctx: Ctx): Promise<(Reading & { pullId: string }) | Response> {
src/http/games_routes.ts +4
@@ -20,6 +20,7 @@ import { BODY_CAPS } from "../kernel/body_caps.ts";
2020 import {
2121 gameBoxPage, gameCommandSubmit, gameCrashShare, gameEnvSubmit, gameGrantSubmit, gameLendSubmit, gameServersSubmit, gameJarDownload, gameJarSubmit, gameModInstall, gameModPack, gameModRemove, gameModUpdate, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage,
2222 } from "../web/pages/games.ts";
23 import { gameConfigCommit, gameConfigPage, gameConfigPreview } from "../web/pages/games_config.ts";
2324 import type { Ctx, Handler } from "./context.ts";
2425 import { InvalidJson } from "./json_body.ts";
2526 import { apiError, boundedMachineBody, json } from "./respond.ts";
@@ -127,6 +128,9 @@ export function gamesRoutes(router: Router<Handler>): void {
127128 router.add("POST", "/games/:box/:service/mods/update", gameModUpdate);
128129 router.add("POST", "/games/:box/:service/mods/remove", gameModRemove);
129130 router.add("POST", "/games/:box/:service/mods/pack", gameModPack);
131 router.add("GET", "/games/:box/:service/config", gameConfigPage);
132 router.add("POST", "/games/:box/:service/config/preview", gameConfigPreview);
133 router.add("POST", "/games/:box/:service/config/commit", gameConfigCommit);
130134 router.add("POST", "/games/:box/:service/sleep", gameSleepSubmit);
131135 router.add("POST", "/games/:box/:service/people", gamePeopleSubmit);
132136 router.add("POST", "/games/:box/:service/world", gameWorldSubmit);
src/http/infra_routes.ts +14 −9
@@ -40,16 +40,20 @@ const composeOf = (get: (k: string) => string): ComposeState => ({
4040 q: get("q").slice(0, 80),
4141 });
4242
43 /** A first visit's compose: the first app that can run, the cheapest place, a new question, a week. */
44 function firstCompose(c: ComposeChoices): ComposeState {
45 const app = c.apps.find((a) => a.why === "")?.app ?? "";
43 /**
44 * A first visit's compose: the first app that can run, the cheapest place, a new question, a week.
45 * From an app's own page (`?app=owner/name`): that app, run for itself, with no end.
46 */
47 function firstCompose(c: ComposeChoices, asked = ""): ComposeState {
48 const named = c.apps.find((a) => a.app === asked)?.app;
49 const app = named ?? c.apps.find((a) => a.why === "")?.app ?? "";
4650 return {
4751 app,
4852 where: c.places.find((p) => p.orderable)?.value ?? "",
49 why: "question",
53 why: named === undefined ? "question" : "app",
5054 experiment: c.experiments[0]?.id ?? "",
5155 question: "",
52 days: String(c.defaultDays),
56 days: named === undefined ? String(c.defaultDays) : "none",
5357 name: nameFor(app),
5458 };
5559 }
@@ -91,7 +95,7 @@ function infraResource(ctx: Ctx): Response {
9195 async function render(
9296 ctx: Ctx,
9397 s: ComposeState | undefined,
94 o: { planId?: string; flash?: { tone: "danger" | "attn"; message: string } },
98 o: { planId?: string; app?: string; flash?: { tone: "danger" | "attn"; message: string } },
9599 status = 200,
96100 ): Promise<Response> {
97101 const user = ctx.auth.user;
@@ -102,7 +106,7 @@ async function render(
102106 let compose = html``;
103107 if (build === undefined) {
104108 const choices = timePhase(ctx.request, "choices", () => composeChoices(ctx.app));
105 const state = s ?? firstCompose(choices);
109 const state = s ?? firstCompose(choices, o.app);
106110 const planned = await timePhaseAsync(ctx.request, "plan", () => planCompose(ctx.app, user, state, choices));
107111 if (!planned.ok) return notFoundPage(ctx);
108112 compose = composeForm(choices, state, planTray(planned.value), domainOf(ctx.app));
@@ -141,12 +145,13 @@ function infraGet(ctx: Ctx): Response {
141145 return page({ ctx, title: "All clouds · Infrastructure", wide: true, scriptJs: SCRIPT, styleCss: INFRA_CSS, body: resourcesPage(tree, [], pane), noDock: true });
142146 }
143147
144 // GET /infra/build, and /infra/build?plan=<id> for a build's progress.
148 // GET /infra/build, /infra/build?app=owner/name from an app's page, and ?plan=<id> for a build's
149 // progress.
145150 function infraBuild(ctx: Ctx): Promise<Response> | Response {
146151 const denied = guard(ctx);
147152 if (denied) return denied;
148153 const planId = ctx.url.searchParams.get("plan") ?? undefined;
149 return render(ctx, undefined, planId === undefined ? {} : { planId });
154 return render(ctx, undefined, planId === undefined ? { app: ctx.url.searchParams.get("app") ?? "" } : { planId });
150155 }
151156
152157 // GET /infra/live?part=running | ?plan=<id>: a live region alone, refetched on an event.
src/http/lazy_lists.ts +3
@@ -640,6 +640,9 @@ export const OPERATIONS_ROUTES = [
640640 ["POST", "/games/:box/:service/mods/update"],
641641 ["POST", "/games/:box/:service/mods/remove"],
642642 ["POST", "/games/:box/:service/mods/pack"],
643 ["GET", "/games/:box/:service/config"],
644 ["POST", "/games/:box/:service/config/preview"],
645 ["POST", "/games/:box/:service/config/commit"],
643646 ["POST", "/games/:box/:service/sleep"],
644647 ["POST", "/games/:box/:service/people"],
645648 ["POST", "/games/:box/:service/world"],
src/http/mcp/tools/games.ts +24 −5

Diff not shown — a line 2,350 characters wide (limit 2,000). +24 −5

View file
src/http/mcp/tools/infra.ts +2 −2
@@ -52,7 +52,7 @@ function named(whole: CloudNode, nodes: readonly CloudNode[], args: Args, says:
5252 export const tool: Tool = {
5353 name: "infra",
5454 listedTo: "admin",
55 doc: "`{ action, id?, want?, question?, names?, result?, bucket?, cursor? }`: `list` (its `says` names every machine; with a filter line as `id`, like `kind:volume cloud:aws cost:>10`, the cloud resources it leaves, each with `partOf`, its app, and `attachedTo`; 50 a page, `cursor` for the next), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a firewall `{firewall: name}` or a DNS record `{dns: true, name, account, type: A|SRV, host, value, port?}` or a game box `{game: true, where, repo, name?, host?}` or Minecraft Java `{design: minecraft, players, where, domain, dns, repo, eula: true, name?, version?}` (its `compose` comes back with the plan) or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `check` DNS records, `code` (infra.json against what runs), `keep`, `begin`, `attach`, `record_result`; `cloud` a machine's name as `id` (its provider's view: power, size, IPs, actions) or a resource's `id` from `list` (as last read); `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.",
55 doc: "`{ action, id?, want?, question?, names?, result?, bucket?, cursor? }`: `list` (its `says` names every machine; with a filter line as `id`, like `kind:volume cloud:aws cost:>10`, the cloud resources it leaves, each with `partOf`, its app, and `attachedTo`; 50 a page, `cursor` for the next), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a firewall `{firewall: name}` or a DNS record `{dns: true, name, account, type: A|SRV, host, value, port?}` or a game box `{game: true, where, repo, name?, host?}` or Minecraft Java `{design: minecraft, players, where, domain, dns, repo, eula: true, name?, version?}` (its `compose` comes back with the plan) or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `check` DNS records, `code` (infra.json against the forge's record), `keep`, `begin`, `attach`, `record_result`; `cloud` a machine's name as `id` (its provider's view: power, size, IPs, actions) or a resource's `id` from `list` (as last read); `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.",
5656 description: "Machines, spend.",
5757 inputSchema: {
5858 type: "object",
@@ -141,7 +141,7 @@ export const tool: Tool = {
141141 return good({ says: lookWords(differ), records: v.value.records });
142142 }
143143 if (action === "code") {
144 // infra.json in each app's repo against what runs: what applying it would change. Read-only.
144 // infra.json in each app's repo against the forge's record: what applying it would change. Read-only.
145145 const files = await infraCode(ctx.app, user);
146146 return files.ok ? good({ says: files.value.length === 0 ? "no app's repo holds an infra.json" : files.value.map((k) => `${k.app}: ${k.says}`).join("; "), files: files.value }) : bad("not_found", "no such tool here");
147147 }
src/kernel/census.ts +5 −1
@@ -16,6 +16,8 @@ export interface ProcessRow {
1616 readonly pgid: number;
1717 /** The kernel's command name (`/proc/<pid>/stat`'s second field), at most 15 bytes. */
1818 readonly comm: string;
19 /** `num_threads`, field 20, when the line has it. */
20 readonly threads?: number;
1921 }
2022
2123 /** Every process in `root` (default `/proc`); one that goes mid-read is skipped. */
@@ -55,7 +57,9 @@ export function parseStat(stat: string): ProcessRow | undefined {
5557 const ppid = Number(fields[1]);
5658 const pgid = Number(fields[2]);
5759 if (![pid, ppid, pgid].every(Number.isSafeInteger)) return undefined;
58 return { pid, ppid, pgid, comm: stat.slice(open + 1, close) };
60 const threads = Number(fields[17]);
61 const comm = stat.slice(open + 1, close);
62 return Number.isSafeInteger(threads) ? { pid, ppid, pgid, comm, threads } : { pid, ppid, pgid, comm };
5963 }
6064
6165 /** How many processes carry each command name, but this process itself. */
src/kernel/loop_watchdog.ts added +98
@@ -0,0 +1,98 @@
1 /**
2 * A line written while the loop is blocked, by something outside the thread (#17708).
3 *
4 * The loop watch (`loop_lag.ts`) is a timer on the thread it watches: it can only say a stall
5 * happened after it ends, so 159.6 s of 0.7.718 left no line until 23:12:15. This is a Worker
6 * (`loop_watchdog_worker.ts`, started by file like the forge's other workers), a thread of its
7 * own, that reads a heartbeat the main thread writes every `beatMs` into shared memory. When the
8 * heartbeat is older than `afterMs` it writes `event loop still blocked` to stderr and to
9 * `<data>/perf/loop-watchdog.log`, again each `repeatMs`, and one closing line when the beat
10 * returns. The file is a kept log (`perf/kept_log.ts`), so its size is capped and rotated.
11 *
12 * When it speaks it also says the host's 1-minute load and the processes and threads in the
13 * container, and under the forge by name (`proc_census.ts`), for the load of 318 to 1,629 that
14 * followed the release: who the forge had started by then.
15 *
16 * What it decides is `watchStep`, a pure function of the heartbeat's age, tested without a thread.
17 */
18
19 import type { WatchdogStart } from "./loop_watchdog_worker.ts";
20
21 export const WATCHDOG_AFTER_MS = 3_000;
22 export const WATCHDOG_REPEAT_MS = 15_000;
23 export const WATCHDOG_BEAT_MS = 250;
24 /**
25 * The watchdog's file under the data directory: a kept log of its own, so no two writers rotate one
26 * file.
27 */
28 export const WATCHDOG_FILE = "perf/loop-watchdog.log";
29
30 export interface WatchdogOptions {
31 afterMs?: number;
32 repeatMs?: number;
33 beatMs?: number;
34 /** The data directory the lines are kept under; none: stderr only. */
35 dataDir?: string | undefined;
36 }
37
38 /** What the watchdog remembers between looks. */
39 export interface WatchState {
40 readonly blocked: boolean;
41 /** The silence at the last line written, ms. */
42 readonly reportedAt: number;
43 /** The longest silence seen in this block, ms. */
44 readonly peak: number;
45 }
46
47 export const CALM: WatchState = { blocked: false, reportedAt: 0, peak: 0 };
48
49 /** One look at a heartbeat `silentMs` old: the next state, and whether a line is due and which. */
50 export function watchStep(
51 state: WatchState,
52 silentMs: number,
53 afterMs: number,
54 repeatMs: number,
55 ): { state: WatchState; say: "blocked" | "closing" | null; silentMs: number } {
56 if (silentMs >= afterMs) {
57 const due = !state.blocked || silentMs - state.reportedAt >= repeatMs;
58 const next = { blocked: true, reportedAt: due ? silentMs : state.reportedAt, peak: silentMs };
59 return { state: next, say: due ? "blocked" : null, silentMs };
60 }
61 if (state.blocked) return { state: CALM, say: "closing", silentMs: state.peak };
62 return { state, say: null, silentMs };
63 }
64
65 /** The line a blocked loop gets; scope `loop`, the log's own shape. */
66 export function blockedLine(at: Date, silentMs: number, closing: boolean, extra = ""): string {
67 const s = (Math.round(silentMs / 100) / 10).toFixed(1);
68 return `${at.toISOString()} WARN [loop] ${
69 closing
70 ? `event loop answered again after at least ${s} s without a heartbeat (seen from outside the thread)`
71 : `event loop still blocked: no heartbeat for ${s} s (seen from outside the thread)${extra}`
72 }`;
73 }
74
75 export interface Watchdog {
76 stop(): void;
77 }
78
79 /** Start the watchdog; the beat is an unref'd timer on this thread. Returns the stop. */
80 export function startLoopWatchdog(o: WatchdogOptions = {}): Watchdog {
81 const afterMs = o.afterMs ?? WATCHDOG_AFTER_MS;
82 const repeatMs = o.repeatMs ?? WATCHDOG_REPEAT_MS;
83 const beatMs = o.beatMs ?? WATCHDOG_BEAT_MS;
84 const sab = new SharedArrayBuffer(8);
85 const beat = new BigInt64Array(sab);
86 Atomics.store(beat, 0, BigInt(Date.now()));
87 const worker = new Worker(new URL("./loop_watchdog_worker.ts", import.meta.url).href);
88 worker.unref();
89 worker.postMessage({ sab, afterMs, repeatMs, dataDir: o.dataDir, pid: process.pid } satisfies WatchdogStart);
90 const timer = setInterval(() => Atomics.store(beat, 0, BigInt(Date.now())), beatMs);
91 timer.unref();
92 return {
93 stop() {
94 clearInterval(timer);
95 worker.terminate();
96 },
97 };
98 }
src/kernel/loop_watchdog_worker.ts added +52
@@ -0,0 +1,52 @@
1 /**
2 * The watchdog's own thread (`loop_watchdog.ts`): it reads the heartbeat the serving thread
3 * writes and, while it is stale, writes a line the serving thread could not (#17708).
4 */
5
6 import { loadavg } from "node:os";
7 import { processRows } from "./census.ts";
8 import { keptLog } from "../perf/kept_log.ts";
9 import { CALM, WATCHDOG_FILE, blockedLine, watchStep } from "./loop_watchdog.ts";
10 import { census, censusWords } from "./proc_census.ts";
11
12 /** What the watchdog is told. */
13 export interface WatchdogStart {
14 readonly sab: SharedArrayBuffer;
15 readonly afterMs: number;
16 readonly repeatMs: number;
17 readonly dataDir: string | undefined;
18 /** The serving process, whose descendants are counted. */
19 readonly pid: number;
20 }
21
22 declare const self: Worker;
23
24 /** Load and the process tree now, as a phrase; a host without `/proc` says only the load. */
25 function surroundings(pid: number): string {
26 const load = `; load 1m ${loadavg()[0]!.toFixed(1)}`;
27 try {
28 return `${load}; ${censusWords(census(processRows(), pid))}`;
29 } catch {
30 return load;
31 }
32 }
33
34 self.onmessage = (e: MessageEvent<WatchdogStart>) => {
35 const { sab, afterMs, repeatMs, dataDir, pid } = e.data;
36 const beat = new BigInt64Array(sab);
37 // A kept log of its own: size capped and rotated; flushed at once, for the loop may stay blocked.
38 const kept = dataDir === undefined ? undefined : keptLog(dataDir, { file: WATCHDOG_FILE });
39 const write = (text: string): void => {
40 process.stderr.write(`${text}\n`);
41 kept?.add(text);
42 kept?.flush();
43 };
44 let state = CALM;
45 setInterval(() => {
46 const now = Date.now();
47 const step = watchStep(state, now - Number(Atomics.load(beat, 0)), afterMs, repeatMs);
48 state = step.state;
49 if (step.say === "blocked") write(blockedLine(new Date(now), step.silentMs, false, surroundings(pid)));
50 else if (step.say === "closing") write(blockedLine(new Date(now), step.silentMs, true));
51 }, Math.max(250, Math.floor(afterMs / 3)));
52 };
src/kernel/proc_census.ts added +56
@@ -0,0 +1,56 @@
1 /**
2 * Who is running, counted by parent (#17708). After 0.7.718 the host's 1-minute load read 318 and,
3 * second-hand, 1,629: more runnable threads than any one thread of the forge could make, so the
4 * first thing to know is how many processes and threads the forge's own tree holds when the loop
5 * stops answering. Rows come from `census.ts` (`processRows`), read by the watchdog's worker, never
6 * by the serving thread.
7 */
8
9 import type { ProcessRow } from "./census.ts";
10
11 export interface Census {
12 /** Every process the reader could see (its own container) and their threads. */
13 readonly processes: number;
14 readonly threads: number;
15 /** The descendants of `root`: how many, their threads, and the names most numerous. */
16 readonly below: { readonly processes: number; readonly threads: number; readonly top: readonly (readonly [string, number])[] };
17 }
18
19 /** Count `rows` and, under `root`, the processes that descend from it. */
20 export function census(rows: readonly ProcessRow[], root: number, top = 4): Census {
21 const kids = new Map<number, ProcessRow[]>();
22 for (const r of rows) {
23 const list = kids.get(r.ppid);
24 if (list === undefined) kids.set(r.ppid, [r]);
25 else list.push(r);
26 }
27 const names = new Map<string, number>();
28 let processes = 0;
29 let threads = 0;
30 const seen = new Set<number>([root]);
31 const queue = [root];
32 while (queue.length > 0) {
33 for (const k of kids.get(queue.shift()!) ?? []) {
34 if (seen.has(k.pid)) continue;
35 seen.add(k.pid);
36 queue.push(k.pid);
37 processes++;
38 threads += k.threads ?? 1;
39 names.set(k.comm, (names.get(k.comm) ?? 0) + 1);
40 }
41 }
42 const ranked = [...names].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, top);
43 return {
44 processes: rows.length,
45 threads: rows.reduce((n, r) => n + (r.threads ?? 1), 0),
46 below: { processes, threads, top: ranked },
47 };
48 }
49
50 /**
51 * The census as a log phrase: `procs 812, threads 1403; under pid: 640 procs (bun 400, git 120)`.
52 */
53 export function censusWords(c: Census): string {
54 const top = c.below.top.map(([n, k]) => `${n} ${k}`).join(", ");
55 return `procs ${c.processes}, threads ${c.threads}; under pid: ${c.below.processes} procs, ${c.below.threads} threads${top === "" ? "" : ` (${top})`}`;
56 }
src/logs/findings.ts added +93
@@ -0,0 +1,93 @@
1 /**
2 * The lines of a failed run's log that say why it failed, most telling first: one answer for the
3 * feed's post, check.txt and whoever reads a log next. A check's failing tests are the ones its own
4 * report named; otherwise the line the run's verdict quotes, or the last line that states an error.
5 * A word in passing ("0 failed", a passing test named for an error) is never an answer: in seven of
6 * eight saved red checks of the forge, the first such word had nothing to do with the failure.
7 *
8 * Every word is masked here, as a log line is (`redactHeld`), and before any cut: half a secret
9 * matches nothing. No caller masks again.
10 */
11
12 import type { Run } from "../core/runs.ts";
13 import { isSummaryLine } from "../checks/bun-test.ts";
14 import { FAIL } from "../checks/gate_tests.ts";
15 import { redactHeld } from "../kernel/log.ts";
16 import { clip } from "../text/clip.ts";
17 import { logLevel } from "./level.ts";
18
19 export interface Finding {
20 /** What broke, in one line. */
21 readonly says: string;
22 /** Its own output, when the check kept it: at most {@link DETAIL_LINES}, ending at the failure. */
23 readonly detail: readonly string[];
24 /** Its 1-based number in `lines`; null when they do not hold it. */
25 readonly line: number | null;
26 }
27
28 export const FINDINGS_MAX = 5;
29 export const DETAIL_LINES = 12;
30 const SAYS_MAX = 400;
31
32 // eslint-disable-next-line no-control-regex
33 const ANSI = /\x1b\[[0-?]*[ -/]*[@-~]/g;
34 const HEADER = /^(\S+\.test\.[cm]?[jt]sx?):$/;
35 /** How a run's log ends when it failed: its verdict, often another line's words, cut. */
36 const VERDICT = "failed: ";
37 /** `error: x`, `fatal: x`, `TypeError: x`, `a.ts(1,2): error TS2322: x`. */
38 const STATED = /^(?:Uncaught )?(?:error|fatal|panic|(?:[A-Za-z]\w*)?(?:Error|Exception))(?:\[[^\]]*\]|\([^)]*\))?: |: error TS\d+: /;
39
40 const say = (text: string): string => clip(redactHeld(text), SAYS_MAX);
41
42 const statesError = (line: string): boolean => STATED.test(line) || logLevel(line) === "error";
43
44 /**
45 * The line each failing test failed at: under its own file's header first, then anywhere (a
46 * sharded log may keep only the tally). Null when the lines do not hold it.
47 */
48 function failLines(lines: readonly string[]): (name: string, file: string | undefined) => number | null {
49 const own = new Map<string, number>();
50 const any = new Map<string, number>();
51 let file = "";
52 lines.forEach((line, i) => {
53 const header = HEADER.exec(line);
54 if (header !== null) file = header[1]!.replace(/^\.\//, "");
55 else if (isSummaryLine(line)) file = "";
56 const name = FAIL.exec(line)?.[1];
57 if (name === undefined) return;
58 if (!any.has(name)) any.set(name, i + 1);
59 if (file !== "" && !own.has(`${file}\0${name}`)) own.set(`${file}\0${name}`, i + 1);
60 });
61 return (name, of) => own.get(`${of ?? ""}\0${name}`) ?? any.get(name) ?? null;
62 }
63
64 /** The verdict's line, and the line it quotes when one above it does. */
65 function verdictOf(lines: readonly string[]): { at: number; quotes: number } | undefined {
66 const at = lines.findLastIndex((l) => l.startsWith(VERDICT));
67 if (at === -1) return undefined;
68 const said = lines[at]!.slice(VERDICT.length).replace(/…$/, "").trim();
69 return { at, quotes: said === "" ? -1 : lines.findLastIndex((l, i) => i < at && l.trim().startsWith(said)) };
70 }
71
72 /** Why a failed run failed, at most {@link FINDINGS_MAX}; empty when no line says. */
73 export function findingsOf(run: Pick<Run, "kind" | "state" | "checkDetail">, log: readonly string[]): Finding[] {
74 if (run.state !== "failed") return [];
75 const lines = log.map((l) => l.replace(ANSI, ""));
76 const detail = run.checkDetail;
77 const tests: readonly { name: string; file?: string; assertion?: string; excerpt?: readonly string[] }[] =
78 detail?.failures !== undefined && detail.failures.length > 0 ? detail.failures : (detail?.names ?? []).map((name) => ({ name }));
79 if (tests.length > 0) {
80 const lineOf = failLines(lines);
81 return tests.slice(0, FINDINGS_MAX).map((t) => ({
82 says: say(t.assertion === undefined ? t.name : `${t.name}: ${t.assertion}`),
83 detail: (t.excerpt ?? []).slice(-DETAIL_LINES).map((l) => redactHeld(l)),
84 // The log holds the name as it was masked on the way in.
85 line: lineOf(t.name, t.file) ?? lineOf(redactHeld(t.name), t.file),
86 }));
87 }
88 const verdict = verdictOf(lines);
89 // A check's output is full of errors its tests made on purpose: only its verdict speaks for it.
90 const stated = run.kind === "check" ? -1 : lines.findLastIndex((l) => !l.startsWith(VERDICT) && statesError(l.trim()));
91 const at = [verdict?.quotes ?? -1, stated, verdict?.at ?? -1].find((i) => i !== -1);
92 return at === undefined ? [] : [{ says: say(lines[at]!.trim()), detail: [], line: at + 1 }];
93 }
src/logs/level.ts added +22
@@ -0,0 +1,22 @@
1 /** The level a log line states of itself, read the same wherever a log is drawn or searched. */
2
3 /** A timestamp a log line may open with: `2026-01-02T03:04:05Z`, `[03:04:05.123]`. */
4 const STAMP = /^\s*\[?(?:\d{4}-\d\d-\d\d[T ])?\d\d:\d\d:\d\d(?:[.,]\d+)?(?:Z|[+-]\d\d:?\d\d)?\]?[\s:|-]*/;
5 const BARE = /^(ERROR|ERR|FATAL|CRITICAL|CRIT|PANIC|WARN|WARNING|DEBUG|TRACE)(?![A-Za-z0-9_])/;
6 const BRACKET = /^[[(<](error|err|fatal|critical|crit|panic|warn|warning|debug|trace)[\])>]/i;
7 const LOGFMT = /^(?:\S+=\S+\s+){0,4}level=(error|err|fatal|warn|warning|debug|trace)\b/i;
8
9 /**
10 * The level a log line states in its first token (after an optional timestamp):
11 * `ERROR x`, `[warn] x`, `level=error x`. Prose that merely mentions a word
12 * ("no errors found", "0 failed") has none.
13 */
14 export function logLevel(line: string): "error" | "warn" | "debug" | undefined {
15 const rest = line.replace(STAMP, "");
16 const word = BARE.exec(rest)?.[1] ?? BRACKET.exec(rest)?.[1] ?? LOGFMT.exec(line)?.[1];
17 if (word === undefined) return undefined;
18 const w = word.toLowerCase();
19 if (w.startsWith("warn")) return "warn";
20 if (w === "debug" || w === "trace") return "debug";
21 return "error";
22 }
src/main.ts +6
@@ -125,6 +125,7 @@ import { reapLeftoverBridges } from "./crew/leftovers.ts";
125125 import { crewRoot } from "./crew/workdir.ts";
126126 import { createLog, teeLines } from "./kernel/log.ts";
127127 import { keptLine, keptLog } from "./perf/kept_log.ts";
128 import { startLoopWatchdog } from "./kernel/loop_watchdog.ts";
128129 import { loadOrNone, startService } from "./kernel/start_service.ts";
129130 import { METER_EVERY_MS, newMeterWatch } from "./crew/meter_watch.ts";
130131 import { watchStalls } from "./kernel/loop_lag.ts";
@@ -311,6 +312,11 @@ watchStalls(loopLog, undefined, undefined, undefined, (late, at) => {
311312 stallRelay.note(late, at);
312313 });
313314
315 // A line from outside this thread while it is blocked: the watch above can only speak after
316 // (#17708).
317 const loopWatchdog = startLoopWatchdog({ dataDir: readOnly ? undefined : dataDir });
318 process.on("exit", () => loopWatchdog.stop());
319
314320 const previewKey = previewIdentityKey(process.env);
315321
316322 const engineShape = engineChoice(process.env, { hosted, readOnly, machine: readMachine() });
src/perf/kept_log.ts +6 −6
@@ -18,8 +18,8 @@
1818 */
1919
2020 import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync } from "node:fs";
21 import { join } from "node:path";
22 import { during } from "./jobs.ts";
21 import { dirname, join } from "node:path";
22 import { background } from "./jobs.ts";
2323
2424 /** The file the lines go to, under the data directory. */
2525 export const KEPT_FILE = join("perf", "loop.log");
@@ -47,10 +47,10 @@ export interface KeptLog {
4747 }
4848
4949 /** The kept log of `dataDir`: buffered appends, rotated by size. */
50 export function keptLog(dataDir: string, o: { maxBytes?: number; keep?: number; flushMs?: number } = {}): KeptLog {
50 export function keptLog(dataDir: string, o: { maxBytes?: number; keep?: number; flushMs?: number; file?: string } = {}): KeptLog {
5151 const maxBytes = o.maxBytes ?? MAX_BYTES;
5252 const keep = o.keep ?? KEEP;
53 const file = join(dataDir, KEPT_FILE);
53 const file = join(dataDir, o.file ?? KEPT_FILE);
5454 let buffer: string[] = [];
5555 let bytes = 0;
5656 let size: number | undefined;
@@ -68,7 +68,7 @@ export function keptLog(dataDir: string, o: { maxBytes?: number; keep?: number;
6868 bytes = 0;
6969 try {
7070 if (size === undefined) {
71 mkdirSync(join(dataDir, "perf"), { recursive: true });
71 mkdirSync(dirname(file), { recursive: true });
7272 size = existsSync(file) ? statSync(file).size : 0;
7373 }
7474 const add = Buffer.byteLength(text);
@@ -79,7 +79,7 @@ export function keptLog(dataDir: string, o: { maxBytes?: number; keep?: number;
7979 size = undefined;
8080 }
8181 };
82 const timer = setInterval(() => during("kept-log-flush", flush), o.flushMs ?? FLUSH_MS);
82 const timer = setInterval(() => background("kept-log-flush", flush), o.flushMs ?? FLUSH_MS);
8383 timer.unref?.();
8484 return {
8585 add(line) {
src/perf/traffic.ts +5 −4
@@ -197,8 +197,8 @@ function bump(
197197 if (anonymous) row.anonymous++;
198198 }
199199
200 function sketchAdd(sketch: Uint8Array, bytes: Uint8Array): void {
201 const hash = Number(Bun.hash.xxHash32(bytes, SALT)) >>> 0;
200 function sketchAdd(sketch: Uint8Array, bytes: Uint8Array, salt: number): void {
201 const hash = Number(Bun.hash.xxHash32(bytes, salt)) >>> 0;
202202 const index = hash >>> (32 - SKETCH_BITS);
203203 const rank = Math.clz32((hash << SKETCH_BITS) >>> 0) + 1;
204204 if (rank > sketch[index]!) sketch[index] = rank;
@@ -250,7 +250,8 @@ function largest(table: Map<string, Row>, limit: number): TopRow[] {
250250 return [...rows.slice(0, limit), rest];
251251 }
252252
253 export function createTrafficLedger(): TrafficLedger {
253 /** The salt is random per process; a test passes a fixed one so its counts are exact. */
254 export function createTrafficLedger(salt: number = SALT): TrafficLedger {
254255 const buckets = new Map<number, Bucket>();
255256 const slot = (minute: number): Bucket | undefined => {
256257 const index = minute % TRAFFIC_MINUTES;
@@ -300,7 +301,7 @@ export function createTrafficLedger(): TrafficLedger {
300301 return;
301302 }
302303 bump(bucket.prefixes, prefixOf(bytes), ms, anonymous);
303 sketchAdd((bucket.sketches[cls] ??= new Uint8Array(SKETCH_SIZE)), bytes);
304 sketchAdd((bucket.sketches[cls] ??= new Uint8Array(SKETCH_SIZE)), bytes, salt);
304305 },
305306 totals(now) {
306307 const newest = Math.floor(now / MINUTE_MS);
src/runs/error_line.ts deleted −30
@@ -1,30 +0,0 @@
1 /**
2 * The line of a run's log that says what broke: the first one carrying an
3 * error or fail marker, and its 1-based place in the lines `readRunLog`
4 * returns — the same count the run page numbers its rows by (`#L<n>`).
5 * Read once, when the run finishes, and kept with the event; the feed never
6 * opens a log.
7 */
8
9 import { clip } from "../text/clip.ts";
10
11 /** bun's `(fail)`, `error:`, `Error`, `failed`, `failure` — as words, any case. */
12 const MARKER = /\(fail\)|\b(?:error|fail(?:ed|ure|s)?)\b/i;
13
14 export const ERROR_LINE_MAX = 120;
15
16 export interface ErrorLine {
17 /** The line, trimmed and cut to `ERROR_LINE_MAX`. */
18 text: string;
19 /** Its 1-based number in the log. */
20 at: number;
21 }
22
23 export function firstErrorLine(lines: readonly string[]): ErrorLine | undefined {
24 for (let i = 0; i < lines.length; i++) {
25 const text = lines[i]!.trim();
26 if (text !== "" && MARKER.test(text))
27 return { text: clip(text, ERROR_LINE_MAX), at: i + 1 };
28 }
29 return undefined;
30 }
src/snapshot/hosted.ts +10 −3
@@ -21,6 +21,7 @@
2121 import { closeSync, constants, fstatSync, lstatSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, realpathSync, rmSync } from "node:fs";
2222 import { lstat, readdir } from "node:fs/promises";
2323 import { dirname, join, resolve, sep } from "node:path";
24 import { JARS_DIR } from "../games/jars.ts";
2425 import { runGit } from "../git/env.ts";
2526 import { findingWords, scanRepos } from "../spawn/move_scan.ts";
2627 import { CHILD_NAME } from "../spawn/placement.ts";
@@ -75,7 +76,7 @@ export interface HostedSource {
7576 export const PARENT_SIDE = "parent/";
7677 export const PARENT_FILES: readonly string[] = [`${PARENT_SIDE}credit.json`, `${PARENT_SIDE}own-code.json`];
7778 /** What a forge keeps in its own directory beside its database: history and records, whole. */
78 export const HISTORY_DIRS = ["runs", "drop", "ledger"] as const;
79 export const HISTORY_DIRS = ["runs", "drop", "ledger", JARS_DIR] as const;
7980 export const HISTORY_FILES = ["parent.json", "plan.json"] as const;
8081
8182 // A letter or digit first, as `spawn/archive.ts` holds: an id never reads as an option (#14783).
@@ -209,7 +210,7 @@ export type HostedCopy = Pick<HostedEntry, "repos" | "key" | "absent" | "omitted
209210
210211 /** Names of left-out files a manifest lists; the rest are counted. */
211212 export const OMITTED_LISTED = 100;
212 /** Bytes of runs/, drop/ and ledger/ together a snapshot of one forge carries. */
213 /** Bytes of runs/, drop/, ledger/ and games/jars/ together a snapshot of one forge carries. */
213214 export const HISTORY_BYTES_MAX = 512 * 1_048_576;
214215
215216 type Cut = "content" | "fixed" | "bundle";
@@ -232,7 +233,7 @@ export interface HostedTools {
232233 /** The most files read from the forge's directory; `HOSTED_FILES_MAX` unless a test lowers it. */
233234 readonly filesMax?: number | undefined;
234235 /**
235 * The most bytes of history (runs, drop, ledger); `HISTORY_BYTES_MAX` unless a test lowers it.
236 * The most bytes of history (`HISTORY_DIRS`); `HISTORY_BYTES_MAX` unless a test lowers it.
236237 */
237238 readonly historyMax?: number | undefined;
238239 }
@@ -574,6 +575,12 @@ export async function copyHosted(child: HostedSource, tools: HostedTools): Promi
574575 };
575576 let room = tools.historyMax ?? HISTORY_BYTES_MAX;
576577 for (const d of HISTORY_DIRS) {
578 // A directory inside another is listed only when the outer one is the forge's own, not a link.
579 const outer = d.split("/").slice(0, -1);
580 if (outer.length > 0 && notOwnDir(root, outer) !== undefined) {
581 if (lstatSync(join(root, ...outer), { throwIfNoEntry: false }) !== undefined) omitted.push({ path: d, why: "it is not in a directory of the forge's own" });
582 continue;
583 }
577584 const found = await historyIn(join(root, d), d, left);
578585 omitted.push(...found.omitted);
579586 for (const f of found.files) {
src/snapshot/restore.ts +13 −2
@@ -45,6 +45,7 @@ import { chmodSync, existsSync, mkdirSync, readdirSync, rmSync } from "node:fs";
4545 import { open as openFile, type FileHandle } from "node:fs/promises";
4646 import { availableParallelism } from "node:os";
4747 import { dirname, join } from "node:path";
48 import { jarsMissing } from "../games/jars.ts";
4849 import { runGit } from "../git/env.ts";
4950 import { installHooks } from "../git/hooks.ts";
5051 import { repoDir } from "../git/repos.ts";
@@ -76,8 +77,14 @@ export interface Restored {
7677 readonly key: "restored" | "raw" | "missing";
7778 /** Sealed values that will not open without the key, by name. */
7879 readonly sealedMissing: readonly string[];
80 /** Uploaded plugin jars the database names that did not come back, in words. */
81 readonly jarsMissing: readonly string[];
7982 }
8083
84 /** What a restore says of jars that did not come back; nothing when all did. */
85 export const jarLines = (missing: readonly string[]): string[] =>
86 missing.length === 0 ? [] : [`${missing.length} uploaded plugin jar(s) did not come back and must be uploaded again:`, ...missing.map((m) => ` ${m}`)];
87
8188 /** Where a restore is, as plain data: `done` of `total` in `phase`, `bytes` so far in it. */
8289 export interface Progress {
8390 readonly phase: "manifest" | "files" | "unpack" | "bundles" | "key";
@@ -596,7 +603,7 @@ export async function restoreSnapshot(
596603 key !== undefined ? "restored" : kind === "raw" ? "raw" : "missing";
597604 const sealedMissing =
598605 have === "missing" ? await sealedNames(join(dataDir, "forge.db")) : [];
599 return { manifest, files, repos, key: have, sealedMissing };
606 return { manifest, files, repos, key: have, sealedMissing, jarsMissing: jarsMissing(dataDir) };
600607 }
601608
602609 /** What one hosted forge's restore brought back. */
@@ -613,6 +620,8 @@ export interface RestoredHosted {
613620 readonly files: number;
614621 readonly repos: number;
615622 readonly key: "restored" | "missing";
623 /** As `Restored.jarsMissing`. */
624 readonly jarsMissing: readonly string[];
616625 }
617626
618627 /**
@@ -676,7 +685,7 @@ export async function restoreHosted(
676685 }
677686 // What its parent wrote of it was private to it, and is again.
678687 if (existsSync(join(dir, "parent.json"))) chmodSync(join(dir, "parent.json"), 0o600);
679 return { name: forge, dir, ledger: ledgerText, parentFiles, files: got.files, repos: got.bundles.length, key: key === undefined ? "missing" : "restored" };
688 return { name: forge, dir, ledger: ledgerText, parentFiles, files: got.files, repos: got.bundles.length, key: key === undefined ? "missing" : "restored", jarsMissing: jarsMissing(dir) };
680689 }
681690
682691 /**
@@ -791,6 +800,7 @@ if (import.meta.main)
791800 try {
792801 const one = await restoreHostedInto(store, snap, forgeName, dataDir, { passphrase: process.env["FORGE_SNAPSHOT_PASSPHRASE"] || undefined });
793802 console.log(`restored ${forgeName} from ${snap}: ${one.files} files, ${one.repos} repositories into ${one.dir}${one.key === "missing" ? "; its key was not restored" : ""}`);
803 for (const line of jarLines(one.jarsMissing)) console.log(line);
794804 process.exit(0);
795805 } catch (e) {
796806 // CLI message on stderr for the person at the terminal.
@@ -819,4 +829,5 @@ if (import.meta.main)
819829 );
820830 for (const n of done.sealedMissing) console.log(` ${n}`);
821831 }
832 for (const line of jarLines(done.jarsMissing)) console.log(line);
822833 })();
src/snapshot/snapshot.ts +5
@@ -40,6 +40,7 @@ import { vacuumFile, vacuumInto } from "./vacuum.ts";
4040 import { closeSync, createReadStream, fstatSync, lstatSync, mkdtempSync, openSync, readdirSync, readSync, rmSync, statSync } from "node:fs";
4141 import { tmpdir } from "node:os";
4242 import { join, relative } from "node:path";
43 import { JARS_DIR } from "../games/jars.ts";
4344 import { envDataDir } from "../apps/data.ts";
4445 import { listApps } from "../core/apps.ts";
4546 import { listEveryRepo } from "../core/repos.ts";
@@ -787,6 +788,10 @@ export async function takeSnapshot(
787788 for (const f of streaming ? [] : filesUnder(dropped))
788789 if (!f.split("/").some((part) => part.startsWith("."))) await putFile(`drop/${f}`, join(dropped, f));
789790
791 // Plugin jars people uploaded for their game servers (`games/store.ts`): kept nowhere else.
792 const jars = join(forge.dataDir, JARS_DIR);
793 for (const f of streaming ? [] : filesUnder(jars)) await putFile(`${JARS_DIR}/${f}`, join(jars, f));
794
790795 // The crew's run logs: history a person may want back. A day's worth to
791796 // a few bundles, in the order the logs were last written: a log still
792797 // growing is in the day's last bundle, and the bundles before it are the
src/spawn/keep_words.ts +5 −2
@@ -47,11 +47,14 @@ const when = (r: ClientRow): number => {
4747 return Number.isNaN(t) ? 0 : t;
4848 };
4949
50 /** The rows in the order asked; "attention" keeps the order they came in. */
50 /**
51 * The rows in the order asked; "attention" keeps the order they came in. A size not measured yet is
52 * not known, not 0: under "cost" it comes after every measured one.
53 */
5154 export function sortForges(rows: readonly ClientRow[], by: ForgeSort): ClientRow[] {
5255 const out = [...rows];
5356 if (by === "quiet") out.sort((a, b) => when(a) - when(b) || a.name.localeCompare(b.name));
5457 else if (by === "recent") out.sort((a, b) => when(b) - when(a) || a.name.localeCompare(b.name));
55 else if (by === "cost") out.sort((a, b) => (b.keepBytes ?? 0) - (a.keepBytes ?? 0) || (b.creditSpentUsd ?? 0) - (a.creditSpentUsd ?? 0) || a.name.localeCompare(b.name));
58 else if (by === "cost") out.sort((a, b) => (b.keepBytes ?? -1) - (a.keepBytes ?? -1) || (b.creditSpentUsd ?? 0) - (a.creditSpentUsd ?? 0) || a.name.localeCompare(b.name));
5659 return out;
5760 }

119 more files not shown.

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs