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
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
11 files
changed +331
−6
- docs/features/games.md
- src/contract/openapi/routes/postApiV1GamesAgentSync.ts
- src/core/migration-pins/20261204010000-game-box-agent-back.pin
- src/core/migrations/20261204010000-game-box-agent-back.ts
- src/games/agent.sh
- src/games/agent_back.ts
- src/games/store.ts
- src/tui/screens/games.ts
- src/web/pages/games.ts
- test/game-agent-rollback.test.ts
- test/game-spare.test.ts
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 | ||
| 188 | 188 | `/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. |
| 189 | 189 | |
| 190 | 190 | **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 = { | ||
| 4 | 4 | method: "post", |
| 5 | 5 | path: "/api/v1/games/agent/sync", |
| 6 | 6 | 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", | |
| 8 | 8 | auth: false, |
| 9 | 9 | role: "anonymous", |
| 10 | 10 | 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}" | ||
| 14 | 14 | ONCE="" |
| 15 | 15 | # How long the agent waits between word that a tool is missing. |
| 16 | 16 | MISSING_EVERY="" |
| 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="" | |
| 27 | AGENT_TRIAL="/.agent.trial" | |
| 28 | AGENT_STARTS="/.agent.starts" | |
| 29 | AGENT_BACK="/.agent.back" | |
| 30 | AGENT_BAD="/.agent.bad" | |
| 31 | AGENT_RETRY_S="" | |
| 32 | AGENT_TRY_S="" | |
| 33 | AGENT_TRY_STARTS="" | |
| 34 | agent_rollback() { | |
| 35 | local why="$1" started new prev have | |
| 36 | read -r started new prev <"" 2>/dev/null | |
| 37 | have="$(sha256sum "" 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 [ "" = "" ] && [ -s ".prev" ] && bash -n ".prev" 2>/dev/null && cp -p "" ".refused" && mv -f ".prev" ""; then | |
| 40 | printf '%s\n%s\n' "" "" >"" | |
| 41 | rm -f "" "" "" | |
| 42 | echo "forge-game-agent: the new agent ; back on the one before (), exiting so systemd starts it" >&2 | |
| 43 | exit 0 | |
| 44 | fi | |
| 45 | rm -f "" "" "" | |
| 46 | } | |
| 47 | # Whether the trial has run out of time, counted from the first answer that was not 2xx. | |
| 48 | agent_trial_late() { | |
| 49 | local tried | |
| 50 | [ -f "" ] || return 0 | |
| 51 | read -r tried _ <"" 2>/dev/null | |
| 52 | if [[ "" =~ ^[0-9]+$ ]] && [ -ge "" ]; then | |
| 53 | agent_rollback "was answered by the forge without success for s" | |
| 54 | fi | |
| 55 | } | |
| 56 | if [ -f "" ] && [ "" != "--boot-report" ]; then | |
| 57 | n= 2>/dev/null || n=1 | |
| 58 | echo "" >"" | |
| 59 | [ "" -gt "" ] && agent_rollback "started $((n - 1)) times without a finished sync" | |
| 60 | agent_trial_late | |
| 61 | fi | |
| 62 | ||
| 17 | 63 | # Run by the boot (`--boot-report`), it reads its own env file, as systemd does for the service. |
| 18 | 64 | if [ -z "" ] && [ -r "/agent.env" ]; then |
| 19 | 65 | set -a |
| @@ -313,12 +359,16 @@ fi | ||
| 313 | 359 | # fetches it, checks its sha and its syntax, puts it in place atomically and exits, and systemd |
| 314 | 360 | # starts the new one. A script whose sha is not the one answered never runs. ---- |
| 315 | 361 | |
| 316 | SELF="" | |
| 317 | 362 | self_update() { |
| 318 | 363 | local want="$1" have next got |
| 319 | 364 | [[ "" =~ ^[0-9a-f]{64}$ ]] || return 0 |
| 320 | 365 | have="$(sha256sum "" 2>/dev/null | cut -d' ' -f1)" |
| 321 | 366 | [ "" = "" ] && 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 "" 2>/dev/null)" = "" ]; then | |
| 370 | [ -ge "" ] || return 0 | |
| 371 | fi | |
| 322 | 372 | next=".next" |
| 323 | 373 | curl -fsS -m 30 -H "@" "/api/v1/games/agent/script" -o "" || { echo "forge-game-agent: the new agent could not be fetched" >&2; return 0; } |
| 324 | 374 | got="$(sha256sum "" | cut -d' ' -f1)" |
| @@ -327,6 +377,10 @@ self_update() { | ||
| 327 | 377 | echo "forge-game-agent: refused the fetched agent: its sha is , the forge said " >&2 |
| 328 | 378 | return 0 |
| 329 | 379 | fi |
| 380 | # The agent replaced stays beside the new one, on trial until a sync is answered. | |
| 381 | cp -p "" ".prev" || { rm -f ""; echo "forge-game-agent: the previous agent could not be kept; not updating" >&2; return 0; } | |
| 382 | printf '%s %s %s\n' "$(date +%s)" "" "" >"" | |
| 383 | rm -f "" "" | |
| 330 | 384 | chmod 0755 "" && mv "" "" |
| 331 | 385 | echo "forge-game-agent: updated to ; exiting so systemd starts it" >&2 |
| 332 | 386 | exit 0 |
| @@ -1437,6 +1491,8 @@ sync() { | ||
| 1437 | 1491 | --arg tokenSha "$(token_offer)" \ |
| 1438 | 1492 | --slurpfile ask "/.sync.ask" \ |
| 1439 | 1493 | --argjson got "$(desk_got)" \ |
| 1494 | --arg backSha "$(sed -n 1p "" 2>/dev/null)" \ | |
| 1495 | --arg backWhy "$(sed -n 2p "" 2>/dev/null)" \ | |
| 1440 | 1496 | '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 |
| 1441 | 1497 | | ["30","31","32","33","34","35","36","37","90","91","92","93","94","95","96","97"] as |
| 1442 | 1498 | # 38;5;n is one of the sixteen colours by its number; a background (48) and the other |
| @@ -1450,6 +1506,7 @@ sync() { | ||
| 1450 | 1506 | {agent: 1, composeSha: , services: [0], logs: [0], results: [0], host: [0], diag: [0], people: [0], metrics: [0], snapshots: [0], chat: [0].lines, chatId: [0].id, lend: , lendWhy: , retry: , jars: true, got: } |
| 1451 | 1507 | + (if == "" then {} else {tokenSha: } end) |
| 1452 | 1508 | + (if [0] == [] then {} else {ask: [0]} end) |
| 1509 | + (if == "" then {} else {agentBack: {sha: , why: }} end) | |
| 1453 | 1510 | | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1 |
| 1454 | 1511 | # The answer is never a file: it can carry a world's signed link. Its status is its last line. |
| 1455 | 1512 | answer="$(curl -sS -m 20 -H "@" -H 'content-type: application/json' --data-binary "@/.sync.body" -w '\n%{http_code}' "/api/v1/games/agent/sync")" || answer=$'\nnothing' |
| @@ -1457,6 +1514,8 @@ sync() { | ||
| 1457 | 1514 | answer="" |
| 1458 | 1515 | if [[ "" != 2?? ]]; then |
| 1459 | 1516 | echo "forge-game-agent: the forge answered the sync " >&2 |
| 1517 | # An answer that is not 2xx starts the trial's clock; no answer at all does not. | |
| 1518 | [[ "" =~ ^[0-9]{3}$ ]] && [ -f "" ] && [ ! -f "" ] && date +%s >"" | |
| 1460 | 1519 | [ "" = 401 ] && token_refused |
| 1461 | 1520 | # The forge may have kept this body before the answer was lost: the next says so, and it |
| 1462 | 1521 | # skips the log lines it already holds, so a console never shows a line twice. |
| @@ -1466,6 +1525,8 @@ sync() { | ||
| 1466 | 1525 | return 1 |
| 1467 | 1526 | fi |
| 1468 | 1527 | token_answered "" |
| 1528 | # An answered sync proves the agent on trial; a fixed agent also clears what an earlier one put back. | |
| 1529 | if [ -f "" ]; then rm -f "" "" "" ".prev" ".refused" ""; fi | |
| 1469 | 1530 | POLLS=1 |
| 1470 | 1531 | desk_heard "/.sync.body" |
| 1471 | 1532 | desk_told "" |
| @@ -1966,6 +2027,7 @@ if [ "${FORGE_GAME_VOLUME_CHECK:-1}" = 1 ] && [ -n "$(volume_device)" ] && [ -n | ||
| 1966 | 2027 | fi |
| 1967 | 2028 | |
| 1968 | 2029 | while :; do |
| 2030 | agent_trial_late | |
| 1969 | 2031 | metadata_close |
| 1970 | 2032 | # The volume a held box waited for is there: systemd starts the agent again, which looks at it. |
| 1971 | 2033 | ! grep -q '^no-volume ' "" 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"; | ||
| 22 | 22 | import type { User } from "../core/users.ts"; |
| 23 | 23 | import { sha256 } from "../kernel/hash.ts"; |
| 24 | 24 | import { id as newId } from "../kernel/id.ts"; |
| 25 | import { agentBackOf } from "./agent_back.ts"; | |
| 25 | 26 | import { lendWhyOf } from "./lend_why.ts"; |
| 26 | 27 | |
| 27 | 28 | export const BOX_NAME = /^[a-z][a-z0-9-]{0,39}$/; |
| @@ -56,6 +57,9 @@ export interface GameBox { | ||
| 56 | 57 | * (`lend_why.ts`). |
| 57 | 58 | */ |
| 58 | 59 | 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; | |
| 59 | 63 | /** The latest diagnosis the agent sent (`diag.ts`), replaced each sync. */ |
| 60 | 64 | readonly diag: Diag; |
| 61 | 65 | /** Each service's world snapshots, newest first, as the agent last listed them (`worlds.ts`). */ |
| @@ -98,6 +102,8 @@ interface BoxRow { | ||
| 98 | 102 | created_at: string; |
| 99 | 103 | boot: string; |
| 100 | 104 | lend_why: string; |
| 105 | agent_back_sha: string; | |
| 106 | agent_back_why: string; | |
| 101 | 107 | diag_json: string; |
| 102 | 108 | snapshots_json: string; |
| 103 | 109 | restored_from: string; |
| @@ -123,6 +129,8 @@ const toBox = (r: BoxRow): GameBox => { | ||
| 123 | 129 | createdAt: r.created_at, |
| 124 | 130 | boot: r.boot, |
| 125 | 131 | lendWhy: r.lend_why, |
| 132 | agentBackSha: r.agent_back_sha, | |
| 133 | agentBackWhy: r.agent_back_why, | |
| 126 | 134 | diag: readDiag(r.diag_json), |
| 127 | 135 | snapshots: readSnapshots(r.snapshots_json), |
| 128 | 136 | restoredFrom: r.restored_from, |
| @@ -613,6 +621,8 @@ export interface SyncBody { | ||
| 613 | 621 | readonly lend?: unknown; |
| 614 | 622 | /** Why the box cannot lend, one of `lend_why.ts`'s phrases; "" or absent when it can. */ |
| 615 | 623 | readonly lendWhy?: unknown; |
| 624 | /** Set by an agent that put its new self back: `{ sha, why }` (`agent_back.ts`). */ | |
| 625 | readonly agentBack?: unknown; | |
| 616 | 626 | /** The box's word about its boot, sent without jq when a tool is missing or by the boot's report. */ |
| 617 | 627 | readonly boot?: string; |
| 618 | 628 | /** The agent holds the answer's `jars`, checked, before it recreates the proxy. */ |
| @@ -723,7 +733,8 @@ export function recordSync( | ||
| 723 | 733 | db.query("UPDATE game_box SET seen_at = ?2, boot = ?3 WHERE id = ?1").run(box.id, at, str(body.boot, 2_000)); |
| 724 | 734 | return; |
| 725 | 735 | } |
| 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( | |
| 727 | 738 | box.id, |
| 728 | 739 | at, |
| 729 | 740 | JSON.stringify(host), |
| @@ -731,6 +742,8 @@ export function recordSync( | ||
| 731 | 742 | keptDiag(body.diag), |
| 732 | 743 | body.jars === true ? 1 : 0, |
| 733 | 744 | lendWhyOf(body.lendWhy), |
| 745 | back.sha, | |
| 746 | back.why, | |
| 734 | 747 | ); |
| 735 | 748 | // An agent from before world snapshots sends none: the last list stays. |
| 736 | 749 | 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 | ||
| 30 | 30 | import { findingsOf } from "../../games/player_events.ts"; |
| 31 | 31 | import { queueWorld, type WorldOp } from "../../games/worlds.ts"; |
| 32 | 32 | import { lendWords, lentRunnerOf, setLend } from "../../games/lend.ts"; |
| 33 | import { agentBackLine } from "../../games/agent_back.ts"; | |
| 33 | 34 | import { lendCannot } from "../../games/lend_why.ts"; |
| 34 | 35 | import { spareRow } from "../../games/spare_row.ts"; |
| 35 | 36 | import { healWords } from "../../games/heal.ts"; |
| @@ -619,7 +620,8 @@ export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | ||
| 619 | 620 | let top = 0; |
| 620 | 621 | const lines = (w: number): string[] => { |
| 621 | 622 | 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), ""])]; | |
| 623 | 625 | // The page's Spare rows, in the same words, first (kept a minute, so a redraw is free). |
| 624 | 626 | const lending = lentRunnerOf(f.app.db, b.id) !== undefined; |
| 625 | 627 | 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 | ||
| 20 | 20 | import { blockEvent, blockHtml, blocksForm, terminalBlocksJs } from "../terminal_blocks.ts"; |
| 21 | 21 | import { statusRow } from "./security.ts"; |
| 22 | 22 | import { lendState, lentRunnerOf, setLend } from "../../games/lend.ts"; |
| 23 | import { agentBackLine } from "../../games/agent_back.ts"; | |
| 23 | 24 | import { lendCannot } from "../../games/lend_why.ts"; |
| 24 | 25 | import { spareRow } from "../../games/spare_row.ts"; |
| 25 | 26 | import { healWords } from "../../games/heal.ts"; |
| @@ -190,7 +191,9 @@ export function gamesPage(ctx: Ctx): Response { | ||
| 190 | 191 | ${b.seenAt === "" ? "never seen" : html`seen ${time(b.seenAt)}`} · host ${mib(b.host["memUsedMiB"])} of |
| 191 | 192 | ${mib(b.host["memMiB"])}`, |
| 192 | 193 | // 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) }])] }), | |
| 194 | 197 | }), |
| 195 | 198 | ), |
| 196 | 199 | )}`, |
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 | ||
| 150 | 150 | db.exec((await import("../src/core/migrations/20261201050000-game-metrics.ts")).default); |
| 151 | 151 | db.exec((await import("../src/core/migrations/20261202000000-game-people.ts")).default.replace(/^.*game_box.*$/m, "")); |
| 152 | 152 | 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, }; | |
| 154 | 154 | const now = Date.parse("2026-12-02T00:00:00Z"); |
| 155 | 155 | const first = spareRow(db, dataDir, box, now); |
| 156 | 156 | expect(first[1]).toEqual(["Forge checks, last 7 days", "not measured"]); |
new above
offline
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.