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

A game box that cannot lend says why, and new boxes can lend #17941

opened this in answer to

Merged 23h 9m ago, live in production

scout/forge:scout/17934-a-game-box-that-cannot-lend-says-why-and → main 0 commits fork

  • Merged. scout/17934-a-game-box-that-cannot-lend-says-why-and was merged into main as 1d3c3d5.

Review

Sign in to review this change.
14 files changed +117 −11
docs/features/game-box.md +1 −1
@@ -42,7 +42,7 @@ Code: `src/games/store.ts` (the `game_box` row and its token, the games store's)
4242
4343 - **Spare while servers sleep (#17576):** `/games/<box>` has two `dl` rows (the `status-rows` of the security page), and the terminal's box screen (`b` on a service) the same two as its first line: "Spare while servers sleep: N core-hours a week, M GB (samples of 7 days). Forge checks, same week: C core-hours." (`src/games/spare.ts`, read by `spare_row.ts`, which keeps the pair a minute per box so a redraw or reload reads nothing). Spare memory = the box's memory − what is awake − a reserve that always fits the largest sleeping server (its highest memory seen awake in the window); spare core-hours = the idle cores (the box's vCPUs − awake servers' CPU, 100 % being a core) of each minute a server sleeps, scaled from the minutes sampled to a week. A box with everything awake has 0. Fewer than 24 hours of samples, or a size or sleeper's memory not known, says "unknown", never 0. The checks' figure is the `cpu_s` of the cost ledger's `check` entries that ended in the last 7 days (read from the end of the month files, stopping at the window's start, at most 4 MiB, not walking the chain; "not measured" when none carried it). A server counts as asleep in a minute that it held no memory.
4444 - **Run checks while servers sleep (#17577):** the box's owner (forge admins own every box) sees a switch on `/games/<box>` (`POST /games/<box>/lend`, same-origin) and as `l` on the terminal's box screen, off by default, in the same words (`src/games/lend.ts`). Switching it on enrols a scoped `lent-box-<name>` runner for the box ([lent-runners.md](lent-runners.md)); switching it off revokes it at once. Its authors are the people who write the box's repository (its owner, teams and crew), read at each claim (a writer removed later is out at once), never a box owner who does not write it; a box with none names nobody, never anyone. The runner's token is not kept: it is held in the forge's memory until the box's next sync carries it over, once (see below).
45 - **The box's side of it (#17578):** the sync answers `lend: { token }` once to a box that says `lend: "none"` while the switch is on (a forge restarted before the token was sent, or a reply lost, revokes that runner and enrols a new one: the box is never left without), and `lend: { off: true }` to one that still says `"have"` after the switch went off. The agent keeps the token in `/opt/forge-game/.runner.auth` (mode 600, beside `.auth`), and each tick claims one job (`wait: 0`) when it is safe: no container started in the last 90 s (`FORGE_GAME_LEND_QUIET`), no compose job running, `MemAvailable` at least 768 MiB (`FORGE_GAME_LEND_FLOOR_MIB`), and `bubblewrap` and `git` installed (new boxes install them; an older box runs nothing until they are there).
45 - **The box's side of it (#17578):** the sync answers `lend: { token }` once to a box that says `lend: "none"` while the switch is on (a forge restarted before the token was sent, or a reply lost, revokes that runner and enrols a new one: the box is never left without), and `lend: { off: true }` to one that still says `"have"` after the switch went off. The agent keeps the token in `/opt/forge-game/.runner.auth` (mode 600, beside `.auth`), and each tick claims one job (`wait: 0`) when it is safe: no container started in the last 90 s (`FORGE_GAME_LEND_QUIET`), no compose job running, `MemAvailable` at least 768 MiB (`FORGE_GAME_LEND_FLOOR_MIB`), and `bubblewrap` and `git` installed (new boxes install them; an older box runs nothing until they are there). A box that holds a runner token and lacks either says so with each check-in (`lendWhy`: one of three fixed phrases, `src/games/lend_why.ts`), and both doors show it while the switch is on: `cannot lend: bubblewrap is not installed` (or `git`, or both) under the switch on `/games/<box>` and in the terminal's box screen, and on that runner's row in Settings → Runners and the terminal's runners screen. It clears with the next check-in once the tool is installed. A new box's boot installs both (`src/games/boot.ts`).
4646 - **The cell:** the agent itself only claims, fetches the commit over the job's own git door as the unprivileged user `forge-job`, and answers. Each step is its own systemd unit (`forge-job-<id>`: `MemoryMax` the job's declared memory, no swap, `CPUQuota` its cpus, 512 tasks, `timeout` its seconds) as that user, in bubblewrap with `--unshare-all`, `/usr` read-only, the checkout at `/work`, a tmpfs `/tmp` and a cleared environment (`CI` and `FORGE_*` of the job only). It sees no `/run` (the Docker socket), no `/opt/forge-game` (`agent.env`, `.auth`, `.runner.auth`, compose), no data volume. The check step has no network at all. The install step shares the network, but an iptables rule on `forge-job`'s traffic rejects every private, loopback, link-local (the cloud's metadata door) and shared-range address, so the game network is not a route (the box's own addresses too, v4 and v6; a host with IPv6 and no `ip6tables` hands the install step back). A step's output is written inside that same tmpfs and no write takes it past 1 MiB (`FORGE_GAME_LEND_OUT_KIB`): the step is killed by SIGXFSZ, and the last 64 KiB is what is read. The disk cap is the checkout's own tmpfs (the job's `diskMiB`, at most 4 GiB, which is also charged to the job's memory cap). A job that names `egress` hosts, declares no memory, or whose step is missing a tool on the box (exit 126 or 127) is handed back (`abandon`): the forge runs it, and it is never red for the box's lack; after a missing tool the box claims nothing for 10 minutes. `/opt/forge-job-tools` is mounted read-only at `/opt/tools` (on `PATH`) when it exists: the toolchain a repository's check needs (bun, say) is put there by the box's owner.
4747 - **A join:** `docker events` (a container starting) is read by the agent, and in that reader: claiming stops (`.wake`), every `forge-job-*` cgroup is frozen at once (`cgroup.freeze`), and nothing waits on the job. While a step runs, a guard looks twice a second: still frozen and `MemAvailable` under the floor, or frozen for 5 minutes (`FORGE_GAME_LEND_FROZEN_S`), and the job is killed (`cgroup.kill`, then the unit stopped) and answered `interrupted`; a quiet box (90 s, memory above the floor) thaws it. `interrupted` puts the job back in the queue with no result: it is never red, and its claim is not counted, so it is never a try of that check's `MAX_CLAIMS` (the check's log says "stopped the job … not a try, nor a result"). The guard also renews the lease every 10 s, frozen or not.
4848 - **Not done, and not proved yet:** nothing here has run on a real box (it waits for the owner's go): tps and mspt of an awake server with and without a job, and the wake time on a join with one running, are still to be measured from `src/games/metrics.ts`'s samples. The cell was checked against stand-ins (`test/game-lend-box.test.ts`), not against a real kernel's bubblewrap.
src/core/migration-pins/20261203070000-game-box-lend-why.pin added +1
@@ -0,0 +1,1 @@
1 1f861d3005a0d4e07d992e3950f5e16d00b15a6af6e914f968e846d229b33409
src/core/migrations/20261203070000-game-box-lend-why.ts added +5
@@ -0,0 +1,5 @@
1 // Why a game box that lends cannot (#17934): the agent's word, one of a few fixed phrases
2 // (games/lend_why.ts); '' when it can. Additive.
3 export default `
4 ALTER TABLE game_box ADD COLUMN lend_why TEXT NOT NULL DEFAULT '';
5 `;
src/games/agent.sh +17 −2
@@ -1392,6 +1392,7 @@ sync() {
13921392 --slurpfile chat "$DIR/.sync.chat" \
13931393 --argjson retry "$([ -f "$DIR/.sync.retry" ] && echo true || echo false)" \
13941394 --arg lend "$(lend_has)" \
1395 --arg lendWhy "$(lend_why)" \
13951396 --arg tokenSha "$(token_offer)" \
13961397 --slurpfile ask "$DIR/.sync.ask" \
13971398 --argjson got "$(desk_got)" \
@@ -1405,7 +1406,7 @@ sync() {
14051406 else [.[0]] + (.[1:] | codes) end;
14061407 (if . == "" then ["0"] else split(";") end) | [codes[] | $t[.] // empty | "\u00a7" + .] | join("");
14071408 def plain: gsub("\u001b\\[(?<p>[0-9;]*)m"; (.p // "" | sect)) | gsub("^(\u00a7r)+|(\u00a7r)+$"; "") | gsub("(\u00a7r)+"; "\u00a7r") | gsub("\u001b\\[[0-9;?]*[ -/]*[@-~]"; "") | gsub("\u001b[@-_]?"; "") | gsub("[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]"; "");
1408 {agent: 1, composeSha: $sha, services: $services[0], logs: $logs[0], results: $results[0], host: $host[0], diag: $diag[0], people: $people[0], metrics: $metrics[0], snapshots: $snapshots[0], chat: $chat[0].lines, chatId: $chat[0].id, lend: $lend, retry: $retry, jars: true, got: $got}
1409 {agent: 1, composeSha: $sha, services: $services[0], logs: $logs[0], results: $results[0], host: $host[0], diag: $diag[0], people: $people[0], metrics: $metrics[0], snapshots: $snapshots[0], chat: $chat[0].lines, chatId: $chat[0].id, lend: $lend, lendWhy: $lendWhy, retry: $retry, jars: true, got: $got}
14091410 + (if $tokenSha == "" then {} else {tokenSha: $tokenSha} end)
14101411 + (if $ask[0] == [] then {} else {ask: $ask[0]} end)
14111412 | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1
@@ -1491,6 +1492,20 @@ SYSTEMCTL="${FORGE_GAME_SYSTEMCTL:-systemctl}"
14911492 LEND_JOBAUTH="$DIR/.lend.job.auth"
14921493 EVICTED=0
14931494
1495 # Why this box cannot lend, in the words the forge keeps (games/lend_why.ts); nothing while it can
1496 # or holds no runner token. The cell is bubblewrap; a job's checkout needs git.
1497 lend_why() {
1498 [ -s "$LEND_AUTH" ] || return 0
1499 local b="" g=""
1500 command -v "$LEND_CELL" >/dev/null 2>&1 || b=bubblewrap
1501 command -v git >/dev/null 2>&1 || g=git
1502 case "$b$g" in
1503 "") ;;
1504 bubblewrapgit) echo "bubblewrap and git are not installed" ;;
1505 *) echo "$b$g is not installed" ;;
1506 esac
1507 }
1508
14941509 lend_has() { [ -s "$LEND_AUTH" ] && echo have || echo none; }
14951510 lend_avail() { awk '/^MemAvailable:/ {print int($2/1024)}' "$LEND_MEMINFO" 2>/dev/null || echo 0; }
14961511 lend_quiet() {
@@ -1566,7 +1581,7 @@ lend_running() {
15661581 lend_tick() {
15671582 [ -s "$LEND_AUTH" ] || return 0
15681583 # A box made before the cell was (no bubblewrap or git) runs nothing: a job never runs uncontained.
1569 command -v "$LEND_CELL" >/dev/null 2>&1 && command -v git >/dev/null 2>&1 || return 0
1584 [ -z "$(lend_why)" ] || return 0
15701585 lend_watch
15711586 lend_running && return 0
15721587 job_running && return 0
src/games/lend_why.ts added +26
@@ -0,0 +1,26 @@
1 /**
2 * Why a game box that lends cannot (#17934). The agent names the tool its cell needs and the box
3 * lacks; the forge keeps only these phrases, whatever the box sent, and every door says them alike.
4 */
5
6 import type { Database } from "bun:sqlite";
7
8 const WHYS = ["bubblewrap is not installed", "git is not installed", "bubblewrap and git are not installed"] as const;
9
10 /** What a sync said, if it is one of the phrases; "" otherwise. */
11 export const lendWhyOf = (raw: unknown): string => (WHYS.find((w) => w === raw) ?? "");
12
13 /**
14 * The line every door shows: "cannot lend: bubblewrap is not installed"; "" when nothing is wrong.
15 */
16 export const lendCannot = (why: string): string => (why === "" ? "" : `cannot lend: ${why}`);
17
18 /** Each live lent runner's box's reason, by runner id: only the runners whose box cannot lend. */
19 export function cannotByRunner(db: Database): Map<string, string> {
20 const rows = db
21 .query<{ id: string; lend_why: string }, []>(
22 "SELECT r.id, b.lend_why FROM check_runner r JOIN game_box b ON b.id = r.box_id WHERE r.revoked_at = 0 AND b.lend_why != ''",
23 )
24 .all();
25 return new Map(rows.map((r) => [r.id, lendCannot(r.lend_why)]));
26 }
src/games/store.ts +12 −1
@@ -22,6 +22,7 @@ import { resolveSecrets, setSecret } from "../core/secret_store.ts";
2222 import type { User } from "../core/users.ts";
2323 import { sha256 } from "../kernel/hash.ts";
2424 import { id as newId } from "../kernel/id.ts";
25 import { lendWhyOf } from "./lend_why.ts";
2526
2627 export const BOX_NAME = /^[a-z][a-z0-9-]{0,39}$/;
2728 export const SERVICE_NAME = /^[a-z0-9][a-z0-9_.-]{0,63}$/;
@@ -50,6 +51,11 @@ export interface GameBox {
5051 readonly createdAt: string;
5152 /** What the box last said about its boot ("missing jq: …", a boot report); empty once it syncs in full. */
5253 readonly boot: string;
54 /**
55 * Why the box cannot lend while its switch is on ("bubblewrap is not installed"); "" when it can
56 * (`lend_why.ts`).
57 */
58 readonly lendWhy: string;
5359 /** The latest diagnosis the agent sent (`diag.ts`), replaced each sync. */
5460 readonly diag: Diag;
5561 /** Each service's world snapshots, newest first, as the agent last listed them (`worlds.ts`). */
@@ -91,6 +97,7 @@ interface BoxRow {
9197 seen_at: string;
9298 created_at: string;
9399 boot: string;
100 lend_why: string;
94101 diag_json: string;
95102 snapshots_json: string;
96103 restored_from: string;
@@ -115,6 +122,7 @@ const toBox = (r: BoxRow): GameBox => {
115122 seenAt: r.seen_at,
116123 createdAt: r.created_at,
117124 boot: r.boot,
125 lendWhy: r.lend_why,
118126 diag: readDiag(r.diag_json),
119127 snapshots: readSnapshots(r.snapshots_json),
120128 restoredFrom: r.restored_from,
@@ -593,6 +601,8 @@ export interface SyncBody {
593601 readonly host?: Record<string, unknown>;
594602 /** "have" when the box holds a runner token for the forge's checks (`lend.ts`). */
595603 readonly lend?: unknown;
604 /** Why the box cannot lend, one of `lend_why.ts`'s phrases; "" or absent when it can. */
605 readonly lendWhy?: unknown;
596606 /** The box's word about its boot, sent without jq when a tool is missing or by the boot's report. */
597607 readonly boot?: string;
598608 /** The agent holds the answer's `jars`, checked, before it recreates the proxy. */
@@ -703,13 +713,14 @@ export function recordSync(
703713 db.query("UPDATE game_box SET seen_at = ?2, boot = ?3 WHERE id = ?1").run(box.id, at, str(body.boot, 2_000));
704714 return;
705715 }
706 db.query("UPDATE game_box SET seen_at = ?2, host_json = ?3, compose_sha = ?4, boot = '', diag_json = ?5, jars = ?6 WHERE id = ?1").run(
716 db.query("UPDATE game_box SET seen_at = ?2, host_json = ?3, compose_sha = ?4, boot = '', diag_json = ?5, jars = ?6, lend_why = ?7 WHERE id = ?1").run(
707717 box.id,
708718 at,
709719 JSON.stringify(host),
710720 str(body.composeSha, 80),
711721 keptDiag(body.diag),
712722 body.jars === true ? 1 : 0,
723 lendWhyOf(body.lendWhy),
713724 );
714725 // An agent from before world snapshots sends none: the last list stays.
715726 if (body.snapshots !== undefined) db.query("UPDATE game_box SET snapshots_json = ?2 WHERE id = ?1").run(box.id, keptSnapshots(body.snapshots));
src/tui/screens/games.ts +3 −1
@@ -29,6 +29,7 @@ import { eventsOf, eventWords, isBedrock, peopleOf, peopleWords, queuePeople } f
2929 import { findingsOf } from "../../games/player_events.ts";
3030 import { queueWorld, type WorldOp } from "../../games/worlds.ts";
3131 import { lendWords, lentRunnerOf, setLend } from "../../games/lend.ts";
32 import { lendCannot } from "../../games/lend_why.ts";
3233 import { spareRow } from "../../games/spare_row.ts";
3334 import { healWords } from "../../games/heal.ts";
3435 import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts";
@@ -609,7 +610,8 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
609610 const b = listBoxes(f.app.db).find((x) => x.id === box.id) ?? box;
610611 const held = heldLines(heldOn(f.app.db, f.user, b)).flatMap((l) => [...wrap(l, w), ""]);
611612 // The page's Spare rows, in the same words, first (kept a minute, so a redraw is free).
612 const lend = mayDo(roleOn(f.app.db, f.user, b.id), "owner") ? [lendWords(lentRunnerOf(f.app.db, b.id) !== undefined), ""] : [];
613 const lending = lentRunnerOf(f.app.db, b.id) !== undefined;
614 const lend = mayDo(roleOn(f.app.db, f.user, b.id), "owner") ? [lendWords(lending), ...(lending && b.lendWhy !== "" ? [lendCannot(b.lendWhy)] : []), ""] : [];
613615 const spare = [spareRow(f.app.db, f.app.config.dataDir, b).map(([k, v]) => `${k}: ${v}.`).join(" "), ""];
614616 if (!mayDo(roleOn(f.app.db, f.user, b.id), "owner")) {
615617 const shared = boxStatusShared(b.diag);
src/tui/screens/runners.ts +3 −1
@@ -9,6 +9,7 @@
99 import { list, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts";
1010 import { isLocal } from "../../checks/runner_pool.ts";
1111 import { listLending, offerLending, resumeLending, stopLending, type LendView } from "../../actions/lending.ts";
12 import { cannotByRunner } from "../../games/lend_why.ts";
1213 import { lendRoomLine, lookHere } from "../../checks/lend_pool.ts";
1314 import { lentLine, scopeLine } from "../../checks/lent_scope.ts";
1415 import { yieldNote, yieldState } from "../../checks/lent_yield.ts";
@@ -57,6 +58,7 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen {
5758 const rows = (): ListRow[] => {
5859 const now = Date.now();
5960 const held = heldByRunner(f.db);
61 const cannot = cannotByRunner(f.db);
6062 const work = workByRunner(f.db);
6163 return entries().map((e) => {
6264 if (e.kind === "offer") {
@@ -74,7 +76,7 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen {
7476 const asked = r.seenAt === 0 ? "has not asked for work" : `last asked ${new Date(r.seenAt).toISOString().slice(0, 16).replace("T", " ")}`;
7577 return {
7678 title: `${r.name} ${stateWords(r, now)}${isLocal(r) ? " (the forge's own)" : ""}`,
77 meta: `${asked}${machine === "" ? "" : ` · ${machine}`} · runs ${w.jobs} at once · holding ${n} · ${w.ran} job${w.ran === 1 ? "" : "s"} run${scopeLine(r, now)}`,
79 meta: `${asked}${machine === "" ? "" : ` · ${machine}`} · runs ${w.jobs} at once · holding ${n} · ${w.ran} job${w.ran === 1 ? "" : "s"} run${scopeLine(r, now)}${cannot.has(r.id) ? ` · ${cannot.get(r.id)}` : ""}`,
7880 };
7981 });
8082 };
src/web/pages/games.ts +2
@@ -19,6 +19,7 @@ import { blockChanges, serviceBlocks, shellBlocks, shellSays } from "../../termi
1919 import { blockEvent, blockHtml, blocksForm, terminalBlocksJs } from "../terminal_blocks.ts";
2020 import { statusRow } from "./security.ts";
2121 import { lendState, lentRunnerOf, setLend } from "../../games/lend.ts";
22 import { lendCannot } from "../../games/lend_why.ts";
2223 import { spareRow } from "../../games/spare_row.ts";
2324 import { healWords } from "../../games/heal.ts";
2425 import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts";
@@ -454,6 +455,7 @@ function lendBlock(ctx: Ctx, box: GameBox): Html {
454455 return html`<section class="settings-block" id="lend">
455456 <h2>Run checks while servers sleep</h2>
456457 <p class="muted small">${lendState(on)}</p>
458 ${on && box.lendWhy !== "" ? html`<p class="small" id="lend-cannot">${lendCannot(box.lendWhy)}</p>` : null}
457459 <form method="post" action="/games/${box.name}/lend" class="row-fields">
458460 <input type="hidden" name="on" value="${on ? "0" : "1"}" />
459461 ${btn(on ? "Switch off" : "Switch on", { type: "submit", variant: "secondary" })}
src/web/pages/runners.ts +5 −3
@@ -11,6 +11,7 @@
1111 import { listLending, offerLending, resumeLending, stopLending, type LendView } from "../../actions/lending.ts";
1212 import { list, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts";
1313 import { isLocal } from "../../checks/runner_pool.ts";
14 import { cannotByRunner } from "../../games/lend_why.ts";
1415 import { lendRoomLine, lookHere } from "../../checks/lend_pool.ts";
1516 import { lentLine, scopeFacts } from "../../checks/lent_scope.ts";
1617 import { yieldNote, yieldState } from "../../checks/lent_yield.ts";
@@ -47,7 +48,7 @@ function runnerTrail(r: Enrolled) {
4748 return html`${r.paused === "" ? "" : form("resume", "Resume")}${form("revoke", "Revoke")}`;
4849 }
4950
50 function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number) {
51 function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, cannot: string) {
5152 const state = runnerState(r.seenAt, now);
5253 const machine = runnerMachineWords(r);
5354 return row({
@@ -65,7 +66,7 @@ function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number) {
6566 : badge("Never asked", { variant: "outline", icon: "ban" })}`,
6667 meta: html`${r.seenAt === 0 ? "Has not asked for work" : html`Last asked for work ${time(new Date(r.seenAt).toISOString())}`}
6768 · runs ${work.jobs} at once · holding ${held} now · ${work.ran} job${work.ran === 1 ? "" : "s"} run · enrolled ${time(r.createdAt, { date: true })}`,
68 facts: [...(machine === "" ? [] : [{ label: "Machine", value: machine }]), ...scopeFacts(r, now)],
69 facts: [...(cannot === "" ? [] : [{ label: "Lending", value: cannot }]), ...(machine === "" ? [] : [{ label: "Machine", value: machine }]), ...scopeFacts(r, now)],
6970 trail: runnerTrail(r),
7071 });
7172 }
@@ -195,6 +196,7 @@ export function runnersPage(ctx: Ctx): Response {
195196 const rendering = performance.now();
196197 const now = Date.now();
197198 const held = heldByRunner(ctx.app.db);
199 const cannot = cannotByRunner(ctx.app.db);
198200 const work = workByRunner(ctx.app.db);
199201 const waiting = yieldNote(yieldState(process.env["FORGE_LEND_YIELD_LOAD"]));
200202 const lent = lentLine(lentIn(ctx.app.db, now));
@@ -205,7 +207,7 @@ export function runnersPage(ctx: Ctx): Response {
205207 ${seen.value.length === 0
206208 ? emptyList("runners")
207209 : html`<ul class="list setting-list" id="runner-list">
208 ${seen.value.map((r) => runnerRow(r, held.get(r.id) ?? 0, work.get(r.id) ?? { jobs: 1, ran: 0 }, now))}
210 ${seen.value.map((r) => runnerRow(r, held.get(r.id) ?? 0, work.get(r.id) ?? { jobs: 1, ran: 0 }, now, cannot.get(r.id) ?? ""))}
209211 </ul>`}
210212 </section>${lendingBlock(ctx)}`;
211213 notePhase(ctx.request, "render", performance.now() - rendering);
test/game-lend-box.test.ts +15
@@ -206,6 +206,21 @@ describe("a game box runs a claimed check in a cell", () => {
206206 expect(end.body).toMatchObject({ done: { steps: [{ name: "check", ok: false, error: "check exited with code 3" }] } });
207207 });
208208
209 test.skipIf(lacks.length > 0)("a box that holds a runner token and lacks bubblewrap says why, and claims nothing", async () => {
210 const b = await box({ steps: [{ name: "check", command: "echo hi" }] }, { env: { FORGE_GAME_LEND_CELL: "/nonexistent/bwrap" } });
211 writeFileSync(join(b.dir, ".runner.auth"), `Authorization: Bearer ${RUNNER}\n`);
212 await b.run();
213 expect(b.seen.find((s) => s.path === "/api/v1/games/agent/sync")?.body["lendWhy"]).toBe("bubblewrap is not installed");
214 expect(b.seen.some((s) => s.path === "/api/v1/runner/claim")).toBe(false);
215 });
216
217 test.skipIf(lacks.length > 0)("a box that can lend says nothing of why", async () => {
218 const b = await box({ steps: [{ name: "check", command: "echo hi" }] });
219 writeFileSync(join(b.dir, ".runner.auth"), `Authorization: Bearer ${RUNNER}\n`);
220 await b.run();
221 expect(b.seen.find((s) => s.path === "/api/v1/games/agent/sync")?.body["lendWhy"]).toBe("");
222 });
223
209224 test.skipIf(lacks.length > 0)("what the box lacks is handed back, never red", async () => {
210225 const b = await box({ steps: [{ name: "check", command: "no_such_tool_17578" }] });
211226 await b.run();
test/game-lend.test.ts +23 −1
@@ -17,7 +17,7 @@ import { createUser, getUserByName, type User } from "../src/core/users.ts";
1717 import { lendAnswer, lentRunnerOf, setLend } from "../src/games/lend.ts";
1818 import { lendAuthors } from "../src/games/lend_fit.ts";
1919 import { recordMetrics } from "../src/games/metrics.ts";
20 import { boxNamed, createGameBox, grant, type GameBox } from "../src/games/store.ts";
20 import { boxNamed, createGameBox, grant, recordSync, type GameBox } from "../src/games/store.ts";
2121 import { setLoadSource } from "../src/checks/lent_yield.ts";
2222 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
2323 import { quietLogs } from "./helpers/globals.ts";
@@ -208,6 +208,28 @@ describe("a game box lends its spare to checks", () => {
208208 expect(claim()!.job.run).toBe("r-alice-100");
209209 });
210210
211 test("a box that cannot lend says why on its page and on the runners page; only fixed phrases are kept", async () => {
212 const sync = (lendWhy: unknown) => recordSync(app.db, boxNamed(app.db, "net")!, { host: { memMiB: 8000 }, lendWhy });
213 // The claim tests above leave the switch on.
214 expect(lentRunnerOf(app.db, box.id)).toBeDefined();
215 try {
216 expect(await (await page(aliceTok)).text()).not.toContain("cannot lend");
217 sync("bubblewrap is not installed");
218 expect(await (await page(aliceTok)).text()).toContain("cannot lend: bubblewrap is not installed");
219 const runners = await http.handle(new Request(`${ORIGIN}/settings/runners`, { headers: { authorization: `Bearer ${aliceTok}` } }));
220 expect(await runners.text()).toContain("cannot lend: bubblewrap is not installed");
221 // Anything else the box sends is dropped, not shown.
222 sync("<script>alert(1)</script>");
223 expect(boxNamed(app.db, "net")!.lendWhy).toBe("");
224 sync("git is not installed");
225 expect(await (await page(aliceTok)).text()).toContain("cannot lend: git is not installed");
226 sync("");
227 expect(await (await page(aliceTok)).text()).not.toContain("cannot lend");
228 } finally {
229 sync("");
230 }
231 });
232
211233 test("a writer removed after switch-on is out at once; a box owner who does not write is never in", async () => {
212234 clearDesk();
213235 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "bolt", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: false });
test/game-spare.test.ts +1 −1
@@ -150,7 +150,7 @@ test("the row is two label/value facts, and kept a minute per box so a redraw re
150150 db.exec((await import("../src/core/migrations/20261201050000-game-metrics.ts")).default);
151151 db.exec((await import("../src/core/migrations/20261202000000-game-people.ts")).default.replace(/^.*game_box.*$/m, ""));
152152 const dataDir = mkdtempSync(join(tmpdir(), "spare-row-"));
153 const box: GameBox = { id: "b", name: "b", repo: "a/b", branch: "main", path: "", pinnedId: "", place: "", monthlyCents: 0, host: {}, composeSha: "", seenAt: "", createdAt: "", boot: "", diag: {} as GameBox["diag"], snapshots: {}, restoredFrom: "", holdsJars: false, };
153 const box: GameBox = { id: "b", name: "b", repo: "a/b", branch: "main", path: "", pinnedId: "", place: "", monthlyCents: 0, host: {}, composeSha: "", seenAt: "", createdAt: "", boot: "", lendWhy: "", diag: {} as GameBox["diag"], snapshots: {}, restoredFrom: "", holdsJars: false, };
154154 const now = Date.parse("2026-12-02T00:00:00Z");
155155 const first = spareRow(db, dataDir, box, now);
156156 expect(first[1]).toEqual(["Forge checks, last 7 days", "not measured"]);
test/tui-games.test.ts +3
@@ -347,6 +347,9 @@ test("the terminal's box screen shows the switch Run checks while servers sleep
347347 await owner.type("l");
348348 await settleUntil(owner.tui, "Run checks while servers sleep: on.");
349349 expect(lentRunnerOf(app.db, box.id)).toBeDefined();
350 recordSync(app.db, box, { host: {}, lendWhy: "bubblewrap is not installed" });
351 owner.tui.ctx.invalidate();
352 await settleUntil(owner.tui, "cannot lend: bubblewrap is not installed");
350353 await owner.type("l");
351354 await settleUntil(owner.tui, "Run checks while servers sleep: off.");
352355 expect(lentRunnerOf(app.db, box.id)).toBeUndefined();

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

Keyboard shortcuts

Docs