Merge remote-tracking branch 'upstream/main' into noc-window

# Conflicts:
#	CHANGELOG.md
#	src/game/99-loop.js
#	tests/harness.js
This commit is contained in:
Christopher Hawker 2026-11-04 20:01:57 +11:00
commit f9d24699c1
83 changed files with 3845 additions and 1031 deletions

View file

@ -11,8 +11,10 @@ src/ the game page, in pieces
i18n/en.js the English for every label → inlined at the top of the page's <script>
styles/NN-*.css → pasted into the page's <style>, in path order
game/NN-area/NN-*.js → pasted into the page's <script>, in path order
agent/NN-*.js → the agent facade the MCP server drives: development page only (@include-dev)
site/ static files copied to the build as they are (dictionaries, icons, sw.js…)
scripts/lib/page.js the assembler: <!-- @include DIR --> → every file under src/DIR, sorted
scripts/lib/page.js the assembler: <!-- @include DIR --> → every file under src/DIR, sorted;
<!-- @include-dev DIR --> the same, in the development page only
scripts/build.js _site/ = site/ + the assembled page, version-stamped, release notes baked in
```
@ -44,12 +46,19 @@ hoisted across files, and top-level statements run in path order. Find code by n
`src/styles/` holds the CSS the same way: base, HUD, drawers, toasts, modal, tablet, then phone.
`src/agent/` is the agent facade (`window.TUBES`): the typed commands, reads and screens the MCP server plays
through. It is assembled into the **development page** only (`npm run dev`, the MCP server, tests that ask for it);
the page players get never has it ([ADR 0004](adr/0004-dev-only-code.md)). Its top-level names all start with
`api`/`API_`, and nothing outside `src/agent/` may use them. Where it must reach into the game (agent mode in the
player's tab locks the clock and draws its badge and Settings section), the game offers `HOOKS` and the flag
`UI.clockLocked` (`50-state.js`), empty and false in the page players get, and `runClock(dt)` (`99-loop.js`).
Rules for the source (checked by `tests/build.test.js` and the assembler): files are named
`NN-lower-case.js`/`.css`, end with a newline and never close their `<script>`/`<style>`; top-level code
may only use top-level values from earlier files; tables people add to have one entry per line, the
id-keyed ones sorted. New features get their own file in the right folder (`edit-the-game` skill).
Development runs on `npm run dev` (assembles on every request, reloads on save);
`npm run page -- -o FILE` writes the assembled page.
Development runs on `npm run dev` (assembles the development page on every request, reloads on save);
`npm run page -- -o FILE` writes the page players get, `npm run page -- --source --dev -o FILE` the development page.
## Other files
@ -62,21 +71,22 @@ Development runs on `npm run dev` (assembles on every request, reloads on save);
| `scripts/lib/page.js` | Assembles the page from `src/` (also from a git ref with `--ref`, for performance baselines) |
| `scripts/lib/compile-labels.js` | Shrinks labels to short ids in the shipped page and dictionaries |
| `scripts/build.js` | Builds `_site/` for GitHub Pages: copies `site/`, writes the page, stamps `__VERSION__`/`__BUILD_DATE__`, bakes release notes, writes `version.json` |
| `scripts/dev.js` | `npm run dev`: development server, no dependencies |
| `scripts/dev.js` | `npm run dev`: development server (loopback unless `--host`), serving the development page and hosting the agent relay |
| `scripts/test.js` | `npm test`: runs every `tests/*.test.js` |
| `scripts/release-notes.js` | Extracts a version's CHANGELOG bullets |
| `scripts/perf-bench.js`, `perf-browser.js`, `perf-stats.js`, `perf-fixture.js` | Big-network benchmark, base vs head, headless and in Chromium as a desktop and a throttled phone, with a significance test per row (posted on every PR by `perf.yml` + `perf-comment.yml`), and the generator of its save, `tests/fixtures/big-network.json` |
| `scripts/mcp.js`, `scripts/lib/mcp-game.js`, `scripts/lib/mcp-commands.js`, `scripts/lib/mcp-page.js` | The game as a local MCP server: typed tools to play, inspect and debug it from an AI client ([MCP.md](MCP.md)) |
| `scripts/mcp.js`, `scripts/lib/mcp-game.js`, `scripts/lib/mcp-headless.js`, `src/agent/` | The game as a local MCP server, on the official SDK over stdio or HTTP: typed tools to play, inspect and debug it from an AI client, headless or in the player's own tab ([MCP.md](MCP.md)) |
| `scripts/agent/relay.js`, `scripts/lib/mcp-browser.js`, `scripts/lib/relay-client.js` | The agent relay `npm run dev` hosts at `/agent`, and the MCP server's side of it: how a tool reaches the game in the player's tab |
| `scripts/i18n-check.js`, `scripts/i18n-add.js`, `scripts/lib/dict.js` | Translation coverage and dictionary order; adding, renaming and removing entries |
| `scripts/legacy/` | The splitter that made `src/` from the old `site/index.html` (and gave its text labels), and `port-branch.js`, which carries older branches over |
| `tests/harness.js` | Loads the assembled page in jsdom with a seeded `Math.random` and a fake canvas |
| `tests/harness.js` | Loads the assembled page in jsdom with a seeded `Math.random` and a fake canvas: the players' page, or the development page with `{agent: true}` |
| `.github/workflows/ci.yml` | Tests and build on every push and PR |
| `.github/workflows/auto-release.yml` | On a `package.json` version bump on `main`: test, tag, GitHub release from the CHANGELOG, start the deploy |
| `.github/workflows/release.yml` | Builds and deploys to GitHub Pages, the only workflow that can |
| `.github/workflows/weekly-puzzle.yml` | Sunday 03:37 UTC: makes the week's puzzle, commits it to `main` (data only, no release) and starts `release.yml` for the live release tag with `weekly=true` |
| `scripts/weekly-puzzle.js`, `site/puzzles/weekly/` | The weekly puzzle generator and its output, one `<key>.json` per week plus `index.json` (see below) |
| `scripts/weekly-scenario.js`, `scripts/lib/scenario-bot.js`, `site/scenarios/weekly/` | The weekly scenario generator, its reference player and its output (see below) |
| `docs/adr/` | Decisions: GitHub Pages only (0001), one page assembled at build (0002), translations by label (0003) |
| `docs/adr/` | Decisions: GitHub Pages only (0001), one page assembled at build (0002), translations by label (0003), development-only code (0004) |
## Globals

View file

@ -1,36 +1,109 @@
# Series of Tubes as an MCP server
`scripts/mcp.js` lets an AI client (Claude Code, Claude Desktop, any MCP client) play, inspect and debug the game
through typed tools. It runs on your machine over stdio and loads the game from this checkout's `src/`, the way the
tests do: one page in jsdom, seeded, with no animation loop. Nothing is hosted and the game page does not change, so
it stays within [ADR 0001](adr/0001-github-pages-only.md): it is a local tool, like `npm run dev`.
through typed tools, over stdio or HTTP, in one of two sessions:
- **Headless** (`node scripts/mcp.js`): a game of its own, loaded from this checkout's `src/` the way the tests load
it: one page in jsdom, seeded, with no animation loop. For playing and debugging when nobody is watching: fresh
starts, bug-report saves, scenarios and puzzles, and fast-forwarding time.
- **Browser** (`node scripts/mcp.js --browser`): the game in your own browser tab, through a local relay, so you can
watch and take part. Toasts fire, panels open, the map moves. The game, its saves, its settings and any window you
open stay yours.
Both run the same tools on the same code: the agent facade in the game page (`src/agent/`, `window.TUBES`), which does
nothing until a tool calls it. It is part of the development page only, never of the page players get
([ADR 0004](adr/0004-dev-only-code.md)). Nothing is hosted, so this stays within
[ADR 0001](adr/0001-github-pages-only.md): it is a local tool, like `npm run dev`. On the public site there is no relay
and no agent mode. The protocol is the official SDK's (`@modelcontextprotocol/server`, a dev dependency).
## Set it up
### Headless
```sh
npm ci
claude mcp add seriesoftubes -- node /path/to/seriesoftubes/scripts/mcp.js
```
Other clients take the same command (`node /path/to/seriesoftubes/scripts/mcp.js`) in their MCP server settings.
`npm run mcp` starts it by hand; clients should use the `node` command, because `npm run` prints a line of its own first.
Use `node` directly: `npm run` prints a line of its own to stdout, which is the protocol channel.
A game is always loaded: a fresh On-call game in Frankfurt until you start or load another. Every game is seeded, so
the same seed and the same moves give the same game.
the same seed and the same moves give the same game. `--seed N` sets the first game's seed.
### Browser
1. `npm run dev`. It hosts the agent relay on its own port, at `/agent`.
2. Open the game at `http://localhost:8080`, start or load the game you want the agent to play, and turn on
**Settings → Agent API → "Let an AI agent drive this game"**. That connects the page to the relay; there are no
tokens and no ports to configure. The section only exists while the page is served over plain `http://` to an
address (`localhost`, `127.0.0.1`, or the IP the dev server is bound to).
3. Point your MCP client at `node /path/to/seriesoftubes/scripts/mcp.js --browser` (add `--relay-port N` if the dev
server runs on another port, `--relay-host ADDR` if it is bound elsewhere).
The order does not matter. The server answers the MCP handshake at once, then waits up to 90 s (`--page-wait-ms`) for
a page on the relay. When one connects it checks that the page was built from the code on disk, and over stdio stops
with a message if the tab is older (reload it). A call the page has not answered after 30 s comes back as an error
(`--call-ms`); a page that goes away answers its calls at once. One tab drives the relay at a time: the newest one wins.
`npm run dev` binds loopback by default. `npm run dev -- --host 0.0.0.0` (to try the game on a phone, say) binds every
interface, the relay with it, and says so: then anything that can reach the address can drive a game whose player
turned agent mode on. Whatever the bind address, the relay only takes connections made to an IP address or
`localhost`, and refuses a page from another site, so a website in your browser cannot reach it.
### Over HTTP
For a client that connects to a running server instead of starting one (another process, a container, another
machine), serve Streamable HTTP:
```sh
node scripts/mcp.js --http 7777 # http://127.0.0.1:7777/mcp, this machine only
claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp
```
- **Where it listens is your choice.** `--http 7777` binds loopback. `--http 0.0.0.0:7777` (or one address) lets
other machines in, and then anyone who can reach it can play; the server says so when it starts.
- **Token (optional).** With `SOT_MCP_TOKEN=…` or `--token-file FILE`, every request needs
`Authorization: Bearer <token>` (`claude mcp add … --header "Authorization: Bearer …"`). Without a token, a server
bound beyond loopback warns. There is no TLS: beyond a network you trust, use `ssh -L 7777:127.0.0.1:7777` or a
TLS proxy in front.
- **Always checked, wherever it listens:** the `Host` must be an address of this machine (or a name given with
`--allow-host`), which stops DNS rebinding, and a request from a web page (an `Origin` other than localhost) is
refused, so no website can drive the game through your browser.
- **Files:** over HTTP, `load_save` and `export_save` take and give JSON only. `--save-dir DIR` lets them read and
write files under `DIR` and nowhere else (symbolic links that lead out are refused).
- **One game for every client.** Calls run one at a time, in the order they arrive; `new_game` or `load_save` from
any client replaces the game for all of them.
- **Either session.** `--http` works headless and with `--browser` alike: then a client elsewhere drives the game
in the player's tab, while the relay stays where `npm run dev` put it.
## The clock
Every session has one of two clocks, and `schema` (section `mode`) says which:
- **The agent's clock**: nothing happens between calls. `advance {days}` runs the days, one `dayTick()` each, as the
game loop runs them, and stops early when a window asks a question or the network goes bankrupt. Headless, this is
the default. In the browser the player picks it in Settings ("The agent moves it"), and the days run on screen.
- **A running clock**: one simulated day passes every so often whatever the agent does, and nothing can stop it, not
even an open window. The agent decides while it runs, and `wait {days}` returns once that many days have passed (or
earlier, when a window asks a question). Headless: `--clock realtime --pace MS` (default 60000 ms a day). In the
browser the player picks a pace from 30 s to 5 min a day; the clock holds while no tool is connected.
`advance` with a running clock and `wait` with the agent's are errors that say which one to use.
## Tools
| Tool | What it does |
|---|---|
| `new_game` | Start a network in any home city with a preset (`soft` for Best Effort, `freeze`, `oncall`, `bgp`, `sandbox`), a seed, your own ASN, and the sandbox's chaos dial |
| `load_save`, `export_save` | Load an exported save (a path or JSON text, migrated as the game does) or write one the real game can import |
| `new_game` | Headless only. Start a network in any home city with a preset (`soft` for Best Effort, `freeze`, `oncall`, `bgp`, `sandbox`), a seed, your own ASN, and the sandbox's chaos dial |
| `load_save`, `export_save` | Headless only. Load an exported save (a path or JSON text, migrated as the game does) or write one the real game can import |
| `status` | Date, cash, revenue and costs by kind, level, tier and why it is not Tier 1, the goal, traffic, reach, POPs, incidents |
| `advance` | Run N days through `dayTick()`. Stops when a window opens or the network goes bankrupt. Returns the log, new incidents, cash and the time each day took |
| `advance`, `wait` | Move time with the agent's clock, or let it pass with a running one. They return the log, new incidents and cash; `advance` also the time each day took |
| `network`, `city`, `find` | The world: policies and what a network asks for, its PoPs, cone and price; a city's exchanges, transit sellers, cables; search by name, id or ASN |
| `traceroute` | The looking glass: which exit wins to a network and why, with the AS path |
| `peering_check` | Would this network peer with you over a PNI or at an exchange, and the game's reason if not |
| `hot_spots` | The fullest links, transit ports and PNIs, the transit bill by carrier, and the biggest traffic still on transit with the way off it |
| `schema` | The typed contract: every action with its arguments, their domains and what it does; what is not available and why; a field-by-field reference of `state` and `results` |
| `schema` | The typed contract: the session (`mode`: headless or browser, the clock, what is held back), every action with its arguments, their domains and what it does; what is not available and why; a field-by-field reference of `state` and `results` |
| `catalog` | The reference tables the arguments point at (cities, networks, ports, optics, interns…), plus the conference calendar with its keys and the RouteScript recipes with their scripts |
| `state`, `results`, `ui` | The saved game itself (`S`), the last traffic computation (`R`) and the view state, as JSON, whole or by path (`pops.fra`, `loanOffers`, `links.<id>`) |
| `actions`, `act` | Every action with its arguments, and running one |
@ -56,27 +129,64 @@ what happened:
`click` presses a button as a player's click does, with the button's own arguments, so a confirmation arms first
and windows step on as they do in the game. Lists the game acts on when they change are listed with their options
and clicked with a value. Neither tool reaches files, save slots, settings, the title screen or the game speed: time
moves only with `advance`. There is no tool that evaluates code in the page.
and clicked with a value. Neither tool reaches files, save slots, settings, the title screen or the game speed.
There is no tool that evaluates code in the page, and nothing but tool names and JSON arguments crosses the relay.
## In the player's browser
The browser mode plays by the player's rules on top of the headless ones:
- **The game is the player's.** There is no `new_game`, `load_save` or `export_save`, and the actions that start,
retry or leave a scenario, puzzle or architect run are refused. Whichever tab is connected is the game.
- **So is the clock**, set in Settings (see above). There is no tool for it.
- **And their windows.** A window the player opened (Settings, the menu, a sheet) is never a question, never closed
and never replaced: the agent plays behind it. `screen` shows it with `playerWindow`, and its buttons are the
player's to press. A sheet the agent opens meanwhile is shown to it and closed again. Only a question the game asks
in answer to the agent's own move takes the screen, as it would after a click.
- **And their settings**: no preference can be changed.
- **The dice stay hidden**: `state` never returns the seed or the days of the next failure, event or scripted attack;
`schema` marks them `withheld`, with the reason.
## Looking into a bug report
1. `load_save` with the save attached to the issue.
1. `load_save` (headless) with the save attached to the issue.
2. `status` and `hot_spots` for the picture, `traceroute` and `peering_check` for one network's traffic, `state`
and `results` for the numbers behind them.
3. `advance` a few days and read `timing.slowestDays` for lag, or the log for what went wrong.
## Troubleshooting the browser mode
- **"no game page answered"**: the tab is not connected. Settings → Agent API → on. No Agent API section in Settings?
The page is not the development page served locally: open it from `npm run dev`, at an address such as
`http://localhost:8080` or `http://127.0.0.1:8080`, not under a DNS name, which the relay refuses.
- **"the game page in the browser disagrees with the code on disk"**: the tab is older than the checkout (perhaps
after a `git pull`). Reload it: `npm run dev` assembles the page on every request.
- **A second tab took over**: one page per relay; the newest tab wins and the old one stops dialing.
## Code
- `scripts/mcp.js`: the stdio transport (JSON-RPC 2.0, one message per line) and the protocol methods.
- `scripts/lib/mcp-game.js`: the session (one game page) and the tool list with input schemas.
- `scripts/lib/mcp-commands.js`: runs inside the page: every action's class, arguments, domains, price and
description, and the `state`/`results` field reference.
- `scripts/lib/mcp-page.js`: runs inside the page and reads or drives the game through its own globals.
- `tests/mcp.test.js`: the protocol, a game played through the tools, determinism, saves, and what stays out of reach.
- `tests/mcp-commands.test.js`: every action classified and its arguments real, outcomes, quotes, typed text,
multi-step builds, confirmations, the reads and the screens.
- `scripts/mcp.js`: the server on the SDK: the tools registered from `TOOLS` for the session's mode, stdio or
Streamable HTTP, the Host, Origin and token checks, the one-at-a-time queue, and the options.
- `scripts/lib/mcp-game.js`: the headless session (one game page) and the tool list, each tool with its input schema
and the modes it works in.
- `scripts/lib/mcp-headless.js`: runs inside the headless page only: starting, loading and exporting games, and the
server's clock.
- `scripts/lib/mcp-browser.js`, `scripts/lib/relay-client.js`: the browser session: the relay's tool side, the wait
for a page and the check that it serves this checkout's contract.
- `scripts/agent/relay.js`: the relay, hosted by `scripts/dev.js` on its own port.
- `src/agent/`: the facade in the page, in the development page only: every action's class, arguments, domains,
price and description (`20-commands.js`), the `state`/`results` field reference and what is withheld
(`30-docs.js`), the reads, the screens, dispatch and the clocks (`70-time.js`); agent mode's switch, clock and
Settings (`75-mode.js`), the page's side of the relay (`80-relay.js`) and the clock where frames do not run
(`85-ticker.js`). The game itself only offers `HOOKS` and `UI.clockLocked` (`src/game/50-state.js`).
- `tests/mcp.test.js`: the protocol over stdio, a game played through the tools, determinism, saves, both clocks, and
what stays out of reach. `tests/mcp-http.test.js`: the HTTP transport, its checks, the token and the save directory.
`tests/mcp-commands.test.js`: every action classified and its arguments real, outcomes, quotes, typed text,
multi-step builds, confirmations, the reads and the screens. `tests/agent-api.test.js`: the facade is inert until
called, and the page players get has none of it. `tests/agent-relay.test.js`, `tests/agent-settings.test.js`: the
relay, the browser mode and its rules, and the Settings. `tests/mcp-parity.test.js`: one scripted session gives the
same outcomes headless and through the relay.
The tools read the game's internals (`S`, `R`, `ACT`, `NETS`…), which are not a stable API: a refactor in `src/` can
break a tool, and the tests are there to catch that in CI. A new action in `ACT` needs an entry in
`scripts/lib/mcp-commands.js` or the server's `DENY` list, or `tests/mcp-commands.test.js` fails.
`src/agent/20-commands.js` (a class, or `API_DENY`), or `tests/mcp-commands.test.js` fails.

View file

@ -0,0 +1,46 @@
# ADR 0004: Development-only code, assembled into the development page only
- Status: accepted
- Date: 2026-11-03
## Context
The MCP server (`npm run mcp`, [MCP.md](../MCP.md)) plays the game through a facade of typed commands, reads and
screens. That facade has to run inside the game page, in its top-level scope: it reads `S`, `R`, `ACT` and the
catalogs directly, and a page in the player's own browser can only run code it was served (nothing may be sent to
it as code). So it belongs in `src/`, next to the game.
But it is about 110 KB of JavaScript (some 40 KB gzipped) that no player can use: seriesoftub.es has no way to
reach it. Shipping it would make every player, most of them on phones, download and parse it on every load,
against the rule that structure costs nothing at runtime ([ADR 0002](0002-one-page-assembled-at-build.md)).
## Decision
- Code only tools use lives in `src/agent/` (and later folders like it), named and ordered like `src/game/`.
- `src/index.html` includes it with `<!-- @include-dev agent -->`, right after `<!-- @include game -->`, inside the
same script, so it shares the game's top-level scope.
- `scripts/lib/page.js` expands an `@include-dev` line only when asked (`assemble({ dev: true })`, `--source --dev`).
Otherwise the line is dropped whole, so the page players get is byte for byte what it would be without the
feature.
- The **development page** (with `src/agent/`) is what `npm run dev` serves, what the MCP server loads and what
`i18n-check` reads. The **players' page** (without it) is what `npm run build` and `npm run serve` ship, what
`npm run perf` measures and what the tests load unless a test asks for `load({ agent: true })`.
## Rules that come with it
- **The game never names agent code.** Nothing in `src/game/`, `src/styles/` or `src/index.html` may refer to
anything `src/agent/` defines: it would work in development and break for players. Every top-level name in
`src/agent/` starts with `api` or `API_` (the facade itself is `window.TUBES`), and `tests/build.test.js` fails on
any use of those names outside `src/agent/`.
- **Agent code runs after the game.** Its files come after `99-loop.js`, so its top level may use anything the game
defines, and must not assume `boot()` has or has not run yet. In practice it only defines tables and functions.
- **Tests load the players' page by default.** So a core change that quietly leans on agent code fails the suite
instead of the release. `tests/pages.test.js` checks that the built page carries no agent code and still plays.
## Consequences
- Players pay nothing for the facade: the build is unchanged by it, and the performance benchmark measures exactly
what ships.
- `npm run serve` stays what it says: the built site as GitHub Pages serves it, without the agent.
- The development page and the players' page differ, by design and only by what `@include-dev` adds. Anything that
must behave like production (perf, the release build test) uses the players' page.