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

A game box agent that does not check in after its update goes back to the one before #18023

opened this in answer to

Closed 10h 34m ago

scout/forge:scout/18019-a-game-box-agent-that-does-not-check-in → main 3 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +331 −6
docs/features/games.md +12
@@ -188,3 +188,15 @@ A game's own refusal is a failure: `op` with a name that does not exist ("That p
188188 `/games/<box>` opens on **How to join** (the box's machine name with Copy, and who is on, server by server), then one row a server: its name, its state in words, players, TPS, then memory, CPU and how long it has been up in the cloud tree's words (`containersIn` in `src/cloud/containers.ts`: "not known" for what the box did not say or once it is silent, nothing for a server that is not running) and the 24 h sparklines, and a quiet button (Start while it is not running, else Restart); Stop, Restart and Remove are behind **More**. A server's page leads with its state, the same memory, CPU and uptime line under it, which says so when the server is not running (the terminal's people part too), its main button (the page's one accent), who is on and **Why someone could not join** (each cause with who, how often and "Tell them": what to say). Console, Numbers, Sleep, World, Environment, Settings and Mods follow, each folded and one tap away; nothing was removed (the numbers stayed in the row). A start, stop or restart that was asked shows on the server ("Starting: asked 10 s ago", then "Started" or why not) until the server answers, and the page updates itself. The player form has no default: choose what to do, in the plain word with the game's own beside it in the choice only (Let in (whitelist), Make operator (op), Ban, Lift a ban (pardon)); headings and notes use the plain word. The terminal says the same: the state line, the address, the "Tell them" fixes and the plain words (`src/games/gist.ts`). No address shows when the box has no machine name.
189189
190190 **Held** (`src/games/hold.ts`): a box whose agent starts nothing until a person has looked at its volume (docs/features/game-box.md) says so first, on `/games/<box>`, on each of its servers' pages, at the top of the terminal's Games and box screens, on its machine in the cloud tree and as `held` in the `games` tool. Its owner reads why, when the agent last looked and the next step; anyone else only that its owner has to look. The agent sends a code (`diag.hold`), never a sentence, and one the forge does not know is said as held without a reason. Held is not stopped: containers that already run are left alone. Start, Restart and Recreate (`src/games/power.ts`), and a world's import, restore and snapshot (`src/games/worlds.ts`: each ends by starting the server), say "held" and are refused at every door, also when an old page or screen asks; Stop and Pull go through, as at the agent. A box that has gone silent is asked, and its agent answers. An older agent sends nothing, and nothing is said.
191
192 ## When a new agent is put back (#18019)
193
194 A new agent is on trial until the forge answers one of its syncs with a 2xx. The old script stays beside it as `agent.sh.prev`.
195
196 What you see: the Games row (an **Agent** fact) and the top of the box's terminal screen read "On its previous agent: the new one (…) was put back: …" with the reason.
197
198 What puts it back: five starts without an answered sync (`FORGE_GAME_TRIAL_STARTS`), or ten minutes (`FORGE_GAME_TRIAL_S`) since the forge first answered with something that is not 2xx. A box that gets no answer at all, because the forge or the network is down, does not start or advance that clock, so an outage never costs a good agent.
199
200 What to do: nothing, or ship a fixed agent. The old agent does not fetch the refused one for six hours (`FORGE_GAME_RETRY_S`), then tries again; a different agent is fetched at once. A sync answered after a new agent clears the line.
201
202 To look: `agent.sh.refused` in the box's agent directory (`/opt/forge-game`) is the script that was put back, `.agent.back` holds its sha and why, and `journalctl -u forge-game-agent` has the line "back on the one before".
src/contract/openapi/routes/postApiV1GamesAgentSync.ts +1 −1
@@ -4,7 +4,7 @@ export const route: Route = {
44 method: "post",
55 path: "/api/v1/games/agent/sync",
66 summary: "A game box agent's sync: status, logs and results in; compose, .env and commands out",
7 detail: "The bearer is the game box's token. Send `{ agent, composeSha, services, logs, results, host, ask? (the proxy's /forge requests) }`; the answer is `{ composeSha, compose? (only when the sha differs), env, commands, told? (answers to those requests), agentSha? (only when there are no commands) }`, each command handed out once; a quick poll (`light: true`) sends results and `ask?` and is answered `{ commands, asked?, told? }`; agentSha is the sha256 of the agent this forge runs, which a box whose own differs fetches from GET /api/v1/games/agent/script",
7 detail: "The bearer is the game box's token. Send `{ agent, composeSha, services, logs, results, host, ask? (the proxy's /forge requests) }`; the answer is `{ composeSha, compose? (only when the sha differs), env, commands, told? (answers to those requests), agentSha? (only when there are no commands) }`, each command handed out once; a quick poll (`light: true`) sends results and `ask?` and is answered `{ commands, asked?, told? }`; an agent put back on its previous script after a new one never finished a sync sends `agentBack: { sha, why }`; agentSha is the sha256 of the agent this forge runs, which a box whose own differs fetches from GET /api/v1/games/agent/script",
88 auth: false,
99 role: "anonymous",
1010 refuses: [401],
src/core/migration-pins/20261204010000-game-box-agent-back.pin added +1
@@ -0,0 +1,1 @@
1 0aa297578d896506dd64908fae6a67d1ffc6feaeb322e553795b74fa94345eb9
src/core/migrations/20261204010000-game-box-agent-back.ts added +7
@@ -0,0 +1,7 @@
1 // A game box whose new agent was put back (#18019): the sha the box refused and why, as its
2 // rolled-back agent said them on its sync (games/agent_back.ts); '' when it runs the agent it was
3 // given. Additive.
4 export default `
5 ALTER TABLE game_box ADD COLUMN agent_back_sha TEXT NOT NULL DEFAULT '';
6 ALTER TABLE game_box ADD COLUMN agent_back_why TEXT NOT NULL DEFAULT '';
7 `;
src/games/agent.sh +63 −1
@@ -14,6 +14,52 @@ EVERY="${FORGE_GAME_EVERY:-5}"
1414 ONCE="${FORGE_GAME_ONCE:-0}"
1515 # How long the agent waits between word that a tool is missing.
1616 MISSING_EVERY="${FORGE_GAME_MISSING_EVERY:-30}"
17 # ---- A new agent is on trial until one sync is answered (#18019). self_update keeps the agent it
18 # replaced beside it (`agent.sh.prev`) and writes `.agent.trial` ("<epoch> <new sha> <previous
19 # sha>"). This runs first, before anything the new agent could fail at: a new agent that has started
20 # AGENT_TRY_STARTS times without a 2xx answer to a sync, or has been answered by the forge with
21 # something that is not 2xx for AGENT_TRY_S seconds (`.agent.bad` keeps when that began), is replaced
22 # by the previous one, which says so on every sync (`.agent.back`: "<sha>" and "<why>" lines) and
23 # does not fetch that sha again for AGENT_RETRY_S seconds. A box that gets no answer at all (the forge
24 # is down, the network is out) neither starts nor advances that clock: it is not the agent's fault.
25 # Systemd starts the one put back. ----
26 SELF="${FORGE_GAME_SELF:-${BASH_SOURCE[0]}}"
27 AGENT_TRIAL="$DIR/.agent.trial"
28 AGENT_STARTS="$DIR/.agent.starts"
29 AGENT_BACK="$DIR/.agent.back"
30 AGENT_BAD="$DIR/.agent.bad"
31 AGENT_RETRY_S="${FORGE_GAME_RETRY_S:-21600}"
32 AGENT_TRY_S="${FORGE_GAME_TRIAL_S:-600}"
33 AGENT_TRY_STARTS="${FORGE_GAME_TRIAL_STARTS:-5}"
34 agent_rollback() {
35 local why="$1" started new prev have
36 read -r started new prev <"$AGENT_TRIAL" 2>/dev/null
37 have="$(sha256sum "$SELF" 2>/dev/null | cut -d' ' -f1)"
38 # Only the agent that is on trial is put back, and only by one that still parses.
39 if [ "$have" = "$new" ] && [ -s "$SELF.prev" ] && bash -n "$SELF.prev" 2>/dev/null && cp -p "$SELF" "$SELF.refused" && mv -f "$SELF.prev" "$SELF"; then
40 printf '%s\n%s\n' "$new" "$why" >"$AGENT_BACK"
41 rm -f "$AGENT_TRIAL" "$AGENT_STARTS" "$AGENT_BAD"
42 echo "forge-game-agent: the new agent $new $why; back on the one before ($prev), exiting so systemd starts it" >&2
43 exit 0
44 fi
45 rm -f "$AGENT_TRIAL" "$AGENT_STARTS" "$AGENT_BAD"
46 }
47 # Whether the trial has run out of time, counted from the first answer that was not 2xx.
48 agent_trial_late() {
outdated

Time out with no answered sync rolls back even when the forge itself was unreachable. That pins the box to the old agent after a forge outage. Only count it when the forge answered and the new agent still failed, or let the refused sha be tried again later.

49 local tried
50 [ -f "$AGENT_TRIAL" ] || return 0
51 read -r tried _ <"$AGENT_BAD" 2>/dev/null
52 if [[ "${tried:-}" =~ ^[0-9]+$ ]] && [ $(($(date +%s) - tried)) -ge "$AGENT_TRY_S" ]; then
53 agent_rollback "was answered by the forge without success for ${AGENT_TRY_S} s"
54 fi
55 }
56 if [ -f "$AGENT_TRIAL" ] && [ "${1:-}" != "--boot-report" ]; then
57 n=$(($(cat "$AGENT_STARTS" 2>/dev/null || echo 0) + 1)) 2>/dev/null || n=1
58 echo "$n" >"$AGENT_STARTS"
59 [ "$n" -gt "$AGENT_TRY_STARTS" ] && agent_rollback "started $((n - 1)) times without a finished sync"
60 agent_trial_late
61 fi
62
1763 # Run by the boot (`--boot-report`), it reads its own env file, as systemd does for the service.
1864 if [ -z "${FORGE_URL:-}" ] && [ -r "$DIR/agent.env" ]; then
1965 set -a
@@ -313,12 +359,16 @@ fi
313359 # fetches it, checks its sha and its syntax, puts it in place atomically and exits, and systemd
314360 # starts the new one. A script whose sha is not the one answered never runs. ----
315361
316 SELF="${FORGE_GAME_SELF:-${BASH_SOURCE[0]}}"
317362 self_update() {
318363 local want="$1" have next got
319364 [[ "$want" =~ ^[0-9a-f]{64}$ ]] || return 0
320365 have="$(sha256sum "$SELF" 2>/dev/null | cut -d' ' -f1)"
321366 [ "$have" = "$want" ] && return 0
367 # One that was put back is not tried again for a while: the forge shows it meanwhile.
368 # After AGENT_RETRY_S it is, so a refusal the forge itself caused does not last for good.
369 if [ "$(head -n 1 "$AGENT_BACK" 2>/dev/null)" = "$want" ]; then
370 [ $(($(date +%s) - $(stat -c %Y "$AGENT_BACK" 2>/dev/null || echo 0))) -ge "$AGENT_RETRY_S" ] || return 0
371 fi
322372 next="$SELF.next"
323373 curl -fsS -m 30 -H "@$AUTH" "${FORGE_URL%/}/api/v1/games/agent/script" -o "$next" || { echo "forge-game-agent: the new agent could not be fetched" >&2; return 0; }
324374 got="$(sha256sum "$next" | cut -d' ' -f1)"
@@ -327,6 +377,10 @@ self_update() {
327377 echo "forge-game-agent: refused the fetched agent: its sha is $got, the forge said $want" >&2
328378 return 0
329379 fi
380 # The agent replaced stays beside the new one, on trial until a sync is answered.
381 cp -p "$SELF" "$SELF.prev" || { rm -f "$next"; echo "forge-game-agent: the previous agent could not be kept; not updating" >&2; return 0; }
382 printf '%s %s %s\n' "$(date +%s)" "$want" "$have" >"$AGENT_TRIAL"
383 rm -f "$AGENT_STARTS" "$AGENT_BAD"
330384 chmod 0755 "$next" && mv "$next" "$SELF"
331385 echo "forge-game-agent: updated to $want; exiting so systemd starts it" >&2
332386 exit 0
@@ -1437,6 +1491,8 @@ sync() {
14371491 --arg tokenSha "$(token_offer)" \
14381492 --slurpfile ask "$DIR/.sync.ask" \
14391493 --argjson got "$(desk_got)" \
1494 --arg backSha "$(sed -n 1p "$AGENT_BACK" 2>/dev/null)" \
1495 --arg backWhy "$(sed -n 2p "$AGENT_BACK" 2>/dev/null)" \
14401496 'def sect: {"0":"r","1":"l","4":"n","22":"r","24":"r","39":"r","30":"0","31":"4","32":"2","33":"6","34":"1","35":"5","36":"3","37":"7","90":"8","91":"c","92":"a","93":"e","94":"9","95":"d","96":"b","97":"f"} as $t
14411497 | ["30","31","32","33","34","35","36","37","90","91","92","93","94","95","96","97"] as $sixteen
14421498 # 38;5;n is one of the sixteen colours by its number; a background (48) and the other
@@ -1450,6 +1506,7 @@ sync() {
14501506 {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}
14511507 + (if $tokenSha == "" then {} else {tokenSha: $tokenSha} end)
14521508 + (if $ask[0] == [] then {} else {ask: $ask[0]} end)
1509 + (if $backSha == "" then {} else {agentBack: {sha: $backSha, why: $backWhy}} end)
14531510 | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1
14541511 # The answer is never a file: it can carry a world's signed link. Its status is its last line.
14551512 answer="$(curl -sS -m 20 -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.body" -w '\n%{http_code}' "${FORGE_URL%/}/api/v1/games/agent/sync")" || answer=$'\nnothing'
@@ -1457,6 +1514,8 @@ sync() {
14571514 answer="${answer%$'\n'*}"
14581515 if [[ "$code" != 2?? ]]; then
14591516 echo "forge-game-agent: the forge answered the sync $code" >&2
1517 # An answer that is not 2xx starts the trial's clock; no answer at all does not.
1518 [[ "$code" =~ ^[0-9]{3}$ ]] && [ -f "$AGENT_TRIAL" ] && [ ! -f "$AGENT_BAD" ] && date +%s >"$AGENT_BAD"
14601519 [ "$code" = 401 ] && token_refused
14611520 # The forge may have kept this body before the answer was lost: the next says so, and it
14621521 # skips the log lines it already holds, so a console never shows a line twice.
@@ -1466,6 +1525,8 @@ sync() {
14661525 return 1
14671526 fi
14681527 token_answered "$answer"
1528 # An answered sync proves the agent on trial; a fixed agent also clears what an earlier one put back.
1529 if [ -f "$AGENT_TRIAL" ]; then rm -f "$AGENT_TRIAL" "$AGENT_STARTS" "$AGENT_BAD" "$SELF.prev" "$SELF.refused" "$AGENT_BACK"; fi
14691530 POLLS=1
14701531 desk_heard "$DIR/.sync.body"
14711532 desk_told "$answer"
@@ -1966,6 +2027,7 @@ if [ "${FORGE_GAME_VOLUME_CHECK:-1}" = 1 ] && [ -n "$(volume_device)" ] && [ -n
19662027 fi
19672028
19682029 while :; do
2030 agent_trial_late
19692031 metadata_close
19702032 # The volume a held box waited for is there: systemd starts the agent again, which looks at it.
19712033 ! grep -q '^no-volume ' "$VOLUME_HOLD" 2>/dev/null || [ -z "$(volume_device)" ] || exit 0
src/games/agent_back.ts added +20
@@ -0,0 +1,20 @@
1 /**
2 * A game box whose new agent never finished a sync is put back on the one before (#18019, the
3 * agent's own `agent_rollback`). The old agent says so on each sync: `agentBack: { sha, why }`. The
4 * forge keeps what passes the checks below and every door says it alike.
5 */
6
7 /** What the sync said, if it is a sha256 and a short plain reason; empty otherwise. */
8 export function agentBackOf(raw: unknown): { sha: string; why: string } {
9 const none = { sha: "", why: "" };
10 if (typeof raw !== "object" || raw === null) return none;
11 const r = raw as { sha?: unknown; why?: unknown };
12 if (typeof r.sha !== "string" || !/^[0-9a-f]{64}$/.test(r.sha)) return none;
13 // Printable ASCII only, 200 at most: the reason is shown on pages and in the terminal.
14 const why = typeof r.why === "string" ? r.why.replace(/[^\x20-\x7e]/g, " ").trim().slice(0, 200) : "";
15 return { sha: r.sha, why };
16 }
17
18 /** The line every door shows; "" when the box runs the agent it was given. */
19 export const agentBackLine = (box: { agentBackSha: string; agentBackWhy: string }): string =>
20 box.agentBackSha === "" ? "" : `On its previous agent: the new one (${box.agentBackSha.slice(0, 12)}) was put back${box.agentBackWhy === "" ? "" : `: ${box.agentBackWhy}`}`;
src/games/store.ts +14 −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 { agentBackOf } from "./agent_back.ts";
2526 import { lendWhyOf } from "./lend_why.ts";
2627
2728 export const BOX_NAME = /^[a-z][a-z0-9-]{0,39}$/;
@@ -56,6 +57,9 @@ export interface GameBox {
5657 * (`lend_why.ts`).
5758 */
5859 readonly lendWhy: string;
60 /** The sha of a new agent the box put back, and why (`agent_back.ts`); "" when none. */
61 readonly agentBackSha: string;
62 readonly agentBackWhy: string;
5963 /** The latest diagnosis the agent sent (`diag.ts`), replaced each sync. */
6064 readonly diag: Diag;
6165 /** Each service's world snapshots, newest first, as the agent last listed them (`worlds.ts`). */
@@ -98,6 +102,8 @@ interface BoxRow {
98102 created_at: string;
99103 boot: string;
100104 lend_why: string;
105 agent_back_sha: string;
106 agent_back_why: string;
101107 diag_json: string;
102108 snapshots_json: string;
103109 restored_from: string;
@@ -123,6 +129,8 @@ const toBox = (r: BoxRow): GameBox => {
123129 createdAt: r.created_at,
124130 boot: r.boot,
125131 lendWhy: r.lend_why,
132 agentBackSha: r.agent_back_sha,
133 agentBackWhy: r.agent_back_why,
126134 diag: readDiag(r.diag_json),
127135 snapshots: readSnapshots(r.snapshots_json),
128136 restoredFrom: r.restored_from,
@@ -613,6 +621,8 @@ export interface SyncBody {
613621 readonly lend?: unknown;
614622 /** Why the box cannot lend, one of `lend_why.ts`'s phrases; "" or absent when it can. */
615623 readonly lendWhy?: unknown;
624 /** Set by an agent that put its new self back: `{ sha, why }` (`agent_back.ts`). */
625 readonly agentBack?: unknown;
616626 /** The box's word about its boot, sent without jq when a tool is missing or by the boot's report. */
617627 readonly boot?: string;
618628 /** The agent holds the answer's `jars`, checked, before it recreates the proxy. */
@@ -723,7 +733,8 @@ export function recordSync(
723733 db.query("UPDATE game_box SET seen_at = ?2, boot = ?3 WHERE id = ?1").run(box.id, at, str(body.boot, 2_000));
724734 return;
725735 }
726 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(
736 const back = agentBackOf(body.agentBack);
737 db.query("UPDATE game_box SET seen_at = ?2, host_json = ?3, compose_sha = ?4, boot = '', diag_json = ?5, jars = ?6, lend_why = ?7, agent_back_sha = ?8, agent_back_why = ?9 WHERE id = ?1").run(
727738 box.id,
728739 at,
729740 JSON.stringify(host),
@@ -731,6 +742,8 @@ export function recordSync(
731742 keptDiag(body.diag),
732743 body.jars === true ? 1 : 0,
733744 lendWhyOf(body.lendWhy),
745 back.sha,
746 back.why,
734747 );
735748 // An agent from before world snapshots sends none: the last list stays.
736749 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
@@ -30,6 +30,7 @@ import { eventsOf, eventWords, isBedrock, peopleOf, peopleWords, queuePeople } f
3030 import { findingsOf } from "../../games/player_events.ts";
3131 import { queueWorld, type WorldOp } from "../../games/worlds.ts";
3232 import { lendWords, lentRunnerOf, setLend } from "../../games/lend.ts";
33 import { agentBackLine } from "../../games/agent_back.ts";
3334 import { lendCannot } from "../../games/lend_why.ts";
3435 import { spareRow } from "../../games/spare_row.ts";
3536 import { healWords } from "../../games/heal.ts";
@@ -619,7 +620,8 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen {
619620 let top = 0;
620621 const lines = (w: number): string[] => {
621622 const b = listBoxes(f.app.db).find((x) => x.id === box.id) ?? box;
622 const held = heldLines(heldOn(f.app.db, f.user, b)).flatMap((l) => [...wrap(l, w), ""]);
623 const back = agentBackLine(b) === "" ? [] : [...wrap(agentBackLine(b), w), ""];
624 const held = [...back, ...heldLines(heldOn(f.app.db, f.user, b)).flatMap((l) => [...wrap(l, w), ""])];
623625 // The page's Spare rows, in the same words, first (kept a minute, so a redraw is free).
624626 const lending = lentRunnerOf(f.app.db, b.id) !== undefined;
625627 const lend = mayDo(roleOn(f.app.db, f.user, b.id), "owner") ? [lendWords(lending), ...(lending && b.lendWhy !== "" ? [lendCannot(b.lendWhy)] : []), ""] : [];
src/web/pages/games.ts +4 −1
@@ -20,6 +20,7 @@ import { blockChanges, serviceBlocks, shellBlocks, shellSays } from "../../termi
2020 import { blockEvent, blockHtml, blocksForm, terminalBlocksJs } from "../terminal_blocks.ts";
2121 import { statusRow } from "./security.ts";
2222 import { lendState, lentRunnerOf, setLend } from "../../games/lend.ts";
23 import { agentBackLine } from "../../games/agent_back.ts";
2324 import { lendCannot } from "../../games/lend_why.ts";
2425 import { spareRow } from "../../games/spare_row.ts";
2526 import { healWords } from "../../games/heal.ts";
@@ -190,7 +191,9 @@ export function gamesPage(ctx: Ctx): Response {
190191 ${b.seenAt === "" ? "never seen" : html`seen ${time(b.seenAt)}`} · host ${mib(b.host["memUsedMiB"])} of
191192 ${mib(b.host["memMiB"])}`,
192193 // The box's own word about its boot, until its agent syncs in full.
193 ...(b.boot === "" ? {} : { facts: [{ label: "Boot", value: bootWords(b) }] }),
194 ...(b.boot === "" && b.agentBackSha === ""
195 ? {}
196 : { facts: [...(b.boot === "" ? [] : [{ label: "Boot", value: bootWords(b) }]), ...(b.agentBackSha === "" ? [] : [{ label: "Agent", value: agentBackLine(b) }])] }),

The Agent fact is shown on the page but no test renders the page with agentBackSha set. Add one that would fail without this line.

194197 }),
195198 ),
196199 )}`,
test/game-agent-rollback.test.ts added +205
@@ -0,0 +1,205 @@
1 /**
2 * A game box whose new agent never finishes a sync goes back to the one before (#18019): the update
3 * keeps the previous script beside the new one; a new agent that exits again and again, or runs
4 * past its time without an answered sync, is replaced by the previous one, which says so on its
5 * sync, never fetches the refused sha again, and the forge shows the box on its old agent and why.
6 *
7 * The agent runs as bash here. With FORGE_TEST_UBUNTU=1 and docker, the same runs go in
8 * ubuntu:24.04 (the box's own image: it installs curl and jq first, so it needs the network).
9 */
10 import { $ } from "bun";
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
12 import { existsSync, mkdirSync, mkdtempSync, readFileSync, utimesSync, writeFileSync } from "node:fs";
13 import { rm } from "node:fs/promises";
14 import { tmpdir } from "node:os";
15 import { join } from "node:path";
16 import { createApp, type App } from "../src/app.ts";
17 import { agentBackLine } from "../src/games/agent_back.ts";
18 import { AGENT_SH } from "../src/games/boot.ts";
19 import { createSession } from "../src/core/sessions.ts";
20 import { createUser } from "../src/core/users.ts";
21 import { createGameBox, grant, listBoxes, recordSync } from "../src/games/store.ts";
22 import { forgeHttp } from "../src/http/server.ts";
23 import { gameBoxScreen } from "../src/tui/screens/games.ts";
24 import { quietCtx, screenText, sessionFor } from "./helpers/tui-text.ts";
25
26 const TOKEN = "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
27 const lacks = ["bash", "curl", "jq"].filter((t) => Bun.which(t) === null);
28 const sha = (text: string) => new Bun.CryptoHasher("sha256").update(text).digest("hex");
29 const inUbuntu = process.env["FORGE_TEST_UBUNTU"] === "1" && Bun.which("docker") !== null;
30
31 // The new agent: the real one with a failure at runtime, right after its trial guard.
32 const broken = `${AGENT_SH.replace("# Run by the boot (`--boot-report`)", "echo 'new agent: jq exploded' >&2; exit 7\n# Run by the boot (`--boot-report`)")}\n# a broken agent\n`;
33 const NEW = sha(broken);
34
35 describe("a new agent on trial", () => {
36 async function box(extra: Record<string, string> = {}) {
37 const root = mkdtempSync(join(tmpdir(), "forge-game-rollback-"));
38 mkdirSync(join(root, "game"));
39 const self = join(root, "agent.sh");
40 writeFileSync(self, AGENT_SH);
41 const syncs: Record<string, unknown>[] = [];
42 let want = NEW;
43 let fail = 0;
44 const forge = Bun.serve({
45 port: 0,
46 hostname: "127.0.0.1",
47 async fetch(req) {
48 const path = new URL(req.url).pathname;
49 if (path === "/api/v1/games/agent/script") return new Response(broken);
50 if (fail > 0) return new Response("no", { status: fail });
51 syncs.push((await req.json().catch(() => ({}))) as Record<string, unknown>);
52 return Response.json({ composeSha: "", commands: [], agentSha: want });
53 },
54 });
55 const run = async () => {
56 const env = {
57 PATH: process.env["PATH"] ?? "",
58 HOME: root,
59 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
60 FORGE_GAME_TOKEN: TOKEN,
61 FORGE_GAME_DIR: join(root, "game"),
62 FORGE_GAME_DOCKER: "true",
63 FORGE_GAME_ONCE: "1",
64 FORGE_GAME_DIAG_S: "0",
65 FORGE_GAME_VOLUME_CHECK: "0",
66 ...extra,
67 };
68 const ran = inUbuntu
69 ? await $`docker run --rm --network host -v ${root}:${root} -w ${root} ${Object.entries(env).flatMap(([k, v]) => ["-e", `${k}=${v}`])} ubuntu:24.04 bash -c ${`apt-get update -qq >/dev/null && apt-get install -y -qq curl jq >/dev/null && bash ${self}`}`.quiet().nothrow()
70 : await $`bash ${self}`.env(env).quiet().nothrow();
71 return { code: ran.exitCode, said: ran.stderr.toString() };
72 };
73 // A new agent that runs fine, on trial beside the one it replaced (no update through the
74 // forge).
75 const onTrial = () => {
76 const fine = `${AGENT_SH}\n# a fine one\n`;
77 writeFileSync(self, fine);
78 writeFileSync(`${self}.prev`, AGENT_SH);
79 writeFileSync(join(root, "game/.agent.trial"), `${Math.floor(Date.now() / 1000)} ${sha(fine)} ${sha(AGENT_SH)}\n`);
80 want = sha(fine);
81 return fine;
82 };
83 return { root, self, onTrial, syncs, run, forge, failWith: (n: number) => void (fail = n), setWant: (w: string) => void (want = w), done: async () => (forge.stop(true), rm(root, { recursive: true, force: true })) };
84 }
85
86 test.skipIf(lacks.length > 0)("the update keeps the previous script beside the new one, and an answered sync ends the trial", async () => {
87 const b = await box();
88 try {
89 await b.run();
90 expect(readFileSync(b.self, "utf8")).toBe(broken);
91 expect(readFileSync(`${b.self}.prev`, "utf8")).toBe(AGENT_SH);
92 expect(readFileSync(join(b.root, "game/.agent.trial"), "utf8").trim().split(" ").slice(1)).toEqual([NEW, sha(AGENT_SH)]);
93 // A good new agent: answered, so no longer on trial.
94 const good = `${AGENT_SH}\n# a good one\n`;
95 writeFileSync(b.self, good);
96 writeFileSync(join(b.root, "game/.agent.trial"), `${Math.floor(Date.now() / 1000)} ${sha(good)} ${sha(AGENT_SH)}\n`);
97 b.setWant(sha(good));
98 await b.run();
99 expect(existsSync(join(b.root, "game/.agent.trial"))).toBe(false);
100 expect(existsSync(`${b.self}.prev`)).toBe(false);
101 } finally {
102 await b.done();
103 }
104 }, 120_000);
105
106 test.skipIf(lacks.length > 0)("a new agent that exits again and again is replaced, says so on its sync, and is not fetched again", async () => {
107 const b = await box({ FORGE_GAME_TRIAL_STARTS: "2" });
108 try {
109 await b.run(); // updates
110 expect((await b.run()).code).toBe(7); // start 1
111 expect((await b.run()).code).toBe(7); // start 2
112 const back = await b.run(); // start 3: past the limit
113 expect(back.code).toBe(0);
114 expect(back.said).toContain("back on the one before");
115 expect(readFileSync(b.self, "utf8")).toBe(AGENT_SH);
116 expect(readFileSync(`${b.self}.refused`, "utf8")).toBe(broken);
117 // The agent put back syncs, says why, and does not fetch the refused sha.
118 b.syncs.length = 0;
119 const next = await b.run();
120 expect(next.said).not.toContain("updated to");
121 expect(b.syncs[0]?.["agentBack"]).toMatchObject({ sha: NEW });
122 expect(JSON.stringify(b.syncs[0]?.["agentBack"])).toContain("started 2 times");
123 expect(readFileSync(b.self, "utf8")).toBe(AGENT_SH);
124 } finally {
125 await b.done();
126 }
127 }, 120_000);
128
129 test.skipIf(lacks.length > 0)("a new agent the forge keeps answering with an error for its time is replaced, and tried again after a while", async () => {
130 const b = await box({ FORGE_GAME_TRIAL_S: "60", FORGE_GAME_RETRY_S: "3600" });
131 try {
132 b.onTrial();
133 b.failWith(500);
134 await b.run(); // the first error answer starts the clock
135 expect(existsSync(join(b.root, "game/.agent.bad"))).toBe(true);
136 writeFileSync(join(b.root, "game/.agent.bad"), `${Math.floor(Date.now() / 1000) - 120}\n`);
137 expect((await b.run()).said).toContain("without success for 60 s");
138 expect(readFileSync(b.self, "utf8")).toBe(AGENT_SH);
139 expect(readFileSync(join(b.root, "game/.agent.back"), "utf8")).toContain(sha(`${AGENT_SH}\n# a fine one\n`));
140 // Barred for now; once the refusal is old enough, the sha is fetched again.
141 b.failWith(0);
142 expect((await b.run()).said).not.toContain("updated to");
143 const old = new Date(Date.now() - 7_200_000);
144 utimesSync(join(b.root, "game/.agent.back"), old, old);
145 // (this forge serves other bytes for it, so the fetch is refused: it was tried.)
146 expect((await b.run()).said).toContain("refused the fetched agent");
147 } finally {
148 await b.done();
149 }
150 }, 120_000);
151
152 test.skipIf(lacks.length > 0)("a forge that does not answer neither starts nor advances the clock: the new agent stays", async () => {
153 const b = await box({ FORGE_GAME_TRIAL_S: "0" });
154 try {
155 const fine = b.onTrial();
156 b.forge.stop(true); // the forge is down
157 for (let i = 0; i < 2; i++) {
158 const ran = await b.run();
159 expect(ran.said).not.toContain("back on the one before");
160 }
161 expect(readFileSync(b.self, "utf8")).toBe(fine);
162 expect(existsSync(join(b.root, "game/.agent.back"))).toBe(false);
163 expect(existsSync(join(b.root, "game/.agent.bad"))).toBe(false);
164 } finally {
165 await b.done();
166 }
167 }, 120_000);
168 });
169
170 describe("the forge shows the box on its old agent", () => {
171 let dir = "";
172 let app: App;
173 beforeAll(() => {
174 dir = mkdtempSync(join(tmpdir(), "forge-game-back-"));
175 app = createApp({ dataDir: dir, port: 0 });
176 });
177 afterAll(async () => {
178 app.close();
179 await rm(dir, { recursive: true, force: true });
180 });
181
182 test("a sync's agentBack is kept, checked and cleared when the box stops saying it", () => {
183 const made = createGameBox(app.db, { name: "mc" });
184 const get = () => listBoxes(app.db).find((b) => b.id === made.id)!;
185 recordSync(app.db, get(), { host: {}, agentBack: { sha: NEW, why: "started 5 times\u0007 without a finished sync" } });
186 expect(agentBackLine(get())).toBe(`On its previous agent: the new one (${NEW.slice(0, 12)}) was put back: started 5 times without a finished sync`);
187 recordSync(app.db, get(), { host: {}, agentBack: { sha: "nope", why: "x" } });
188 expect(agentBackLine(get())).toBe("");
189 });
190
191 test("the Games row and the box's terminal screen carry the line", async () => {
192 const made = createGameBox(app.db, { name: "shown" });
193 const u = await createUser(app.db, { username: "olive", email: "[email protected]", password: "a-good-passphrase", origin: "seed", trusted: true });
194 if (!u.ok) throw new Error("user");
195 grant(app.db, made.id, u.value.id, "owner");
196 recordSync(app.db, listBoxes(app.db).find((b) => b.id === made.id)!, { host: {}, agentBack: { sha: NEW, why: "started 5 times without a finished sync" } });
197 const line = agentBackLine(listBoxes(app.db).find((b) => b.id === made.id)!);
198 const page = await forgeHttp(app).handle(new Request("http://forge.test/games", { headers: { cookie: `forge_session=${createSession(app.db, u.value.id).token}` } }));
199 const html = await page.text();
200 expect(html).toContain("On its previous agent: the new one (" + NEW.slice(0, 12) + ")");
201 const text = screenText(gameBoxScreen(sessionFor(app, u.value), quietCtx(), listBoxes(app.db).find((b) => b.id === made.id)!), 100, 30).replace(/\s+/g, " ");
202 expect(text).toContain("On its previous agent: the new one (" + NEW.slice(0, 12) + ")");
203 expect(line.length).toBeGreaterThan(0);
204 });
205 });
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: "", lendWhy: "", 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: "", agentBackSha: "", agentBackWhy: "", 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"]);

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

Keyboard shortcuts

Docs