Compare commits

..

No commits in common. "main" and "v1.3.0" have entirely different histories.
main ... v1.3.0

613 changed files with 2842 additions and 102281 deletions

View file

@ -1,85 +0,0 @@
---
name: add-strings
description: Add or change player-facing text in Series of Tubes: labels in the code, English in src/i18n/en.js, and every translation (site/i18n/*.js) kept complete.
---
# Adding or changing player-facing text
Text is keyed by **label** ([docs/adr/0003-translations-by-label.md](../../../docs/adr/0003-translations-by-label.md)).
The code says `tr('pnis.delivery_2_to_6_weeks')`; the English is in `src/i18n/en.js`; Italian, Portuguese
and French are `site/i18n/it.js`, `pt.js`, `fr.js`. Every label the code uses needs English, and every
language needs every label.
## In the code
- `tr('area.label', {name})`: translate now and fill `{placeholders}`.
- `trn('area.label', n, vars)`: plurals. One label, whose entries are `{"one": "…", "other": "…"}`;
`{n}` is filled in for you.
- `N_('area.label')`: a label kept in a table or a save and translated where it is shown with
`tr(x)`. Anything stored in `S` must be an `N_()` label (or an index), never translated text and never
a label written any other way: the build shortens every label it sees in `tr()`/`trn()` to an id that
changes between releases, and keeps the `N_()` ones whole.
- The label is always a string literal, the first argument of `tr`/`trn`/`N_`. A label anywhere else
(`const x='pnis.ready'`) is an error in `npm run i18n:check`.
- Static HTML in `src/index.html`: `data-i18n="area.label"` on the element, with its English inside it;
`data-i18n-aria-label="…"` and `data-i18n-title="…"` next to those attributes.
- Keep HTML (`<b>`, `<br>`, `<small>`) and `{placeholders}` identical in every language.
- Don't build sentences from translated fragments; translate whole sentences.
## Naming a label
`area.some_words`: the area is the file or topic it is shown in (`pnis`, `own_cable`, `dashboard`,
`page` for the static markup), or `common` for text used all over and short everyday words
(`common.close`, `common.customers`). The words are the first few words of the English, lower case,
`_` between them: `pnis.ready_in_about_n_days`. Labels are only for finding things; players never see
them. Reuse an existing label when the text and the meaning are the same (`grep -n '"Close"' src/i18n/en.js`).
## In the dictionaries
Every dictionary is one entry per line, **sorted by label**, so new text from different pull requests
lands on different lines. Don't edit them by hand; the script writes English and translations together:
```bash
cat > /tmp/strings.json <<'JSON'
{
"en": { "pnis.ready_in_about_n_days": "Ready in about {n} days",
"save.n_pop": { "one": "{n} POP", "other": "{n} POPs" } },
"it": { "pnis.ready_in_about_n_days": "Pronto tra circa {n} giorni",
"save.n_pop": { "one": "{n} POP", "other": "{n} POP" } },
"pt": { "pnis.ready_in_about_n_days": "Pronto em cerca de {n} dias" },
"fr": { "pnis.ready_in_about_n_days": "Prêt dans environ {n} jours" }
}
JSON
node scripts/i18n-add.js /tmp/strings.json # a string or {one, other} sets an entry, null removes it
node scripts/i18n-add.js --rename old.label new.label # in every dictionary and everywhere in src/
```
- **Changing English wording** (a typo, a clearer phrase, same meaning): change only the English. The
translations stay right.
- **Changing the meaning**: give the text a new label (`--rename`, then update the English and every
translation), so no language keeps a translation that now says something else.
- **Removing text**: `null` under `"en"` removes the label from every dictionary.
`npm run i18n:fix` re-sorts a dictionary that got out of order (a hand edit, a merge).
## Italian style
Natural, friendly Italian, informal "tu". Keep networking terms that Italian engineers
use in English (peering, transit, router, POP, PNI, LAG, dark fiber). Translate puns
into an Italian joke when one fits; otherwise keep the pun name and translate the rest.
## German style
Natural, friendly German, informal "du". Networking terms that German engineers say in English stay
English (Peering, Transit, Dark Fiber, Wave, Port, Router, POP, IX, Exchange, Backbone, Link, Traffic,
Route Server, Line System, LAG, PNI, Fabric, Scrubbing), but plain "fiber" is "Glasfaser",
"fiber pair" is "Faserpaar" and "eyeballs" are always "Privatkunden". "/mo" is "/Monat", "{n}d" is
"{n} T.", money keeps the game's `$100k` style, quotes are „…“. Translate puns into a German joke
when one fits; otherwise keep the pun name.
## Check
```bash
node scripts/i18n-check.js # en.js: 0 problems; each language: 0 missing, 0 unused, 0 broken
npm test # includes tests/i18n.test.js (every screen in every language) and the shipped page
```

View file

@ -1,79 +0,0 @@
---
name: edit-the-game
description: Find, change and add game code in Series of Tubes, which lives in many small files under src/ that the build joins into one page. Use for any feature, fix or refactor in the game itself (anything in src/).
---
# Editing the game
The game's source is `src/`. The build (`scripts/lib/page.js`) pastes the files together, in path order,
into one `index.html` with one inline `<style>` and one inline `<script>`. That is exactly what players
load, so splitting code across files costs nothing at runtime. Why it works this way:
[docs/adr/0002-one-page-assembled-at-build.md](../../../docs/adr/0002-one-page-assembled-at-build.md).
```
src/index.html the shell: <head>, static markup, `<!-- @include styles -->`, `<!-- @include game -->`
src/styles/NN-*.css CSS, in order (phones last)
src/game/NN-area/NN-*.js the game script, in order (see the map in docs/ARCHITECTURE.md)
src/agent/NN-*.js the agent facade the MCP server drives: in the development page only
site/ static files copied as they are (dictionaries, icons, service worker)
```
## Find the code
Search by name, not by line: `grep -rn "function compute(" src/game`. Folder names say what lives
there: `10-catalog` prices and gear, `20-world` cities and cables, `30-networks` other ASes,
`70-rules` peering and market rules, `80-simulation` routing and the save gate, `85-incidents`,
`88-days` the daily tick, `90-actions` every player action, `93-ui` HUD and panels, `94-dashboard`,
`95-modals`, `96-map` the canvas. `docs/ARCHITECTURE.md` has the full table.
## Run it
```bash
npm run dev # http://localhost:8080, assembled on every request, reloads on save
npm test # all suites (assembles src/ in memory; no build needed)
npm test -- tests/peering.test.js # one suite
```
A browser error points at a line of the assembled page; the dev server prints the `src/` file and line
next to it. `npm run page -- -o /tmp/page.html` writes the page players get if you want to look at it;
`npm run page -- --source --dev -o /tmp/page.html` the development page `npm run dev` serves.
## Where new code goes
- **A new feature or system:** its own file in the folder of its topic, e.g.
`src/game/70-rules/85-route-servers.js`. Pick a number between its neighbours; gaps are there for this.
Small files that own one topic are what keep pull requests from conflicting.
- **Order matters at the top level.** Files run in path order. Top-level `const`/`let` values and
top-level statements may only use top-level values from earlier files. Functions are fine anywhere:
everything is one script, so function declarations are hoisted and are all defined by the time
anything runs after boot. When in doubt, put constants in an earlier file and logic in functions.
- **Actions:** add `name:(args)=>{…},` to the matching `src/game/90-actions/*.js`. Only
`10-interface.js` declares `const ACT={`; the others are `Object.assign(ACT,{ … });`. A new area can get
a new `NN-area.js` file of that second form. The MCP server types every action: a new one also gets
an entry in `src/agent/20-commands.js` (a game command with its argument domains, a view, a draft,
a session action, or `API_DENY`); `tests/mcp-commands.test.js` fails until it has one.
- **Agent code** (`src/agent/`, the facade the MCP server plays through) is assembled into the
development page only (`<!-- @include-dev agent -->`): players never download it. Its top-level names
start with `api`/`API_`, and **nothing in `src/game/` may name them**: that would work in `npm run dev`
and break for players (`tests/build.test.js` checks). Tests load the players' page; a test of the
facade asks for `load({ agent: true })`. Where agent code must change what the game does (agent mode
locks the clock, adds a Settings section and a HUD badge), the game calls `HOOKS.x?.()` and reads
`UI.clockLocked` (`50-state.js`), and agent code fills them in: add a hook there rather than an `if` for
the agent in a game file. See docs/adr/0004-dev-only-code.md.
- **Panels and modals:** `93-ui/` (HUD, side panels), `94-dashboard/` (NOC dashboard, bank), `95-modals/`.
- **Styles:** the matching `src/styles/*.css`; phone rules go in `60-phone.css`.
- **Data tables** (cities, cables, networks): one entry per line, and keep id-keyed objects such as
`CITY_LL` sorted by id, so two people adding cities touch different lines.
- **Static markup** goes in `src/index.html`; it is short and rarely changes.
- **Files that ship as they are** (icons, dictionaries, `sw.js`, `robots.txt`) live in `site/`.
`site/index.html` must not exist; the build refuses it.
Every partial ends with a newline and must not contain `</script>` or `</style>` at the start of a line.
File names are `NN-lower-case.js` / `.css`; `tests/build.test.js` checks both.
## Still the same rules
Everything in CLAUDE.md applies unchanged: translate every string (`add-strings`), sanitize saves,
phones first, a test with every change (`write-tests`), performance shown against `main`
(`performance`), hosting on GitHub Pages only (`github-pages`), a CHANGELOG bullet for players.
The CHANGELOG is the one file every change touches; a conflict there is expected: keep both bullets.

View file

@ -1,102 +0,0 @@
---
name: gameplay-rules
description: The design rules of Series of Tubes, each with an id and the test that enforces it. Use whenever you add or change cities, countries, networks (NETS, upstreams, traffic shares, presence), cables, exchanges, data centers, customers, scenarios, puzzles, presets or rules, balance numbers or progression, and before committing any such change.
---
# Gameplay rules
These are what the game promises, held up by `tests/gameplay-rules.test.js` (one `test()` per id, on the live
`CITIES`, `NETS`, `CABLES`, `SCN`, `PZ`, `PRESETS`…). Each rule is true of the intended design.
## Procedure
1. Changing anything above? Run `npm test -- tests/gameplay-rules.test.js` (under a minute) before committing.
Changing orbit prices, crusts, incidents or orbit customers? Also run `npm test -- tests/pie-balance.test.js` (O7's
game-loop half, about a minute).
2. A failure names what breaks the rule and how to fix it. Fix the data or the code.
3. Only when real life really is different, add an entry to `EXCEPTIONS` in the test (keyed by rule id, sorted, with
its reason in plain words). Never delete or loosen a check to make it pass. A stale exception fails too.
4. A new rule gets an id in the right section here, one line, a why, and its own `test('ID: …')`.
## World
| Id | Rule | Why |
| --- | --- | --- |
| W1 | Every city has a country code (`cc`, ISO 3166-1 alpha-2; territories have their own: PR, GU, RE, MQ, CW…), a region, a landmass and coordinates. | Borders, prices and the eyeball rule all hang off the country. |
| W2 | Every country on the map has at least two consumer networks of its own: an eyeball network, or a Tier 1 or Tier 2 incumbent that sells to homes, whose home markets (`cc` on the network) include that country and which has a PoP there. | Real countries have competing local ISPs, and peering locally is half the game. Add real operators in `src/game/30-networks/32-homegrown-eyeballs.js`. |
| W3 | Every city can buy transit from someone, or is a documented exception (Pitcairn: land your own cable, reach it through a pie dish, or rent a satellite circuit from a teleport; Stuttgart: peering only). | A start or an expansion must never be a dead end by accident. |
| W4 | Cable pairs join two distinct real cities, have a length, and cable ids are unique. | Broken landings break routing and the own-cable planner. |
| W5 | A city alone on its landmass has a cable or a beach to land one. | Islands are reachable. |
| W6 | Every island Wi-Fi zone (`WISP`, #83) hangs off a satellite city (`satRemote`) within 1,000 km of it, seen together with it by a GEO bird; its pool is 3 to 12 G of homes; its spur is at most 1,500 km, or there is none (`km:0`); ids are sorted. | A zone is the outer islands of the city they look to, reachable from the first teleport; smaller ones never pay, and pie terminals serve them. |
## Networks
| Id | Rule | Why |
| --- | --- | --- |
| N1 | Network ids and ASNs are unique; ASNs are public (the real one for real-world networks). | Saves key on ids; players look ASNs up. |
| N2 | Names are puns: no network, cable, exchange, data center, router, optic, satellite or satellite operator, cable ship or maintenance club is called by a real name (blocklist `REAL_NAMES` in the test), and no lazy "-ish" names. | CLAUDE.md. Add the real name to the blocklist whenever you add its pun. |
| N3 | Every non-Tier-1, non-content network is in a founding Tier 1's customer cone (`up`), or is a documented island (transit-free incumbents, China, Korea, Australia…). Upstreams exist and are never content. | Tier 1 by customer cone (#85): a new network outside the cones makes Tier 1 harder for every save, old ones included. |
| N4 | No upstream cycles. | Cones must be trees, not loops. |
| N5 | Traffic shares are positive and below 20%; `NSH` and the regional tables sum to 1; content carries at least 30%. | Shares drive every flow; eyeballs mostly ask for traffic. |
| N6 | Every network has a type, a peering policy (selective ones state `minIx`/`minPni`), a colour and a translated blurb; carriers have a price. | Panels and the peering rules read them. |
| N7 | PoPs are real, distinct cities; exchange ports only where the city has an exchange and the network has a PoP. | Presence follows PeeringDB-style reality. |
| N8 | A POP's traffic to the networks that sell to homes (`cc`) goes mostly to those whose users live near it: at home above the world share, on other continents below (`locSh()`, `45-home-markets.js`). Only that split moves: a city's total and every network without home markets keep their shares. | People mostly talk to people near them, and peering with an eyeball where its users are must beat hauling its traffic to two cities (#48). |
## Modes and rules
| Id | Rule | Why |
| --- | --- | --- |
| M1 | On-call is the classic game: it equals `RULE_DEF`, and a save without rules loads as On-call. The seeded suites (`tests/game.test.js`, `tests/rules.test.js`) are its behaviour. | Old saves never change under them. |
| M2 | Presets are ordered: Best Effort never harsher than Change Freeze, Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market; and a seeded year of incidents). Only Best Effort mends sea cuts without ships, skips conferences, rescues instead of game over, has patient customers and instant PNIs. | The names promise it. |
| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, sold-out routes, de-peering and hardware prices (`market`), lead times (`lead`), the clock, cable ships (`sea`), conferences (`confs`), going broke (`broke`), customer patience (`moods`), PNI delivery (`pnis`), scarce IPv4, CGNAT and IPv6-only homes behind NAT64 (`ip4`, On-call and BGP at 3 a.m. only; scenarios opt in), and the day's toasts (quiet notifications). A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. |
| M4 | Scenarios and the weekly challenge always run On-call plus their own `S.scn.rules`. | Fair scores. |
| M5 | Sandbox has no locked feature: open gates, every level, own cables, endless money. | It is a sandbox. |
| M6 | A Normal game picks its charter once, when it starts (sandbox, puzzles and scenarios never do). A charter changes what you set out to do, never what things cost: the Cable broker gets glass (fiber, line systems, optics, own subsea cables and the routers to light them) from day one at the prices everyone pays at the top level, and everything else by level. | Same prices and rules for every charter (#300). |
## Content
| Id | Rule | Why |
| --- | --- | --- |
| C1 | Every scenario has a name, a goal, an `ok()` its progress card (`SCN_PROG`) shows, and cannot be won on day 0; so does every committed weekly scenario (`site/scenarios/weekly/`, its goal type's card in `WS_GOALS`). | A goal must need play. |
| C2 | Every puzzle has a 1-star and a 3-star reference solution in `REF` of `tests/puzzles.test.js`, which builds and scores them. | Every puzzle is solvable and every star reachable. |
| C3 | Every player-facing string is translated in every language (`node scripts/i18n-check.js`: 0 missing, 0 unused, 0 broken). | CLAUDE.md; see `add-strings`. |
| C4 | Every Architect run, handmade (`REF` in `tests/architect.test.js`) or weekly (`ref` in its file, `scripts/weekly-architect.js --check`), has a reference build that passes every brief's chaos monkey review and earns three stars; every weekly brief takes at least one change (a tube, a bigger tube, a move), and later briefs' cities stay hidden until they come. | A run you cannot finish, or a brief that asks for nothing, is not a puzzle; knowing the next brief makes it a chore. |
## Fun and fairness
| Id | Rule | Why |
| --- | --- | --- |
| F1 | A new network gets a gentle start (counted from the network's own first day; hardware prices hold for the calendar's first 180 days, see F11): no outage before day 45, no event before day 40 and only good news before day 50, nothing sold out for 90 days, hardware prices hold for 180, and a new customer loses no mood for 15 days. Its first IPv4 block covers the start: no home behind CGNAT, no IPv4 bill and no IPv4 warning before day 50, even signing every offer that fits. | New players learn before they get punished. |
| F2 | On On-call, a simple build in a start city (broadband, the cheapest 100G transit, an exchange port with the route server) makes money within 3 months, in Frankfurt, New York, Singapore and Johannesburg. | Seeded today it turns a profit in month 1 or 2; a balance change that breaks this makes the start too hard. |
| F3 | A specialist path (#187) only brings a customer type in below its level when the network can already serve it, or nearly: the spotted cities have POPs, the latency is met, the fiber carries at least three quarters of the smallest order. | Capability, not luck: an offer you cannot fulfil with a reasonable build is a trap. |
| F4 | The chaos monkey visits only On-call and BGP at 3 a.m. (never Change Freeze, Sandbox, puzzles or scenarios), not before day 180, for 120 to 240 days; while it is here its snips replace the ordinary failures, each snip heals within a week, and it goes after tubes with no other way round first. | A test of resilience you can prepare for, not a pile-on: the reward goes to networks built with a second path. |
| F5 | Capacity you rent to other carriers never outgrows the route's market: the capacity market sells a listing over time as carriers between the two cities want it, never past what they want that day (both cities' eyeballs, a landing town counting the big city it serves, grown about 15% a year up to 8 times, and at most 2.5 times its usual size on its hottest day), and a random offer never past what the eyeballs alone support. | Rent that scales with your own glass and not with demand is a money machine (#203); a market that never moves or grows makes no decisions. |
| F6 | An alien wave rents for at most 30% of what its fiber costs a month (lease plus amplifiers), each wave sold between two cities is never dearer than the one before, and a route sold out to its market earns less than eight times that cost. | A buyer would lease the fiber rather than pay many times its price; the old price made one wave worth the whole fiber and a full route 11 to 35 times its lease (#203). |
| F7 | Extra crews cut a build on land to half its planned time at most. | Permits, rights of way and trenching set the pace; a 1,000-day build finishing tomorrow made lead times meaningless (#203). |
| F8 | In the capacity market (Lambda Bazaar), a managed wave comes out of capacity you lit yourself (your own traffic gets that much less, and the customer suffers when your optics cannot carry it), rides one channel (an 800G or 1.6T wave needs an optic that big), and is priced against its fiber: a 400G wave 2.7 times a 100G one on land and 3.8 times on subsea, each bigger size cheaper per bit. Spectrum lists at 30% of the fiber's monthly cost, and heat moves any price by at most −30% to +35%. | Selling lit capacity must cost capacity, or every fiber sells twice; the ratios are 2025 market prices (TeleGeography), so bigger waves win on volume, not on price per bit. |
| F9 | A strict latency contract (`BIZ_T.lowlat`, #137) comes only from customer level 7, is 1.6T or 3.2T and never grows past 3.2T, has a latency limit something you can build meets (`latMaxOf`, as trading links), pays more per Gbps than any other big circuit on the same route even with all their extras, and once its 15-day grace is over credits a day's fee and loses patience faster for every day over its limit. | Real low-latency routes sell at a premium for guaranteed milliseconds and pay service credits when they miss; the cap keeps one contract from carrying a level. |
| F10 | Growth goes sideways, plus one paid way up: a PNI bundles eight members per router at its POP, up to 32 (`pniLagMax()`); transit, exchange and fabric LAGs stay at eight (`LAG_MAX`). Giant AI circuits land at campuses (`MEGA`) in at least 30 metros, no metro more than two, picked less often where giant circuits already crowd the city. | Raising caps only moves the wall; a fatter PNI costs a router (its price and its port slots), and the late game's demand spreads over many metros as real AI and cloud campuses do (#61, #323). |
| F11 | A network that joins a server session after its first 180 days starts on the session's date with F1's gentle start, the charter and the tutorial counted from its own first day, a starting-cash top-up as large as the rise in hardware prices (START_CASH × (hwTrend − 1), at most $60k), and its first 365 days of home broadband income matched (after wholesale cuts, outside investors' share); the market stays on the session's date. | One market for everyone, and a friend who joins late still gets a fair start. |
| F12 | Island Wi-Fi (#83), on a zone's own books at full take-up in era 1 (its homes at island prices less the towers' upkeep and the backhaul rent; the teleport, tracking antennas and a Starblink gateway are shared and left out), makes money on at least one way in; a spur earns more than any satellite option, MEO at least as much as GEO and LEO at least as much as MEO where both reach; spurs up to 250 km pay back within 5 years against the best GEO or MEO stage, up to 1,000 km within 10. | The ladder (GEO, then MEO or LEO, then your own cable) must be worth climbing, and its first rung must not lose money; the longest spurs are a choice, not a given. |
## DDoS
| Id | Rule | Why |
| --- | --- | --- |
| D1 | Attack sizes come from the world, never from your network: a heavy tail (median near 9 G, one in a hundred over 650 G) scaled by the era, capped at the era's record, and for the first 180 days (or with one POP) never more than twice your biggest port. Ten times the subscribers means the same attacks. | Sizes that grew with the network made every late-game flood larger than the internet's record (#242). |
| D2 | A flood enters on every port the internet reaches you on, by each network's share, and a port carries only what fits: everyone on a full port loses the same share. | Real floods are spread by geography; one fat port at a single POP is the weak spot (#242). |
| D3 | Only upstream tools (RTBH, clean pipe) and an engaged scrubbing center keep a flood off your ports. Flowspec acts on the ingress router, after the port, within that router's own rule budget. | Flowspec protects customers, not the external connections; TCAM is finite. |
| D4 | RTBH costs only the target: it goes dark (and its mood drops once), everyone else is saved, and the attack counts as sacrificed, not held. | RTBH is the tool that saves the network and is bad for that one customer, so it must be a real choice. |
## Orbit (Pie in the Sky, `docs/plans/pie-in-the-sky.md`)
| Id | Rule | Why |
| --- | --- | --- |
| O1 | The rocket company unlocks only on the Tier 1 win of a save started on its version (`S.pieV>=1`, set by `newGame()`; a save without it loads as 0), or from day 0 with open gates (sandbox). Never in puzzles, the Architect or scenarios. Losing Tier 1 keeps everything flying but builds nothing new. | An endgame for people who earned it; old won saves must not change under their players. |
| O2 | A crust under 40% coverage carries nothing; from 40% a half-baked crust carries a share that grows to all of its capacity at 60% (a slope, not a cliff), and orbit never carries more than the pie dishes' antennas (x rain, jamming): terminals and sky paths share each dish. | Satellites are not magic bandwidth; the ground segment is the bottleneck, as in real life. |
| O3 | A cut-off pie dish (its POP on an island the backbone does not reach) carries only its own POP's traffic (backhaul, to a landing dish on the backbone) and local terminals, never transit between other cities: no POP on the backbone routes through it. Backhaul is small (the dish's antennas, the landing dish's and the crust's room) and pays the orbit's latency. | Orbit extends your network to a town no cable reaches; it does not replace building one, and laying fiber stays the real fix. |
| O4 | Through space with lasers, light travels at c in vacuum (about 1.47 times glass), up and down at the shell's height; orbit never carries traffic between cities under 3,000 km apart and only latency-routed circuits fly: IP traffic, bulk and scenic circuits stay on fiber. | Real constellations win only on long routes, and their capacity is small. |
| O5 | Launches fail only with chaos on (`rule('chaos')`), and never in the first 90 days after the unlock; heavy test flights explode by design, not by chance. Orbit incidents and geopolitical spats (`pieChaos()`) follow the same rule. | Like F1: learn the thing before it punishes you. |
| O7 | A fresh Tier 1 cannot afford a full Shortcrust from its first year's money: even a big network's yearly profit plus the largest loan a bank would offer (and the Ex-Im Pie Bank's most) stays below the cheapest full build (`pieFullCost('short')`). And a full lasered Shortcrust, played through the game loop on the big-network save by a sensible policy (reusable rockets, two pads, no launches past the crust's size except replacements, safe mode in storms, dishes grown with demand at well-served POPs, every orbit offer signed), pays back on its own books (`S.pie.book`: every launch, replacement, dish, licence and running cost against orbit income) in 5 to 10 years, never sooner; government money (the Rural Digital Pie Fund, Pitcairn's satellite grant) brings that forward by at most two years, never under four (`tests/pie-balance.test.js`; `PIE_BALANCE_YEARS=10` prints the long run). | Obscenely expensive is the joke and the goal; a constellation in year one would be a cheat code. |
| O8 | Rented LEO (Starblink, #83) reaches only within `SAT_ORB.leo.km` of a gateway under its shell (`SAT_ORB.leo.lat`) at a POP on your fiber (the mainland, or an island with a lit wired link or transit); once a crust of your own carries traffic it sells nothing new (no gateway, circuit or growth), while circuits already rented keep running; and every size costs more per Gbps than any subsea wave over its whole reach. | A bent pipe is regional; the rented tier must not undercut your own constellation; and a cable stays the better buy wherever one can go. |

View file

@ -1,70 +0,0 @@
---
name: github-pages
description: Series of Tubes is hosted on GitHub Pages and nowhere else, non-negotiably. Use before any change to hosting, deploys, the build output, caching, the service worker, new runtime requests or anything that would need a server, and whenever someone suggests another host.
---
# GitHub Pages, always
Series of Tubes is served by GitHub Pages at https://seriesoftub.es and **only** there. This is settled
([docs/adr/0001-github-pages-only.md](../../../docs/adr/0001-github-pages-only.md)) and not up for
discussion: do not propose, prepare or "keep the door open" for another host, a CDN in front, a
backend or server-side rendering, even when asked to evaluate options. If a feature seems to need
one, redesign the feature.
## What that means for a change
- **The output is static files.** `npm run build` writes `_site/`: the assembled page, `site/`'s files,
`version.json`. No server code, no runtime secrets: everything there is public.
- **No HTTP headers, redirects or rewrites.** Pages ignores `_headers`, `_redirects`, `.htaccess`,
`vercel.json`, `netlify.toml`. Need a policy? Use a `<meta>` tag. Need a different URL? Add a
static file there.
- **Caching is Pages' (short, the same for every file) plus the service worker's.** Offline play and
updates are `site/sw.js`'s job; its cache name carries the version. When you add a file the game
needs offline, add it to `CORE` there.
- **Same origin.** The page, dictionaries, icons and data come from seriesoftub.es. Do not add CDN
libraries or third-party APIs the game needs to work; the web fonts and the analytics counter are
the only exceptions and the game runs without them.
- **More files are fine, from the same origin.** Pages serves many small files well over HTTP/2.
Still: the game page itself stays one assembled `index.html` (see
[ADR 0002](../../../docs/adr/0002-one-page-assembled-at-build.md)), and anything the first frame
needs must not add a round trip.
- **Limits:** about 1 GB for the whole site, 100 MB per file.
- **Paths:** the site lives at the domain root (`site/CNAME`), so `/` paths are fine; unknown paths get
`404.html`.
- **Local tools are not hosting.** `npm run dev` and the MCP server (`npm run mcp`, also over `--http`)
run on a developer's own machine against a checkout; nothing they serve is deployed, and the game
never depends on them. Their code stays out of `_site/` (`src/agent/` is development-only, see
`docs/adr/0004-dev-only-code.md`).
- **The container image is a tool too.** `docker/` packages those tools; `docker.yml` publishes it to GHCR for releases
(version tags only, no `latest`) and never to Pages. Someone may run its development server where they like; that is
not a host of the game, and the game never depends on it.
## How it deploys
Only releases deploy. Bumping `version` in `package.json` on `main` runs `auto-release.yml`, which tags,
publishes the GitHub release and starts `release.yml`: test, `REQUIRE_NOTES=1 npm run build`,
`actions/upload-pages-artifact` with `./_site`, `actions/deploy-pages`. That job is the only one with
`pages: write`. Pushes to `main` and pull requests build but never deploy. The `release` skill has the
steps.
**The one exception: the weekly puzzle.** Every Sunday at 03:37 UTC `weekly-puzzle.yml` commits the new
`site/puzzles/weekly/<key>.json` to `main` (data only, no version bump) and starts `release.yml` for the **live
release tag** with `weekly=true`. That run rebuilds exactly the live release, with every weekly file from `main`
added, checks them with `scripts/weekly-puzzle.js --check`, and deploys it in the same `pages` concurrency group.
Players get no update banner (the version does not change). Every release build also copies all weekly files from
`main`, so a release never drops a published week, and regenerates (in the build, deterministically) any week
not over yet that the release's prices no longer fit. Weekly files are plain JSON the game fetches only when the
Puzzles list opens and never trusts; the service worker serves them network-first. The weekly scenario rides along in
the same run: `scripts/weekly-scenario.js` writes `site/scenarios/weekly/<key>.json` (fetched when the Scenarios list
opens), committed and deployed with the puzzle, never by a second workflow. See `docs/ARCHITECTURE.md`.
## Before you hand back a change that touches the build, deploy or loading
```bash
npm run build && npm run serve # the production build, served as static files
npm test -- tests/pages.test.js # static-only, all references resolve, Pages-only deploy
```
`tests/pages.test.js` fails on host configuration files, files over the limits, local references
that do not exist in `_site/`, scripts loaded from other origins, and any workflow that deploys
anywhere else. Do not weaken it to make a change pass; change the change.

View file

@ -1,104 +0,0 @@
---
name: performance
description: Measure and demonstrate the performance of every Series of Tubes change on a very large network, compare it with main, and report the numbers.
---
# Performance is always demonstrated
Every change to the game (anything in `src/` or `site/`) shows its performance on a very large network,
compared with `main`, before it is merged or released. A speed claim without numbers does not
count, and neither does "it feels fine on my small game". Most players who complain about lag
have huge late-game networks, and most of them are on phones.
## Measure
```bash
npm run perf -- --base-ref origin/main # headless only, a few minutes
npm run perf -- --base-ref origin/main --browser # plus real Chromium, desktop and phone (what CI runs)
```
`--base-ref` assembles that commit's page with its own scripts (`node scripts/lib/page.js --ref REF`;
for commits from before the split it reads their `site/index.html`). `--base FILE` takes a built page
instead. The head is always this checkout's `src/`, assembled the way the build does it.
`scripts/perf-bench.js` loads `tests/fixtures/big-network.json` (about 100 POPs, 150 links,
950 PNIs, 830 cache boxes, 110 IX ports, 170 customers) into the base and into this checkout and
times them in alternating turns, 15 runs each. It prints one table per environment:
- **Headless (jsdom):** our JavaScript. The most stable numbers for routing and simulation, but jsdom's
DOM is about 30× slower than a browser's and it has no layout, so its panel and dashboard rows say
little about what players feel.
- **Chromium, desktop** and **Chromium, phone** (`--browser`, `scripts/perf-browser.js`): the real DOM,
layout and canvas. The phone is 390×844 at 3× pixel density with the CPU slowed down 4×, about a
mid-range Android. Each version runs in its own browser. Use these rows for anything in the interface,
and to catch forced layouts (reading `scrollTop`, `offsetHeight` and friends right after changing the
DOM), which jsdom cannot see at all.
Browsers leave layout and canvas drawing for the next frame, so each timed run ends by forcing both;
without that, DOM and map work would look free. For the same reason, a profile that puts a lot of
time on a line reading `scrollTop` is usually showing layout that has to happen anyway, not waste:
check with the benchmark before "fixing" it.
Each table has these rows:
- Routing: `compute()`
- One game day: `dayTick()`
- An action: `after()`
- Side panel and left list
- NOC dashboard tabs
- Map at three zoom levels
and it says whether both versions route the save's traffic identically.
`--browser` needs Chromium: a local `playwright` with its browser works as is; otherwise
`playwright-core` (a dev dependency, installed by `npm ci`) drives the Chrome in `PERF_CHROME` or
`--chrome PATH`. CI uses the Chrome that ships with GitHub's Ubuntu runners.
Without `--base` it just times this checkout. `--runs N`, `--md FILE`, `--json FILE` and
`--summary FILE` are there for CI and for digging.
`--save FILE` swaps the fixture for another save, such as a laggy save from a bug report. Both a plain
save and a file from the in-game menu's Export save work:
```bash
npm run perf -- --save ~/Downloads/series-of-tubes-save.json --base-ref origin/main
```
Routing speed-ups must also keep the two equivalence tests green: `tests/speed.test.js` (the fast
path against the same code with its shortcuts switched off) and `tests/routing-reference.test.js`
(the indexed exit choice against a plain scan of every exit, across preferences, RouteScript,
incidents and failures).
## Demonstrate
- **Every pull request**: the Performance workflow runs the same comparison and posts the table as a
comment on the PR (updated on every push). Read it before merging. Locally, paste the table into
the PR description or the commit summary you report.
- **Everything you hand back to Frederic** that touched `src/` or `site/`: include the table, or at least the
rows that moved, in your summary. Say plainly when something got slower.
- **Before a release**: compare the release against the previous tag
(`npm run perf -- --base-ref v<last>`) and mention notable changes.
## Read the table
- Shared machines (CI runners, cloud sandboxes) swing a single run by ±30% on identical code, and no
timing method gets around it: CPU time is as noisy as wall time there. So a row only gets a verdict
when it moved by 15% or more **and** the samples say it is real: p < 0.01 in a Mann–Whitney U test
(`scripts/perf-stats.js`), and more than 2 ms (8 ms on the phone). Otherwise it shows ≈, whatever
the percentage. The `p` column says how sure each row is.
- A big percentage with ≈ means "could be noise". If it matters for the change, run again (or with
`--runs 25`) and report both runs; do not report a single noisy number as a finding.
- ⚠️ slower (15% or more) or 🔴 slower (50% or more) needs a reason in the PR, or a fix. A new
feature may cost time; a refactor or a fix should not.
- "Routing results differ" is expected when a change is meant to change gameplay (new cities,
balance, routing rules), and a bug when it only promises to be faster.
- Headless Chromium draws the canvas in software, real phones usually on the GPU, so map rows in the
Chromium tables overstate drawing cost. For drawing changes, also look at the game on a phone.
- Absolute numbers depend on the machine. Compare base and head from the same run, never numbers
from different runs or machines.
## Keeping the fixture useful
The save loads through `migrate()` like any player's save, so new state gets its defaults. Only
regenerate it (`node scripts/perf-fixture.js`, several minutes) when the save format changes in a
way old saves cannot load, or the game grows new heavy systems the save does not exercise. Say in
the commit that the baseline changed, because numbers before and after are no longer comparable.

View file

@ -1,109 +0,0 @@
---
name: release
description: Cut and ship a Series of Tubes release (patch or minor) from main via the auto-release workflow.
---
# Releasing Series of Tubes
Bumping `version` in `package.json` on `main` is the release button. CI tests the push
as usual; when it passes, `auto-release.yml` (which runs after every CI on `main`) sees
the new version, tags `v<version>` on the commit CI tested, publishes a GitHub release with
that version's CHANGELOG section as notes, and dispatches `release.yml`, which builds
`_site/` (`npm run build`: the page assembled from `src/` plus `site/`) and deploys it
to GitHub Pages (https://seriesoftub.es). GitHub Pages is the only host, ever: see the
`github-pages` skill.
## Weekly puzzles are not releases
`weekly-puzzle.yml` publishes a new puzzle every Sunday morning without a release: it commits the JSON under
`site/puzzles/weekly/` to `main` and redeploys the live tag through `release.yml` (`weekly=true`). Never bump the
version for a weekly puzzle. To publish or fix one by hand: `node scripts/weekly-puzzle.js --key 2026-W45 --force`,
`node scripts/weekly-puzzle.js --check`, commit to `main`, then run the "Weekly puzzle" workflow (or
`gh workflow run release.yml --ref <live tag> -f tag=<live tag> -f weekly=true`). A release includes every weekly
file on `main` when it builds.
The weekly scenario (`site/scenarios/weekly/`, `scripts/weekly-scenario.js`) ships in the same run and the same way:
`--key`, `--force` and `--check` work alike. Its `--check` replays each week not over yet with the reference plan in
the file; a new par is just written, a week the reference no longer wins is regenerated with `rev` + 1.
**Prices change, weeks follow.** `--check` re-solves every week not over yet with the game it runs; a week whose
budget no longer verifies is regenerated deterministically (the same puzzle with a new budget if that works, else a
fresh one for the same key) with `rev` + 1, which resets players' stars for that week only. Past weeks are left alone
unless the game rejects them. `release.yml` runs it before the tests on every deploy and fails only if a week cannot be
regenerated. A change to prices, cables or cities fails `npm test` until you run `node scripts/weekly-puzzle.js --check`
and commit the regenerated files with it (and `node scripts/weekly-scenario.js --check` for the scenarios).
## Only release when Frederic says so
Never bump the version on your own. Finished work is committed and pushed with its
bullets under `## [Unreleased]`, and you say it is ready to ship. A release happens only
when Frederic explicitly asks for one ("release", "ship it"), and then it includes
everything under `## [Unreleased]`. Docs, skills, CI, issue templates, tests and
refactors are just pushed and never need a release.
## At most one release per hour
Players get an update banner and a "What's new" window for every release, so ship at
most one release an hour. Before bumping, check when the last one went out:
```bash
gh api repos/fjaeckel/seriesoftubes/releases/latest --jq '.tag_name+" "+.published_at'
```
- **Less than 60 minutes ago:** even when asked, say so and suggest waiting until the hour
is up; release only if Frederic still wants it now.
- **60 minutes or more:** release everything under `## [Unreleased]` together, as one
version.
- **Live game broken for players** (it won't start, saves are lost, a phone can't get
past a screen): tell Frederic right away and propose a hotfix release; still wait for
his go.
## Pick the version
- Several changes batched together: use the biggest one (any feature → minor).
- Patch (`x.y.Z`): fixes, small tweaks, wording, icons.
- Minor (`x.Y.0`): new features or content.
## Steps
1. Don't run the test suite, the game or benchmarks before a release: CI tests the
version bump (a red CI releases nothing), and the Performance workflow benchmarks it. Just
check that the latest CI run on `main` is green (`gh run list --repo fjaeckel/seriesoftubes --limit 4`).
2. In `CHANGELOG.md`, move the bullets from `## [Unreleased]` into a new section
right below it: `## [x.y.z] — YYYY-MM-DD` (em dash, today's date). Keep an empty
`## [Unreleased]` heading above it. The build fails if the section has no bullets.
3. Bump the version in **both** files:
- `package.json` → `"version"`
- `package-lock.json` → top-level `"version"` and `packages[""].version`
4. (Nothing to run here: the workflow tests the release before it tags it.)
5. Commit on `main` as Frederic, with no attribution trailers:
```bash
git -c user.name="Frederic Jung" -c user.email="frederic@jc-ix.net" commit \
--author="Frederic Jung <frederic@jc-ix.net>" -m "Short summary (x.y.z)"
git push origin main
```
6. Watch the workflows until all three finish (CI, then Auto-release, then Release to GitHub Pages):
```bash
gh run list --repo fjaeckel/seriesoftubes --limit 4
gh run watch <id> --repo fjaeckel/seriesoftubes
```
7. Confirm it is live: `https://seriesoftub.es/version.json` shows the new version.
## Release notes rules
- The first sentence of each bullet is all the in-app "What's new" shows (at most five
bullets; longer notes get a link to the full GitHub release). Make that sentence
stand on its own: "Tier 1 networks can lay their own subsea cable (#22)." Detail goes
after it.
- Written for players, in plain English. One bullet per change, issue numbers like `(#37)`.
- Never mention hidden easter eggs or explain jokes.
- No internal function names.
## If something fails
- "not newer than the latest release": the version was not bumped, or was bumped
backwards.
- "CHANGELOG.md has no notes under ## [x.y.z]": the heading doesn't match the version
exactly or has no bullets.
- Tests fail in the workflow but pass locally: look for unseeded randomness in a test.
- Fix forward with a new patch version; never move or delete an existing tag.

View file

@ -1,71 +0,0 @@
---
name: write-tests
description: Write deterministic jsdom tests for Series of Tubes features and fixes in tests/*.test.js.
---
# Writing tests
Tests use `node:test` and `tests/harness.js`, which assembles the game page from `src/`
(once per test file) and loads it in jsdom with the animation loop off, a seeded `Math.random` and a recording fake canvas.
Code runs inside the page through `ev()`. `load()` is the page players get; tests of the agent facade
(`src/agent/`, `window.TUBES`) ask for the development page with `load({ agent: true })`.
## Pattern
```js
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
test('what the player should see happen', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
ev("ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()");
assert.ok(ev("R.served") > 0);
assert.deepEqual(errors, []); // always: no page errors
});
```
## Where to put it
Pick the suite by topic: `game` (core loop), `build`, `persist` (save/import/migrate),
`services` (customers), `peering`, `issues` (GitHub issue regressions, name them
`#NN …`), `regions`, `modes` (scenarios, sandbox, weekly), `i18n`, `pages` (hosting).
For a new feature, prefer a new file named after it (`tests/route-servers.test.js`): every
`tests/*.test.js` runs on its own (`scripts/test.js`), and a file of your own never conflicts
with someone else's tests. Appending to the big suites (`issues`, `regions`) is where
pull requests collide. Run one file with `npm test -- tests/route-servers.test.js`.
## Rules
- **Text in assertions:** match what the player sees (`/Ready in about 3 days/`), or compare with
`ev("tr('pnis.ready_in_about_n_days',{n:3})")`. Tests run the source page, where labels are readable;
the shipped page (ids instead of labels) is covered by `tests/pages.test.js`.
- **Deterministic.** Never rely on luck. Use the default seed, `window.__reseed(n)`,
or set state directly (`S.day=…`, `S.ev.x=…`).
- **Force a specific random failure or event** by patching the picker:
```js
ev("runNow(eval('('+failureRun.toString().replace('if(only)type=only;',\"type='crash';\")+')')())");
```
`failureRun()` is a generator (its yield is the routing): play it with `runNow()`. Check the current source for the
exact line first (`grep -rn "function\* failureRun" src/game`); it may differ. Or simply `fireFailure('crash')`.
- **Drive the game through `ACT`** like a player would, then `compute()` or `dayTick()`.
- **Saves:** for persistence changes, round-trip `JSON.stringify(S)` through
`parseSave()`/`migrate()`, and test that an *old* save without the new field still loads.
- **UI:** render with `renderAll()` and query `dom.window.document`; check phone
layouts by setting `window.innerWidth = 390` before rendering.
- Run `npm test`; the whole suite must pass, not just the new test.
## Servers, sockets and anything async
CI runs four parts at once, each with its files in parallel, so a test can wait seconds for things that take
milliseconds on your machine. Never sleep a fixed time and then assert: wait for the state with `tests/net.js`.
- `until(() => condition)` resolves true as soon as it holds (false after 20 s); assert on its result.
- `freePort()` asks the OS for a free port; never a fixed or random one.
- `kill(child)` stops a spawned server and resolves once it is gone.
- Listen and connect on `127.0.0.1`, not `localhost` (it can resolve to `::1` only on a CI runner).
- For HTTP to a test server, pass `agent: false`: a kept-alive socket can be reset by the server's idle timer.
- A fixed wait is fine only to prove that something does *not* happen.
Hunt a suspected flake before pushing: `npm test -- --stress 8 tests/x.test.js` runs 8 copies at once, busier than CI.

View file

@ -1,10 +0,0 @@
# The image takes only what docker/Dockerfile copies; everything else (git history, tests, docs, local saves,
# node_modules, _site) stays out of the build context.
*
!package.json
!package-lock.json
!src/
!site/
!scripts/
!tests/harness.js
!docker/docker-entrypoint.sh

3
.gitattributes vendored
View file

@ -1,3 +0,0 @@
# The assembler joins src/ byte for byte and refuses CR line endings; keep LF everywhere it reads.
src/** text eol=lf
site/i18n/*.js text eol=lf

View file

@ -1,87 +0,0 @@
name: Bug report
description: Something in the game is broken, looks wrong or crashes.
title: "[bug] "
labels: [bug, triage]
body:
- type: markdown
attributes:
value: |
Thanks for reporting! The more of this you fill in, the faster it gets fixed.
**One bug per issue, please.**
- type: textarea
id: what
attributes:
label: What happened?
description: Describe what went wrong. Screenshots or a screen recording help a lot. Drag them into this box.
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: What did you do right before it happened?
placeholder: |
1. Open the Infra tab in Frankfurt
2. Tap "Upgrade to 400G"
3. …
validations:
required: true
- type: textarea
id: expected
attributes:
label: What did you expect instead?
validations:
required: true
- type: input
id: version
attributes:
label: Game version
description: Shown at the bottom of the title screen, and in the menu under "What's new".
placeholder: "1.25.1"
validations:
required: true
- type: dropdown
id: device
attributes:
label: Device
options:
- Android phone
- iPhone
- Android tablet
- iPad
- Desktop or laptop
- Other
validations:
required: true
- type: input
id: browser
attributes:
label: Browser and version
placeholder: "Firefox 159 on Android 16, Safari on iOS 26.1, Chrome 141 on Windows…"
validations:
required: true
- type: dropdown
id: installed
attributes:
label: Installed as an app?
description: Did you add Series of Tubes to your home screen, or do you play in a browser tab?
options:
- In a browser tab
- Installed on the home screen
- Not sure
validations:
required: true
- type: textarea
id: save
attributes:
label: Saved game (optional, very helpful)
description: Menu → "Export save", then attach the file here. It lets us load your exact network.
- type: checkboxes
id: checks
attributes:
label: Before you submit
options:
- label: I searched the existing issues and this one is not already reported.
required: true
- label: This issue is about one bug only.
required: true

View file

@ -1,54 +0,0 @@
name: Feature request
description: An idea for something new in the game.
title: "[feature] "
labels: [enhancement, triage]
body:
- type: markdown
attributes:
value: |
Ideas are welcome! The best ones describe what happens in real networks and how it could become a fun mechanic.
**One idea per issue, please.**
- type: dropdown
id: area
attributes:
label: Part of the game
options:
- Map and interface
- Phones and tablets
- Network building (POPs, links, fiber, routers)
- Peering, transit and exchanges
- Customers
- Money, banks and prices
- Incidents and events
- Scenarios, goals and badges
- Something else
validations:
required: true
- type: textarea
id: problem
attributes:
label: What problem does it solve, or what is missing?
description: For example "When I reach Tier 1 I can't find where my transit ports are."
validations:
required: true
- type: textarea
id: idea
attributes:
label: Your idea
description: How would it work in the game?
validations:
required: true
- type: textarea
id: real
attributes:
label: How does this work in real life? (optional)
description: Links, war stories and real-world numbers make an idea much easier to model well.
- type: checkboxes
id: checks
attributes:
label: Before you submit
options:
- label: I searched the existing issues and nobody suggested this yet.
required: true
- label: This issue is about one idea only.
required: true

View file

@ -1,40 +0,0 @@
name: Balance or realism
description: Something works, but prices, odds or behaviour feel off compared with the real internet.
title: "[balance] "
labels: [balance, triage]
body:
- type: textarea
id: what
attributes:
label: What feels off?
description: For example "Overland waves between continents are cheaper than subsea, but in real life it's the other way round."
validations:
required: true
- type: textarea
id: real
attributes:
label: How it is in real life
description: Real prices, ratios, links or experience from your own network.
validations:
required: true
- type: textarea
id: suggestion
attributes:
label: What would you change? (optional)
- type: input
id: version
attributes:
label: Game version
description: Shown at the bottom of the title screen, and in the menu under "What's new".
placeholder: "1.25.1"
validations:
required: true
- type: checkboxes
id: checks
attributes:
label: Before you submit
options:
- label: I searched the existing issues and this is not already reported.
required: true
- label: This issue is about one topic only.
required: true

View file

@ -1,42 +0,0 @@
name: Translation
description: A wrong, awkward or missing translation, or a new language.
title: "[translation] "
labels: [translation, triage]
body:
- type: dropdown
id: lang
attributes:
label: Language
options:
- Italiano
- A new language (say which below)
validations:
required: true
- type: textarea
id: where
attributes:
label: Where in the game?
description: Which screen, panel or message? A screenshot helps.
validations:
required: true
- type: textarea
id: current
attributes:
label: Current text
validations:
required: true
- type: textarea
id: suggested
attributes:
label: Suggested text
validations:
required: true
- type: checkboxes
id: checks
attributes:
label: Before you submit
options:
- label: I am a fluent speaker of this language.
required: true
- label: I searched the existing issues first.
required: true

View file

@ -1,8 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: Chat with other players on Signal
url: https://signal.group/#CjQKIJwvEt5fYt1pvw7J2pV664CyUyGJXmAJLV8ia3nUdAD7EhA_FzdxflEzkNmcvDHdVgLQ
about: Screenshots, chat and peering-policy flame wars. Bugs and ideas go here as issues, so they don't scroll away.
- name: How the internet really works
url: https://tkjaer.github.io/how-the-internet-works/
about: Curious how the real thing works? This interactive map explains it far better than any game.

View file

@ -1,39 +0,0 @@
# Keeps what the workflows and the container image pin up to date: every GitHub Action is pinned to a commit SHA
# (Dependabot moves the SHA and its version comment together), the image's Node base to a digest, and the npm tools
# to the lockfile. Updates come as pull requests, one group per ecosystem, once a week.
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
day: monday
groups:
actions:
patterns: ["*"]
commit-message:
prefix: "CI"
- package-ecosystem: docker
directory: /docker
schedule:
interval: weekly
day: monday
# The image runs the Node major CI tests on (ci.yml); a new major comes with CI, by hand.
ignore:
- dependency-name: node
update-types: ["version-update:semver-major"]
commit-message:
prefix: "Container"
- package-ecosystem: npm
directory: /
schedule:
interval: weekly
day: monday
groups:
tools:
patterns: ["*"]
update-types: [minor, patch]
commit-message:
prefix: "Tools"

View file

@ -1,14 +0,0 @@
<!-- One small feature or one fix per pull request, please. See CONTRIBUTING.md. -->
## What and why
## How it was tested
<!-- Tests added or changed, and what you checked by hand (phone width, both orientations, Italian). -->
## Performance
<!-- Changes to src/ must show their performance on a big network. The Performance check posts the
numbers as a comment on this PR. Locally:
npm run perf -- --base-ref origin/main
Explain anything marked slower. -->

View file

@ -1,117 +0,0 @@
name: Auto-release
# Bumping "version" in package.json on main is the release button: this tags
# v<version>, publishes a GitHub release with that version's CHANGELOG section
# as notes, and starts the deploy. Releases created with the workflow token do
# not fire the "released" event, so the deploy is started explicitly, from the
# tag, which keeps the github-pages environment's v* tag rule happy.
#
# It runs when CI finishes on main, so a release never repeats the push's tests:
# CI green on the commit that bumped the version is the go. A red CI releases
# nothing. Started by hand, it has no CI result to go by, so it tests first.
on:
workflow_run:
workflows: [CI]
types: [completed]
branches: [main]
workflow_dispatch:
permissions:
contents: write # create the tag and the release
actions: write # start the deploy workflow
concurrency:
group: auto-release
cancel-in-progress: false
jobs:
check:
# After CI: only a green run of a push to main (not a PR's run, not a release's own call).
if: >-
github.event_name == 'workflow_dispatch' ||
(github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push')
runs-on: ubuntu-latest
env:
GH_TOKEN: ${{ github.token }}
outputs:
skip: ${{ steps.v.outputs.skip }}
ver: ${{ steps.v.outputs.ver }}
tag: ${{ steps.v.outputs.tag }}
pre: ${{ steps.v.outputs.pre }}
# The commit CI tested (main may have moved on since); by hand, main as it is now.
sha: ${{ github.event.workflow_run.head_sha || github.sha }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.event.workflow_run.head_sha || github.sha }}
fetch-depth: 0
- name: Work out the version and whether it is new
id: v
run: |
set -euo pipefail
ver=$(node -p "require('./package.json').version")
tag="v$ver"
echo "ver=$ver" >> "$GITHUB_OUTPUT"
echo "tag=$tag" >> "$GITHUB_OUTPUT"
if git ls-remote --exit-code --tags origin "refs/tags/$tag" >/dev/null; then
echo "$tag already exists, nothing to release."
echo "skip=true" >> "$GITHUB_OUTPUT"; exit 0
fi
latest=$(gh release list --repo "$GITHUB_REPOSITORY" --exclude-pre-releases --limit 1 --json tagName -q '.[0].tagName' || true)
latest="${latest#v}"
if [ -n "$latest" ] && [ "$(printf '%s\n%s\n' "$latest" "$ver" | sort -V | tail -n1)" != "$ver" ]; then
echo "::error::$ver is not newer than the latest release $latest"; exit 1
fi
awk -v v="$ver" 'index($0,"## ["v"]")==1{f=1;next} /^## \[/{f=0} f' CHANGELOG.md | sed -e '/./,$!d' > notes.md
if ! grep -q '[^[:space:]]' notes.md; then
echo "::error::CHANGELOG.md has no notes under ## [$ver]"; exit 1
fi
case "$ver" in *-*) echo "pre=true" >> "$GITHUB_OUTPUT";; *) echo "pre=false" >> "$GITHUB_OUTPUT";; esac
echo "skip=false" >> "$GITHUB_OUTPUT"
# Only when started by hand: after a push, CI has already tested this commit. By hand the commit is main as it is
# (github.sha, what check.outputs.sha is then), named directly so CI never checks out a ref a workflow_run handed over.
tests:
needs: check
if: needs.check.outputs.skip == 'false' && github.event_name == 'workflow_dispatch'
uses: ./.github/workflows/ci.yml
with:
ref: ${{ github.sha }}
release:
needs: [check, tests]
if: >-
always() && needs.check.result == 'success' && needs.check.outputs.skip == 'false' &&
(needs.tests.result == 'success' || needs.tests.result == 'skipped')
runs-on: ubuntu-latest
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ needs.check.outputs.tag }}
VER: ${{ needs.check.outputs.ver }}
PRE: ${{ needs.check.outputs.pre }}
SHA: ${{ needs.check.outputs.sha }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ needs.check.outputs.sha }}
- name: Publish the release
run: |
set -euo pipefail
awk -v v="$VER" 'index($0,"## ["v"]")==1{f=1;next} /^## \[/{f=0} f' CHANGELOG.md | sed -e '/./,$!d' > notes.md
pre=(); [ "$PRE" = "true" ] && pre=(--prerelease)
gh release create "$TAG" --repo "$GITHUB_REPOSITORY" \
--target "$SHA" --title "$VER" --notes-file notes.md "${pre[@]}"
- name: Deploy it
# Pre-releases are for testing and never go live. CI (or the tests above) already passed on this commit,
# so the deploy does not test it again (tested=true).
if: env.PRE == 'false'
run: gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG" -f tested=true
- name: Publish the Docker image
# Same pattern as the deploy above: the image is built and pushed from the
# release tag by docker.yml. Pre-releases get one too: an image tag is
# pulled on purpose, so a test image costs nothing.
run: gh workflow run docker.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG"

View file

@ -1,142 +1,23 @@
name: CI name: CI
# Every push and PR, and the releases too (auto-release.yml and release.yml call this workflow), so the tests run
# one way, split over several runners, everywhere.
on: on:
push: push:
branches: [main] branches: [main]
pull_request: pull_request:
workflow_call:
inputs:
ref:
description: The commit or tag to test (a release tag); the caller's commit when empty
type: string
default: ''
permissions: permissions:
contents: read contents: read
# A newer push to the same pull request makes the older run pointless: cancel it instead of queueing behind it.
# Runs on main always finish. A release's call gets a group of its own, so it never waits behind main's push run.
concurrency:
group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}${{ inputs.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
# Runners for the tests. Standard GitHub-hosted runners (4 cores each) are the only free ones for a public repo,
# and a run may use up to 20 at once, so more parts is how the tests get faster. Each part costs ~30 s of setup.
PARTS: 6
jobs: jobs:
# Splits the test files into parts of about equal time, once, so every part works from the same plan. The times test:
# come from the last run on main (the cache, see "timings" below), else from the committed tests/durations.json.
plan:
runs-on: ubuntu-latest runs-on: ubuntu-latest
outputs:
parts: ${{ steps.plan.outputs.parts }}
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@v7
with: - uses: actions/setup-node@v7
ref: ${{ inputs.ref }}
- uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: tests/durations.json
key: test-durations-${{ github.run_id }}
restore-keys: test-durations-
- id: plan
run: echo "parts=$(node scripts/test.js --plan "$PARTS")" >> "$GITHUB_OUTPUT"
part:
name: part ${{ strategy.job-index }}
needs: plan
runs-on: ubuntu-latest
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
files: ${{ fromJSON(needs.plan.outputs.parts) }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ inputs.ref }}
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 24
cache: npm
- run: npm ci
- name: Tests
env:
FILES: ${{ matrix.files }}
# Word splitting on purpose: FILES is a space-separated list of tests/*.test.js paths.
run: npm test -- --timings "$RUNNER_TEMP/timings.json" $FILES
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: always()
with:
name: timings-${{ strategy.job-index }}
path: ${{ runner.temp }}/timings.json
retention-days: 1
if-no-files-found: ignore
build:
name: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ inputs.ref }}
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with: with:
node-version: 24 node-version: 24
cache: npm cache: npm
- run: npm ci - run: npm ci
- run: npm test
- name: Build (not deployed — only releases deploy) - name: Build (not deployed — only releases deploy)
run: npm run build run: npm run build
translations:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ inputs.ref }}
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 24
cache: npm
- run: npm ci
- name: Translation coverage
run: node scripts/i18n-check.js --summary "$GITHUB_STEP_SUMMARY"
# The one check to look at: green only when the plan, every part, the build and the translations are.
test:
needs: [plan, part, build, translations]
if: always()
runs-on: ubuntu-latest
steps:
- name: Everything passed
run: |
echo "plan: ${{ needs.plan.result }}, parts: ${{ needs.part.result }}, build: ${{ needs.build.result }}, translations: ${{ needs.translations.result }}"
test "${{ needs.plan.result }}" = success && test "${{ needs.part.result }}" = success
test "${{ needs.build.result }}" = success && test "${{ needs.translations.result }}" = success
# After a run on main: each file's time from this run goes into the cache, so the next run (main or a PR) splits
# its parts by today's tests. Nobody has to remember to refresh tests/durations.json.
timings:
needs: part
if: always() && github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.part.result != 'skipped'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: tests/durations.json
key: test-durations-${{ github.run_id }}
restore-keys: test-durations-
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: timings-*
path: ${{ runner.temp }}/timings
- run: node scripts/test-timings.js --merge "$RUNNER_TEMP/timings"
- uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: tests/durations.json
key: test-durations-${{ github.run_id }}

View file

@ -1,35 +0,0 @@
name: Claude
# Comment "@claude ..." on an issue or PR (for example "@claude review this
# against CLAUDE.md") and Claude answers in the thread. Comment events run in
# this repo's context, so this also works on PRs from forks, where secrets are
# otherwise withheld. Only people with write access can trigger it.
# Needs the Claude GitHub app and a CLAUDE_CODE_OAUTH_TOKEN secret (claude setup-token).
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
pull_request_review:
types: [submitted]
jobs:
claude:
if: >-
(github.event_name != 'pull_request_review' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude'))
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
issues: write
id-token: write
actions: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 1
- uses: anthropics/claude-code-action@61a9c274fa7110a66dfafc1bbbced03833eb25fe # v1.0.269
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}

View file

@ -1,187 +0,0 @@
name: Container image
# Publishes ghcr.io/<owner>/<repo>:<version> for releases, and nothing else: auto-release.yml dispatches this workflow
# with the new tag (pre-releases too). There is no :latest and no image per commit. Pushes and pull requests that change
# what goes into the image only build it and try both modes; they never publish. The image packages the MCP server and
# the development server; the game itself is hosted on GitHub Pages only (docs/adr/0001-github-pages-only.md).
on:
workflow_dispatch:
inputs:
tag:
description: Release tag to build and publish (e.g. v2.10.1)
required: true
push:
branches: [main]
paths:
- docker/**
- .dockerignore
- package.json
- package-lock.json
- scripts/**
- tests/harness.js
- .github/workflows/docker.yml
pull_request:
paths:
- docker/**
- .dockerignore
- package.json
- package-lock.json
- scripts/**
- tests/harness.js
- .github/workflows/docker.yml
permissions:
contents: read
concurrency:
group: docker-${{ github.event_name }}-${{ inputs.tag || github.ref }}
cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }}
jobs:
# A push that bumps the version is a release on its way: once CI passes, auto-release.yml starts this workflow for
# the tag, which tests the same code before it publishes. Testing the push too would be the same run twice.
gate:
runs-on: ubuntu-latest
outputs:
run: ${{ steps.g.outputs.run }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ inputs.tag || '' }}
persist-credentials: false
- id: g
run: |
tag="v$(jq -r .version package.json)"
if [ "$GITHUB_EVENT_NAME" = push ] && ! git ls-remote --exit-code --tags origin "refs/tags/$tag" >/dev/null; then
echo "$tag is not tagged yet: the release will test this commit when it publishes."
echo "run=false" >> "$GITHUB_OUTPUT"
else
echo "run=true" >> "$GITHUB_OUTPUT"
fi
test:
needs: gate
if: needs.gate.outputs.run == 'true'
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ inputs.tag || '' }}
persist-credentials: false
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- name: Build for this runner
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
with:
context: .
file: docker/Dockerfile
platforms: linux/amd64
load: true
push: false
tags: sot:test
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Try both modes
run: |
set -euo pipefail
init='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"ci","version":"1"}}}'
mcp() { curl -sS -o /tmp/out -w '%{http_code}' -X POST http://127.0.0.1:7777/mcp \
-H 'content-type: application/json' -H 'accept: application/json, text/event-stream' "$@" -d "$init"; }
until_up() { for i in $(seq 1 60); do curl -s -o /dev/null "$1" && return 0; sleep 1; done; docker logs "$2"; exit 1; }
# Headless, with a token: refused without it, answered with it.
docker run -d --name sot-h -p 127.0.0.1:7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=ci-token sot:test
until_up http://127.0.0.1:7777/ sot-h
test "$(mcp)" = 401
test "$(mcp -H 'authorization: Bearer ci-token')" = 200
grep -q serverInfo /tmp/out
docker rm -f sot-h
# No token given: the container makes one, says so, and wants it.
docker run -d --name sot-t -p 127.0.0.1:7777:7777 -e MCP_MODE=headless sot:test
until_up http://127.0.0.1:7777/ sot-t
test "$(mcp)" = 401
tok=$(docker logs sot-t 2>&1 | sed -n "s/.*this run's token is //p" | head -1)
test -n "$tok"
test "$(mcp -H "authorization: Bearer $tok")" = 200
docker rm -f sot-t
# Browser mode: the development page and the MCP server.
docker run -d --name sot-b -p 127.0.0.1:8080:8080 -p 127.0.0.1:7777:7777 -e SOT_MCP_TOKEN=ci-token sot:test
until_up http://127.0.0.1:8080/ sot-b
test "$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/)" = 200
until_up http://127.0.0.1:7777/ sot-b
test "$(mcp -H 'authorization: Bearer ci-token')" = 200
docker rm -f sot-b
# The server runs as node, not root.
test "$(docker run --rm --entrypoint id sot:test -u)" != 0
publish:
if: github.event_name == 'workflow_dispatch'
needs: test
runs-on: ubuntu-latest
timeout-minutes: 45
permissions:
contents: read
packages: write
steps:
- name: Check the tag
env:
TAG: ${{ inputs.tag }}
run: |
[[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || { echo "::error::Not a release tag: $TAG"; exit 1; }
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ inputs.tag }}
persist-credentials: false
- name: Work out the image name and version
id: meta
env:
TAG: ${{ inputs.tag }}
run: |
set -euo pipefail
want="v$(jq -r .version package.json)"
if [ "$TAG" != "$want" ]; then echo "::error::Release tag $TAG does not match package.json ($want)"; exit 1; fi
# Named after this repository (ghcr.io/<owner>/<repo>, lowercased), so forks publish their own.
echo "image=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_OUTPUT"
echo "version=${TAG#v}" >> "$GITHUB_OUTPUT"
echo "revision=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
echo "created=$(git log -1 --format=%cI)" >> "$GITHUB_OUTPUT"
- uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push the release's version
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
with:
context: .
file: docker/Dockerfile
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}
labels: |
org.opencontainers.image.title=Series of Tubes MCP server
org.opencontainers.image.description=The Series of Tubes MCP server and development server, so an AI client can play the game.
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
org.opencontainers.image.documentation=${{ github.server_url }}/${{ github.repository }}/blob/${{ inputs.tag }}/docs/MCP.md
org.opencontainers.image.version=${{ steps.meta.outputs.version }}
org.opencontainers.image.revision=${{ steps.meta.outputs.revision }}
org.opencontainers.image.created=${{ steps.meta.outputs.created }}
org.opencontainers.image.licenses=MIT
provenance: mode=max
sbom: true
cache-from: type=gha
cache-to: type=gha,mode=max

View file

@ -1,43 +0,0 @@
name: Performance comment
# Posts the table from the Performance workflow on its pull request, and updates the same comment on every push.
# Runs in this repository's context with write access, so it only reads the uploaded text and never runs PR code.
on:
workflow_run:
workflows: [Performance]
types: [completed]
permissions:
pull-requests: write
issues: write
actions: read
jobs:
comment:
if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success'
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: perf
# Outside the workspace: the files come from a PR's run and are only ever read as text.
path: ${{ runner.temp }}/perf
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Post or update the comment
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
REPO: ${{ github.repository }}
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
run: |
cd "$RUNNER_TEMP/perf"
pr=$(tr -cd '0-9' < pr-number.txt)
[ -n "$pr" ] || { echo "no PR number"; exit 0; }
# Trust the number only if that PR's head is the commit that was benchmarked.
head=$(gh api "repos/$REPO/pulls/$pr" --jq .head.sha)
[ "$head" = "$HEAD_SHA" ] || { echo "PR #$pr has moved on since this run"; exit 0; }
{ echo '<!-- perf-bench -->'; head -c 60000 perf.md; } > body.md
id=$(gh api "repos/$REPO/issues/$pr/comments" --paginate --jq '.[] | select(.user.login == "github-actions[bot]" and (.body | startswith("<!-- perf-bench -->"))) | .id' | head -n 1)
if [ -n "$id" ]; then gh api -X PATCH "repos/$REPO/issues/comments/$id" -F body=@body.md > /dev/null
else gh api -X POST "repos/$REPO/issues/$pr/comments" -F body=@body.md > /dev/null; fi
echo "Posted to #$pr"

View file

@ -1,58 +0,0 @@
name: Performance
# Times the PR against its base on a very large network, headless and in Chrome (desktop and a throttled phone),
# and uploads the tables. A separate workflow
# (perf-comment.yml) posts it on the PR: runs for pull requests from forks have no write access.
on:
pull_request:
paths:
- 'src/**'
- 'site/**'
- 'scripts/lib/**'
- 'scripts/perf-*.js'
- 'tests/fixtures/**'
- 'tests/harness.js'
workflow_dispatch:
permissions:
contents: read
jobs:
bench:
runs-on: ubuntu-latest
timeout-minutes: 40
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 24
cache: npm
- run: npm ci
- name: Base version of the game
if: github.event_name == 'pull_request'
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
run: |
git fetch --depth=1 origin "$BASE_SHA"
# The base's page, assembled by the base's own scripts (or its site/index.html from before the split).
node scripts/lib/page.js --ref FETCH_HEAD -o "$RUNNER_TEMP/base.html"
echo "BASE_ARG=--base $RUNNER_TEMP/base.html" >> "$GITHUB_ENV"
- name: Benchmark
# The runner image ships Google Chrome; playwright-core (a dev dependency) drives it, no browser download.
run: |
export PERF_CHROME="$(command -v google-chrome || command -v google-chrome-stable || command -v chromium)"
echo "Chrome: $PERF_CHROME ($("$PERF_CHROME" --version))"
node scripts/perf-bench.js $BASE_ARG --browser --md perf.md --summary "$GITHUB_STEP_SUMMARY"
- name: Remember the PR number
if: github.event_name == 'pull_request'
env:
PR: ${{ github.event.pull_request.number }}
run: echo "$PR" > pr-number.txt
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
if: github.event_name == 'pull_request'
with:
name: perf
path: |
perf.md
pr-number.txt
retention-days: 7

View file

@ -2,63 +2,38 @@ name: Release to GitHub Pages
# The live site at https://seriesoftub.es only ever serves a published release. # The live site at https://seriesoftub.es only ever serves a published release.
# Pushes to main run CI but never deploy. To ship: bump "version" in # Pushes to main run CI but never deploy. To ship: bump "version" in
# package.json and date its CHANGELOG section; auto-release.yml then tags, # package.json, add a CHANGELOG entry, merge, then publish a GitHub release
# publishes the release and starts this workflow from the tag. Publishing a # tagged v<version>.
# release by hand works too. Every Sunday weekly-puzzle.yml redeploys the live
# release from its tag with the new weekly puzzle added (input weekly).
on: on:
release: release:
# "released" also fires when a pre-release is promoted to a full release. types: [published]
types: [released]
workflow_dispatch: workflow_dispatch:
inputs: inputs:
tag: tag:
description: Existing release tag to redeploy (e.g. v1.0.0) description: Existing release tag to redeploy (e.g. v1.0.0)
required: true required: true
allow_older:
description: Allow deploying a version older than what is live (rollback)
type: boolean
default: false
weekly:
description: Only the weekly puzzles changed (weekly-puzzle.yml); the release itself was tested when it shipped
type: boolean
default: false
tested:
description: The tag's tests already passed (auto-release.yml tests it before tagging)
type: boolean
default: false
# Least privilege: only the deploy job can write to Pages.
permissions: permissions:
contents: read contents: read
pages: write
id-token: write
concurrency: concurrency:
group: pages group: pages
cancel-in-progress: false cancel-in-progress: false
jobs: jobs:
# The release's tests, split over several runners like every push (ci.yml). Skipped when auto-release.yml has just
# run them on this tag, and for a weekly redeploy (the build step below tests the weekly files against the tag).
tests:
if: ${{ (github.event_name == 'workflow_dispatch' || !github.event.release.prerelease) && !inputs.weekly && !inputs.tested }}
uses: ./.github/workflows/ci.yml
with:
ref: ${{ github.event.release.tag_name || inputs.tag }}
build: build:
needs: tests
# Pre-releases are for testing and never go live. # Pre-releases are for testing and never go live.
if: ${{ always() && (github.event_name == 'workflow_dispatch' || !github.event.release.prerelease) && (needs.tests.result == 'success' || needs.tests.result == 'skipped') }} if: ${{ github.event_name == 'workflow_dispatch' || !github.event.release.prerelease }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:
TAG: ${{ github.event.release.tag_name || inputs.tag }} TAG: ${{ github.event.release.tag_name || inputs.tag }}
ALLOW_OLDER: ${{ inputs.allow_older || false }}
GH_TOKEN: ${{ github.token }}
steps: steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - uses: actions/checkout@v7
with: with:
ref: ${{ env.TAG }} ref: ${{ env.TAG }}
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - uses: actions/setup-node@v7
with: with:
node-version: 24 node-version: 24
cache: npm cache: npm
@ -70,80 +45,28 @@ jobs:
echo "::error::Release tag $TAG does not match package.json version ($want)" echo "::error::Release tag $TAG does not match package.json version ($want)"
exit 1 exit 1
fi fi
- name: Never deploy pre-releases or roll the live site back by accident
run: |
set -euo pipefail
if [ "$(gh release view "$TAG" --repo "$GITHUB_REPOSITORY" --json isPrerelease -q .isPrerelease)" = "true" ]; then
echo "::error::$TAG is a pre-release; pre-releases never deploy"; exit 1
fi
live=$(curl -sSf https://seriesoftub.es/version.json 2>/dev/null | jq -r .version || echo "0.0.0")
new="${TAG#v}"
if [ "$ALLOW_OLDER" != "true" ] && [ "$(printf '%s\n%s\n' "$live" "$new" | sort -V | tail -n1)" != "$new" ]; then
echo "::error::$new is older than the live $live. Re-run with allow_older to roll back on purpose."; exit 1
fi
# Weekly puzzles are published on main between releases (weekly-puzzle.yml). Every deploy ships all of them,
# so neither a release nor a weekly redeploy ever drops a week that is already out.
- name: Weekly puzzles and scenarios from main
run: |
set -euo pipefail
git fetch --no-tags --depth=1 origin main
for d in site/puzzles/weekly site/scenarios/weekly site/architect/weekly; do
if git cat-file -e "FETCH_HEAD:$d" 2>/dev/null; then
rm -rf "$d"
git checkout FETCH_HEAD -- "$d"
echo "$d: $(ls "$d" | grep -c '^[0-9].*\.json$')"
fi
done
- run: npm ci - run: npm ci
# This release's prices may no longer fit a week already published: --check regenerates every week not over - run: npm test
# yet whose budget no longer verifies (deterministically, so main's next weekly run commits the same files),
# and fails the deploy only if that fails. Before the tests, which check the weeks too.
- name: Fit the weekly puzzles to this release
run: |
set -euo pipefail
# A release from before the weekly puzzles ships the files without reading them: nothing to check.
if [ ! -f scripts/weekly-puzzle.js ]; then echo "This release does not read weekly puzzles yet."; exit 0; fi
node scripts/weekly-puzzle.js --check
if [ -f scripts/weekly-scenario.js ]; then node scripts/weekly-scenario.js --check; fi
if [ -f scripts/weekly-architect.js ]; then node scripts/weekly-architect.js --check; fi
# The weekly files come from main, not the tag. When they (after fitting) are the tag's own, CI already tested
# them with it; otherwise (a newer week, a refitted one) they are tested against this release here.
- name: Are the weekly files the tag's own?
id: weekly
run: |
if [ -z "$(git status --porcelain -- site/puzzles/weekly site/scenarios/weekly site/architect/weekly)" ]; then
echo "Same weekly files as the tag: tested with it already."; echo "same=true" >> "$GITHUB_OUTPUT"
else
git status --short -- site/puzzles/weekly site/scenarios/weekly site/architect/weekly; echo "same=false" >> "$GITHUB_OUTPUT"
fi
- name: Test the weekly puzzles against this release
if: ${{ hashFiles('scripts/weekly-puzzle.js') != '' && (steps.weekly.outputs.same != 'true' || !(inputs.tested || needs.tests.result == 'success')) }}
run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js $(ls tests/weekly-scenario.test.js tests/weekly-architect.test.js 2>/dev/null)
- name: Build site - name: Build site
run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build run: VERSION="${TAG#v}" npm run build
- uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 - uses: actions/upload-pages-artifact@v5
with: with:
path: ./_site path: ./_site
# A skipped job skips everything that needs it, even through build (which runs anyway): without always() here, a
# release whose tests auto-release.yml already ran built and never deployed (v3.2.0).
deploy: deploy:
needs: build needs: build
if: ${{ always() && needs.build.result == 'success' }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment: environment:
name: github-pages name: github-pages
url: ${{ steps.deployment.outputs.page_url }} url: ${{ steps.deployment.outputs.page_url }}
steps: steps:
- id: deployment - id: deployment
uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 uses: actions/deploy-pages@v5
# Tell IndexNow (Bing, Yandex, Seznam, …) about the new version, only after
# the site is live. # the site is live.
indexnow: indexnow:
needs: deploy needs: deploy
if: ${{ always() && needs.deploy.result == 'success' && !inputs.weekly }}
runs-on: ubuntu-latest runs-on: ubuntu-latest
env: env:
# IndexNow keys are public by design (also served at /<key>.txt). # IndexNow keys are public by design (also served at /<key>.txt).

View file

@ -1,88 +0,0 @@
name: Weekly puzzle
# Every Sunday morning: make this week's puzzle (scripts/weekly-puzzle.js), scenario (scripts/weekly-scenario.js) and
# Architect run (scripts/weekly-architect.js),
# commit them to main as a data-only change, and redeploy the live release with them, once. Weeks start Sunday
# 06:00 Berlin time; 03:37 UTC is 04:37 in winter and 05:37 in summer, so the files are live before the week starts.
#
# No version bump, so no release: auto-release.yml only runs when package.json changes (and pushes made with
# the workflow token start no workflows at all). The deploy itself is release.yml, still the only workflow
# that can write to Pages, started from the live release's tag with weekly=true: it rebuilds exactly that
# release with every weekly puzzle from main added, in the same "pages" concurrency group as any release.
on:
schedule:
- cron: '37 3 * * 0'
workflow_dispatch:
inputs:
key:
description: Week to make, e.g. 2026-W45 (default the week starting this Sunday)
required: false
deploy:
description: Redeploy the live release with it
type: boolean
default: true
permissions:
contents: write # commit the puzzle to main
actions: write # start release.yml
concurrency:
group: weekly-puzzle
cancel-in-progress: false
jobs:
puzzle:
runs-on: ubuntu-latest
timeout-minutes: 30
env:
GH_TOKEN: ${{ github.token }}
KEY: ${{ inputs.key }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: main
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version: 24
cache: npm
- run: npm ci
# Weeks already out that main's prices no longer fit are regenerated first, so the new week's history is current.
- name: Fit the published weeks to main
run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && node scripts/weekly-architect.js --check
- name: Make the puzzle and the scenario
run: |
set -euo pipefail
if [ -n "$KEY" ]; then
[[ "$KEY" =~ ^[0-9]{4}-W[0-9]{2}$ ]] || { echo "::error::$KEY is not a week key"; exit 1; }
node scripts/weekly-puzzle.js --key "$KEY"
node scripts/weekly-scenario.js --key "$KEY"
node scripts/weekly-architect.js --key "$KEY"
else
node scripts/weekly-puzzle.js
node scripts/weekly-scenario.js
node scripts/weekly-architect.js
fi
- name: Check every weekly puzzle
run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && node scripts/weekly-architect.js --check && npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js tests/weekly-scenario.test.js tests/weekly-architect.test.js
- name: Commit it to main
run: |
set -euo pipefail
git add site/puzzles/weekly site/scenarios/weekly site/architect/weekly
# Data only: anything else changed means something is wrong.
if git status --porcelain | grep -v -e ' site/puzzles/weekly/' -e ' site/scenarios/weekly/' -e ' site/architect/weekly/' | grep -q .; then git status --porcelain; echo "::error::unexpected changes"; exit 1; fi
if git diff --cached --quiet; then echo "Nothing new to commit."; exit 0; fi
git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \
commit -m "Weekly puzzle and scenario $(git diff --cached --name-only | grep -o '[0-9]\{4\}-W[0-9]\{2\}' | sort -u | paste -sd ' ')"
git push origin HEAD:main
- name: Redeploy the live release with it
if: github.event_name == 'schedule' || inputs.deploy
run: |
set -euo pipefail
tag=$(gh release list --repo "$GITHUB_REPOSITORY" --exclude-pre-releases --exclude-drafts --limit 1 --json tagName -q '.[0].tagName')
[ -n "$tag" ] || { echo "::error::no release to redeploy"; exit 1; }
# Releases from before the weekly puzzles cannot take them (and their game would not read them).
if ! git fetch --no-tags --depth=1 origin "refs/tags/$tag" || ! git show FETCH_HEAD:.github/workflows/release.yml | grep -q '^ weekly:'; then
echo "::notice::$tag predates weekly puzzles; the puzzle is on main and ships with the next release."; exit 0
fi
gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$tag" -f tag="$tag" -f weekly=true
echo "Redeploying $tag with the weekly puzzles."

1
.gitignore vendored
View file

@ -1,4 +1,3 @@
node_modules/ node_modules/
_site/ _site/
.DS_Store .DS_Store
mp-data/

File diff suppressed because it is too large Load diff

102
CLAUDE.md
View file

@ -1,102 +0,0 @@
# Series of Tubes: notes for Claude
A free cartoon browser game about how the internet works, live at
https://seriesoftub.es, hosted on GitHub Pages. The game is one static page with no framework.
Its source is many small files in `src/` (`src/styles/*.css`, `src/game/**/*.js`, the shell
`src/index.html`); the build pastes them together, in path order, into a single `index.html`, the
same one-file page players have always loaded. Static files (dictionaries, icons, service worker)
live in `site/`. `src/agent/` (the facade the MCP server plays through) goes into the development page only,
never into the page players get, and nothing in `src/game/` may use it (`docs/adr/0004-dev-only-code.md`).
Read these before larger changes:
- `docs/ARCHITECTURE.md`: where the code is, and how a day of simulation runs.
- `docs/adr/`: decisions that are settled (GitHub Pages only; one page assembled at build).
- `.claude/skills/`: step-by-step procedures (`edit-the-game`, `github-pages`, release,
translations, tests, performance).
- `.claude/skills/gameplay-rules/`: the game's design rules (W1, N3, F2…), each enforced by
`tests/gameplay-rules.test.js`; run it before changing cities, networks, cables, modes or balance.
## Commands
```bash
npm ci # once: installs jsdom for the tests
npm run dev # play while developing: http://localhost:8080, reloads on save (--host to share)
npm test # node:test + jsdom, every tests/*.test.js, must stay green
node scripts/i18n-check.js # must report "0 missing, 0 unused, 0 broken" (and sorted dictionaries)
node scripts/i18n-add.js FILE.json # add/change/remove translations (see `add-strings`)
npm run build # builds _site/ for GitHub Pages (assembles src/, stamps version, bakes release notes)
npm run serve # build and serve the production site locally
npm run perf -- --base-ref origin/main # big-network benchmark vs main (see `performance`)
npm run perf -- --base-ref origin/main --browser # the same, also in real Chromium (desktop and phone)
npm run mcp # the game as a local MCP server for AI clients, stdio or --http (docs/MCP.md)
```
## Hard rules
- **GitHub Pages, always.** The game is hosted on GitHub Pages and nowhere else. This is not up
for discussion: never propose or prepare another host, a CDN in front, a backend, server-side
rendering, redirects or custom headers. The build output stays plain static files from one
origin. If a feature seems to need a server, redesign the feature. See the `github-pages` skill
and `docs/adr/0001-github-pages-only.md`.
- **No runtime cost for structure.** The page ships as one assembled `index.html`. Organise code
into files under `src/` freely (build time is cheap), but never in a way that adds requests or
work to page load or to the game loop.
- **Git:** work on `main`, no branches. Commits are authored and committed as
`Frederic Jung <frederic@jc-ix.net>`. Never add `Co-Authored-By`, `Claude-Session`
or any other attribution trailers.
- **Releases only when Frederic says so.** Never bump the version on your own: push finished
work with its CHANGELOG bullets under `## [Unreleased]` and say it is ready. When he asks
for a release, follow the `release` skill: small fixes get a patch (`x.y.Z`), features a
minor, at most one release per hour. Docs, skills, CI, tests and refactors never need one.
- **Release notes in the app are short**: only the first sentence of each CHANGELOG bullet
(and at most five bullets) shows in "What's new", with a link to the full GitHub
release. Write that first sentence so it stands on its own.
- **Names are puns.** No real company names for networks, vendors, cables, banks,
data centers or exchanges (Cogentle, Goggle, NetChill, Junipurr, Arrrhipster…).
Real conference names (NANOG, RIPE, DENOG) are fine. Avoid lazy "-ish" names: find
a real pun, or keep the plain word.
- **Easter eggs stay secret.** Never mention hidden jokes or easter eggs (for example
whatever `elephant()` does) in commit messages, release notes or the CHANGELOG.
- **Every player-facing string is translated, by label.** Code uses `tr('area.label')`,
`trn('area.label', n)` or `N_('area.label')` (anything stored in a save: `N_()`), never English text.
Add the English (`src/i18n/en.js`) and every translation (`site/i18n/*.js`) in the same change with
`scripts/i18n-add.js` (see `add-strings`).
- **Phones first.** About 70% of players are on phones. Every new panel, button and
modal must work at 360 px wide, in portrait and landscape, using the phone tab bar
and bottom sheets. Check `isPhone()` layouts, not just desktop.
- **Saves are sacred.** Old saves must keep loading. Any new state field gets a default
in `newGame()` and a check/repair in `sanitize()`; renamed fields are migrated there.
- **Performance is always demonstrated.** Every change to `src/` or `site/` is measured on the big-network
fixture against `main` (`npm run perf -- --base-ref origin/main`, see the `performance` skill),
and the numbers go into the PR and into your summary. Every PR also gets them as a comment from
CI. Anything slower needs a reason or a fix.
- **Tests come with features.** Add or extend a test in `tests/` for every feature or
fix (a new feature gets its own `tests/<feature>.test.js`). Tests are seeded, so they must not
depend on luck.
- **CHANGELOG style:** plain English, written for players, one bullet per change,
issue numbers in parentheses like `(#37)`. No internal names, no jokes explained. The CHANGELOG
is the one file every change touches; conflicts there are expected (keep both bullets).
## Style of the code
- Dense JavaScript in small topic files under `src/game/` (see `edit-the-game`): a new feature gets
its own `NN-name.js` in the folder of its topic, actions go in the matching
`src/game/90-actions/*.js`. All files share one top-level scope; top-level values may only use
top-level values from earlier files. Match the surrounding style: short helper names, arrow
functions, template-literal HTML, no new dependencies.
- Lists people add to (cities, cables, networks, dictionaries) are one entry per line; id-keyed
objects and dictionaries stay sorted, so additions do not collide.
- UI is rebuilt from state: change `S`, then call `after()` (recompute, check goals,
re-render, save). Buttons are `btn(label, actName, args, cls, disabled)`, which
dispatch to `ACT[actName](args)` through `data-act`/`data-args`.
- Never trust saved or imported state: anything read from `S` that came from a save
must already have been validated in `sanitize()`.
- Keep comments short and about *why*.
## Tone
Friendly, nerdy and accurate underneath the jokes. Mechanics should follow how
networks really work (95th-percentile billing, peering policies, LAGs, DWDM reach,
route leaks, RPKI) and then exaggerate for fun. When unsure how something works in
real life, look it up before modelling it.

View file

@ -1,60 +0,0 @@
# Code of Conduct
Series of Tubes is a cartoon game about how the internet works, built by people who
love networks and people who are just curious about them. Everyone is welcome here:
seasoned network engineers, students, translators, players who have never heard of BGP,
and people who just want to suggest a city with a funny data center name.
The short version: **be excellent to each other.**
## Where this applies
Everywhere people meet around this project: GitHub issues, pull requests, reviews and
discussions, the Series of Tubes Signal group, and anywhere else you represent the
project, online or at a conference bar after NANOG.
## What we want
- **Welcome people.** Newcomers are how every community stays alive. Nobody was born
knowing what a route reflector is. Explain things kindly, and assume the question is
sincere.
- **Be patient across languages.** Many of us write in our second or third language.
Judge the idea, not the grammar.
- **Disagree about ideas, not people.** Argue about peering policy, balance and puns as
hard as you like. Criticise the change, never the person who made it.
- **Assume good intent.** Text loses tone. If something reads badly, ask before you
react.
- **Give credit.** Thank people for reports, fixes and ideas, and say where an idea came
from.
- **Own your mistakes.** We all fat-finger a config now and then. Apologise, fix it,
move on.
- **Keep the jokes kind.** This game runs on puns. The target of a joke is a network,
a cable or a router, never a person or a group of people.
## What we don't accept
- Harassment of any kind, in public or in private messages.
- Insults, slurs, or demeaning comments about anyone's gender, gender identity or
expression, sexual orientation, disability, appearance, body, age, race, ethnicity,
nationality, religion, experience level or anything else about who they are.
- Sexual language or imagery, and unwelcome attention of any kind.
- Threats, intimidation, stalking, or encouraging anyone else to do these things.
- Sharing someone's private information (an address, a phone number, a real name they
have not shared) without their permission.
- Trolling, deliberately derailing discussions, or flooding issues and chats.
- Continuing to contact someone after they have asked you to stop.
## If something happens
If someone makes you or others feel unwelcome or unsafe, tell the maintainer, Frederic,
in a private message in the Signal group. You do not need to be the person it happened
to, and you do not need proof or perfect wording. Reports are kept confidential.
We will listen, look at what happened, and do what fits: a friendly word, a request to
edit or delete something, a warning, or removing someone from the project's spaces for a
while or for good. Whoever reports in good faith will never be punished for it.
## Making it better
This document is for everyone here. If something is missing or unclear, open an issue
or a pull request, like for any other part of the project.

View file

@ -1,153 +0,0 @@
# Contributing to Series of Tubes
Thanks for wanting to help build the cartoon internet. Bug reports, ideas, puns,
translations and code are all welcome.
Everyone is welcome here, and everyone follows our [Code of Conduct](CODE_OF_CONDUCT.md).
The short version: be excellent to each other.
## Reporting bugs and ideas
Open an issue on GitHub and pick the form that fits: bug report, feature request,
balance or realism, or translation. Blank issues are turned off so every report has
what we need to triage it. For bugs, an export of your save (menu → Export save)
lets us load your exact network. One topic per issue, please.
Ideas are best when they say what happens in real networks and how that could become
a fun mechanic.
The [Signal group](https://signal.group/#CjQKIJwvEt5fYt1pvw7J2pV664CyUyGJXmAJLV8ia3nUdAD7EhA_FzdxflEzkNmcvDHdVgLQ) is for hanging out with other players, not for
reports: anything meaningful (a bug, an idea, a balance problem) goes into an issue,
even if you first mentioned it in the chat. Things said only in Signal get lost.
## Development
The game is one static page with no framework, hosted on GitHub Pages. Its source is split into
small files under `src/` (styles in `src/styles/`, the game script in `src/game/`), which the build
joins, in path order, into a single `index.html`. Static files such as the translations live in `site/`.
```bash
npm ci # installs jsdom for the tests
npm run dev # http://localhost:8080, reloads when you save a file
npm test # all tests must pass
node scripts/i18n-check.js # translations must be complete and sorted
npm run serve # the production build, as GitHub Pages will serve it
```
Where things are, and how a day of the simulation runs: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
### Keeping pull requests apart
Many people work on the game at once. A few habits keep your pull request from colliding with theirs:
- Put a new feature in its own file in the folder of its topic (for example
`src/game/70-rules/85-route-servers.js`), and its tests in their own `tests/<feature>.test.js`.
New files in `src/` and `tests/` are picked up automatically; nothing needs registering.
- Add actions to the matching file in `src/game/90-actions/`, not wherever there is room.
- Lists (cities, cables, networks) take one entry per line; keep id-keyed tables sorted.
- Text is keyed by labels (`tr('pnis.ready_in_about_n_days')`, English in `src/i18n/en.js`). Add new
text with `node scripts/i18n-add.js` rather than by hand: it writes the English and the translations
and keeps every dictionary sorted, so your new strings don't land on the same lines as everyone
else's. Fixing English wording no longer touches the translations.
- The `CHANGELOG.md` bullet is the one place everybody writes. If it conflicts, keep both bullets.
### Your branch still edits `site/index.html`?
Until version 1.34 the whole game was one file, `site/index.html`. If your branch was started before
the split, merge `main` and let a script move your changes into `src/`:
```bash
git fetch origin
git merge origin/main # stops: site/index.html was deleted on main
node scripts/legacy/port-branch.js # moves your edits into the matching src/ files
git status # fix any conflict it lists, then
npm test && git commit
```
It splits your version of the page and the one you started from the same way `src/` was made (your
English text becomes labels too), merges each piece into `src/`, and applies your English and
dictionary changes entry by entry. It only reports conflicts
where your change and `main` touched the same lines.
## Pull requests
### Pick an issue labelled `implement`
Open issues are not a to-do list. Every issue is triaged first: some are accepted, some
still need discussion, some are left for the maintainer and some won't happen at all.
**Only issues labelled [`implement`](https://github.com/fjaeckel/seriesoftubes/labels/implement)
are open for outside contributions.** Pull requests for any other issue will be closed,
however good the code is. Say in the issue that you're taking it, so two people don't
build the same thing.
**Each account may have at most 4 open pull requests at a time, drafts included.**
GitHub won't let you open a fifth until one of them is merged or closed.
### A note on AI agents
AI tools are welcome as a helper, but please don't point an agent at the issue tracker
and let it open issues or pull requests on its own. We've had batches of automated
"fix all the issues" pull requests, which is why the limit above exists. Each one still
takes a human to read, check and close, and that time comes out of the game.
So: write issues yourself, about what *you* saw. Only open a pull request you have run,
tested and can explain. Automated issues and pull requests are closed without a detailed
review, and accounts that keep sending them may be blocked. A short, honest, human-written
contribution is always welcome, even if your English or your code isn't perfect yet.
### What every pull request needs
- Keep pull requests small: one small feature or one fix each, targeting `main`.
Every pull request must be reviewable by a human in one sitting. Large drops,
sweeping rewrites or many unrelated changes in one PR will be asked to be split up,
and that applies just as much to AI-generated code.
- Add or update a test in `tests/` for every feature or fix. Tests are seeded and
must not depend on luck.
- Add a bullet for players under `## [Unreleased]` in `CHANGELOG.md`, in plain English.
Releases are cut by the maintainer.
- Show the performance of changes to `src/` on a big network. The Performance check posts a table
comparing your PR with `main` as a comment; to run it yourself:
`npm run perf -- --base-ref origin/main`
(add `--browser` to also time it in Chromium as a desktop and a phone, like CI does).
Anything marked slower needs an explanation.
- The game is hosted on GitHub Pages, and that will not change. Changes must work as plain static
files: no server code, no other host, no redirects or custom headers (see
[docs/adr/0001-github-pages-only.md](docs/adr/0001-github-pages-only.md)).
- Old saves must keep loading. New state needs a default for new games and a check in
`sanitize()`.
- Check your change on a phone-sized screen (about 360 px wide). Most players are on
phones.
## House rules for content
- **Every name is a pun.** No real company names for networks, vendors, cables, banks,
data centers or exchanges. Real conference names (NANOG, RIPE, DENOG…) are fine.
Please don't use lazy "-ish" names; find a proper pun or use a plain word.
- **Accurate underneath the jokes.** Mechanics should be recognisable to a network
engineer: exaggerated, not invented.
- **Friendly humour.** Punch at technology, bureaucracy and ourselves, not at people.
## Translations
Every player-facing string goes through `tr()`, `trn()` or `N_()`. Dictionaries live
in `site/i18n/` (label → translation, one entry per line, sorted; the English for each label is in
`src/i18n/en.js`). To add a language, copy `it.js`, translate the values (`en.js` lists the same labels
in the same order), register the language in the language list in `src/index.html`, and run
`node scripts/i18n-check.js <lang>` until it reports nothing missing, unused or broken. The CI job "translations" runs the same check on every pull request, shows each language's coverage in the run summary, and also fails if a new language is not added to the language list or to the offline cache in `site/sw.js`.
Language pull requests must be reviewed by a human who speaks the language, and
checked in the game itself, not only in the dictionary file. Passing the checker is
not enough. The reviewer plays with the language switched on and looks for anything
that got worse:
- text overflowing buttons, panels or toasts, especially on phones
- truncated or broken layouts, missing placeholders, raw `{name}` or HTML showing
- awkward or machine-sounding phrasing, wrong networking terms
- puns and jokes that no longer land
Note in the pull request what you checked and on which screen sizes.
## License
By contributing, you agree that your contributions are licensed under the
[MIT License](LICENSE).

21
LICENSE
View file

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2026 Frederic Jung
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -13,7 +13,7 @@ You start with one router in one city and grow into a transit-free Tier 1:
- **Interconnection:** IP transit billed on the 95th percentile, internet exchanges - **Interconnection:** IP transit billed on the 95th percentile, internet exchanges
with route servers, open/selective/restrictive/paid peering, PNIs, embedded CDN with route servers, open/selective/restrictive/paid peering, PNIs, embedded CDN
caches, and NNI fabrics for virtual circuits and remote peering. caches, and NNI fabrics for virtual circuits and remote peering.
- **Infrastructure:** leased waves on around 40 subsea cable systems modelled on real ones, - **Infrastructure:** leased waves on around 40 real-ish subsea cable systems,
dark fiber (leased or self-built) lit with DWDM and ZR+ optics, router dark fiber (leased or self-built) lit with DWDM and ZR+ optics, router
generations that cap your port speeds, and LAGs to bundle ports when one isn't enough. generations that cap your port speeds, and LAGs to bundle ports when one isn't enough.
- **Traffic engineering:** see exactly what fills each link, tune link metrics and - **Traffic engineering:** see exactly what fills each link, tune link metrics and
@ -24,63 +24,86 @@ You start with one router in one city and grow into a transit-free Tier 1:
Every company is a pun. No real company names are used. Every company is a pun. No real company names are used.
## Learn how it really works
This game simplifies a lot, and gets some things gloriously wrong on purpose. For
the real thing, go to **[How the Internet Works](https://tkjaer.github.io/how-the-internet-works/)**
by Thomas Kjær Aabo ([source](https://github.com/tkjaer/how-the-internet-works)):
an interactive, zoomable map that follows your data from Wi-Fi and copper to
undersea fiber, as the internet works today, in 2010 and in 1995, with simple or
technical explanations. If you enjoy Series of Tubes, you will learn more from
an hour there than from a year of laying cartoon fiber here.
## Playing locally ## Playing locally
It is a single static page, assembled from the files in `src/` by a small Node script: It is a single static page with no build step for development:
```sh ```sh
npm ci open site/index.html # or: npm run serve
npm run dev # http://localhost:8080
``` ```
Progress is saved in your browser's local storage. Progress is saved in your browser's local storage.
The game speaks English, Italian, Portuguese, French, Spanish and German. It follows your browser's language the first time
and remembers the one you pick under Settings or on the title screen.
## Development ## Development
```sh ```sh
npm ci npm ci
npm run dev # development server on localhost (--host to share): assembles src/ on every request, reloads on save
npm test # headless tests: boot, geography, a year of play, every incident, every panel npm test # headless tests: boot, geography, a year of play, every incident, every panel
npm run build # writes the site for GitHub Pages to _site/, with version and date stamped in npm run build # writes the deployable site to _site/ with version and date stamped in
npm run i18n:check # lists text missing from (or stale in) the translations
npm run mcp # the game as an MCP server, so an AI client can play and debug it, headless or in your tab (docs/MCP.md)
``` ```
## Community ```
site/ everything that is deployed
index.html the whole game (HTML, CSS and JS in one file)
images/og-image.png social preview (1200×630)
favicon.*, icon-* favicons, app icons, manifest
robots.txt, sitemap.xml, llms.txt, 404.html, CNAME
scripts/build.sh copies site/ to _site/ and stamps __VERSION__ / __BUILD_DATE__
tests/ node:test + jsdom
.github/workflows/ ci.yml (every push) and release.yml (Pages deploy)
```
Come hang out in the **[Series of Tubes Signal group](https://signal.group/#CjQKIJwvEt5fYt1pvw7J2pV664CyUyGJXmAJLV8ia3nUdAD7EhA_FzdxflEzkNmcvDHdVgLQ)**. Share screenshots of your ## Releasing
network, suggest cities, and argue about peering policy with other players.
There are fewer backhoes there than in the real thing.
Signal is for chatting. Bugs, feature requests and anything else that should not get Only published releases reach [seriesoftub.es](https://seriesoftub.es). Pushes to
lost go into a **[GitHub issue](https://github.com/fjaeckel/seriesoftubes/issues/new/choose)**. `main` run CI and nothing else.
## Star history 1. Bump `version` in `package.json` (semver) and add a `CHANGELOG.md` entry.
Write the bullets for players: the build turns that section into the in-game
"What's new" card and into `/version.json`, which open games poll to offer a reload.
2. Merge to `main`.
3. Publish a GitHub release tagged `v<version>`, e.g. `gh release create v1.1.0 --generate-notes`.
<a href="https://star-history.com/#fjaeckel/seriesoftubes&Date"> The release workflow checks that the tag matches `package.json`, runs the tests,
<picture> builds, deploys to GitHub Pages and pings IndexNow. Pre-releases never deploy.
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=fjaeckel/seriesoftubes&type=Date&theme=dark" /> To redeploy an existing release, run the workflow manually with its tag.
<img alt="Star history of Series of Tubes" src="https://api.star-history.com/svg?repos=fjaeckel/seriesoftubes&type=Date" />
</picture>
</a>
## Contributing ## Hosting setup
Issues and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md). Everyone taking part follows the [Code of Conduct](CODE_OF_CONDUCT.md): be excellent to each other. GitHub Pages serves the site with **Source: GitHub Actions** and the custom domain
`seriesoftub.es`. DNS for the apex domain:
## License ```
seriesoftub.es. A 185.199.108.153
seriesoftub.es. A 185.199.109.153
seriesoftub.es. A 185.199.110.153
seriesoftub.es. A 185.199.111.153
seriesoftub.es. AAAA 2606:50c0:8000::153
seriesoftub.es. AAAA 2606:50c0:8001::153
seriesoftub.es. AAAA 2606:50c0:8002::153
seriesoftub.es. AAAA 2606:50c0:8003::153
www.seriesoftub.es. CNAME fjaeckel.github.io.
stats.seriesoftub.es. CNAME seocho.jc-ix.net.
```
[MIT](LICENSE) © 2026 Frederic Jung Once DNS resolves, enable **Enforce HTTPS** in the repository's Pages settings.
## Analytics
The game uses [Ridiculytics](https://github.com/fjaeckel/ridiculytics): cookieless,
no persistent identifiers, self-hosted at `stats.seriesoftub.es`. It only reports
from `seriesoftub.es` itself; local copies, previews and forks stay silent. The
script is pinned to `ridiculytics@1.0.1` with an SRI hash.
Besides page views and session length, the game sends a few coarse events, all
under the collector's 50-name cap: `game_new`, `game_continue`, `play_1m` …
`play_120m` (active, unpaused play time), `goal_<id>`, `level_2`–`level_4`,
`game_year_2/3/5`, `win_tier1` and `bankrupt`.
The collector must allow the site, e.g. in `sites.yaml`:
```yaml
sites:
- domain: seriesoftub.es
origins: ["https://seriesoftub.es", "https://www.seriesoftub.es"]
```

View file

@ -1,28 +0,0 @@
# The MCP server and the development server in one image (docs/MCP.md, "In a container"). docker.yml builds it and
# publishes it to GHCR for releases only; nothing here is ever deployed to GitHub Pages (docs/adr/0001-github-pages-only.md).
# The base is pinned by digest and kept current by Dependabot (.github/dependabot.yml); CI tests on the same Node major.
FROM node:24-slim@sha256:01d566e8d94d8c619591d78652babfccd3c6992a3dffa9ed5ab39e11cf6c70e9
WORKDIR /series-of-tubes
# Dependencies first, exactly as locked, so a change to the code reuses this layer. Every dependency is a dev one (the
# game has none), and the servers need them all. No install scripts run.
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund --ignore-scripts && npm cache clean --force
# Only what the servers read: the game's source and static files, the scripts, and the harness the MCP server plays
# through. Owned by root and read-only to the server, which runs as node.
COPY src ./src
COPY site ./site
COPY scripts ./scripts
COPY tests/harness.js ./tests/harness.js
COPY --chmod=0755 docker/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
# --save-dir /saves needs somewhere the server may write: a volume mounted here takes this ownership.
RUN mkdir /saves && chown node:node /saves
VOLUME /saves
USER node
ENV NPM_CONFIG_UPDATE_NOTIFIER=false
EXPOSE 8080 7777
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]

View file

@ -1,55 +0,0 @@
#!/usr/bin/env bash
# Starts the container's servers (docker/Dockerfile, docs/MCP.md "In a container").
# MCP_MODE=browser (default): the development server on :8080, with the relay a player's tab dials, and the MCP server
# on :7777 driving that tab.
# MCP_MODE=headless: only the MCP server, with a game of its own.
# Everything after the image name goes to scripts/mcp.js (node scripts/mcp.js --help lists the options).
set -uo pipefail
cd /series-of-tubes
mode=${MCP_MODE:-browser}
case "$mode" in
browser|headless) ;;
*) echo "[entrypoint] MCP_MODE must be browser or headless, not '$mode'" >&2; exit 1 ;;
esac
extra=("$@")
has() { local a; for a in "${extra[@]}"; do [ "$a" = "$1" ] && return 0; done; return 1; }
# A container must listen beyond loopback to be reachable at all; --http in the arguments overrides it.
http=(--http 0.0.0.0:7777)
has --http && http=()
# Listening beyond loopback, the MCP server would take orders from anyone who reaches the port (its Host check stops
# browsers, not other clients), so it gets a token. None given (SOT_MCP_TOKEN or --token-file): this run makes one and
# prints it. MCP_NO_TOKEN=1 turns that off, for a port published to 127.0.0.1 only.
if [ -z "${SOT_MCP_TOKEN:-}" ] && ! has --token-file && [ "${MCP_NO_TOKEN:-}" != 1 ]; then
SOT_MCP_TOKEN=$(node -e "process.stdout.write(require('node:crypto').randomBytes(24).toString('base64url'))")
export SOT_MCP_TOKEN
echo "[entrypoint] No SOT_MCP_TOKEN given: this run's token is $SOT_MCP_TOKEN" >&2
echo "[entrypoint] claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp --header \"Authorization: Bearer $SOT_MCP_TOKEN\"" >&2
fi
pids=()
start() { "$@" & pids+=("$!"); }
shutdown() {
trap '' TERM INT
kill -TERM "${pids[@]}" 2>/dev/null || true
wait "${pids[@]}" 2>/dev/null || true
exit "${1:-0}"
}
trap shutdown TERM INT
# node directly, not npm run: one process less, and signals reach the server.
if [ "$mode" = browser ]; then
start node scripts/dev.js --host 0.0.0.0 --port 8080
start node scripts/mcp.js --browser "${http[@]}" "${extra[@]}"
else
start node scripts/mcp.js "${http[@]}" "${extra[@]}"
fi
# One server stopping stops the container, with its status, so a restart policy can bring both back.
status=0
wait -n || status=$?
echo "[entrypoint] a server exited with status $status; stopping the container" >&2
shutdown "$status"

View file

@ -1,374 +0,0 @@
# Architecture
Series of Tubes is a static web game hosted on **GitHub Pages, and only there**
([ADR 0001](adr/0001-github-pages-only.md)). Its source is split into many small files under `src/`;
the build joins them into **one self-contained `index.html`** (one inline `<style>`, one inline
`<script>`), exactly the page players have always loaded ([ADR 0002](adr/0002-one-page-assembled-at-build.md)).
```
src/ the game page, in pieces
index.html shell: <head>, static markup, the language loader, the @include lines
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)
game/98-server-play/, styles/43-server-play.css
→ server-run play: only in a multiplayer build's page (MP_API, assemble({mp}))
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;
<!-- @include-dev DIR --> the same, in the development page only;
mp: true adds the multiplayer-only files (MP_ONLY), simId() is their build id
scripts/build.js _site/ = site/ + the assembled page, version-stamped, release notes baked in
```
Because the partials are concatenated into one classic script, they share one top-level scope, just as
when they were one file: `S`, `CITY` or `compute()` are visible everywhere, function declarations are
hoisted across files, and top-level statements run in path order. Find code by name
(`grep -rn "function compute(" src/game`); the folders follow the game's layers:
| Folder under `src/game/` | What lives there |
| --- | --- |
| `00-core/` | `tr()`/`trn()`/`N_()` and the dictionary; version, release notes and the analytics counter |
| `10-catalog/` | Prices and gear: POP and port costs, routers (`RG`), supply chain, port slots, dark fiber systems and optics (`OPT`), reach and subsea upgrades |
| `20-world/` | Map projection, landmasses, coastline, city coordinates (`CITY_LL`), `CITIES`, `CABLES` |
| `30-networks/` | Other ASes (`NETS`), rival exchanges (`XIX`), the long tail, traffic shares (`NSH`) |
| `40-progress/` | Customer types (`BIZ_T`), `LEVELS` and their requirements, `GOALS`; the per-save ruleset (`S.rules`, `rule()`, `PRESETS`, `chaosMul()`, `leadDays()`) |
| `50-state.js` | The globals `S`, `R`, `UI`; `emptyR()` |
| `60-features/` | Moving a customer to another path (`37-customer-paths.js`), banks and loans, scenarios and the weekly challenge, puzzles and the published weekly puzzle, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`), the sales desk (`S.sales`, `salesDay()`, `salesShape()` on new offers, orbit ones through `pieSlShape()`; signing for you: `S.slAuto`, `slAutoDay()`; renewal haggles: `S.slAuto.ren`, `slRenDay()`) |
| `70-rules/` | Formatting helpers and market rules: exchanges, PNIs, the peering desk (requests answered by policy), peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank |
| `80-simulation/` | Dijkstra, RouteScript, where a DDoS flood goes (`ddosLoad()`/`ddosAfter()`, called by `compute()`), `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, the customer lifecycle (contracts, renewals, the bandwidth market, why customers leave), geography pricing and latency, second sites and service |
| `85-incidents/` | `addInc()`, DDoS attacks (targets, sizes, scoring, the NOC card) and scrubbing, `failureRun()`/`fireFailure()`, `clearInc()`, `fireEvent()`, the chaos monkey, cable ships (`50-cable-ships.js`: a subsea cut sends a club ship from its port along the cable routes; voyages in `S.fleet`, drawn by `96-map/88-cable-ships.js`) |
| `88-days/` | `dayTick()`, new offers, badges, `checkGoals()` |
| `90-actions/` | The `ACT` map, one file per area (`const ACT` in `10-interface.js`, `Object.assign(ACT,…)` in the rest), and their helpers |
| `91-save.js`, `92-audio.js` | Save, export and import; sound effects |
| `93-ui/` | DOM helpers (`$`, `btn`, `morph`), the theme (light, dark or Auto: `15-theme.js`), the phone tab bar, install pitch, HUD, left panel, city and link panels, decommissioning |
| `94-dashboard/` | Scenario and level progress, where to meet a network, customers and connections overviews, cities with no POP yet, lease swaps, the NOC dashboard and its own window for a second display (`90-noc-window.js`: this page at `?noc=<slot>`, a read-only copy of `S` and `R` over a BroadcastChannel, clicks sent back to the game; `91-noc-wall.js`: its wallboard), the bank, hints |
| `95-modals/` | Toasts, notifications, modals, title screen, what's new, help, the link and own-cable modals |
| `96-map/` | The canvas: resize, the map's colours per theme (`15-palette.js`), land and clouds, settings, level of detail, link geometry, how each tube looks, the WebGL map (the default, 2D as fallback: context, background, tubes, and the sprite atlas cities, labels and markers are drawn from, in 2D too), `draw()`, the world layer, cities, input and click delegation |
| `99-loop.js` | `frame()` and `boot()` |
`src/styles/` holds the CSS the same way: base, the dark theme's colours (`05-theme.css`), 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 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
| Path | What it is |
| --- | --- |
| `src/i18n/en.js` | English: label → text, one entry per line, sorted; inlined into the page by `<!-- @include i18n -->` |
| `site/i18n/it.js`, `pt.js`, `fr.js`, `es.js`, `de.js` | Translations: label → text, the same layout; loaded only for that language |
| `site/sw.js` | Service worker: network-first for pages, stale-while-revalidate for assets. Cache name is stamped with the version |
| `site/site.webmanifest`, icons, `404.html`, `CNAME`, `robots.txt`, `sitemap.xml`, `llms.txt` | PWA and GitHub Pages files, copied as they are |
| `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 (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/gpu-bench.js`, `scripts/lib/gpu-bench-client.js` | `npm run bench:gpu -- --save FILE`: the map in your own browser on your own graphics card, 2D against WebGL, scenario by scenario; the table shows in the page and in the terminal |
| `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: the players' page, or the development page with `{agent: true}`. The page's scripts run straight in the window (jsdom's parser is slow on 2 MB of script) |
| `scripts/test.js`, `tests/durations.json` | Runs the tests, every file in its own process; splits them into parts of equal time for CI (`--plan`, `--shard`) by each file's seconds, which CI refreshes after every run on `main` |
| `.github/workflows/ci.yml` | Tests (split over 6 runners), build and translations on every push and PR; the releases call it too, so the tests run one way everywhere |
| `.github/workflows/auto-release.yml` | After every green CI on `main`: if `package.json` has a new version, tag the commit CI tested, publish the GitHub release from the CHANGELOG, start the deploy (`tested=true`, so it does not test again) |
| `.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), development-only code (0004) |
## This fork's own files
This copy adds features upstream does not have. They follow the same rules as the rest of `src/`, and are listed here
apart so that upstream's tables above merge cleanly. The multiplayer server is for self-hosted copies only: a plain
build stays the static page described above.
| Path | What it is |
| --- | --- |
| `src/game/60-features/96-pop-standard.js` (grown from upstream's POP standard), `src/game/90-actions/88-build-standard.js`, `src/game/93-ui/59-build-standard.js` | The build standard: one target for every POP, port and fiber (`BSTD`, saved sparse in `S.popStd`), what is below it and what bringing it up costs (`bstdPlan()`, `bstdQuote()`), the sheet, "Bring everything up now" (`bstdApply`) and the intern's "Keep to the build standard" order (`std`, in `95-standing-orders.js`). The router model and the line system are picked here and nowhere else |
| `src/game/93-ui/15-theme.js`, `src/styles/05-theme.css`, `src/game/96-map/15-palette.js` | Dark mode (#80): Light, Dark or Auto per device (`sot-theme`), set on `<html data-theme>` before the first paint; the panels' dark colours as CSS custom properties; the map's colours per theme |
| `src/game/60-features/33-address-space.js`, `src/game/90-actions/54-address-space.js`, `src/game/94-dashboard/72-address-space.js` | IPv4 address space (#150): blocks held, bought, leased in and leased out (`S.ip4`), customers' blocks, CGNAT and its ratio; the bank's Address space section |
| `src/game/60-features/34-ipv6-only.js`, `src/game/90-actions/55-ipv6-only.js` | IPv6-only broadband: a city's home routers swapped for 464XLAT, and the NAT64 pool next to CGNAT; the build standard's `v6` row rolls it out (`ip6Todo()`, `ip6Owed()`) |
| `src/game/80-simulation/65-express.js`, `src/game/90-actions/87-express.js`, `src/game/93-ui/72-express.js`, `src/game/96-map/51-express-geometry.js` | Express lightpaths (#58): a link of kind `xp` from A to C over a chain of ROADM fibers, passing the cities between as light; its rules, actions, panels, the link window's Express tab, and how the map draws it |
| `src/game/10-catalog/75-satellites.js`, `src/game/60-features/45-teleports.js`, `src/game/90-actions/87-teleports.js`, `src/game/93-ui/72-teleport-panels.js` | Satellites (#83): teleports at POPs (`p.tele`) and rented GEO and MEO circuits (links of kind `sat`): the birds and their reach, the rules and money, the actions and the panels |
| `src/game/10-catalog/76-wisp-zones.js`, `src/game/60-features/46-wisp-zones.js`, `src/game/90-actions/87-wisp-zones.js`, `src/game/93-ui/73-wisp-panels.js` | Island Wi-Fi (#83): zones of outer islands (`WISP`), each a pool of homes at its city's POP (`p.wisp`) whose Gbps join the city's demand; their backhaul from the city's teleport (GEO, MEO, Starblink LEO) or a spur cable, the spur cut (incident `wspur`), the money, the actions and the panels |
| `src/game/60-features/89-multiplayer.js`, `src/game/95-modals/48-multiplayer.js`, `src/game/90-actions/92-multiplayer.js`, `src/styles/41-multiplayer.css` | Multiplayer, only in a copy built with `MP_API` ([MULTIPLAYER.md](MULTIPLAYER.md)): `S.mp`, saves and cards sent to the session server, the `#mp=` link; the title screen's door, the session panel and the HUD chip; `srvOn()`, false until server-run play is switched on |
| `src/game/60-features/81-late-joiners.js` | Late joiners of a server session: a network begins on the session's date (`S.day0`; `netAge()` counts its first-days rules from there), with a hardware top-up and a year of home broadband matched (`R.rev.late`); the Goals card, the bank section and the city pitch. Dormant until the host passes a start day (T3) |
| `src/game/98-server-play/`, `src/styles/43-server-play.css` | The page's side of server-run play (T4), only in a multiplayer build's page; a comment so far ([plans/server-run.md](plans/server-run.md)) |
| `scripts/mp-server.js`, `scripts/lib/mp.js` | The multiplayer session server: the command line and the built site, and the API with its storage. `npm run dev -- --mp` mounts the API in the development server |
| `scripts/lib/mp-sim-acts.js` | Server-run play's act tables (SEND, ASK, VOTE, LOCAL, CONFIRM, DRAFTS, TEXT, WINDOWS…) and the envelope check every request passes |
| `scripts/lib/mp-sim-engine.js`, `scripts/lib/mp-sim-worker.js`, `scripts/lib/mp-sim-realm.js` | The server-run engine (merged, not wired in yet): worker threads, each holding a vm realm per network that runs the plain page's game, behind the promise API the session host will use ([plans/server-run.md](plans/server-run.md)) |
| `tests/lib/mp-sim-*.js`, `tests/fixtures/mp-sim/` | Server-run play's contracts for the tests: the shape checker, the fake engine, the fixtures and their generator, the button crawl, and the player that plays a realm against a page |
| `docs/plans/next-session.md`, `server-run.md`, `multiplayer-phase2.md` | What is left and what waits for a decision; the server-run design and its status; the phase 2 design (on hold) |
## Globals
- **`S`**: the whole saved game (one JSON object). Cash, day, POPs, links, transit,
IX ports, PNIs, caches, customers (`biz`), offers, incidents (`inc`), live events
(`ev`), stats, settings. Saved to `localStorage` key `sot-save-v1:<slot>` (one per network, see below).
- **`R`**: results of the last `compute()`: per-link load, per-exit use, served and
demanded traffic, reach, costs and revenue. Never saved; always rebuilt.
- **`UI`**: view state (selection, open tabs, speed, confirmations). Not game state.
- **`cam`**: map camera (x, y, zoom).
Lookup tables built at load: `CITY[id]`, `NET[id]`, `CABLE`, `FAB`, `BIZ_T`, `REQS`.
## The life of a day
`frame()` (requestAnimationFrame) accumulates time (`runClock()`); every `DAY_MS × speed` it starts a day, inside a
try/catch so one bad tick never freezes the game. In play the day runs with the route worker (below), one day in flight
at a time: the clock waits for the day, never the other way round, so a machine that cannot keep up at ×8 plays slower
instead of freezing to catch up. Without a worker it calls `dayTick()`, at most four times per frame.
A day is a generator, `dayRun()` (`src/game/88-days/10-day-tick.js`): `dayPreRun()` (the world moves on), then
`dayPost()`, and the intern's shift (`opsRun()`) and the sales desk's (`slAutoRun()`) inside it are generators too. Each
`yield` is a `compute()` the day needs before it goes on: the day's own routing, then a recompute after failures and
events, and after the intern's jobs. `dayTick()` (tests, the fallback) answers each one with `compute()` on the spot
(`dayGo()`); in play the route worker answers them. `yield DAY_REST` is not a routing, only a place where a long day may
let a frame through. Same steps, same random numbers either way: routing draws none. Nothing of a day routes on the page:
a failure (`failureRun()`; `fireFailure()` plays one at once through `runNow()`), a DDoS and Auto-RTBH (`ddosNewsRun()`),
the chaos monkey's snip (`mkSnipRun()`), an event's cut (`eventRun()`: its routing is deferred to the next yield) and the
sales desk's trials (a `{trial}` yield the worker answers with yes or no, `offerTrial()`) are all steps. The intern's
orders are generators too, with a rest after each job. `UI.tick` (what the day itself announces, which quiet
notifications may keep to the NOC log) is set around every step (`dayStep()`), on both sides of the worker.
A big autosave is packed, turned into text and compressed in the worker (`rwSave()`), the page only writes it. The
diverse-paths map and the latency floors new offers need are worked out a millisecond a frame ahead (`diversityWarm()`,
`latWarm()`). A rest waits for the next frame only when none was drawn just now (`rwLater()`).
The daily mood check asks "a path without subsea" for each customer that wants one: during that loop the land-connected
islands are worked out once (`TERR`, `terrIslands()`), and two cities have a land path when they share one.
The day:
1. Advances `S.day`, runs scheduled world events (conferences, IX price wars, licences).
2. Runs `compute()` to route today's traffic.
3. Records history for 95th-percentile billing, stats and streaks.
4. Rolls failures (`failureRun()`) and events (`fireEvent()`) when their timers run out,
and expires incidents.
Then the NOC intern's standing orders (`opsRun()`, or `opsDay()` in one go), if one is hired: each order clicks the
same `ACT` actions a player would, muted, within its monthly budget, and the shift routes again (a yield) before
decommissioning, which reads today's loads, and at the end, each only if a job changed the network. An order that
throws is paused; the day goes on. The NOC gets one notice a week. The orders plan for every POP each day, so what
they count is counted for all POPs in one pass (`portsAt()`, `cachePlan()`, `pniFlows()`, `pniBatch()`), never one
pass over the network per POP.
Then the sales desk (`slAutoDay()`), if someone runs sales and the player lets them sign: deals are Sales', never
the intern's. Each salesperson signs in their own style (a routing trial a day, or the shark's sign-everything).
5. Updates customer mood, churn and new offers; IX members join; loans tick.
6. Every 30 days: bills the month (revenue minus costs) and checks for bankruptcy.
7. Checks goals, level, badges and scenario end conditions.
## compute(): the traffic model
1. Builds a graph from your live links: parallel links between the same two cities
merge into one edge with summed capacity. The routing metric belongs to the city pair
(`S.pairMet`) and sets the edge's weight; Dijkstra gives shortest paths from each POP.
Links on standby (`l.standby`) add their capacity to the edge, but when loads are
handed back to links the active ones fill first and standby links take the rest.
2. Builds the exit list `E`: embedded caches (rank 0), PNIs and IX ports (2, both peering),
transit (3). Each exit has a capacity, the networks it can reach (`ok(net)`) and an
egress preference (`high`, `normal`, `low` = backup only). A transit port can also be set to
carry (`t.carry`): see step 4.
3. Builds flows: for every POP, its demand (eyeballs and customers) split across
destination networks by their traffic share (`NSH`, with regional variants for
China, Russia and Korea), localised per city: the networks that sell to homes split their part by where their users
live (`locSh()`, `30-networks/45-home-markets.js`, #48). Incidents can add junk flows or scale demand.
4. Routes flows rank by rank: the nearest usable exit first, ECMP across equal exits (a PNI goes before an
IX port at the same distance: `PNI_TIE`, #298),
consuming link, router (`nodeCap`) and exit capacity. A carrier's own transit port also
goes first, before plain transit, for traffic bound for that carrier or for a network that buys
transit from it (`25-direct-egress.js`: the shorter AS path): always at its own POP, and from every
POP when the port is set to carry. Such a port is still an ordinary transit exit for the other
POPs. Backup, RouteScript and Auto-TE rules keep their say, and so does a Prefer-marked port at its own POP (the other
POPs keep the rule). With Auto-TE, overflow spills
onto alternate paths (spill tiers, `spill at 80% within 10 ms`, first try the fastest detour under the line within
that budget: `tiers()` in `29-route-core.js`); RouteScript rules (`teRules()`) can prefer, avoid, cap, drain
or blackhole.
5. Layer-2 customers (L2VPN, SD-WAN, waves) are carved out of link capacity first.
6. Totals costs (`R.cost`) and revenue (`R.rev`) per month.
It runs every day and after every action, so it is built for big networks: the graph works on city
indices (`CIDX`), each exit is asked once per network what it can reach, and `R.ef` (what crosses each
link) is only put together for a link when something reads it.
What follows from the network's shape alone is kept from one call to the next (`29-route-cache.js`): the shortest
paths from every POP, and who reaches whom with each network's exit lists. Each has a key made of everything it is
built from (the live graph with its weights; every exit with what it reaches and how it is preferred, RouteScript and
the events that move routes), so most days, when only demand changes, they are reused, and any other change rebuilds
them. Only indices are kept: exits, lists and paths are made fresh every call, because routing writes on them.
`tests/route-cache.test.js` checks the keys, and the equivalence tests route with and without the kept tables.
`scripts/route-fuzz.js` plays hundreds of random seeded games on main's page and this checkout's at once, comparing all
of R and S after every move and day, with the kept tables and without (`tests/route-fuzz.test.js` plays a few).
Each loop of `compute()` runs in a function of its own (the money is `computeMoney()`). V8 optimises a small function
quickly and keeps it; `compute()` as one 33 KB function never stayed optimised: it ran in baseline code, boxing every
number, and was compiled again and again in the background only to be thrown away, which cost more CPU than the routing
itself. Keep it that way: a new loop goes in a function.
The routing core, the loops that place every flow on an exit (`rankPass`, `directPass`, `sendGroup`, `send`, `push`,
`carry`, `altPath`), lives in `ROUTE` (`29-route-core.js`), made once at load: `compute()` hands it the day's state
(`ROUTE.nodes()`, `ROUTE.run()`). Made inside `compute()`, as they were, they were new functions every call, and V8 threw
away the code it had compiled for the old ones. The core reads exits by number from typed columns (`USED`, `CAPX`, `CIX`,
`HPX`, `VISX`), and each list as an object of one shape (`lx()`). For each list and source city, the route cache also
keeps the list in the order routing tries it (`xOrder()`: by preference, then distance, a stable sort): on a day the cache
is used, a flow's first group is where that order starts, past the exits that filled up, instead of a scan of the whole
list, and what is left needs no sort. Auto-TE marks the pairs that have no detour (`TEF`), the answer to most of its
asks. `tests/day-steps.test.js` and the routing equivalence tests hold all this to the same results.
Served share per city (`sfOf`) drives eyeball revenue and customer mood.
## Routing in a worker
During play, each day's `compute()` runs off the main thread (`src/game/80-simulation/28-route-worker.js`), so a big
network does not freeze the page once a day.
- **Built from the page itself.** The worker is the page's own inline game script (`document.currentScript.textContent`)
run again from a Blob URL, after a short prelude of inert stand-ins for `document`, storage and the other DOM globals,
and the player's dictionary. Nothing is fetched: GitHub Pages still serves one page, and a release cannot mismatch.
In the worker `RW_IN` is true and `boot()` never runs; the catalogs are rebuilt by the same top-level code.
- **The day in steps.** In play, `frame()` calls `rwDay()`, which runs `dayRun()` (see "The life of a day") with
`rwGo()`: the steps run on the page up to a yield, then S and what routing reads of yesterday's R (`R.load`,
`R.l2route`, `R.efg`) are posted, and the day goes on in `rwDone()` when R comes back. The next day waits until the
last step has run. So a day sees exactly the routing it would have had in one go: same results, same random numbers.
At a `DAY_REST`, a day that has run `RW.budget` ms (half a frame: 3 to 8, or up to 32 on a device slower than 50 frames a second) already goes on after the next frame
(`RW.later`, `rwLater()`), so a phone gets its frames between the steps of a big network's day. Half a day is never
saved; nothing else starts meanwhile. `tests/day-steps.test.js` plays a second page as the worker and compares every
day with `dayTick()`.
- **What crosses.** `R.ef` and `R.fl` are lazy getters; their pieces (`R.efp`, `R.flc`) travel instead, typed arrays
transferred, and `efBuild()`/`flDefine()` (in `30-compute.js`) rebuild the same lazy R on the page. What crossed each
link (`R.efp.L`) crosses as typed arrays with each exit key once (`rwLOut()`), and the page decodes a link only when
something reads it (`rwLIn()`). Two parts are not sent again when they would be the same: `R.egDesc` comes back as 0
when it is the last one key for key (the page keeps `RW.desc`), and `R.efg` is not posted back while R is the worker's
own last answer (`RW.wR`; the worker keeps it in `RW.last`). Both sides read every message in order, so they always
hold the same last one; `tests/day-steps.test.js` plays a second page as the worker and checks it all.
- **Actions mid-day.** Every `compute()` bumps `RW.gen`. If an action routed while a day was in flight, the worker's
answer is stale: it is dropped and the day ends with the action's R.
- **Fallbacks.** Tests (`__TUBES_TEST__`, and jsdom has no Worker), `window.__TUBES_SYNC__`, a browser without workers, a
post that fails or a worker that errors take the synchronous path (`rwKill()` routes the day in flight on the page).
- **Still on the main thread**, because the caller reads R right away: actions (`after()`), loading a game, failures and
RouteScript what-ifs and the link panel's cut check. Everything a day routes (failures, events, DDoS, the chaos monkey,
the intern's shift, the sales desk's trials) is a yield of the day, so it goes to the worker.
## Actions and rendering
- Player actions live in `ACT`. Buttons render as `btn(label, act, args, cls, disabled)`
and a delegated click handler calls `ACT[act](JSON args)`.
- An action validates its inputs (they come from the DOM), mutates `S`, shows a
`toast()` and calls `after()`.
- `after()` = `purgeInc()` + `compute()` + `checkGoals()` + `renderAll()` + `save()`.
- `renderLeft()` draws the left tabs (deals, NOC, customers…), `renderPanel()` the
selection panel (city, link, network). On phones these become bottom sheets
controlled by `renderTabbar()`.
- These panels and the dashboard are rebuilt as HTML every tick and written with `morph()`, which
patches only what changed. Buttons whose action changed are replaced, so taps stay safe (#44).
- The map is a canvas drawn by `draw()` from `frame()`. Zoomed out (`lodFar()`) it uses
a simplified style; parallel waves are grouped by `linkGroups()`. `mapStill()` decides whether a frame is drawn:
when nothing changed (paused, animations off) it is not, except once a second; when only the animation clock moved
(packets, waves, clouds, floaters) the map is ambient and drawn at most 30 times a second; anything else that moves
(camera, pointer, selection, the network) gets every frame (`tests/frame-pacing.test.js`).
## The weekly puzzle
A puzzle week runs from Sunday 06:00 Berlin time to the next Sunday 06:00, and is named after the ISO week of
its Monday (the week starting Sunday 1 November 2026 is `2026-W45`); `pzWeekKey()` and `pzWeekStart()` in
`src/game/60-features/93-puzzles-weekly.js` handle summer time and the year boundary.
Every Sunday `weekly-puzzle.yml` runs `scripts/weekly-puzzle.js`, which loads the real game headless, picks a
theme the last three weeks did not have (region tour, ring, detour around a hub, ocean crossing, island hopping,
latency sprint) and cities the last four weeks did not use, gives them traffic (content in the first city, eyeballs
in the others, a circuit with a latency cap for a sprint), searches for the cheapest topology that connects them and
the cheapest one that survives any single cut (a whole cable, or a trench), then sizes both with the game's own
routing (`scripts/lib/puzzle-solver.js`: links and routers big enough for every flow, after any cut too, then as
small as they go). The budget sits just above that N-1 build. Both references are judged by the game's own star
code and must earn one and three stars, or the puzzle is thrown away. The file holds only ids, numbers and
translation labels with their fill-ins
(`{"v":2,"key","theme","cities","src","dem","via","avoid","budget","twist","name":{"l","p"},"joke":{"l","p"},"ref","rev"?}`).
`--check` re-validates every file the way the game does.
The game fetches `puzzles/weekly/<key>.json` (relative, same origin) only when the Puzzles list opens, and checks
it field by field (`pzWkValid()`): known fields, playable cities, labels from the theme's own list, sane numbers.
When it is missing, offline or wrong, the seeded weekly (`pzWeekly()`) stands in, so the weekly puzzle always
works. The service worker fetches these files network-first and keeps a copy for offline play.
The weekly ships without a release: the workflow commits only `site/puzzles/weekly/` to `main` (no version bump,
so `auto-release.yml` stays quiet) and starts `release.yml` from the live release's tag with `weekly=true`, which
rebuilds that exact release with every weekly file from `main` and deploys it. Every release build takes the
weekly files from `main` too, so no deploy ever drops a published week.
The weekly scenario is its twin, in the same weeks and the same workflow run: `scripts/weekly-scenario.js` writes
`site/scenarios/weekly/<key>.json`. A template (plain data in the script) picks a theme, a home city, rules from the
scenario vocabulary (`scnRule` keys, `WEEK_MODS`) and a goal type with parameters; each goal type (`WS_GOALS` in
`src/game/60-features/94-scenarios-weekly.js`) is implemented once in the game, with its progress card. A reference
player (`scripts/lib/scenario-bot.js`) plays it through `ACT`, seeded with the scenario's seed; the goal's number is
calibrated from that run, the scenario must not be won on day 0, the reference must win with a tenth of the days to
spare, and its finishing day is the par. The file keeps the reference plan (`ref`), which `--check` replays. The game
fetches the file when the Scenarios list opens, checks it with `wsValid()` (again in `sanitize()` on load), and falls
back to the in-browser `weekly()`.
## Saves, imports and migration
- `save()` writes `S` to localStorage every few seconds and after actions, into this window's slot
(`UI.slot`, `src/game/91-slots.js`): `sot-save-v1:<id>`, plain JSON or `gz:`-compressed above a million
characters, with a stamp `sv:{seq,at}` appended. Then the index `sot-slots` (name, ASN, preset, day, tier,
cash, last played, size, seq) is updated; the title screen lists networks from the index alone. A save whose text is
the one the slot already holds (`SLOT.txt`: a paused game, nothing changed) is not written again, unless the page is
closing: on a big network the storage write costs more than making the text.
- Each tab keeps its slot in `sessionStorage['sot-slot']`. One window per slot: a Web Lock
(`sot-slot:<id>`) where supported, plus a heartbeat `sot-open:<id>`; BroadcastChannel `sot-slots` asks
another window to hand over, and the `storage` event stops a window whose slot was saved newer elsewhere
(higher seq) or deleted. A window never writes a slot whose index seq is newer than its own.
- The single save of older versions (`sot-save-v1`) is copied to slot `main` and read back before the
index lists it; the old key is removed only by that slot's next successful save.
- `boot()` loads the save through `migrate()` → `sanitize()`. If loading throws, the
slot is kept and marked damaged in the index (it can still be exported or deleted).
- Puzzles never write a slot; while one runs, `save()` writes the network set aside (`UI.pzKeep`).
- `sanitize(s)` is the gate for all untrusted state (saves and imported files): it
drops unknown ids, clamps numbers, repairs references and fills defaults. Every new
field in `S` needs a line there.
## Translations
Text is keyed by label ([ADR 0003](adr/0003-translations-by-label.md)):
- `tr('area.label', vars)` looks up `DICT['area.label']` and fills `{placeholders}`; `trn('area.label', n)`
picks `one` or `other` of a plural; `N_('area.label')` marks a label kept in a table or a save, translated
where it is shown.
- `DICT` is the English (`src/i18n/en.js`, inlined into the page) with the player's language
(`site/i18n/<lang>.js`) laid over it. English text from saves of 1.33 and older still finds its translation.
- Static markup uses `data-i18n="label"`, `data-i18n-aria-label`, `data-i18n-title`; `i18nDom()` swaps it at boot.
- The build swaps labels for short ids in the shipped page and dictionaries (`scripts/lib/compile-labels.js`);
`N_()` labels stay whole because saves keep them.
- `npm run i18n:check` checks the English against the code and every translation against the English.
## Tests
`tests/*.test.js` use `node:test` and `tests/harness.js`, which assembles `src/` in memory, so tests
never run a stale build. `npm test` runs every file in `tests/`; a new suite needs no registration:
```js
const { load } = require('./harness');
const { ev, errors } = load(); // seeded, deterministic
ev("ACT.start({});S.cash=1e8;ACT.launchBB({city:'fra'})");
ev("compute()");
assert.equal(ev("R.reach>0"), true);
assert.deepEqual(errors, []);
```
`ev()` runs code inside the page. To force a specific random failure, patch the
picker, e.g. evaluate `failureRun` with a `.replace(…)` and play it with `runNow(…)` (it is a generator).
Use `window.__reseed(n)` to reset the random sequence mid-test.

View file

@ -1,238 +0,0 @@
# 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, 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.
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. `--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.
### In a container
Every release publishes a multi-arch (amd64/arm64) image at `ghcr.io/fjaeckel/seriesoftubes:<version>`
(`docker.yml`, dispatched by the release; pre-releases too). There is no `latest` and no image per commit: pick a
version from the [releases](https://github.com/fjaeckel/seriesoftubes/releases). It holds the MCP server and the
development server, nothing else from the repository, and runs as `node`, not root. It is published to GHCR only; the
game itself is served from GitHub Pages and nowhere else.
- **`MCP_MODE=browser`** (the default) serves the development page on 8080, with the relay, and runs the MCP server on
7777 driving that tab. **`MCP_MODE=headless`** runs only the MCP server, with a game of its own.
- **Options** go after the image name, to `scripts/mcp.js` (`node scripts/mcp.js --help`). The MCP server listens on
`0.0.0.0:7777` inside the container, since loopback there is unreachable; pass your own `--http` to change it.
- **A token, always.** The Host check stops browsers, not other clients, so a published port without a token is open to
anyone who reaches it. Give one with `-e SOT_MCP_TOKEN=…` (or `--token-file`); without one the container makes a
token for this run and prints it, with the `claude mcp add` line to use it. `MCP_NO_TOKEN=1` turns that off.
- **Publish the ports to loopback** (`-p 127.0.0.1:7777:7777`), as below. A bare `-p 7777:7777` listens on every
interface of the host, and Docker's rules go around ufw and firewalld. To reach it from elsewhere, keep the token,
add `--allow-host NAME` for the name or address clients use (requests naming the host's address are refused
otherwise, since that is not an address inside the container), and put TLS in front.
- **The relay has no token** (as with `npm run dev -- --host`): in browser mode, anyone who reaches port 8080 can drive
a game whose player turned agent mode on. Publish it to loopback too.
```sh
V=2.10.1 # a release
# Headless, with your own token
docker run -d --name sot -p 127.0.0.1:7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=secret \
ghcr.io/fjaeckel/seriesoftubes:$V --clock realtime --pace 60000
claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp --header "Authorization: Bearer secret"
# The browser session: open http://localhost:8080, then Settings → Agent API. The token is in `docker logs sot`.
docker run -d --name sot -p 127.0.0.1:8080:8080 -p 127.0.0.1:7777:7777 ghcr.io/fjaeckel/seriesoftubes:$V
```
`load_save` and `export_save` take JSON only unless the server runs with `--save-dir`; the image has `/saves` for it,
owned by the server's user, so mount a volume there:
```sh
docker run -d -p 127.0.0.1:7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=secret -v sot-saves:/saves \
ghcr.io/fjaeckel/seriesoftubes:$V --save-dir /saves
```
The image's Node base is pinned by digest, its dependencies by the lockfile, and every workflow action by commit;
Dependabot (`.github/dependabot.yml`) keeps them current. Pull requests that touch the image build it and try both modes
without publishing.
## 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` | 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`, `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: 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 |
| `screen`, `panel`, `click`, `open_link` | The game's own windows, panels, left drawer, NOC dashboard, bank and puzzle box as text with numbered buttons; press one; open a link's build window |
## Acting
`act` checks the arguments against `schema` first: a wrong id or value is an error that says what would fit, and
nothing runs. The action then runs as the game runs it, with what a player would type and pick filled in: a rename,
a RouteScript, a custom metric, the route and size of a link, the source and line system of dark fiber, the design
of a cable, the POPs to close. Confirmations are given, so `rmLink` removes the link in one call. The result says
what happened:
| `outcome` | Meaning |
|---|---|
| `applied` | Something changed. `charged` is what the game's money gate took; `cashChange` also counts goal rewards |
| `rejected` | The game said no; `toasts` has its words |
| `no_effect` | Nothing changed and nothing was said: usually a wrong id or a precondition |
| `shown` | A view or a draft: only the screen changed |
| `decision` | A window asks a question (a De-Kicks quote, a retention offer). Answer with one of `decision.options` or `closeModal`; other game commands wait until then |
| `quote` | With `dryRun`: `{setup, monthly, days, blocked}`, priced with the game's own helpers. Nothing happens, and no dice are rolled |
| `stopped` | The network is bankrupt |
`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.
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` (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 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
`src/agent/20-commands.js` (a class, or `API_DENY`), or `tests/mcp-commands.test.js` fails.

View file

@ -1,222 +0,0 @@
# Multiplayer (self-hosted copies)
The game at [seriesoftub.es](https://seriesoftub.es) is hosted on GitHub Pages and nowhere else
([ADR 0001](adr/0001-github-pages-only.md)), so it has no server and no multiplayer. This page is for a copy you host
yourself: there, a small session server that ships with the source (`scripts/mp-server.js`) lets players build their
networks side by side.
A plain `npm run build` is unchanged: the page has no multiplayer door, no chip and makes no request for it. Multiplayer
is switched on only when the build is told where the session server lives.
## What it does (phase 1)
- **Sessions by code.** One player starts a session from the title screen (Multiplayer: their network's name, home city
and rules preset, optionally a session name) and gets a six-character code such as `K7Q-2XD`. Friends join with that
code. Codes use Crockford's base32 (no I, L, O or U); they are case-insensitive, and the dash is optional.
- **One world.** Everyone in a session plays a Normal game with the creator's rules preset (Best Effort, Change Freeze,
On-call or BGP at 3 a.m.) and the session's random seed, so day 0 is the same world for all. The session hands each
player an AS number from 200000–214999 that nobody else in the session and no network on the map uses. Each network
is still simulated in its own player's browser; from the first different click on, the worlds drift apart.
- **Saves on the server.** Each network's save goes to the server on a new game day, at most every 15 seconds (gzipped
when it is big), and when the page is hidden or closed if anything changed since the last push (a paused game's
building too). Opening the network on any device fetches the server's save first and loads it if another device
played on.
- **Seeing each other.** Every push carries a small public *card*: day, tier, POPs, links between them (with capacity),
exchanges, transit providers, peering policy, reach, peak and served traffic, customers, revenue per month, cash as an
order of magnitude, and a score. The session panel (the 🌐 chip in the top bar, or the menu) shows the leaderboard
(Tier 1 first, then Tier 2, then traffic served), a feed (joins, leaves, Tier 2, Tier 1 and who got there first) and a
chat. While the panel is open it refreshes every 5 seconds; otherwise the roster rides along with each push.
- **Moving to another device.** The panel's "Move to another device" holds a link `https://your.host/#mp=CODE.pid.token`.
The part after `#` never reaches any server. Opening it (or copying the link) first sends this device's latest save,
and opening the link loads the network into that browser. Treat it like a password: anyone with it can play as you.
A browser keeps the link's token only once the server has accepted it, so a wrong or mistyped link never replaces the
one it already has; when the server cannot be reached, the link stays in the address bar for a reload to try again.
- **Offline.** The game never waits for the server. When it cannot be reached, the game says so once, keeps playing and
tries again later (30 s, then 1, 2, 4, at most 5 minutes apart; the open session panel keeps looking every 5 seconds
without stretching that wait).
Not yet (phase 2): peering, transit and competition between players inside the simulation. The card already carries
what that will need (POPs, links, exchanges, transit, peering policy, reach).
## Being built: the server runs the game
Work has started on server-run play. In a multiplayer build, the session server will run every network's days, so all
players of a session share one calendar and one speed, and the page will only show the network and send the player's
clicks. The engine that runs networks on the server is in the source (`scripts/lib/mp-sim-*.js`), but nothing uses it
yet and it is not switched on: sessions work exactly as this page describes, with each network simulated in its own
player's browser. The design and how far it has got are in [plans/server-run.md](plans/server-run.md).
## Build
```bash
MP_API=/api/mp npm run build # _site/ with multiplayer on; the page talks to /api/mp on its own origin
```
`MP_API` must be a path on the same origin (letters, digits, `/`, `_`, `-`; no trailing slash, and not starting with
`//`, which a browser reads as another host). Anything else fails the build. Without it, or empty, the build is the
plain one.
## Run the server
```bash
node scripts/mp-server.js --site _site --data /var/lib/tubes-mp --port 8090
# or: npm run mp -- --site _site --data /var/lib/tubes-mp
```
One process serves the API under `/api/mp` and, with `--site`, the built game too (like GitHub Pages would: `/` is
`index.html`, a missing file gets `404.html`, nothing outside the folder is ever served). It binds `127.0.0.1` by default:
put a reverse proxy with HTTPS in front. Plain `node:http`, no dependencies beyond Node 20 or newer.
| Option | Default | |
|---|---|---|
| `--port N` | 8090 (or `$PORT`) | port to listen on |
| `--host H` | 127.0.0.1 | address to bind |
| `--data DIR` | `./mp-data` | sessions and saves; created if missing |
| `--site DIR` | none | also serve the built game from DIR |
| `--base PATH` | `/api/mp` | the API's path; must match `MP_API` |
| `--prune-days N` | 60 | sessions nobody touched for N days are deleted, at startup and daily |
| `--max-sessions N` | 1000 | sessions on this server |
| `--max-players N` | 12 | players per session (at most 12) |
| `--create-per-hour N` | 10 | new sessions one address may start per hour |
| `--sessions-per-hour N` | 100 | new sessions per hour on the whole server, from all addresses together |
| `--trust-proxy` | off | take the client's address from `X-Forwarded-For` (only behind your own proxy) |
| `--verbose` | off | one log line per API request (never tokens) |
Behind a reverse proxy every request comes from the proxy's address, so the per-address limits only mean something with
`--trust-proxy` (the server then uses the last address in `X-Forwarded-For`, the one your proxy added); without it, all
players share one address's limits, such as 4 save uploads at once. An IPv6 address counts as its /64, since one phone
or home usually has a whole /64 to itself.
To try it locally without a build: `npm run dev -- --mp` runs the API inside the dev server (sessions in `mp-data/`) and
turns multiplayer on in the dev page. Open a second window (a private one counts as another browser) to be the second
player.
### nginx
```nginx
server {
listen 443 ssl http2;
server_name tubes.example.org;
ssl_certificate /etc/letsencrypt/live/tubes.example.org/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/tubes.example.org/privkey.pem;
client_max_body_size 5m; # a save is at most 4 MB
location / {
proxy_pass http://127.0.0.1:8090; # the game and /api/mp, from the one process
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
```
Run the server with `--site /srv/tubes/_site --data /var/lib/tubes-mp --trust-proxy`.
### Caddy
```caddy
tubes.example.org {
request_body {
max_size 5MB
}
reverse_proxy 127.0.0.1:8090
}
```
Caddy sets `X-Forwarded-For` itself and gets the certificate on its own; run the server with `--trust-proxy` as above.
### systemd
```ini
[Unit]
Description=Series of Tubes multiplayer
After=network.target
[Service]
ExecStart=/usr/bin/node /srv/tubes/scripts/mp-server.js --site /srv/tubes/_site --data /var/lib/tubes-mp --trust-proxy
User=tubes
Restart=on-failure
StateDirectory=tubes-mp
[Install]
WantedBy=multi-user.target
```
## Backups
Everything is in the data folder: `<CODE>.json` per session (settings, players, cards, feed, and each save's number) and
`<CODE>.<pid>.save` per player's save (its text exactly as the game sent it). Every write goes to a temporary file that is then renamed over the old one, so a
copy of the folder (`rsync`, a snapshot, `tar`) taken while the server runs holds whole files. Restore by stopping the
server, putting the files back and starting it again. A player's token is stored only as its SHA-256, so a backup cannot
be used to play as anyone.
## Limits
- 12 players per session, 1000 sessions per server (configurable).
- A save is at most 4 MB of text (the game gzips anything over 32 kB: the big test network, 236 kB of JSON, goes as about 50 kB). Other
requests are at most 16 kB.
- Chat lines: at most 200 characters, one a second and six per 30 seconds per player. The feed keeps the last 100 lines.
- Per address and hour (an IPv6 address counts as its /64): 10 new sessions, 60 joins, 120 wrong codes (after that,
every code is refused for a while from there, so guessing codes gets nowhere; a player who sends their own session's
code with its token is never refused for it). At most 100 new sessions an hour on the whole server.
- Saves and cards: one save upload at a time per player (another one meanwhile gets 429), at most 4 at once from one
address and 16 on the whole server (503 with `busy: true` beyond that; the game then tries again a little later,
quietly), and per player at most 20 saves and 60 cards a minute (the game sends one every 15 seconds at most). A
save's body must arrive within two minutes. A card alone is written to disk within two seconds, together with any
others that came in meanwhile.
- Network names: at most 32 characters; control characters, `<`, `>`, `&`, quotes and backticks are removed. The page
escapes everything other players wrote anyway.
- A page that is being hidden or closed can only send 64 KiB (the browser's limit for such requests, counted in bytes),
so a network whose save does not fit sends its card alone then; its save goes with the next push from that device.
## How saves stay in order
Each network in a session carries a save number (`S.mp.seq`). When a save is due to go to the server, the game picks
the next number before it writes the save, so the save kept in the browser and the one sent carry the same number;
reopening the network then finds nothing newer on the server unless another device pushed one. The server refuses a
number that is not newer than its own (HTTP 409, with its number), and only counts a save once it is on disk. Then the
player is told once that the network moved on elsewhere and chooses: load the newer save from the server (only one at
least as new as the server said it had: never an older one), or keep this one (at the end of the current game day it
goes with `force` and a number past the server's).
The token is never part of the save: it lives in the browser's storage under `sot-mp:<code>:<pid>`. An exported or
imported save keeps its session but cannot talk to the server without the token (the game says it is no longer in its
session and plays on alone).
## API
JSON in and out, same origin, no cookies, no CORS headers. Every call but starting and joining needs
`Authorization: Bearer <pid>.<token>`. Errors are `{"error": "…"}` with a fitting status (400, 401, 404, 405, 409, 413,
415, 429, 503).
| Call | Body | Answer |
|---|---|---|
| `POST /api/mp/sessions` | `{net:{name,home}, preset, title?, avoid?}` | `201 {code, pid, token, seed, asn, preset, color, title}` |
| `POST /api/mp/sessions/:code/join` | `{net:{name,home}, avoid?}` | the same, for the joiner (`409 {full:true}` when full) |
| `GET /api/mp/sessions/:code` | | `{code, title, preset, seed, created, players:[{pid, name, asn, color, card, seen, joined}], feed}` |
| `PUT /api/mp/sessions/:code/card` | `{card}` | the roster |
| `PUT /api/mp/sessions/:code/save` | `{seq, at, data, card?, force?}` | `{ok, seq, at, roster}`, or `409 {seq, at}`; `429` while another one is on its way, `503` when the server is busy |
| `GET /api/mp/sessions/:code/save` | | `{seq, at, data}` (your own save only) |
| `POST /api/mp/sessions/:code/feed` | `{text}` | the roster |
| `DELETE /api/mp/sessions/:code/me` | | `{ok}`; the session goes when its last player leaves |
`avoid` lists AS numbers the server must not hand out (the game sends the map's own networks in that range). `preset` is
one of `soft`, `freeze`, `oncall`, `bgp`. `data` is the save as the game writes it: JSON text, or `gz:` and base64.
The card, as the server keeps it (unknown fields are dropped, numbers clamped, ids checked for shape; the page checks
the ids against its own catalogs again): `day`, `tier` (`t1`, `t2`, `t3`), `t1`, `lvl`, `pops` (city ids), `links`
(`[a, b, Gbps]`, up to 300), `ix`, `transit` (network ids), `ppol` (`open`, `selective`, `closed`), `reach` (0–1),
`peak`, `served` (Gbps), `cust`, `rev` (per month), `cashB` (−1 in debt, else the power of ten of the cash), `score`.
Cards are what each player's browser says: nothing on the server checks that a network really is that big.
## Code
- Server: `scripts/lib/mp.js` (the API and storage), `scripts/mp-server.js` (the command line and the static site).
- Game: `src/game/60-features/89-multiplayer.js` (state, sync, the card, the `#mp=` link),
`src/game/95-modals/48-multiplayer.js` (door, sheets, panel, chip), `src/game/90-actions/92-multiplayer.js`
(actions), `src/styles/41-multiplayer.css`. The build stamps `MP_API` into `src/game/00-core/20-analytics.js`.
- Tests: `tests/mp-server.test.js`, `tests/multiplayer.test.js`.
- Server-run play (being built, not switched on): the act tables `scripts/lib/mp-sim-acts.js`, the engine
`scripts/lib/mp-sim-engine.js`, `mp-sim-worker.js` and `mp-sim-realm.js`, the page's side `src/game/98-server-play/`
(a comment so far), and the tests `tests/mp-sim-*.test.js` and `tests/server-sim-prereqs.test.js`.

View file

@ -1,57 +0,0 @@
# ADR 0001: Series of Tubes is hosted on GitHub Pages, and only there
- Status: accepted, not open for renegotiation
- Date: 2026-10-27
- Decided by: Frederic Jung
## Decision
The game is served by **GitHub Pages**, from the custom domain in `site/CNAME`
(https://seriesoftub.es). That is the only hosting. There is no second host, no fallback host and no
plan to move.
Every change has to keep working there. A change that only works with a server, a different host,
a CDN in front, edge functions, rewrites or custom response headers is the wrong design for this
project, however good it is otherwise. Change the design, not the host.
## What GitHub Pages gives us, and what it does not
| We can rely on | We cannot have |
| --- | --- |
| Static files over HTTPS from one origin, with gzip | Any server code: no API routes, no SSR, no PHP, no edge or serverless functions |
| The deploy in `release.yml` (`actions/upload-pages-artifact` + `actions/deploy-pages`) | Custom HTTP headers (`Cache-Control`, CSP, COOP/COEP): use `<meta>` tags or do without |
| `404.html` for unknown paths | Redirect or rewrite rules (`_redirects`, `.htaccess`, `vercel.json`, `netlify.toml`) |
| `CNAME` for the domain | Per-file caching rules: Pages sets its own short cache lifetime for everything |
| A size limit of about 1 GB for the site and 100 MB per file | Secrets at runtime: everything in `_site/` is public |
Anything that needs data at runtime fetches it from the same origin as a static file
(`version.json`), from the player's own browser (`localStorage`), or not at all.
## Consequences
- **The build is the place for work.** Anything clever (assembling the page from `src/`, stamping the
version, baking release notes) happens in `scripts/build.js`, at build time, in GitHub Actions.
The build may get slower; what it produces must stay plain static files. See
[ADR 0002](0002-one-page-assembled-at-build.md).
- **Same origin for everything the game loads.** The page, the dictionaries, icons and the service
worker all come from seriesoftub.es. The only cross-origin requests are the web fonts and the
privacy-friendly analytics counter (its script and its endpoint), and the game works without both.
Don't add more: no CDN-hosted libraries, no third-party APIs the game depends on.
- **The service worker is the cache policy.** Since Pages decides HTTP caching, `site/sw.js` decides
what is cached for offline play, versioned by the release.
- **Deploys only come from releases.** `release.yml` is the only workflow with `pages: write`. Pushes to
`main` never deploy.
- **Tools are not hosting.** `npm run dev`, the MCP server and the container image that packages them
(`docker/`, published to GHCR for releases) are tools. What someone serves with them is theirs; seriesoftub.es is
the game, and nothing is ever deployed anywhere but GitHub Pages.
- **Tests guard it.** `tests/pages.test.js` checks that a build is plain static files that GitHub
Pages can serve as they are: no server or host configuration files, every local reference resolving
inside `_site/`, nothing over the size limits, `CNAME` and `404.html` in place, and the deploy going
through the official Pages actions.
## Proposals that are out of scope
Moving to Netlify, Vercel, Cloudflare Pages or a VPS; putting a CDN or proxy in front; adding a
backend for accounts, leaderboards or cloud saves; server-side rendering. Features in that direction
must be built from static files and the browser (for example, an exported save file instead of a cloud
save), or not at all.

View file

@ -1,68 +0,0 @@
# ADR 0002: Source in many files, shipped as one page assembled at build
- Status: accepted
- Date: 2026-10-27
## Context
Until 1.34 the whole game was `site/index.html`: about 900 KB and 5,100 lines of HTML, CSS and JavaScript
in one file, edited by many contributors at once. Nearly every pull request touched that file, so
pull requests conflicted with each other all the time, reviews meant scrolling a 900 KB file, and
nobody could tell from a diff's file list what a change was about.
What had to stay: hosting on GitHub Pages ([ADR 0001](0001-github-pages-only.md)), load time and in-game
speed (most players are on phones), saves, the tests that reach into the page's globals (`S`, `R`,
`ACT`, `compute()`), and no new runtime dependencies.
## Decision
- The page's source lives in `src/`: a shell (`src/index.html`) with `<!-- @include DIR -->` lines,
the styles in `src/styles/*.css` and the game script in `src/game/**/*.js`.
- `scripts/lib/page.js` assembles them by **plain concatenation in path order** into the same single,
self-contained `index.html` as before: one inline `<style>`, one inline classic `<script>`.
The numeric prefixes (`10-`, `20-`…) set that order; gaps leave room to add files in between.
- `scripts/build.js` builds `_site/` from that page plus the static files in `site/`.
- Nothing else changes at runtime. When the split landed, the assembled page was byte-for-byte the old
`site/index.html`.
## Why concatenation, and not ES modules or a bundler
- **Zero runtime cost.** One HTML request, as before. ES modules would mean many requests (or a bundler),
module graph evaluation and a new loading order; at best they break even.
- **The code is one script on purpose.** The partials share top-level names (`S`, `R`, `UI`, `CITY`,
`tr`…) and function declarations are hoisted across the whole script. Concatenated, every partial
sees exactly what it saw before, with no `import`/`export` lists to keep in sync (another source of
conflicts) and no circular-import pitfalls.
- **Tests keep working.** jsdom loads the assembled page, and tests still call into its globals and
patch functions by their source text.
- **No dependencies.** The assembler is about a hundred lines of Node with nothing to install, so it
runs anywhere `npm test` does, including GitHub Actions.
- **It is reversible.** If a bundler is ever worth it, the partials are already the modules it needs.
## Rules that come with it
- **Order matters for top-level code.** `const`/`let` and statements at the top level of a partial run
in path order, so a partial can only use top-level *values* from partials that come before it (or
inside functions that run later, after boot). Functions can be called from anywhere once the page
has loaded.
- **A partial is a complete set of statements.** Each file ends with a newline and never closes the
`<script>`/`<style>` it is pasted into; the assembler refuses files that break this.
- **Put new code where its topic is.** A new feature gets its own partial in the right folder (for
example `src/game/70-rules/85-my-feature.js`), its actions go in the matching
`src/game/90-actions/*.js`, its panel in `src/game/93-ui/` or `src/game/94-dashboard/`. Small files
that own one topic are what keep pull requests apart.
- **Keep lists one entry per line.** Tables people add to (cities, cables, networks, dictionaries) have
one entry per line, and the id-keyed ones are sorted, so additions land in different places.
- **The CHANGELOG is the one shared file every change touches**, on purpose: one bullet per change under
`## [Unreleased]`. A conflict there is expected and easy: keep both bullets.
## Consequences
- Development needs one command: `npm run dev` serves the page assembled on every request and reloads
the browser on save. Opening a file straight from disk no longer runs the game.
- Error line numbers in the browser refer to the assembled page; the dev server prints the matching
`src/` file and line in the console.
- Branches started before the split are carried over with `scripts/legacy/port-branch.js`
(see CONTRIBUTING.md).
- The performance workflow builds the base's page from git with that commit's own assembler
(`node scripts/lib/page.js --ref REF`), so base and head are always compared as players get them.

View file

@ -1,57 +0,0 @@
# ADR 0003: Translations are keyed by labels, not by English text
- Status: accepted
- Date: 2026-10-27
## Context
Until 1.34 the English text was the key: code said `tr('Delivery: 2 to 6 weeks')`, and every dictionary
repeated that English as its key, `"Delivery: 2 to 6 weeks":"Consegna: da 2 a 6 settimane"`. So each of
the ~2,900 strings existed four times (code, it, pt, fr), and more with every language. Fixing a typo in
English meant renaming the key in every dictionary in the same change, or every translation silently
fell back to English. Long sentences as keys made dictionary diffs hard to read and easy to conflict.
## Decision
- Code uses **labels**: `tr('pnis.delivery_2_to_6_weeks')`, `trn('save.n_pop', n)`, `N_('common.optics')`.
A label is `area.words`: the area is where the text is used (`pnis`, `own_cable`, `page`, or `common`
for text used in several places and short shared words), the words are a few of its first words.
- **English is a dictionary too**, `src/i18n/en.js`, in the same format as the translations. It is part of
the page source: the build inlines it into the game script, so English players load nothing extra
(see [ADR 0002](0002-one-page-assembled-at-build.md)). Translations stay static files,
`site/i18n/<lang>.js`, loaded only for that language.
- **Plurals are one label** with `{"one": …, "other": …}` in every language: `trn('save.n_pop', n, vars)`.
- **Static markup** says `data-i18n="label"` (and `data-i18n-aria-label`, `data-i18n-title`) and keeps its
English text, so the page still reads in English without JavaScript and for search engines. The checker
makes sure that English matches `en.js`.
- At runtime, `DICT` is the English with the player's language laid over it: a missing translation shows
the English, an unknown label shows itself (the checker makes sure there are none).
## Consequences
- **Changing English wording is one line** in `en.js`. If the meaning changes, give it a new label
instead (`scripts/i18n-add.js --rename` moves one everywhere), so translators see it as new and the
old translation does not linger with the wrong meaning.
- **`npm run i18n:check`** verifies that every label used in `src/` is defined in English, every
English label is used, every translation keeps its English's placeholders, HTML tags and plural forms,
and every dictionary is sorted.
- **Saves:** a few things in a save hold text to show later (sold-out reasons,
attack names). New saves hold labels. Saves from before labels (1.34 and older) hold the English text; `tr()` maps it
back to its label the first time it sees one, so old saves still show the player's language.
- **Translators** read `src/i18n/en.js` next to their file; both are sorted by the same labels, so the
same line numbers line up.
- **The shipped page uses short ids, not labels.** Shipped as written, every label would be in the page
twice (in the code and as a key of the inlined English): about 20% more page after compression. So
the build (`scripts/lib/compile-labels.js`) gives every label a short id (`tr('1a')`) in the code, the
markup and every dictionary. Labels passed to `N_()` keep their name in the shipped page, because the
game stores those in saves and an id would mean something else in the next release. The checker
rejects a label that is not the first argument of `tr()`/`trn()`/`N_()`, since the build cannot see it.
`src/`, `npm run dev` and the tests all use the readable labels; `tests/pages.test.js` plays the
shipped page in English, Italian and French.
- **Performance:** measured against 1.34 on the big-network save, routing, a game day, panels, the
dashboard and the map are all unchanged, and boot time too. The page is about 4% bigger after
compression (321 → 335 KB): the English moved from the code into its own dictionary, with an id each.
The translation files are about 40% smaller (it.js 143 → 85 KB), so Italian, Portuguese and French
players download less than before. `tr()` is still one property lookup.
- Branches from before this change are converted by `scripts/legacy/port-branch.js` like the rest of the
split: their English-keyed calls and dictionaries get the same labels.

View file

@ -1,46 +0,0 @@
# 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.

View file

@ -1,408 +0,0 @@
# Multiplayer phase 2: players inside each other's simulations
Status: design only, not built. Phase 1 (sessions, server-side saves, leaderboard) is in `docs/MULTIPLAYER.md`.
Clock: this design assumes each player's game keeps its own time. A shared session clock is proposed in
`docs/plans/next-session.md` (item 3). If it is adopted, the parts timed in real minutes or on each player's own clock
(tenders, `idle`, notice, the soak test) move to game days.
**Conventions:**
- Line numbers are `main` at `1e7638c`.
- Phase 1 (multiplayer sessions, merged on `main`) provides `S.mp`, `MP`, `mpCard`/`mpCardOk`, and `cleanCard` in `scripts/lib/mp.js`.
- Everything runs only when `MP_API` is stamped and `S.mpx` is not null. The plain GitHub Pages build is unchanged (`pages.test.js`, `build.test.js`).
## 1. Starting point and grafts
**Base: "contracts".** It had the best totals in two of the three scorings, and the best feasibility and risk.
- Players are pseudo carriers `mp:<pid>`, registered only in `NET` with single-entry `CONE`/`CONE_S`/`DOWN`/`ANC`.
- `NETS`, `NET_IDS`, `NSH`, `t1Need()`, seen/grace and the gameplay-rules tests never see a player.
- No catalog id contains `:`, and nothing iterates `NET`.
**I checked this on big-network** (a throwaway probe, not committed): a buyer row on `mp:p1` in `S.transit` plus a player PNI, through `compute`, 5 day ticks, the intern, every panel and tab, traceroute, `t1Why`/`isTier1` and a `migrate` round trip.
Results:
- No errors anywhere.
- The rows were kept while registered and dropped once unregistered.
- Warm compute went from 32.3 to 33.2 ms (median of 25 alternating runs).
- `R.sessions` rose by 1. That confirms the exploit fixed below.
**How each fatal flaw the judges found is removed:**
| Judged flaw | Fix |
|---|---|
| The seller's `S.biz` row is exposed to dropBiz, decommission, ddosTargets, Pie moods and the mood loop | The seller side is a deal entry read in exactly two places, demand and money (nets) |
| Peering is cosmetic, yet player PNIs count toward `isTier2`/`t1Club` | Player traffic ships with peering (§2.3). Player sessions never enter `R.sessions` |
| Health is all or nothing, and bought transit reaches every network | A capacity factor (`t.mpf`) and a `miss` id list, from day one |
| A↔B transit loops | The server refuses with 409; clients drop loop links in a fixed pid order (nets) |
| A stale or alt buyer keeps paying the commit forever | The seller earns, and carries load, only while the buyer's clock runs. Prices are capped against the catalog |
| A bought wave can be upgraded past its agreed price | `upLink`/`rmLink`/`setStandby` refuse it (gameplay) |
| "An active deal with no row" is ambiguous | A per-deal `made` flag (§5) |
| `NKN` flips inside `compute()` | It is always `NN+4` |
**Grafted from the other designs:**
- From nets: the two-sided route-server rule; cones through players; PNI lead from `hstr`, with capacity set by the smaller side; the Tier 1 clique star.
- From gameplay: waves, tenders, poaching, consortium seats, notice on each player's own clock, and the LOA handshake.
**Rejected:** players as `NETS` entries (a mutable catalog, a rescaled `NSH`), reach bitmaps (they break between builds), a Tier 1 that depends on other players, automatic ratio strikes, and own-day timers that end a deal (they fire within seconds at 8×; own-day notice only paces each side's own teardown).
## 2. Mechanics
### 2.1 Pseudo carriers (`src/game/30-networks/45-player-carriers.js`, new)
`mpBind(s)` does three things:
1. deletes every `mp:*` key;
2. registers `{id:'mp:'+pid, name, asn, type:'t2', pol:'open', share:0, price:1, pops:[], up:[], ix:[], cc:'', col, blurb:tr('mp.another_player'), mp:1}` for each `s.mpx.who` entry;
3. sets `MPB.k`.
It runs at the start of every `sanitize` and every `compute()` (`if(MPB.k!==(S.mpx?S.mpx.k:''))mpBind(S)`). That covers the route worker, slot switches, imports, the failed-load rollback (`91-slots.js:105`) and puzzles. `nocWinState` (`94-dashboard/90-noc-window.js:45`) calls it too.
Because the carrier has `pops:[]` and is not in `NETS`, no catalog list ever offers a player:
- `sellsAt` and `buyTransit`;
- the intern's providers, `peerAll` and `pniAll`;
- the peering desk and own-exchange joins.
The `peer` action returns at `ixMembers(city).includes(net)` (`40-sites-peering-caches.js:14`).
### 2.2 Transit between players (the Tier 1 endgame)
**Who can sell:** a player publishes `tp` ($/Gbps/month) while `R.reach >= 0.99` and they have at least one POP.
**Buying:** "Buy transit from X here" posts a `t` deal (city, tier, LAG). The server makes it `live` at once (a price list is a standing offer) when all of these hold:
- the seller's card has `tp`;
- both cards list the city;
- there is no cycle;
- the limits hold.
**Price:** `min(tp, mpCap(city))`, where `mpCap = 2 × the cheapest catalog transitPerG(n,city,false)` there, or the catalog median if nobody sells there.
- Both sides compute it from the static catalog, ignoring each save's own `priceMul`.
- Both clamp again when they receive the deal.
**Buyer side: an ordinary `S.transit` row** `{id:'mt-'+deal, net:'mp:'+seller, city, tier, n, mp:deal, mpp:price}`.
- **Comes free:** the router port (`40-ports.js:20`), p95 history (`10-day-tick.js:37`), hot ports, traceroute, incidents, the panels, and `isTier1()===false`.
- **Billing:** `transitMo` (`40-billing.js:9`) uses `t.mpp` instead of `transitPerG(...)*S.priceMul`. The commit floor, `PORT.tmo` and `krFee` still apply.
- **Capacity:** `30-compute.js:53` multiplies by `t.mpf` = min(1, the seller's `sv[city]`/0.95), in 0.05 steps.
- **Reach:** `:54`'s `ok` also needs `!mm.has(n)` (the seller's `miss`).
- **Route cache:** the hash of every miss set joins the flags at `:70` (`+(S.mpx?S.mpx.xk:'')`), so `rcExitKey` rebuilds when a seller's reach changes.
- **Outage:** `t.down=S.day+1` when the seller's POP is down or the seller has left.
**Seller side: a `sell` entry in `S.mpx.deals`, never in `S.biz`.**
- **Load:** `mpDem(bizBw)` after the biz loop (`:95`) adds `u`, the buyer's reported use. It leaves by catalog share over the seller's own backbone, peering and upstreams; a Tier 1 carries it settlement-free.
- **Money:** `V.mp = Σ price × max(q, 20% of port) × min(1, sfOf(R2,city)/0.95)`. `q` is the buyer's p95; the last factor is the business customers' SLA credit. `V.mp` is added to `revMo` (`:382`) and to the revshare base (`:380`).
- **Port:** the seller's port counts in `portsUsed` (`10-catalog/40-ports.js`, after `:21`).
- **Idle buyer:** if the buyer's roster `idle` is ≥ 300 s (no newer game day reached the server), load and revenue are 0.
- A paused or closed buyer has no traffic to bill, and a fast seller cannot bill a frozen buyer.
- An alt account has to keep playing, and still pays at most the capped price.
**Loops:**
- The server returns 409 `loop` if the seller already buys from the buyer, directly or through others (a search over at most 12 players).
- Clients build the player-transit graph from `who[].pt` and add edges sorted by (buyer pid, seller pid), dropping any that closes a cycle, so every client drops the same edge.
- So reach passes down a reseller chain one push per hop, never settling at a false 1.
**Tier 1 stays defined by the built-in networks.**
- `R.reach` only sums `NSH`, so neither `isTier1` (`80-hot-ports-and-rank.js:20`) nor the mood check `R.reach>0.99` (`10-day-tick.js:51`) can depend on players.
- Buying player transit costs Tier 1, and `t1Why` already says so. Selling never does.
- Refusing to peer blocks nobody's win.
### 2.3 Peering between players, carrying traffic
**PNI (`pni` deal, always accepted by hand).** Each side adds `S.pni` `{id:'mn-'+deal, net:'mp:'+other, city, tier, n, mp:deal, ready:S.day+lead}`.
- **Lead time:** `lead = pniNow() ? 0 : leadDays(14 + hstr(deal+myPid) % 29)`, with no random numbers.
- **Cost:** each side pays its own `pniMo`.
- **Capacity:** the smaller of the two sides (theirs comes from `dl[].g`). It is 0 until both cards report `ok`: the LOA and cross-connect handshake.
**IX (`ix` deal).** The server makes it `live` if the responder's policy is open, `no` if closed, and `offer` if selective. Once live, both sides set `S.peers['mp:P@x']`.
**Route server:** no deal. P peers with me at `x` when both `S.rs[x]` and `P.rs ∋ x` hold and both policies are open. That is the same rule on both clients.
**Sessions:**
- `mpIx(x)` lists the player peers at an exchange. `ixSessions` (`20-exchanges.js:29`) stays catalog-only.
- At `30-compute.js:61`, player PNIs skip `R2.sessions++` (`if(!p.mp)`) and count in `R.mpSess` instead.
- So friends can never inflate `isTier2`/`t1Club`.
**Player traffic** (new `src/game/80-simulation/36-mp-traffic.js`). `compute.js:343` calls `mpTraffic({E,SPP,NRES,HAS,R2,carry,NN})` once, after `citySrv` (`:341-342`). The parts are handed in the way `ddosLoad` gets them (`:188`).
- **Demand:** each POP sends `cityEye[c]·w_P` to each active player P.
- `w_P = min(0.02, (biz_P + 0.3·eye_P)/75000)`, and `Σw ≤ 0.1`.
- **Exits that reach P:**
- rank 2: a ready PNI with P, or an IX exit with `mpIx(x) ∋ P`;
- rank 2.5: the same exits toward Q when P buys from Q, which gives cones through players;
- rank 3: player transit from Q when `P===Q` or `Q.mr ∋ P`, and catalog transit when `P.on`;
- `pref:'low'` moves an exit to rank 4.
- **Pushing:** exits are sorted by distance once per POP. Traffic goes along `walkI(SPP[c],ci,e.ci)` and is limited by `l.res`, `NRES` and `e.cap-e.used`.
- **Recording:** each push calls `carry(l,e.ek,NN+3,…)`. `NKN` is always `NN+4` (`:130`), and that column is named `'players'` at `:16`.
- **Effects:**
- Transit p95, hot ports and link loads include player traffic, so peering saves transit money.
- `R2.mp={dem,srv,peer,lost,full,by}` records the totals.
- The pass runs after every catalog flow, so `R.served`, `R.demand`, moods, levels, `peerShare` and Tier 1 never change.
**Cost of a de-peering war:**
- `computeMoney` applies `V.eyeballs *= 1 - mp.lost/(demand+mp.dem)`, where `lost` is traffic with no route at all.
- Two transit-free Tier 1 players who won't peer cannot reach each other: catalog Tier 1s don't pass on routes they learn from peers. Each loses up to 2% of eyeball revenue, which is real Level 3 vs Cogent drama at a bounded cost. Neither loses Tier 1.
- Two eyeball players who don't peer pay transit p95 for each other's traffic.
**Clique star (cosmetic):** card `cq=1` when you are Tier 1 and reach every player whose card says `t1` by your own PNI or IX session. The leaderboard sorts the star first.
**De-peering:** `end` the deal. Each side removes its rows 7 own days after it first sees the end.
### 2.4 Competition
**Overlap:** `clComp` (`75-customer-lifecycle.js:30`) also counts rival players whose card POPs cover the customer's cities. The rolls stay hash-stable (`clR`).
**Poaching:**
- `clLeave` (`:64`), for "cheap" or "multi" with a rival POP in the city, posts the customer to `/lost`.
- The server gives it to one rival, chosen by `hstr`, as a gift.
- The rival checks it with `okBiz`, `BIZ_T` and `rate ≤ catalog×mkt()×1.2`, then puts it in `S.offers` with `ref` set to the loser's name.
**Tenders:**
- **Issue:** while at least two players are active (`idle` < 300 s), the server issues `{n, city}` every 5 real minutes. The city is seeded from the active players' POPs.
- **Content:** derived from `hstr(seed|n)` and the `BIZ_T` lists, so every client sees the same tender.
- **Bids:** a ratio r from 0.6 to 1.0. You can bid while paused, and an optional standing auto-bid covers your cities.
- **Closing:** after 10 real minutes, or once every active player has bid. Wall-clock time, because no game clock is shared.
- **Winner:** the best `(1.2-r)·sq`, where `sq` is served share. The tender goes into `S.offers` with `mp:1`, expiring in 10 own days, and is signed with the normal `accept`.
### 2.5 Shared fiber
**Waves and IRUs (`wave`/`iru` deals):**
- **Seller side:** books spectrum or pairs via `+mpSold(l.id)` in the three counters (`60-requirements.js:72,75`, `37-fiber-broker.js:16`). It earns `V.mp += rate×(fiberOk?1:0)`.
- **Buyer side:** an `S.links` row `{kind:'wave'|'df', own:false, mo:price, mp:deal}`, which copies cut/eqDown/ready from `dl`.
**Consortium seats:** built like `seatBuy` (`86-specialist.js:4`), at `ownCabCost(km)×myPairs/totalPairs` (`36-specialist.js:54`).
**Deferred:**
- Joint exchanges, which need an id namespace (`isIx`, `50-sanitize.js:2`).
- An opt-in "Tier 1 must reach every Tier 1 player" rule.
## 3. Server (`scripts/lib/mp-deals.js`, pure logic, with routes in phase 1's `scripts/lib/mp.js`)
**The deal record** is public to the session, like PeeringDB. The session keeps a counter `dv`, bumped on every change.
```
{id:'d'+base36, k:'t'|'pni'|'ix'|'wave'|'iru', a, b, s (seller), at (city|ix|'a|b'), tier, n, price, slots, st, rev, t0, tl, te, by, why}
```
| from | event | to | allowed for |
|---|---|---|---|
| – | create `t` | `live`, or 409 `not_selling`/`no_pop`/`loop`/`dup`/`limit` | the buyer |
| – | create `ix` | `live` (b open and present) / `no` (b closed) / `offer` | a |
| – | create `pni`/`wave`/`iru` | `offer` | a |
| `offer` | accept / decline / withdraw / 7 days pass | `live` / `no` / `gone` / `gone` | b / b / a / server |
| `live` | end | `end` (`quit`) | a or b |
| `live` | a side's card never reports `ok` within 7 days | `end` (`unbuilt`) | server |
| `live` | no card from a party for 14 days | `end` (`idle`) | server |
| any open deal | a party leaves or is pruned | `end` (`left`) | server |
| `no`/`gone`/`end` | 7 days pass | deleted | server |
**Errors:** every write sends `rev`. A stale `rev` or an illegal transition gets 409, and the wrong party gets 403.
**Limits:**
- one open deal per (pair, kind, place);
- 10 open offers and 24 live deals per player;
- 300 deals per session;
- price 0.05–50, tier 0–15, n 1–8;
- 30 writes per minute per player.
**Feed:** the server writes a line for each transition ("X sells transit to Y in Frankfurt", "X de-peered Y").
**Endpoints:**
- `POST /api/mp/sessions/:code/deals {k,to,at,tier,n,price?,slots?}` returns 201 `{deal,dv}`.
- `POST …/deals/:id {op,rev}` with `op` one of accept, decline, withdraw or end.
- `POST …/lost` reports a lost customer; `POST …/tenders/:n/bid {r}`; `PUT …/autobid`.
- The roster responses (`GET` the session, and `PUT` the card or save) add:
- `deals[]` (my deals, any state) and `dv`. Other players' links come from their cards' `pt`;
- `tenders[]` and my `gifts[]`;
- each player's `idle`: seconds since their card last carried a newer day.
So nothing needs extra polling.
## 4. Card fields beyond phase 1
Every field below is added to both `cleanCard` and `mpCardOk`. Phase 1's `transit` field stays catalog-only, because `NET_RE` would silently drop `mp:` ids.
| field | content |
|---|---|
| `nv` | build version |
| `pt` | pids I buy transit from |
| `rs` | exchanges with my route server on |
| `tp` | my transit price, or null |
| `miss` | catalog ids I can't reach, biggest share first, ≤160 (a reach of 0.99 can still miss 72) |
| `on` | 1 if the internet of built-in networks can reach me: catalog transit, PNIs with every `t1Need()` network, or a seller with `on` |
| `mr` | pids I reach |
| `eye`, `biz` | Gbps, 2 significant digits |
| `sq` | served share |
| `sv` | `{city: delivered share}` where I sell, ≤64, in 0.05 steps |
| `dl` | `[{id,u,q,g,ok,up,cut,eq,rdy}]`, one per live deal, ≤64 |
| `cq` | clique star |
The card grows by about 4 KB at most. ASNs need nothing new: phase 1 already sends the catalog ASNs to avoid (`mpAvoid`, `mp.js:238`).
## 5. Client day flow (`src/game/60-features/89-player-deals.js`, new)
Phase 1's `mpRosterOk` is extended to whitelist `deals`, `dv`, `tenders`, `gifts` and `idle` (plus new `MP_FEED` kinds). The validated roster stays in `MP.roster`, never in S. `mpDay(d)` runs first in `dayPre`, right after `S.day++` (`10-day-tick.js:10`):
1. **Copy changes in.** If `dv`, `idle` or any card changed, rebuild `S.mpx.who` and `S.mpx.deals` from the validated data, with values in steps. Then recompute `k`/`xk` and call `mpBind(S)`.
2. **Reconcile each deal:**
- **live, not `made`:** create my row (`S.pops[at]`, `portOk`, `portGate`, `spend(setup)`) and set `made`. If that fails, the deal waits under a "waiting on you" badge, with no client timer; the server ends it as `unbuilt`.
- **live, `made`, but the row is gone** (for example after a decommission, which `decomImpact` warns about): post `end` with `why:'gone'`. Decommissioning a city where I sell also ends those sell deals.
- **ended** (or missing from the server's list): set `until=d+notice` (14 own days for transit, 7 for the rest) and remove the rows when it passes.
3. **Copy the coupling values onto the rows:**
- on transit rows: `t.mpf` and `t.down`;
- on PNI rows: their side's capacity and whether it is ready;
- on link rows: cut, eqDown and ready;
- on my seller entries: `u`, `q` and whether the buyer is active.
4. `compute()` runs (worker or not), then `dayPost`, then phase 1's push carries the new fields. `dl` comes from yesterday's R.
**My own clicks** (`mpOffer`, `mpAnswer`, `mpEnd`, `mpSell`, `mpBid`) apply as soon as the server answers, with `mpApply();after()`. If `RW.job` is set, they apply at the next `dayPre` instead.
Multiplayer code never calls `Math.random`.
## 6. Saves and sanitize
**New field:** `S.mpx = null | {k, xk, dv, who:[≤11], deals:[≤64]}`. `deals` holds only my own deals. Cones, `on` and who-buys-from-whom come from `who[].pt`.
- `mpx:null` is the default in `newGame` (`80-new-game.js:4`), so old saves get null.
**Order in `sanitize`:** move phase 1's `mpSanitize(s)` from `50-sanitize.js:113` up to `:21`, then call `mpxSanitize(s)`. Both now run before `opsSanitize` (`:22`) and every `isNet` filter (`:34-35, :54-55`).
**`mpxSanitize`:**
- **When it is null:** unless `MP_API` is stamped and `s.mp` is valid in normal mode. An imported multiplayer save then just loses its player rows.
- **Players (`who`):** pids checked against the regex, unique, never my own.
- **Names:** stripped like the phase 1 server does (control characters and `<>&"'\``, at most 32). They are not escaped, because `labOf`/`hotPorts` print catalog names unescaped too.
- **Ids:** pass `isCity`/`isIx`. `miss` must be catalog ids, and `pt`/`mr` must be pids in `who`.
- **Numbers:** clamped and stepped.
- **Deals:** kinds from a whitelist, the other party present, `at` checked, `tier` within `PORT`, the price at most `mpCap`.
- **Loops:** `pt` edges are dropped in (buyer, seller) pid order.
- **Keys:** `k`/`xk` are recomputed, never trusted.
- **Last step:** it ends with `mpBind(s)`.
**`mpOrphans(s)`** runs right after `:113`:
- it drops tagged `transit`/`pni`/`links`/`peers` entries that have no deal;
- it drops untagged rows on `mp:` networks;
- it strips `mp`/`mpp`/`mpf` from untagged rows, so a forged `mpp:0` gives no free transit.
**`RK_SKIP`:** `mpx` stays off it, because `compute` reads it. Phase 1's `mp` stays on, because `compute` must never read it; the `route-skip.test.js` proxy enforces both.
**Size:** at most +15 KB per save.
## 7. Ordered steps
Each step ends with `npm test` green, the i18n check clean, MCP classification, a CHANGELOG bullet and perf numbers.
**1. Dormant core (no server, no UI).**
- `45-player-carriers.js`.
- `80-new-game.js:4`; `50-sanitize.js:21`/`:113`.
- `30-compute.js`:
- `:28` bind check;
- `:53-54` `mpf` and `miss`;
- `:61` `if(!p.mp)`;
- `:62` `*(p.mp?mpPniF(p):1)`;
- `:70` `xk`;
- `:95` `mpDem`;
- `:130`/`:16` the players column;
- `:375-382` `V.mp`.
- `40-billing.js:9`; `40-ports.js:21`.
- **Guards:**
- `lagT`/`lagP`/`cancelTransit` (`20-pops-transit-ix.js:6,7,11`), `unpeer`/`cancelPni` (`40-sites-peering-caches.js:16,30`) and `downT` (`21-ix-downgrade.js:6`) route to `mpEnd` or a renegotiation offer;
- `cleanPipe` (`80-security-and-china.js:8`) refuses `mp` rows;
- `trExits` (`50-traceroute.js:20`) applies `miss`, and `hotPorts` (`80-hot-ports-and-rank.js:4`) applies `mpf`;
- `connUp` (`40-connections.js:18`) shows no upgrade for these rows;
- the intern (`95-standing-orders.js:155,180,250`) skips `mp` rows;
- `upLink`/`rmLink`/`setStandby` (`60-links.js:2,6`).
- `src/agent/30-docs.js`.
- **Tests:** `mp-sanitize`, and `mp-transit` with `S.mpx` injected.
**2. Deals and transit, end to end.**
- `scripts/lib/mp-deals.js` and the `mp.js` routes and timers.
- The card fields.
- `89-player-deals.js`, called from `10-day-tick.js:10`.
- `90-actions/92-player-deals.js`, classified in `src/agent/20-commands.js`.
- `95-modals/49-player-deals.js`: a Deals tab in the session sheet, a bottom sheet at 360 px.
- `90-noc-window.js:45`; `decomImpact`; all six languages.
- **Tests:** `mp-deals-server`, and `mp-transit` with `fetch` mocked.
**3. Peering and player traffic.**
- `pni`/`ix` deals, `mpIx`, and `36-mp-traffic.js` with its hook at `:343`.
- The `V.eyeballs` factor, `R.mpSess` and the star.
- Player Gbps in the PNI list and the connections list.
- **Test:** `mp-peering`.
**4. Competition:** `clComp`, poaching, tenders.
**5. Shared fiber:** waves, IRUs, seats.
**6. `scripts/mp-soak.js`:** opt-in, never part of `npm test`.
## 8. Performance budget
**Single-player.** Each `compute()` costs one string comparison, one property read per transit and PNI row, and one more `ACN` column per edge.
- `npm run perf -- --base-ref origin/main` must stay within noise (≤1%).
- `emptyR()` gains no keys; `R.mp`, `R.mpSess` and `V.mp` exist only when `S.mpx` is set.
**Multiplayer.** The carrier mechanics are measured above: 32.3 → 33.2 ms. A new `big-network-mp` workload (the fixture plus 11 players and 20 deals, built by `scripts/perf-mp-fixture.js`) must meet:
- `mpTraffic` ≤ 1.5 ms (one exit sort per POP, then O(players×exits), with paths cached for each pair of cities);
- `mpBind` ≤ 0.1 ms;
- warm `compute` ≤ +5% compared with the same fixture without players.
A cold route happens only when `xk` changes, at most once a game day. Report jsdom and `--browser` numbers.
## 9. Test plan
**`mp-deals-server`** (spawned server, temporary directory):
- every transition and who may make it (403/409);
- the policy outcomes for `ix` (live, no, offer);
- 409 `loop` on A→B→C→A;
- the limits;
- the `unbuilt`, `idle` and `left` ends, and expiry, with an injected clock;
- card validation;
- restart persistence.
**`mp-transit`:**
- the buyer's exit and label, `transitMo` using `mpp`, `isTier1` false;
- `mpf` scales capacity, and `miss` blocks reach and changes `xk`;
- the seller's demand rises by `u`, `V.mp` follows the formula, and the seller keeps Tier 1;
- an idle buyer gives zero load and revenue;
- a forged `mpp` is stripped;
- worker parity (the `route-worker.test.js` pattern);
- no `Math.random` calls;
- the inbox is never applied mid-day.
**`mp-peering`:**
- a PNI carries traffic only once both ends are ready;
- de-peering raises transit p95;
- two unpeered Tier 1 players lose revenue, and both stay Tier 1;
- 24 player PNIs leave `R.sessions` unchanged;
- C reaches B through A's cone;
- the route-server rule is two-sided;
- the PNI lead time is stable.
**`mp-sanitize`:**
- fuzzing does not throw and stays bounded: 1,000 entries, HTML in names, loops, unknown ids, `mp:` rows in a single-player save;
- old saves load;
- a multiplayer-to-single-player slot switch clears every `mp:*`;
- `<img onerror>` stays text in the panels and the Deals sheet at 360 px.
**`mp-competition` and `mp-fiber`:**
- rival players raise `clComp`;
- gifts are validated;
- every client derives the same tender;
- cuts are copied;
- a bought wave can't be upgraded.
**Existing gates:**
- `route-skip` (same digest with `S.mpx` null or empty), `compute-idempotent`, `routing-reference`, `route-cache`;
- `gameplay-rules`, plus a check that no `mp:` id is in `NETS`/`NSH`;
- `persist`, `save-size`, `save-text`, `mcp-commands`, `i18n`, `pages`, `build`, `multiplayer`, `mp-server`.
**Soak test (the "hardcore" local run):**
- The server plus 12 seeded jsdom players in `worker_threads` (about 0.5 GB each, with `--jobs` capped).
- Each plays about 2,000 days at its own speed, with a random agent making, answering and ending deals.
- During the run: server restarts, reloads through `migrate`, a player leaving, tampered cards and a burst of 409s.
- It checks: no errors or NaN, an acyclic deal graph, each seller's `V.mp` matching the buyer's bill, every save reloading, and a single-player control game keeping `main`'s digest.
## 10. Failure modes
| Case | Handling |
|---|---|
| The other player is paused or offline | Their last card stands: an idle buyer brings no load or money, and a buyer keeps the seller's last values. After 14 days the server ends the deal (`idle`) |
| A player leaves | The deal ends (`left`) and each side tears down after notice. `mpBind` drops the carrier on the next sanitize |
| Server down | Play goes on with the frozen `S.mpx`. New deals fail with one toast |
| Two devices | Phase 1's seq/409 picks the save; `made` settles the rows |
| Version skew | Unknown `miss` ids are dropped; networks the seller's build lacks count as reachable |
| Tampered card or save | Whitelists, clamps, steps, local price caps, orphan stripping. Money comes only from local formulas |

View file

@ -1,179 +0,0 @@
# What is left (as of 2026-11-09)
Work in this fork, pushed to the `vanvik` Forgejo remote (never to `origin`). Written on top of 3e30621, with the
batch of fixes below ("Built in the batch of 2026-11-09"). Nothing below is switched on or built unless it says so.
## Built so far
On top of upstream, merged up to 3.3.0 (61e31c5 "Merge upstream: Lambda Bazaar, traffic badges, moving customers and
faster routing (3.3.0)"; earlier merges 032470f and 4b922ab):
- **Build standard**: 2b48a6a "A build standard for the whole network, kept by the intern", and fbae6fc "The build
standard owns the router model and the line system; one owner per fiber" (the router model and line system are
picked in the sheet only; the `routers` and `optup` orders read them from there).
- **Multiplayer phase 1** for self-hosted copies: 95aa9b6 "Multiplayer for self-hosted copies: sessions, server-side
saves, a leaderboard" (`docs/MULTIPLAYER.md`).
- **Dark mode (#80)**: 2cd6b71 "Dark mode: Light, Dark or Auto under Settings › Theme".
- **IPv4 address space (#150)**: eac0604 "IPv4 address space: scarce, bought, leased, leased out; IPv6 is free", and
69328ce "IPv6-only broadband: 464XLAT city by city, a NAT64 pool next to CGNAT".
- **Express fiber (#58)**: 8e1f2d6 "Express fiber: light a wave through a city without its router".
- **Satellite teleports (#83)**: e1ae8e0 "Satellite teleports: GEO and MEO circuits for islands and remote towns".
- A fix after the 3.1.0 merge: e8808f6 "The connections list no longer breaks on a 400G fabric port".
- **Server-run play, parts 1 and 2** (merged, not switched on): T1 is d1e127d "Server-run play, part 1: game
prerequisites and shared contracts". T2 is 065c922 "Server-run play, part 2: the engine" with its fixes c5c7ea9,
72f31e8, 3b8c331, 9597d89, 77f4035 and 3e30621. The design, its status and what building T2 changed in it are in
`docs/plans/server-run.md`.
### Built in the batch of 2026-11-09
Nine commits after 3e30621, the one that wrote this list and "Review fixes for the small-fix batch" (folded into
the entries below); every code change comes with its test:
- 8068a45 "Plans: the server-run design in the repo, what is left now, and the fork's files" (this file,
`server-run.md`, the fork's files in `ARCHITECTURE.md`, a note in `MULTIPLAYER.md`).
- **Dark mode (#80)**, 27ffa33: red text is `--tx-red` (a lighter red at night) everywhere it is text, in the styles
and in 19 game files; fills, borders and bars that carry white letters keep `--bad`. The market's Hot and Cool tags
take `--tint-o`/`--tx-amber` and `--tint-b`/`--tx-blue`. `tests/dark-mode.test.js` fails on any new
`color:var(--bad)`. Decided not to: light mode's `--bad` on white (3.24, under AA) stays as upstream has it.
- **IPv4 (#150)**, 7930d33: IPv4 notices in the notification log open the Address space (log target `{a:'ip4'}`,
`ip4Open` in `NOC_GO`); with IPv4 off since, they open the bank.
- **Satellites (#83)**, 2dc8274: the "no subsea cable lands here" hint (#321) names a satellite circuit where one can
reach the city, with a "From X" button per teleport (up to four) to the order sheet (`satNoCable()`), or where a teleport would
have to go. It covers only the city the hint names.
- **Express fiber (#58)**, ae78e82: a regen site added later charges a regen card per express channel on its fiber
(`regenAddCost()`, used by the action, the button's price and the MCP quote); a dirty connector (loss with
`glass:true`) dims every express on the fiber (`xpGlassF()`), and the express panel names the fiber. Decided not to:
an MTU mismatch, microbursts and a marginal optic's CRC errors stay with the fiber's own routers and optics, which an
express passes by (as an optic failure already did, while amp-hut and ROADM incidents darken expresses).
- **Satellites (#83)**, 1f76639: selective networks refuse to peer where a satellite circuit is the island's or
town's only way out (`satOnly()`: a fiber or cable with no optics of its own does not count): 60 in 100 refuse a
GEO hop, 15 in 100 a MEO one, each network's answer fixed; a session already there stops carrying until a wave or
cable is lit. Decided not to: a worse traffic ratio for MEO,
refusals at exchanges you run, and any effect on PNIs already there.
- **Build standard**, 286ae48: "Bring everything up now" and the intern follow one rule: a fiber a customer's alien or
managed wave rides keeps its line system (`dfWaveCust()`), and the sheet says why (`bstd.held_wave`); leased pairs
and IRUs no longer hold a fiber for the intern. Left as it was: the fiber panel's own upgrade button (`ACT.upSys`)
still swaps under a sold wave, with its warning toast.
- **Standing orders**, 02b6c24: the shift's log keeps at most three broken orders, the week's tally no longer makes an
empty list of places, and `opsTidy()` is gone (`tests/canonical-state.test.js` passes without it).
- **IPv6-only broadband (#150)**, 417160f: the build standard's "Broadband: IPv6-only" row (`BSTD` `v6`, shown only
while `ip4On()`). `bstdPlan()` makes one job per dual-stack broadband city (`ip6Todo()`), the most dual-stack homes
first, priced as the whole swap (`ip6Cost()`); the button and the `std` order start one only with all of it above
the floor on top of what running swaps still owe (`ip6Owed()`), and the order counts it against its month's budget.
What running swaps owe, whoever started them, is set aside for every later job: the button's, and every standing
order's (`X.ow` in `opsShift()`, refreshed when the `std` order starts a swap). Decided not to: a separate hold in
`ip6Day()` at the cash floor; with the money set aside, the swaps pay down to the floor at most.
## The user's answers (2026-11-09)
The four questions of the server-run design:
1. A player who joins an old session starts on the **session's date**: one shared calendar. The game's day-0 rules
then have to count from each network's own start (`server-run.md`, "What Q1 changes").
2. Single player in a multiplayer build runs **on the server** by default; "this device" stays an option.
3. An empty session that wakes runs at **1×**.
4. Phase-1 sessions **start fresh**: nothing is migrated.
## On hold until the user says go
- **#97 co-op companies** (several players run one network, with roles, budgets and approvals).
- **Multiplayer phase 2** (players as carriers in each other's simulations: transit, peering, PNIs, shared fiber):
design in `docs/plans/multiplayer-phase2.md`. When it restarts, that design needs rework for the shared server clock:
it assumes each player's own clock, and tenders and notice timed in real minutes.
- **#144 directional traffic**, last and on its own: keep the totals, split them by traffic profile, utilization is the
busier direction. It comes after #58 because both touch link capacity (express channels count too).
## Open questions waiting for the user
Asked on 2026-11-09, not answered yet:
1. ~~**Late joiners' prices and beginner grace.**~~ *Answered 2026-11-11 ("late joiners get a late joiners bonus and a
year of double income per Gbps of FTTP sold/provided") and built: the day-0 rules count from the network's own start
(`S.day0`, `netAge()`), and a network that joins after day 180 gets a hardware top-up and its first year of home
broadband matched (`60-features/81-late-joiners.js`, gameplay rule F11). Dormant until T3 passes a start day.*
2. **Other players' POPs on the map.** Draw other players' POPs and links on your map (from their cards) as part of
the server-run work, or wait for phase 2?
3. **The other modes in a multiplayer build.** Sandbox, scenarios, puzzles and the weekly keep running on the device.
Fine, or should sandbox (or all of them) also run on the server?
4. **Dark mode and the build standard upstream.** Upstream contributors have said they will open pull requests for a
dark mode (#80) and a bulk redundancy kit (#317), and a three-tier router standard sits on another contributor's
branch (#315). Offer the fork's dark mode and build standard upstream before those land, or keep them fork-only and
settle the clash at the next merge?
5. **#58 whole-fiber splicing.** Is the express lightpath enough, or should a whole fiber pair also splice through a
city (one dark fiber A–C through B, with no ROADM at B)? The issue asks for "waves and/or entire fibers".
6. ~~**#83 WISP zones and a rented LEO tier.**~~ *Answered 2026-11-11 ("wisp and leo please") and built: Starblink
LEO circuits from a gateway at a teleport on your fiber (level 5), and Island Wi-Fi for 18 zones of outer islands
over GEO, MEO or Starblink and a spur cable (`60-features/45-teleports.js`, `60-features/46-wisp-zones.js`, gameplay
rules O8, W6 and F12).*
7. ~~**Investors' cut of IPv4 lease income.**~~ *Answered 2026-11-11 (yes) and built: investors on a revenue share
take their cut of IPv4 lease income, as of fiber pairs leased out; a sale stays all the player's.*
8. **Founding an exchange on a basic router.** Founding your own exchange gives a 400G port even where the POP's router
only takes 100G, though the shop would not sell that port. Document it as a limitation, block founding until the
router takes 400G, or found at the router's largest port size? (`tests/server-sim-prereqs.test.js` asserts today's
behaviour.)
9. **The six old wip worktrees.** They hold nothing `main` lacks. Delete them and their branches?
## Next
- **After the user's go:** T3 (host and protocol), T4 (the browser client) and the integration of server-run play,
as `docs/plans/server-run.md` describes them, with the corrections at its top. The game's side of the Q1 work is
built (`S.day0`, the day-0 rules, `begin.day`, `CLOCK.off` gone, the late joiner's head start); T3 sends the start
day, checks every network's day after each tick and replaces the line-up of 4.7 ("What Q1 changes").
## Known limitations of what shipped
- **Multiplayer (phase 1):** each browser runs its own clock, so the players' worlds drift apart (server-run play fixes
this for new sessions only); other players' POPs are not drawn on the map (open question 2); cards are what each
browser reports, and the server does not check them; a save over ~60 KB sends only the card when the tab closes, and
the save goes with that device's next push; a session network still makes its save on the page, so it misses 3.3.0's
smoother saves in the worker; the capacity market and path moves are each player's own, with no market shared
between players; the HUD chip in phone landscape wider than 760 px has not been checked by eye (worth doing when T4
changes the chip). Behind a reverse proxy, run the server with `--trust-proxy`, or every player shares one address's
rate limits.
- **Server-run engine (merged, not switched on):** a checkpoint is over its size budget, and so are a snapshot, a big
realm's memory and a small network's day; a checkpoint written before c5c7ea9 restores close to exact, not exact; the
engine has no per-call deadline of its own; a worker of its own whose session's loads all fail stays idle until the
next unload; the path window would read routes the page never gets (`server-run.md`, "Corrections from building
T2").
- **Build standard:** the game menu's last row of tiles is not full (7 tiles, or 8 in a multiplayer game, in rows of
3). The sheet's quote and "Bring everything up now" judge a line-system swap without routing (`bstdDarkOk()`: a
quiet fiber, under 10% of its capacity, or a parallel link with room; any express with traffic holds its fibers,
`bstdXpBusy()`), so the quote is the bill; only the intern routes to test. A quiet fiber with no way around can
still go dark from the button for a day. A fiber a customer's alien or managed wave rides keeps its line system for
both the button and the intern (`dfWaveCust()`); the fiber panel's own upgrade button still swaps it, with only a
toast to warn. `bstdSet` accepts the `v6` target while IPv4 is plentiful: it is saved, hidden and never planned. An
old save's `routers.model` moved into the standard (only from a running
order with an intern hired; a paused one's is dropped) also becomes what new POPs get. A model or line system in the
standard is a ceiling for the `routers` and `optup` orders (their next-one-up rule only applies with "keep"), as an
order's own model was before; `optup` has no per-POP exceptions, so it moves fiber at POPs excepted from `std` too.
- **Dark mode (#80):** the share card PNG and the web manifest stay light; the WebGL map was checked by tests only, not
by eye in a real GPU browser.
- **IPv4 (#150):** the intern does not manage addresses (optional in the issue); transfers are instant (real ones take
weeks); blocks granted to old saves can be sold after two years (a one-off windfall); CGNAT annoyance costs refunds
but does not slow broadband growth.
- **IPv6-only broadband:** no one-off grumble while a city's home routers are swapped; a new home in an IPv6-only city
pays its router even when cash is short (a running cost, so a finished city never looks like a stopped swap). The
NAT64 ratio is not in the build standard (the swap is), and the standard starts a swap only with the whole of it to
spare, stricter than the city panel's button (the first day's routers).
- **Express fiber (#58):** a whole fiber pair does not splice through a city (every fiber end is a POP; expresses
cover the need; open question 5). Of a fiber's own incidents only the dirty connector dims its expresses; MTU,
microbursts and a marginal optic stay with its routers and optics.
- **Island Wi-Fi (#83):** a zone's traffic enters at its own city's POP, so Starblink serves it only from a gateway in
that city (16 of the 18 zones; a gateway anywhere in reach would serve the same 16): Nunavut and Southeast Alaska lie
beyond the 56° shell and MEO's ring, so they stay on GEO (Southeast Alaska keeps its spur). One circuit, one move
and one spur per zone; a standby satellite pays full rent; no standing order for island backhaul, no zones on the
map or the multiplayer card, no rain fade. The spurs follow real domestic cables: Tahiti to the Tuamotus and
Marquesas (Natitua), Tonga's domestic cable (cut by the Hunga Tonga eruption in 2022), Papua New Guinea's Kumul,
the Solomons' and the Maldives' domestic networks, the Bahamas' and Cape Verde's inter-island cables, and Southeast
Alaska's.
- **Satellites (#83):** the rented GEO and MEO circuits never
fail (no rain fade or sun outage; Pie in the Sky has its own); no island volcano or Caribbean and Pacific hurricane
events; no "Island Hopper" scenario; no footprints on the map; no satellite tab in the drag-to-link window (ordering
is from the city panel; the no-cable hint offers a teleport's order sheet only for the city it names); selective
networks judge a satellite-only island by fixed shares (60 in 100 refuse GEO, 15 in 100 MEO), not by its traffic;
GEO/MEO losses and prices are design numbers; well-cabled islands (Wellington, Hobart) also count as "can be
served"; MEO needs 5° elevation (10° would drop 416 pairs); Pitcairn's $120k satellite grant stays Pie-only.
## Housekeeping
- `npm run perf -- --browser` runs with `PERF_CHROME=/usr/bin/chromium`.
- The phase-1 playtest on port 8090 runs from its own checkout outside the repo, with its data in
`mp-data/playtest`: leave it alone unless the user asks. Its one session can go once a server-run build replaces it
(answer 4).
- The six old wip worktrees under `.claude/worktrees/` wait for the user's answer (open question 9).

View file

@ -1,123 +0,0 @@
# Pie in the Sky (implementation spec)
Local branch `pie-in-the-sky`. Never push. Commit as `Frederic Jung <frederic@jc-ix.net>`, no attribution
trailers (CLAUDE.md). Full design doc lives in Claude Docs; this file is the contract for the code.
## What it is
The endgame for players who just became Tier 1 in a save started on this version (and sandbox from day 0):
found a rocket company, launch thousands of satellites ("pies") into shells ("crusts"), build dedicated
base stations ("pie dishes") everywhere, and connect them with your own backbone. Obscenely expensive.
Satirical tone: a cartoon Founder (no real person) who breaks every promise by a year; a press office that
calls every failure a success. All names are puns (rule N2); add each real name riffed on to `REAL_NAMES`.
## Gate (rule O1)
- `newGame()` sets `pieV:1, pie:null`. `sanitize()`: missing `pieV` -> 0, so old saves never get it.
- Unlock fires only on the transition in `checkGoals()` where `g.win&&!S.won` flips `S.won`, when `S.pieV>=1`.
- Sandbox (`gatesOpen()` / open gates): available from day 0, real prices, `book.wouldHave` shame counter.
- Losing Tier 1 (`!(S.won&&isTier1())`): everything keeps working; no new launches, dishes, factory orders.
- Never in puzzles, Architect, scenarios, weekly challenge.
## State
```
S.pieV
S.pie = null | {born, co:{name}, fac:bool, rd:{reuse:bool,heavy:bool,heavyTests:int},
pads:[{city,next,boosters:[{id,flights}]}],
crusts:{short|frozen|upper|flaky:{cohorts:[{n,day,las}], queued}},
dishes:[{id,city,ant,down}], lic:{[cc]:{state,until}}, q:[launches],
founder:{posts:[...last 20], promises, broken, due, jit, next, kid, bill, nerv, hype, leak, mars}, (antics: 60-features/99-pie-jitters.js) book:{spent,earned,wouldHave},
spat:{...active geopolitical spats}, safe:bool}
```
Pies are cohorts, never one object per satellite. `sanitize()` clamps all of it.
## Catalog (`src/game/10-catalog/70-pie.js`), all prices x `PIE_MUL` x `hwMul()`
| Item | One-off | Running |
| --- | --- | --- |
| Found company | $250M | $5M/mo |
| Pie factory | $1B | $8M/mo, 120 pies/mo |
| Pie | $0.5M (+$0.25M lasers) | - |
| Launch pad (coastal/beach city with a POP) | $400M | $2M/mo, equatorial -15% per launch |
| Falcon Punch launch | $60M, 20 pies | - |
| Reuse R&D (Falcon Punch Again) | $500M; launch $30M; booster lost $40M | - |
| Heavy R&D (Starshipping & Handling) | $3B; $100M/launch, 100 pies, first 3 test flights explode | - |
| Insurance | 8% of launch, optional | - |
| Pie dish (city with a POP) | $25M + $2M per antenna | $300k/mo |
| Landing rights | $10M-$100M per country by market size | yearly |
| LEO-IX port | $50M | $1M/mo |
| Founder launch party | $2M per launch, automatic | - |
Crusts: short 550 km / 1584 full / |lat|<=53; frozen 560 km / 520 / polar; upper 1100 km / 1200 / |lat|<=60;
flaky 340 km / 2500 / dense cities, life 3y. Life 5y otherwise. Coverage < 60% = half-baked: carries 0 under 40%, then a share growing to all of it at 60% (pieCarry). Pies wear out over the last 30% of their life, a few a day (pieAlive), not a whole launch month at once.
## Routing (rules O2-O4)
Crust > 40% = virtual hub (capacity pieCap = g x coverage x carry). Live, licensed, connected dish <-> hub edge: latency (alt up+down)/c + 2 ms.
With lasers: hub-to-hub along great circle at c (vacuum). Capacity = min(crust cap x coverage,
antennas x Gbps x rain). Orbit never beats fiber under ~3000 km. Graph grows by dishes + crusts only.
Dishes with no path to the backbone carry no transit (O3), but backhaul their own POP: all its traffic (eyeballs, customers,
circuits) goes up its dish and down at a landing dish on the backbone (bent pipe <= 1,000 km, lasers past that). Capacity =
min(cut-off dish's room after terminals, landing dish's room, crust's room); latency = the orbit path. Spats, safe mode, a
down crust, landing rights or a backhoe cut it. Must not slow `compute()` for saves without pies.
## Customers
`pizza` (homes/boats), `flywifi` (airlines, latency), `boat` (cruise). `mars` gets an orbit option only
in `pieV` saves. Remote cities (Pitcairn, Arctic) servable from orbit.
## Incidents (`rule('chaos')`, quiet 90 days after unlock)
Rapid Unscheduled Disassembly, booster falls over, solar storm (safe mode), food fight (debris, rare,
Space Roomba fix), rain fade, backhoe at the dish, astronomers (VisorSat), Founder posts at 3 a.m.,
chaos monkey snips a laser link.
A solar storm also puts Starblink, the rented LEO tier at your teleports (#83), in safe mode for a day or two.
## Geopolitical spats (cartoon, even-handed, countries as data, never real leaders)
Reuse the existing sanctions / sovereign-drill / China licence machinery where it fits.
- Landing rights: each country licenses separately; big markets cost most; some refuse for a while.
- Data stays home: a country requires an in-country pie dish for its customers.
- Spectrum squabble: two neighbours both want the same band; pick a side, the other closes for 180 days.
- Kill switch, please: a government wants an off switch during "national exam week"; comply (customer
mood drop) or refuse (licence suspended 90 days).
- Orbital land grab: a rival constellation's home regulator files first; your next crust costs more.
- Jamming near a border: capacity over a region drops for some days.
- Launch diplomacy: a country offers a subsidised pad if you build 3 dishes there.
- Not over my airspace: two countries each demand their traffic avoid the other's dishes.
Each spat is a notification with 2 choices; outcomes deterministic per seed.
## Government money (`60-features/99-pie-subsidies.js`, a section of the bank)
- Rural Digital Pie Fund: reverse auctions for towns only orbit reaches (a cut-off POP on backhaul, or a small town of
your terminal customers). You ask 90%, 70% or 50% of the reserve; a rival asks 40-100%; the lower ask wins and is paid
monthly for 5 years. From a 90-day deadline the town's service, averaged per month, must stay at 70%, or the award is
revoked and half of what it paid is clawed back. Counts in `book.earned`.
- Ex-Im Pie Bank: a BANKS loan (never offered by the usual banks) of half the value of the pies flying and booked, at most
20% of a full Shortcrust (O7 counts it), 1.5-2.5% over 60 months. Covenants: launch n pies in a year, keep a dish in the
lending country. A breach: the bank's penalty, +3 points, the launch deadline moved, and with chaos a spat there
(`home` or `lic`). Off the books: financing, not orbit income.
- Pitcairn: served from orbit (its POP on backhaul, or home terminals there) at 90% of its demand, latency forgiven, the UK
pays `GRANT_SKY_MO` instead of `GRANT_MO`. Counts in `book.earned`.
## Visualisation: a separate animated 3D globe
Satellites are NEVER drawn on the existing map (no cost there). The map only gets static pie dish icons
at POPs, drawn with the existing city layer. Satellites live on an animated 3D globe (orthographic
projection on a 2D canvas, no WebGL, no library) inside the Pie Control panel, rendered only while it is
open, paused when hidden, capped frame budget, fewer dots on phones. Final look is chosen from mockups.
## Rules O1-O7 (`gameplay-rules` skill + tests)
O1 gate, O2 half-baked carries nothing / capacity <= dishes, O3 disconnected dish no transit, O4 vacuum
latency, never beats fiber < 3000 km, O5 chaos + 90 quiet days, O6 rideshare <= demand,
O7 fresh Tier 1 cannot afford a full Shortcrust in year 1; full constellation never pays back < 5 years.
O8 (the rented LEO tier, #83): Starblink sells no new gateway, circuit or growth once a crust of yours carries
traffic; circuits already rented keep running, billed with the teleports, never on `S.pie.book`.
## Every change
Translated strings via `scripts/i18n-add.js` (0/0/0), sanitize, phones first, a seeded test
(`tests/pie-in-the-sky.test.js` and friends), perf vs `main` (`npm run perf -- --base-ref main`) must not
get worse, CHANGELOG bullet under `## [Unreleased]`.

File diff suppressed because it is too large Load diff

890
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,37 +1,17 @@
{ {
"name": "seriesoftubes", "name": "seriesoftubes",
"version": "3.5.0", "version": "1.3.0",
"description": "A cartoon browser game about building the internet.", "description": "A cartoon browser game about building the internet.",
"private": true, "private": true,
"license": "MIT",
"homepage": "https://seriesoftub.es/", "homepage": "https://seriesoftub.es/",
"repository": { "repository": { "type": "git", "url": "git+https://github.com/fjaeckel/seriesoftubes.git" },
"type": "git",
"url": "git+https://github.com/fjaeckel/seriesoftubes.git"
},
"scripts": { "scripts": {
"test": "node scripts/test.js", "test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js",
"test:timings": "node scripts/test-timings.js", "build": "bash scripts/build.sh",
"build": "node scripts/build.js", "serve": "npm run build && npx --yes serve@14.2.4 _site"
"i18n:check": "node scripts/i18n-check.js",
"i18n:fix": "node scripts/i18n-check.js --fix",
"dev": "node scripts/dev.js",
"page": "node scripts/lib/page.js",
"serve": "npm run build && npx --yes serve@14.2.4 _site",
"perf": "node scripts/perf-bench.js",
"bench:gpu": "node scripts/gpu-bench.js",
"mcp": "node scripts/mcp.js",
"mcp:browser": "node scripts/mcp.js --browser",
"mp": "node scripts/mp-server.js"
},
"engines": {
"node": ">=20"
}, },
"engines": { "node": ">=20" },
"devDependencies": { "devDependencies": {
"@modelcontextprotocol/node": "2.1.2", "jsdom": "24.1.3"
"@modelcontextprotocol/server": "2.4.0",
"jsdom": "31.0.0",
"playwright-core": "1.65.0",
"ws": "8.22.1"
} }
} }

View file

@ -1,115 +0,0 @@
#!/usr/bin/env node
// The agent relay: a WebSocket router between the game page and tool clients. The page (src/agent/80-relay.js, agent
// mode in Settings) connects as the one "page"; tools (the MCP server, a script) connect as "tool" peers and send
// {kind:'call', id, tool, args}, which the relay routes to the page and back as {kind:'result', id, ...}. It holds no
// game state and knows no game logic: a dumb router (every client states its role; there is no token), so the whole
// player/operator boundary stays in the page's facade and in the driver.
//
// The relay rides the page's own HTTP server, on the same port, at the path AGENT_PATH: there is no second port, and
// the page infers its endpoint from where it was loaded (location.host). `npm run dev` hosts it in-process
// (scripts/dev.js); `createRelay({ server })` is the whole file, shared by the dev server and the tests.
//
// Security: no token. The bind address is the dev server's --host, loopback unless the operator chooses otherwise;
// what can reach that address may drive a game whose player turned agent mode on. What no bind address opens up: a
// website in the player's browser dialing the relay. Browsers send Origin on every WebSocket handshake and Node
// clients do not, and an Origin that does not name this very host (the page's own server) is refused below.
// Same-origin alone would let DNS rebinding through (evil.example re-pointed at 127.0.0.1 is "same-origin" with
// itself), so the Host must also be an address, never a name: an IP literal, localhost or *.localhost. Every client
// still states its role before anything routes, and one page at a time: a new page replaces the old one (a reload).
const { WebSocketServer } = require('ws');
const AUTH_MS = 5000; // a client must state its role within this, or the socket closes
const AGENT_PATH = '/agent'; // the relay's path on the page's own HTTP port
// `server`: the http.Server that serves the game page. The WebSocket rides it, same port.
// Host header → whether it names this machine by address (IP literal, localhost) rather than by a
// DNS name someone else controls.
function hostOk(h) {
if (typeof h !== 'string' || !h) return false;
let name;
try { name = new URL(`http://${h}`).hostname.toLowerCase(); } catch { return false; }
return name === 'localhost' || name.endsWith('.localhost') || /^\[[0-9a-f:.]+\]$/.test(name) || /^\d{1,3}(\.\d{1,3}){3}$/.test(name);
}
function createRelay({ server } = {}) {
if (!server) throw new Error('createRelay needs the http.Server that serves the page');
const wss = new WebSocketServer({ server, path: AGENT_PATH });
let page = null; // the one connected game page
const tools = new Set(); // connected tool clients
const pending = new Map(); // relay-scoped call id → {tool, id, page}
let seq = 0;
const send = (ws, o) => { if (ws.readyState === 1) ws.send(JSON.stringify(o)); };
// Presence goes both ways: tools learn whether a page is connected, the page learns how many
// tools are — agent mode holds the game's clock while none are (src/agent/80-relay.js).
const presence = () => {
const p = !!(page && page.readyState === 1);
const n = [...tools].filter((t) => t.readyState === 1).length;
for (const t of tools) send(t, { kind: 'presence', page: p });
if (page) send(page, { kind: 'presence', tools: n });
};
wss.on('connection', (ws, req) => {
// Browsers send Origin on every WebSocket handshake, Node clients (our tools) never do.
// Same-origin only, host against Host: a foreign site must not dial the loopback relay
// and drive (or replace) the game — this closes that hole at no cost to either side.
if (!hostOk(req.headers.host)) { ws.close(4004, 'bad host'); return; }
const origin = req.headers.origin;
if (origin) {
let host = null;
try { host = new URL(origin).host; } catch { host = null; }
if (!host || host !== req.headers.host) { ws.close(4004, 'bad origin'); return; }
}
let role = null;
const authTimer = setTimeout(() => { if (!role) ws.close(4003, 'no auth'); }, AUTH_MS);
const dead = () => {
clearTimeout(authTimer);
if (ws === page) {
page = null;
// Answer the calls this page was sent with, so no tool waits out its timeout: the
// call is lost (reload, tab closed, replaced), not pending — say so, at once.
for (const [id, p] of [...pending]) if (p.page === ws) {
pending.delete(id);
send(p.tool, { kind: 'result', id: p.id, error: 'the game page disconnected before answering (reload or another tab took over)' });
}
}
tools.delete(ws);
for (const [id, p] of [...pending]) if (p.tool === ws) pending.delete(id);
presence(); // tools left: the page must know, to hold its clock
};
ws.on('message', (data) => {
let m; try { m = JSON.parse(String(data)); } catch { return; }
if (!m || typeof m !== 'object') return;
if (!role) {
if (m.kind !== 'auth' || (m.role !== 'page' && m.role !== 'tool')) { ws.close(4001, 'bad role'); return; }
role = m.role; clearTimeout(authTimer);
if (role === 'page') { if (page && page.readyState === 1) page.close(4000, 'replaced'); page = ws; presence(); }
else { tools.add(ws); presence(); }
return;
}
if (role === 'tool' && m.kind === 'call' && m.id !== undefined && typeof m.tool === 'string') {
if (!page || page.readyState !== 1) { send(ws, { kind: 'result', id: m.id, error: 'no game page connected: open the game in a browser with the relay on in Settings' }); return; }
const id = 'r' + (++seq);
pending.set(id, { tool: ws, id: m.id, page });
send(page, { kind: 'call', id, tool: m.tool, args: m.args || {} });
return;
}
if (role === 'page' && m.kind === 'result' && m.id !== undefined) {
const p = pending.get(m.id); if (!p) return;
pending.delete(m.id);
send(p.tool, { kind: 'result', id: p.id, dayBefore: m.dayBefore, dayAfter: m.dayAfter, value: m.value, error: m.error });
}
});
ws.on('close', dead);
ws.on('error', () => dead());
});
return {
wss, path: AGENT_PATH,
// What the relay holds right now, so tests wait for a state instead of sleeping.
status: () => ({ page: !!(page && page.readyState === 1), tools: [...tools].filter((t) => t.readyState === 1).length, calls: pending.size }),
close() { for (const c of [page, ...tools]) { try { c.close(4002, 'relay shutdown'); } catch {} } try { wss.close(); } catch {} },
};
}
module.exports = { createRelay };

View file

@ -1,73 +0,0 @@
#!/usr/bin/env node
// Builds the deployable site into _site/ (or $OUT) for GitHub Pages: copies the static files in site/,
// assembles the game page from src/ into one index.html, and stamps the version (from package.json) and
// the build date into the files that carry them. The output is plain static files and nothing else,
// because GitHub Pages is where the game lives (docs/adr/0001-github-pages-only.md).
//
// npm run build VERSION, BUILD_DATE and OUT can be set in the environment
// REQUIRE_NOTES=1 npm run build fail when CHANGELOG.md has no bullets for this version
// MP_API=/api/mp npm run build a self-hosted copy with multiplayer (docs/MULTIPLAYER.md): the
// page talks to scripts/mp-server.js at that path, same origin, and
// has the server-run play (src/game/98-server-play/) and its SIM_ID
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const { shipped, simId, assemble, ROOT } = require('./lib/page');
const VERSION = process.env.VERSION || require(path.join(ROOT, 'package.json')).version;
const BUILD_DATE = process.env.BUILD_DATE || new Date().toISOString().slice(0, 10);
const OUT = path.resolve(ROOT, process.env.OUT || '_site');
const die = (msg) => { console.error(`error: ${msg}`); process.exit(1); };
if (!/^[0-9]+\.[0-9]+\.[0-9]+([-.+][0-9A-Za-z.-]+)?$/.test(VERSION)) die(`VERSION '${VERSION}' is not a semantic version`);
if (!/^\d{4}-\d{2}-\d{2}$/.test(BUILD_DATE)) die(`BUILD_DATE '${BUILD_DATE}' is not YYYY-MM-DD`);
if (OUT === ROOT || OUT === path.join(ROOT, 'site') || OUT === path.join(ROOT, 'src')) die(`refusing to build into ${OUT}`);
// Multiplayer is off unless MP_API names the session server's path on the page's own origin ("//host/x" would be
// another host, and the player's token would go there).
const MP_API = process.env.MP_API || '';
if (MP_API && !/^\/(?!\/)[A-Za-z0-9/_-]*[A-Za-z0-9_-]$/.test(MP_API)) die(`MP_API '${MP_API}' must be a path on the same origin, like /api/mp`);
fs.rmSync(OUT, { recursive: true, force: true });
fs.cpSync(path.join(ROOT, 'site'), OUT, { recursive: true });
if (fs.existsSync(path.join(OUT, 'index.html'))) die('site/index.html must not exist: the page is assembled from src/');
// The page and the translations ship with labels shrunk to short ids (docs/adr/0003-translations-by-label.md).
const D = require('./lib/dict');
const { html: page0, dicts } = shipped(Object.fromEntries(D.langs().map((l) => [l, D.read(l).dict])), { mp: !!MP_API });
// Server-run play's build id: only a multiplayer build has one (scripts/lib/page.js simId()).
const SIM_ID = MP_API ? simId(assemble({ mp: true }).html) : '';
fs.writeFileSync(path.join(OUT, 'index.html'), page0);
for (const [lang, dict] of Object.entries(dicts)) fs.writeFileSync(path.join(OUT, 'i18n', `${lang}.js`), D.format(lang, '', dict));
for (const f of ['index.html', 'sitemap.xml', 'llms.txt', 'sw.js']) {
const p = path.join(OUT, f);
fs.writeFileSync(p, fs.readFileSync(p, 'utf8').replaceAll('__VERSION__', VERSION).replaceAll('__BUILD_DATE__', BUILD_DATE));
}
// Release notes for this version, baked into the page ("What's new") and published as version.json so
// open games can spot a newer release.
const notes = execFileSync(process.execPath, [path.join(__dirname, 'release-notes.js'), VERSION], { encoding: 'utf8' });
if (process.env.REQUIRE_NOTES === '1' && notes === '[]') die(`CHANGELOG.md has no '## [${VERSION}]' section with bullets (still under [Unreleased]?)`);
const page = path.join(OUT, 'index.html'), PH = '/*__RELEASE_NOTES__*/[]', html = fs.readFileSync(page, 'utf8');
if (!html.includes(PH)) die('release-notes placeholder missing from the page');
// Function replacer: no $& / $$ expansion. Escape "<" so a note can never close the <script>.
// A release can also open with a story (prose before its first bullet), shown in full in "What's new".
const story = execFileSync(process.execPath, [path.join(__dirname, 'release-notes.js'), VERSION, '--story'], { encoding: 'utf8' }), PS = '/*__RELEASE_STORY__*/[]';
if (!html.includes(PS)) die('release-story placeholder missing from the page');
const PM = "/*__MP_API__*/''", PI = "/*__SIM_ID__*/''";
if (!html.includes(PM)) die('multiplayer placeholder missing from the page');
if (!html.includes(PI)) die('server-play build id placeholder missing from the page');
let out = html.replace(PH, () => notes.replace(/</g, '\\u003c')).replace(PS, () => story.replace(/</g, '\\u003c')).replace(PM, () => `'${MP_API}'`);
if (SIM_ID) out = out.replace(PI, () => `'${SIM_ID}'`);
fs.writeFileSync(page, out);
fs.writeFileSync(path.join(OUT, 'version.json'), JSON.stringify({ version: VERSION, date: BUILD_DATE, notes: JSON.parse(notes), story: JSON.parse(story), ...(SIM_ID ? { simId: SIM_ID } : {}) }, null, 2) + '\n');
// Nothing may ship half-stamped.
const left = [];
const scan = (dir) => { for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) scan(p);
else if (/__VERSION__|__BUILD_DATE__/.test(fs.readFileSync(p, 'latin1'))) left.push(path.relative(OUT, p));
} };
scan(OUT);
if (left.length) die(`unreplaced placeholders left in ${left.join(', ')}`);
console.log(`Built Series of Tubes ${VERSION} (${BUILD_DATE}) into ${path.relative(ROOT, OUT) || OUT}/`);

31
scripts/build.sh Executable file
View file

@ -0,0 +1,31 @@
#!/usr/bin/env bash
# Builds the deployable site into _site/: copies site/ and stamps the version
# (from package.json) and the build date into the pages that carry them.
set -euo pipefail
cd "$(dirname "$0")/.."
VERSION="${VERSION:-$(node -p "require('./package.json').version")}"
BUILD_DATE="${BUILD_DATE:-$(date -u +%Y-%m-%d)}"
rm -rf _site
cp -R site _site
for f in _site/index.html _site/sitemap.xml _site/llms.txt; do
sed -i.bak -e "s/__VERSION__/${VERSION}/g" -e "s/__BUILD_DATE__/${BUILD_DATE}/g" "$f"
rm -f "$f.bak"
done
# Release notes for this version, baked into the page ("What's new") and
# published as version.json so open games can spot a newer release.
NOTES="$(node scripts/release-notes.js "$VERSION")"
node -e '
const fs=require("fs"),[,v,d,notes]=process.argv;
const f="_site/index.html";
fs.writeFileSync(f,fs.readFileSync(f,"utf8").replace("/*__RELEASE_NOTES__*/[]",notes));
fs.writeFileSync("_site/version.json",JSON.stringify({version:v,date:d,notes:JSON.parse(notes)},null,2)+"\n");
' "$VERSION" "$BUILD_DATE" "$NOTES"
if grep -rl "__VERSION__\|__BUILD_DATE__" _site >/dev/null; then
echo "error: unreplaced placeholders left in _site" >&2
exit 1
fi
echo "Built Series of Tubes ${VERSION} (${BUILD_DATE}) into _site/"

View file

@ -1,88 +0,0 @@
#!/usr/bin/env node
// Development server: http://127.0.0.1:8080 (--host/--port, or HOST=/PORT=, to change). The page is assembled from
// src/ on every request, static files come straight from site/, and the browser reloads itself when you save a file.
// The page is not version-stamped, so the game runs in dev mode (IS_DEV) like a local copy always has, and it is
// the development page: with the agent facade (src/agent/, window.TUBES) that the page players get has not.
// The agent relay rides this same server, same port, path /agent: agent mode in the game's Settings dials it, and
// tools (node scripts/mcp.js --browser) drive the page this server serves.
// Binds loopback by default; --host binds wherever the operator chooses, the relay with it. Plain node:http and the
// relay's ws. For the production build as GitHub Pages will serve it: npm run serve.
// --mp also runs the multiplayer API (docs/MULTIPLAYER.md) at /api/mp, sessions kept in mp-data/, and turns multiplayer
// on in the page: two browser windows (or a private one) can then play one session locally.
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const { assemble, ROOT } = require('./lib/page');
const { createRelay } = require('./agent/relay');
const { lit } = require('./lib/js-literal');
// --host/--port; a bare --host binds loopback (never undefined, which would listen on every interface).
const argOf = (k) => { const i = process.argv.indexOf(k); return i >= 0 && process.argv[i + 1] && !process.argv[i + 1].startsWith('--') ? process.argv[i + 1] : null; };
const HOST = argOf('--host') || process.env.HOST || '127.0.0.1';
const PORT = (() => { const p = +argOf('--port'); return Number.isInteger(p) && p > 0 && p < 65536 ? p : (+process.env.PORT || 8080); })();
const SITE = path.join(ROOT, 'site');
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css', '.json': 'application/json',
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml',
'.webmanifest': 'application/manifest+json' };
const RELOAD = '<script>new EventSource("/__dev").onmessage=()=>location.reload()</script>';
const MP = process.argv.includes('--mp') ? require('./lib/mp').createMp({ dir: path.join(ROOT, 'mp-data'), createPerHour: 1000, joinPerHour: 1000, log: (s) => console.error(s) }) : null;
const clients = new Set();
function page() {
const { html, map } = assemble({ dev: true });
// Errors report a line of the assembled page; the console also says which file under src/ that is.
const hint = `<script>addEventListener('error',e=>{const n=e.lineno,m=n&&(${lit(map)}).find(m=>n>=m.from&&n<=m.to);if(m)console.warn('↑ src/'+m.file+':'+(n-m.from+1))});</script>`;
return (MP ? html.replace("/*__MP_API__*/''", () => "'/api/mp'") : html).replace('</body>', `${hint}${RELOAD}</body>`);
}
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (MP && MP.handle(req, res)) return;
if (url.pathname === '/__dev') {
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });
res.write(': hi\n\n');
clients.add(res);
req.on('close', () => clients.delete(res));
return;
}
try {
if (url.pathname === '/' || url.pathname === '/index.html') {
res.writeHead(200, { 'content-type': TYPES['.html'], 'cache-control': 'no-store' });
return res.end(page());
}
const file = path.join(SITE, path.normalize(decodeURIComponent(url.pathname)).replace(/^([/\\]|\.\.)+/, ''));
if (!file.startsWith(SITE + path.sep) || !fs.statSync(file, { throwIfNoEntry: false })?.isFile()) {
res.writeHead(404, { 'content-type': TYPES['.html'] });
return res.end(fs.readFileSync(path.join(SITE, '404.html')));
}
res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' });
fs.createReadStream(file).pipe(res);
} catch (e) {
// The stack goes to the terminal running the server, never into the response.
console.error(e);
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
res.end('Could not build the page: see the terminal running npm run dev.');
}
});
const relay = createRelay({ server });
server.on('error', (e) => { console.error(`error: could not listen on ${HOST}:${PORT}: ${e.message}`); process.exit(1); });
server.listen(PORT, HOST, () => {
// The banner reports the socket's real address, not the flag it was asked for.
const ad = server.address(), at = `${ad.family === 'IPv6' ? `[${ad.address}]` : ad.address}:${ad.port}`;
const local = /^(127\.|::1$|localhost$)/.test(ad.address);
console.log(`Series of Tubes (dev): http://${at}/ — edits in src/ and site/ reload the page`);
console.error(`[series-of-tubes] agent relay on ws://${at}${relay.path} (no token)${local ? '' : `: bound to ${ad.address}, so anything that can reach this address can drive a game whose player turned agent mode on`}`);
console.error('[series-of-tubes] to let an agent play: Settings → Agent API in the game, then node scripts/mcp.js --browser');
if (MP) console.error(`[series-of-tubes] multiplayer on: API at http://${at}/api/mp, sessions in ${path.relative(ROOT, MP.dir) || MP.dir}/`);
});
const shutdown = () => { relay.close(); process.exit(0); };
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
let timer = null;
for (const dir of ['src', 'site']) {
fs.watch(path.join(ROOT, dir), { recursive: true }, () => {
clearTimeout(timer);
timer = setTimeout(() => { for (const c of clients) c.write('data: reload\n\n'); }, 100);
});
}

View file

@ -1,76 +0,0 @@
#!/usr/bin/env node
// The map's speed on your own graphics card, 2D against WebGL, in the browser you play in:
//
// npm run bench:gpu -- --save path/to/save.json (an exported save, or a plain one; default: the perf fixture)
//
// then open the printed address in Chrome, Edge or Firefox and press Start. Headless benchmarks (npm run perf) draw the
// canvas in software, so they cannot say what a GPU does; this one runs where the GPU is. Each scenario plays a few
// seconds with the 2D map and with the WebGL tubes, the table shows in the page, and the server prints it here when the
// run ends. Options: --port N (8090), --secs N per scenario (6), --host 0.0.0.0 to open it from a phone on your network,
// --out FILE to also write the table there. Under WSL, the Windows browser reaches http://localhost:PORT as it is.
// In the address: ?only=gl or ?only=2d (one renderer), ?scen=x1-mid,pan (some scenarios), ?dpr=2 (a 4K screen's
// pixels on a smaller one), ?auto (start at once). The game's clock keeps running: incidents do not pause it.
const fs = require('node:fs');
const os = require('node:os');
const http = require('node:http');
const path = require('node:path');
const { assemble, ROOT } = require('./lib/page');
const { lit } = require('./lib/js-literal');
const args = process.argv.slice(2);
const opt = (k, d) => { const i = args.indexOf('--' + k); return i >= 0 ? args[i + 1] : d; };
const PORT = +opt('port', 8090), HOST = opt('host', 'localhost'), SECS = +opt('secs', 6), OUT = opt('out', null);
const SAVE = path.resolve(opt('save', path.join(ROOT, 'tests', 'fixtures', 'big-network.json')));
const SITE = path.join(ROOT, 'site');
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css', '.json': 'application/json',
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.webmanifest': 'application/manifest+json' };
// An exported save is {app, version, S}; a plain one is S itself.
const save = (() => { const d = JSON.parse(fs.readFileSync(SAVE, 'utf8')); return JSON.stringify({ S: d && d.S && d.S.pops ? d.S : d }); })();
const client = fs.readFileSync(path.join(__dirname, 'lib', 'gpu-bench-client.js'), 'utf8');
const page = () => assemble().html.replace('</body>', `<script>window.__BENCH__=${lit({ secs: SECS })};</script><script>${client}</script></body>`);
/* Only the page this server hands out may talk to it. Any other site open in the same browser could otherwise
POST results (printed to this terminal, written to --out) or, through DNS rebinding, read the save. So the Host
header must name this server, and a POST must come from its own origin. */
const HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', HOST.includes(':') ? `[${HOST}]` : HOST]);
if (HOST === '0.0.0.0') for (const l of Object.values(os.networkInterfaces()).flat()) if (l && l.family === 'IPv4') HOSTS.add(l.address);
const hostOk = (h) => { const m = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(h || ''); return !!m && HOSTS.has(m[1].toLowerCase()) && (m[2] ? +m[2] : 80) === PORT; };
const MAX_BODY = 2 * 1048576;
// What the page sends is printed and written as text: no terminal escape sequences or other control characters.
const plain = (s) => String(s ?? '').replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u2028\u2029]/g, '');
http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
try {
if (!hostOk(req.headers.host)) { res.writeHead(421); return res.end(); }
if (url.pathname === '/' || url.pathname === '/index.html') { res.writeHead(200, { 'content-type': TYPES['.html'], 'cache-control': 'no-store' }); return res.end(page()); }
if (url.pathname === '/__bench/save.json') { res.writeHead(200, { 'content-type': TYPES['.json'], 'cache-control': 'no-store' }); return res.end(save); }
if (url.pathname === '/__bench/results' && req.method === 'POST') {
if (req.headers.origin !== `http://${req.headers.host}`) { res.writeHead(403); return res.end(); }
let body = '', size = 0, over = false;
req.on('data', (c) => { size += c.length; if (size > MAX_BODY) { over = true; req.destroy(); return; } body += c; });
req.on('end', () => {
if (over) return;
try { const r = JSON.parse(body), md = plain(r && r.md); console.log('\n' + md + '\n'); if (OUT) { fs.writeFileSync(OUT, md + '\n\n```json\n' + plain(JSON.stringify(r, null, 1)) + '\n```\n'); console.log(`(also written to ${OUT})`); } } catch (e) { console.error('bad results:', e.message); }
res.writeHead(204); res.end(); });
return;
}
// The service worker would cache this page over the real one: none here.
if (url.pathname === '/sw.js') { res.writeHead(404); return res.end(); }
const file = path.join(SITE, path.normalize(decodeURIComponent(url.pathname)).replace(/^([/\\]|\.\.)+/, ''));
if (!file.startsWith(SITE + path.sep) || !fs.statSync(file, { throwIfNoEntry: false })?.isFile()) { res.writeHead(404); return res.end(); }
res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' });
fs.createReadStream(file).pipe(res);
} catch (e) {
// A malformed address (decodeURIComponent) or a missing file: the details stay in this terminal.
console.error('bench server:', e && e.message || e);
res.writeHead(e instanceof URIError ? 400 : 500); res.end();
}
}).listen(PORT, HOST, () => {
const s = JSON.parse(save).S;
console.log(`GPU benchmark: ${path.basename(SAVE)} (${Object.keys(s.pops || {}).length} POPs, ${(s.links || []).length} links), ${SECS}s per scenario`);
console.log(`Open http://localhost:${PORT}/ in your browser, press Start and keep the tab in front.`);
if (HOST === '0.0.0.0') for (const l of Object.values(os.networkInterfaces()).flat()) if (l && l.family === 'IPv4' && !l.internal) console.log(` from another device: http://${l.address}:${PORT}/`);
console.log('Ctrl+C to stop.');
});

View file

@ -1,69 +0,0 @@
#!/usr/bin/env node
// Adds, changes, renames or removes labels, keeping every dictionary sorted (scripts/lib/dict.js).
// English is src/i18n/en.js; translations are site/i18n/<lang>.js.
//
// node scripts/i18n-add.js changes.json {"en": {"pnis.ready": "Ready in {n} days"},
// "it": {"pnis.ready": "Pronto tra {n} giorni"},
// "fr": {"pnis.old_label": null}}
// a string sets the text, {"one":…,"other":…} sets a plural,
// null removes it (null under "en" removes it from every language)
// node scripts/i18n-add.js - the same JSON from stdin
// node scripts/i18n-add.js --rename old.label new.label in every dictionary and everywhere in src/
const fs = require('node:fs');
const path = require('node:path');
const D = require('./lib/dict');
const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/;
const all = () => ['en', ...D.langs()];
const die = (m) => { console.error(m); process.exit(1); };
const args = process.argv.slice(2);
if (args[0] === '--rename') {
const [, from, to] = args;
if (!LABEL.test(from || '') || !LABEL.test(to || '')) die('usage: i18n-add.js --rename old.label new.label');
for (const lang of all()) {
const { header, dict } = D.read(lang);
if (!(from in dict)) continue;
if (to in dict) die(`${lang}: already has ${to}`);
dict[to] = dict[from];
delete dict[from];
D.write(lang, dict, header);
}
// The code: quoted labels in tr()/trn()/N_() calls and tables, and data-i18n attributes.
const { listFiles } = require('./lib/page');
const src = path.join(__dirname, '..', 'src');
let n = 0;
for (const f of listFiles(src)) {
if (f === 'i18n/en.js') continue;
const p = path.join(src, f), t = fs.readFileSync(p, 'utf8');
const u = t.replace(new RegExp(String.raw`(['"\x60])${from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\1`, 'g'), (m, q) => { n++; return q + to + q; });
if (u !== t) fs.writeFileSync(p, u);
}
console.log(`renamed ${from} → ${to} in every dictionary and ${n} place(s) in src/`);
process.exit(0);
}
if (args.length !== 1) die('usage: i18n-add.js changes.json | - | --rename old.label new.label');
const changes = JSON.parse(fs.readFileSync(args[0] === '-' ? 0 : args[0], 'utf8'));
const en = D.read('en').dict;
const order = Object.keys(changes).sort((a, b) => (a === 'en' ? -1 : b === 'en' ? 1 : 0)); // English first
for (const lang of order) {
if (!all().includes(lang)) die(`no dictionary for ${lang} (English is src/i18n/en.js, translations site/i18n/<lang>.js)`);
const { header, dict } = lang === 'en' ? { header: D.read('en').header, dict: en } : D.read(lang);
let set = 0, del = 0;
for (const [label, v] of Object.entries(changes[lang])) {
if (!LABEL.test(label)) die(`${lang}: ${JSON.stringify(label)} is not a label like 'area.some_words'`);
if (v === null) {
if (label in dict) { delete dict[label]; del++; }
if (lang === 'en') for (const l of D.langs()) { const d = D.read(l); if (label in d.dict) { delete d.dict[label]; D.write(l, d.dict, d.header); } }
continue;
}
const ok = typeof v === 'string' ? !!v.trim() : v && typeof v.one === 'string' && typeof v.other === 'string' && v.one.trim() && v.other.trim();
if (!ok) die(`${lang}: ${label}: give a non-empty string, or {"one": …, "other": …}`);
if (lang !== 'en' && !(label in en)) die(`${lang}: ${label} has no English yet; add it under "en" first`);
if (lang !== 'en' && (typeof v === 'string') !== (typeof en[label] === 'string')) die(`${lang}: ${label} must be ${typeof en[label] === 'string' ? 'a string' : 'a plural {one, other}'} like its English`);
dict[label] = v; set++;
}
D.write(lang, dict, header);
console.log(`${lang}: ${set} set, ${del} removed`);
}

View file

@ -1,167 +0,0 @@
#!/usr/bin/env node
// Checks the translations. Text is keyed by label: tr('area.some_label') in src/ and data-i18n="…"
// (data-i18n-aria-label, data-i18n-title) in src/index.html, with the English in src/i18n/en.js.
//
// node scripts/i18n-check.js [lang ...] [--summary FILE] [--fix] (default: every site/i18n/*.js)
//
// English: every label the code uses is defined, every defined label is used, labels look like
// `area.words`, and the English left in the static markup matches en.js.
// Each translation: nothing missing, nothing stale, and every entry keeps the {placeholders}, HTML tags and
// plural forms of its English. Every dictionary is sorted, one entry per line (--fix sorts them), each
// language is offered in the game and cached for offline play. --summary appends a Markdown coverage table
// (the CI job writes it to the run's summary page).
const fs = require('node:fs');
const path = require('node:path');
const D = require('./lib/dict');
const { CALL } = require('./legacy/labels');
const SITE = path.join(__dirname, '..', 'site');
// The development page of a multiplayer build: it has every label, the agent's (src/agent/) and the server-play
// client's (src/game/98-server-play/, only in MP builds) too. src: another source tree (tests).
const page = (src) => require('./lib/page').assemble({ src, dev: true, mp: true }).html;
const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/;
// The bodies of the page's bare <script> tags. Our own assembled page, so a plain search is enough.
function inlineScripts(html) {
const out = [];
for (let i = html.indexOf('<script>'); i >= 0; i = html.indexOf('<script>', i)) {
const end = html.indexOf('</script>', i += 8);
if (end < 0) break;
out.push(html.slice(i, end)); i = end;
}
return out;
}
// The labels the game uses, with problems in how they are used.
function sourceLabels(html) {
const labels = new Set(), problems = [];
const scripts = inlineScripts(html).join('\n');
for (const m of scripts.matchAll(CALL)) {
const l = m[2].slice(1, -1);
if (!LABEL.test(l)) problems.push(`${m[1]}(${m[2].slice(0, 60)}…): not a label like 'area.some_words'`);
else labels.add(l);
if (m[1] === 'trn' && m[3]) problems.push(`trn(${m[2]}, ${m[3].slice(0, 30)}…): plurals take one label, trn('area.label', n)`);
}
// A label the build cannot see (a bare string, not the first argument of tr/trn/N_) would not be shrunk
// along with its dictionary entry, and would show as raw text in the shipped game.
const code = scripts.replace(/\(window\.I18N=window\.I18N\|\|\{\}\)\.en=\{[\s\S]*?\n\};\n/, '');
const seen = new Set();
for (const m of code.matchAll(CALL)) seen.add(m.index + m[0].indexOf(m[2]));
for (const m of code.matchAll(/(['"\x60])([a-z0-9_]+(?:\.[a-z0-9_]+)+)\1/g)) {
if (!seen.has(m.index) && /_|\.[a-z]+\./.test(m[2]) && !/\.(js|json|html|css|png|svg|es)$/.test(m[2])) problems.push(`label ${m[2]} outside tr()/trn()/N_(): wrap it in N_() so the build can see it`);
}
const { JSDOM } = require('jsdom');
const doc = new JSDOM(html).window.document;
const markup = [];
for (const el of doc.querySelectorAll('[data-i18n]')) markup.push([el.dataset.i18n, el.textContent, 'text']);
for (const a of ['aria-label', 'title']) for (const el of doc.querySelectorAll(`[data-i18n-${a}]`)) markup.push([el.getAttribute(`data-i18n-${a}`), el.getAttribute(a), a]);
for (const el of doc.querySelectorAll('[aria-label]:not([data-i18n-aria-label]),[title]:not([data-i18n-title])')) {
if (!el.closest('noscript')) problems.push(`<${el.tagName.toLowerCase()} ${el.hasAttribute('title') ? 'title' : 'aria-label'}="…"> in the markup has no data-i18n-${el.hasAttribute('title') ? 'title' : 'aria-label'} label`);
}
for (const [l] of markup) LABEL.test(l) ? labels.add(l) : problems.push(`data-i18n="${l}": not a label`);
return { labels, markup, problems };
}
function loadDict(file) {
const lang = path.basename(file, '.js');
return D.parse(fs.readFileSync(file, 'utf8'), lang);
}
const placeholders = (s) => (s.match(/\{\w+\}/g) || []).sort().join(' ');
const tags = (s) => (s.match(/<\/?[a-z][a-z0-9]*/gi) || []).map((t) => t.toLowerCase()).sort().join(' ');
const forms = (v) => (typeof v === 'string' ? [['', v]] : v && typeof v === 'object' ? [['one', v.one], ['other', v.other]] : [['', v]]);
// Entries whose translation is empty, has the wrong shape (plural or not), or drops or invents a
// {placeholder} or an HTML tag. Without `en`, an entry is compared with itself (shape and emptiness only).
function brokenEntries(dict, en = null) {
return Object.entries(dict).filter(([l, xx]) => {
const e = en ? en[l] : xx;
if (e === undefined) return false; // stale, reported as unused
if ((typeof e === 'string') !== (typeof xx === 'string')) return true;
const ef = forms(e), xf = forms(xx);
return xf.some(([k, x], i) => typeof x !== 'string' || !x.trim() || placeholders(ef[i][1]) !== placeholders(x) || tags(ef[i][1]) !== tags(x)) ||
ef.some(([k]) => k && typeof xx[k] !== 'string');
}).map(([l]) => l);
}
function check(en, dict) {
return {
missing: Object.keys(en).filter((k) => !(k in dict)),
unused: Object.keys(dict).filter((k) => !(k in en)),
broken: brokenEntries(dict, en),
};
}
// The English dictionary against the code.
function checkEnglish(src, en) {
const out = [...src.problems];
for (const l of src.labels) if (!(l in en)) out.push(`label used but not in src/i18n/en.js: ${l}`);
for (const l of Object.keys(en)) {
if (!src.labels.has(l)) out.push(`in src/i18n/en.js but never used: ${l}`);
if (!LABEL.test(l)) out.push(`not a label like 'area.some_words': ${l}`);
}
for (const [l, text, where] of src.markup) {
if (typeof en[l] === 'string' && en[l] !== text) out.push(`markup ${where} for ${l} says ${JSON.stringify(text)}, en.js says ${JSON.stringify(en[l])}`);
}
for (const l of brokenEntries(en)) out.push(`empty or malformed English: ${l}`);
if (!D.tidy('en')) out.push('src/i18n/en.js is not sorted one entry per line: run npm run i18n:fix');
return out;
}
module.exports = { loadDict, brokenEntries, sourceLabels, page };
// A language file only works if the game offers it and the offline cache keeps it.
function registration(lang, html) {
const sw = fs.readFileSync(path.join(SITE, 'sw.js'), 'utf8');
const out = [];
const m = html.match(/SOT_LANGS=\{([^}]*)\}/);
if (!m || !new RegExp(String.raw`(^|[,{\s])${lang.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\s*:`).test(m[1])) out.push('not in the language list (SOT_LANGS in src/index.html)');
if (!sw.includes(`/i18n/${lang}.js`)) out.push('not cached for offline play (CORE in site/sw.js)');
if (!D.tidy(lang)) out.push('not sorted one entry per line: run npm run i18n:fix');
return out;
}
if (require.main === module) {
const args = process.argv.slice(2);
const si = args.indexOf('--summary');
const summary = si >= 0 ? args.splice(si, 2)[1] : null; // append a Markdown table here (CI: $GITHUB_STEP_SUMMARY)
const fi = args.indexOf('--fix');
if (fi >= 0) {
args.splice(fi, 1);
for (const lang of ['en', ...(args.length ? args : D.langs())]) { const { header, dict } = D.read(lang); D.write(lang, dict, header); }
}
const html = page();
const en = D.read('en').dict;
const src = sourceLabels(html);
const enProblems = checkEnglish(src, en);
const n = Object.keys(en).length;
console.log(`en.js: ${n} labels, ${enProblems.length} problems`);
for (const p of enProblems) console.log(` ${p}`);
let bad = enProblems.length > 0;
const langs = args.length ? args : D.langs();
const rows = [], results = {};
for (const lang of langs) {
const r = results[lang] = check(en, loadDict(D.fileOf(lang)));
const reg = registration(lang, html);
const cov = n ? (n - r.missing.length) / n : 1;
const pctTxt = `${(Math.floor(cov * 1000) / 10).toFixed(1)}%`;
console.log(`${lang}.js: ${r.missing.length} missing, ${r.unused.length} unused, ${r.broken.length} broken (${pctTxt} of ${n} labels)`);
for (const [label, list] of [['missing', r.missing], ['unused', r.unused], ['broken', r.broken], ['registration', reg]]) {
for (const k of list) console.log(` ${label}: ${k}${label === 'missing' ? ` (${JSON.stringify(forms(en[k])[0][1]).slice(0, 80)})` : ''}`);
}
const ok = r.missing.length + r.unused.length + r.broken.length + reg.length === 0;
bad ||= !ok;
rows.push(`| ${lang} | ${pctTxt} | ${r.missing.length} | ${r.unused.length} | ${r.broken.length} | ${reg.length ? reg.join('; ') : 'ok'} | ${ok ? '✅' : '❌'} |`);
}
if (summary) {
const list = (title, items) => items.length ? `\n<details><summary>${title} (${items.length})</summary>\n\n${items.slice(0, 200).map((k) => '- `' + k.replace(/`/g, "'") + '`').join('\n')}\n</details>\n` : '';
let md = `## Translations\n\n${n} labels in the game${enProblems.length ? `, ${enProblems.length} problems with the English` : ''}.\n\n| Language | Coverage | Missing | Unused | Broken | Registered | |\n|---|---|---|---|---|---|---|\n${rows.join('\n')}\n`;
md += list('English: problems', enProblems);
for (const lang of langs) {
const r = results[lang];
md += list(`${lang}: missing`, r.missing) + list(`${lang}: broken`, r.broken) + list(`${lang}: unused`, r.unused);
}
fs.appendFileSync(summary, md + '\n');
}
process.exit(bad ? 1 : 0);
}

View file

@ -1,138 +0,0 @@
// Turns English-keyed translation calls into label-keyed ones, for code written before labels (1.34 and
// older): tr('Delivery: about a month') → tr('pnis.delivery_about_a_month'), trn('{n} POP','{n} POPs',n)
// → trn('common.n_pop',n), and data-i18n markup → data-i18n="page.…". It is how src/ got its labels, and
// transforms.js runs it on old branches so their work lines up with src/ (see port-branch.js).
//
// Labels for text that already has one come from `known` (the English dictionary, src/i18n/en.js);
// new text gets a label made from its first words and where it is used, the same way every time.
const vm = require('node:vm');
const LIT = String.raw`'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|\x60(?:[^\x60\\$]|\\.|\$(?!\{))*\x60`;
const CALL = new RegExp(String.raw`(?<![\w$.])(tr|trn|N_)\(\s*(${LIT})(?:\s*,\s*(${LIT}))?`, 'g');
const CTX = vm.createContext({});
const literal = (s) => vm.runInContext(s, CTX);
const hash = (t) => { let h = 2166136261; for (let i = 0; i < t.length; i++) { h ^= t.charCodeAt(i); h = Math.imul(h, 16777619); } return (h >>> 0).toString(16).padStart(8, '0'); };
// "<b>Laser shortage!</b> {n} days…" → "laser_shortage_n_days"
function slug(text) {
const words = text.replace(/<[^>]*>/g, ' ').normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase()
.replace(/[^a-z0-9]+/g, ' ').trim().split(' ').filter(Boolean);
let s = '';
for (const w of words) { if (s && (s + '_' + w).length > 36) break; s = s ? s + '_' + w : w; if (s.split('_').length >= 6) break; }
return s || 'x';
}
// "game/70-rules/30-pnis.js" → "pnis"; the shell → "page".
const areaOf = (file) => file === 'index.html' ? 'page' : file.split('/').pop().replace(/^\d+-/, '').replace(/\.[a-z]+$/, '').replace(/-/g, '_');
const folderOf = (file) => file === 'index.html' ? 'page' : file.split('/').slice(0, -1).pop().replace(/^\d+-/, '').replace(/-/g, '_');
// A plural is keyed by both forms.
const pkey = (one, other) => `${one}\u0000${other}`;
const ENT = { amp: '&', lt: '<', gt: '>', quot: '"', '#39': "'", apos: "'", nbsp: ' ' };
const decode = (s) => s.replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g, (m, e) => ENT[e]);
// Every translatable text in the partials: [{file, kind:'call'|'markup'|'attr', key, one, other, …}].
function scan(parts) {
const out = [];
for (const [file, text] of parts) {
if (file.endsWith('.js') || file === 'index.html') {
for (const m of text.matchAll(CALL)) {
if (file === 'index.html' && !inScript(text, m.index)) continue;
if (m[1] === 'trn') {
if (!m[3]) throw new Error(`${file}: trn() needs two literal forms: ${m[0].slice(0, 60)}`);
const one = literal(m[2]), other = literal(m[3]);
out.push({ file, kind: 'call', fn: 'trn', key: pkey(one, other), one, other, at: m.index + m[0].indexOf(m[2]), end: m.index + m[0].length });
} else {
const t = literal(m[2]);
out.push({ file, kind: 'call', fn: m[1], key: t, text: t, at: m.index + m[0].indexOf(m[2]), end: m.index + m[0].indexOf(m[2]) + m[2].length });
}
}
}
if (file === 'index.html') {
for (const m of text.matchAll(/<([a-z][a-z0-9]*)\b([^>]*?)\sdata-i18n>([^<]*)<\/\1>/g)) {
out.push({ file, kind: 'markup', key: decode(m[3]), text: decode(m[3]), at: m.index + m[0].indexOf(' data-i18n>'), end: m.index + m[0].indexOf(' data-i18n>') + ' data-i18n'.length });
}
for (const m of text.matchAll(/<[a-z][a-z0-9]*\b[^>]*>/g)) {
if (inScript(text, m.index)) continue;
for (const a of m[0].matchAll(/\s(aria-label|title)="([^"]*)"/g)) {
const pos = m.index + a.index + a[0].length;
out.push({ file, kind: 'attr', attr: a[1], key: decode(a[2]), text: decode(a[2]), at: pos, end: pos });
}
}
}
}
return out;
}
// Inside one of the shell's <script> elements (the language loader), where text is code, not markup.
function inScript(html, i) {
const open = html.lastIndexOf('<script', i), close = html.lastIndexOf('</script>', i);
return open > close;
}
// Labels for every text in the scan: known ones from `known` (Map key → label), new ones made here.
function assign(items, known) {
const labels = new Map(known), taken = new Set(known.values());
const files = new Map();
for (const it of items) { if (!files.has(it.key)) files.set(it.key, new Set()); files.get(it.key).add(it.file); }
for (const it of items) {
if (labels.has(it.key)) continue;
const fs = [...files.get(it.key)];
const folders = new Set(fs.map(folderOf));
// Short, plain words ("Off", "Close", "Customers") are shared vocabulary wherever they appear.
const short = !/[{<]/.test(it.one ?? it.text) && slug(it.one ?? it.text).split('_').length <= 2;
const area = short ? 'common' : fs.length === 1 ? areaOf(fs[0]) : folders.size === 1 ? [...folders][0] : 'common';
const base = `${area}.${slug(it.one ?? it.text)}`;
let l = base;
if (taken.has(l)) l = `${base}_${hash(it.key).slice(0, 4)}`;
if (taken.has(l)) l = `${base}_${hash(it.key)}`;
labels.set(it.key, l);
taken.add(l);
}
return labels;
}
// Rewrites the partials to use labels. Returns {parts, en}: en maps each label to its English
// (a string, or {one, other} for plurals), for every text these partials use.
function labelize(parts, known = new Map()) {
const items = scan(parts);
const labels = assign(items, known);
const en = new Map();
const byFile = new Map();
for (const it of items) {
const l = labels.get(it.key);
en.set(l, it.fn === 'trn' ? { one: it.one, other: it.other } : it.text);
if (!byFile.has(it.file)) byFile.set(it.file, []);
byFile.get(it.file).push({ ...it, label: l });
}
const out = parts.map(([file, text]) => {
const list = (byFile.get(file) || []).sort((a, b) => b.at - a.at);
for (const it of list) {
const rep = it.kind === 'call' ? `'${it.label}'`
: it.kind === 'markup' ? ` data-i18n="${it.label}"`
: ` data-i18n-${it.attr}="${it.label}"`;
text = text.slice(0, it.at) + rep + text.slice(it.end);
}
return [file, text];
});
return { parts: out, en, labels };
}
// The `known` map from an English dictionary object {label: text | {one, other}}.
function knownFrom(enDict) {
const k = new Map();
for (const [l, v] of Object.entries(enDict || {})) k.set(typeof v === 'string' ? v : pkey(v.one, v.other), l);
return k;
}
// A dictionary keyed by English text (it.js before labels) → keyed by label, using the labels made above.
function relabelDict(old, labels) {
const out = {};
for (const [key, l] of labels) {
if (key.includes('\u0000')) {
const [one, other] = key.split('\u0000');
if (typeof old[one] === 'string' && typeof old[other] === 'string') out[l] = { one: old[one], other: old[other] };
} else if (typeof old[key] === 'string') out[l] = old[key];
}
return out;
}
module.exports = { labelize, knownFrom, relabelDict, scan, slug, pkey, CALL, LIT };

View file

@ -1,134 +0,0 @@
#!/usr/bin/env node
// Carries a branch that still edits site/index.html (started before the page was split into src/) over
// to the src/ layout. Run it in the middle of merging main into that branch:
//
// git checkout my-branch
// git merge origin/main # stops: site/index.html was deleted on main
// node scripts/legacy/port-branch.js # moves your edits into src/, merges the dictionaries
// git status # fix any conflict markers it reports, then
// git commit
//
// How: your branch's site/index.html and the one you started from are both split with the same rules
// that made src/ (split-index-html.js + transforms.js), and each partial gets a three-way merge
// (git merge-file) into the src/ file from main. Your dictionary changes (site/i18n/*.js) are applied
// entry by entry onto main's sorted dictionaries, so appended lines never conflict. Text keyed by English
// (1.34 and older) gets the labels src/ uses, and new text gets new labels in src/i18n/en.js (labels.js).
//
// It also works the other way round, merging commits made on the old layout into a branch that has src/.
// Options: --base REF (the pre-split commit the old-layout side started from; default: merge-base of HEAD
// and MERGE_HEAD) and --theirs REF (the old-layout side; default: whichever side has site/index.html).
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync, spawnSync } = require('node:child_process');
const { split } = require('./split-index-html');
const { transformFull } = require('./transforms');
const { relabelDict } = require('./labels');
const D = require('../lib/dict');
const ROOT = path.join(__dirname, '..', '..');
const args = process.argv.slice(2);
const opt = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };
const git = (...a) => execFileSync('git', a, { cwd: ROOT, encoding: 'utf8', maxBuffer: 1 << 28, stdio: ['ignore', 'pipe', 'pipe'] });
const show = (ref, p) => { try { return git('show', `${ref}:${p}`); } catch { return null; } };
const die = (m) => { console.error(`port-branch: ${m}`); process.exit(1); };
let mergeHead = null;
try { mergeHead = git('rev-parse', '-q', '--verify', 'MERGE_HEAD').trim(); } catch {}
// Works in both directions: merging main into an old branch, or old-layout commits into a src/ branch.
// "theirs" is the side that still has site/index.html; the other side (with src/) is the target.
const hasSrc = (ref) => show(ref, 'src/index.html') !== null;
const theirs = opt('--theirs', null) || (mergeHead && hasSrc('HEAD') ? mergeHead : 'HEAD');
const target = mergeHead ? (theirs === mergeHead ? 'HEAD' : mergeHead) : null;
const base = opt('--base', null) || (mergeHead ? git('merge-base', 'HEAD', mergeHead).trim() : null);
if (!base) die('no merge in progress: run `git merge origin/main` first, or pass --base REF');
if (!fs.existsSync(path.join(ROOT, 'src', 'index.html'))) die('src/ is missing: merge main (which has src/) first');
const basePage = show(base, 'site/index.html'), theirPage = show(theirs, 'site/index.html');
if (!basePage) die(`${base} has no site/index.html; is it from before the split?`);
if (!theirPage) die(`${theirs} has no site/index.html; nothing to port`);
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-port-'));
const parts = (html, label) => {
try { const r = transformFull(split(html)); return Object.assign(new Map(r.parts), { labels: r.labels }); }
catch (e) { die(`could not split ${label}'s site/index.html the way src/ was made: ${e.message}`); }
};
const B = parts(basePage, 'the base'), T = parts(theirPage, 'your branch');
let changed = 0;
const conflicts = [];
// Applies the entries that changed between two dictionaries onto a third, reporting entries changed on both sides.
const same = (x, y) => JSON.stringify(x) === JSON.stringify(y); // plurals are objects
function applyDelta(db, dt, dict, rel) {
let n = 0;
for (const k of new Set([...Object.keys(db), ...Object.keys(dt)])) {
if (same(db[k], dt[k])) continue;
if (k in dict && !same(db[k], dict[k]) && !same(dict[k], dt[k]) && k in dt) conflicts.push(`${rel}: ${JSON.stringify(k)} changed on both sides (kept yours)`);
if (k in dt) dict[k] = dt[k]; else delete dict[k];
n++;
}
return n;
}
for (const [file, t] of T) {
const b = B.get(file);
if (b === t) continue; // you did not touch this part
if (file === 'i18n/en.js') {
// English is merged entry by entry, like the translations below.
const e = D.read('en');
const n = applyDelta(b ? D.parse(b, 'en') : {}, D.parse(t, 'en'), e.dict, 'src/i18n/en.js');
D.write('en', e.dict, e.header);
git('add', 'src/i18n/en.js');
console.log(`src/i18n/en.js: ${n} of your entries applied`);
continue;
}
const ours = path.join(ROOT, 'src', file);
if (!fs.existsSync(ours)) { conflicts.push(`${file} (no longer exists on main; apply your change by hand)`); continue; }
const fb = path.join(tmp, 'base'), ft = path.join(tmp, 'theirs');
fs.writeFileSync(fb, b || '');
fs.writeFileSync(ft, t);
const r = spawnSync('git', ['merge-file', '-L', 'main', '-L', 'base', '-L', 'your branch', ours, fb, ft], { cwd: ROOT });
changed++;
if (r.status !== 0) conflicts.push(`src/${file}`);
}
// Text your side still uses (for example inside a conflict) whose English main has since changed or dropped:
// keep its English, so whichever side of the conflict you keep has its text.
{
const tEn = T.get('i18n/en.js') ? D.parse(T.get('i18n/en.js'), 'en') : {};
const e = D.read('en');
const used = new Set();
for (const f of require('../lib/page').listFiles(path.join(ROOT, 'src'))) {
if (f === 'i18n/en.js') continue;
for (const m of fs.readFileSync(path.join(ROOT, 'src', f), 'utf8').matchAll(/['"]([a-z0-9_]+(?:\.[a-z0-9_]+)+)['"]/g)) used.add(m[1]);
}
const back = [...used].filter((l) => !(l in e.dict) && l in tEn);
if (back.length) { for (const l of back) e.dict[l] = tEn[l]; D.write('en', e.dict, e.header); git('add', 'src/i18n/en.js'); }
}
// Dictionaries: your additions, edits and removals, applied onto main's sorted files.
for (const lang of D.langs()) {
const rel = `site/i18n/${lang}.js`;
const tb = show(base, rel), tt = show(theirs, rel);
if (!tt || tb === tt) continue;
// Old dictionaries are keyed by English text: give them the same labels the code got.
const old = (t, labels) => { const d = D.parse(t, lang); return Object.keys(d).some((k) => /\s/.test(k)) ? relabelDict(d, labels) : d; };
const db = tb ? old(tb, B.labels) : {}, dt = old(tt, T.labels);
const main = target ? show(target, rel) : null;
// During a merge the working file may hold conflict markers, so start from main's own copy.
const { header, dict } = main ? { header: main.slice(0, main.indexOf('(window.I18N')), dict: D.parse(main, lang) } : D.read(lang);
const n = applyDelta(db, dt, dict, rel);
D.write(lang, dict, header);
git('add', rel);
console.log(`${rel}: ${n} of your entries applied`);
}
if (fs.existsSync(path.join(ROOT, 'site', 'index.html'))) fs.rmSync(path.join(ROOT, 'site', 'index.html'));
try { git('rm', '-q', '--cached', '--ignore-unmatch', 'site/index.html'); } catch {}
fs.rmSync(tmp, { recursive: true, force: true });
console.log(`Ported your site/index.html changes into ${changed} file(s) under src/.`);
if (conflicts.length) {
console.log('Resolve these by hand (look for <<<<<<< markers), then git add them:');
for (const c of conflicts) console.log(` ${c}`);
process.exit(1);
}
git('add', 'src');
console.log('No conflicts. Run npm test, then git commit.');

View file

@ -1,187 +0,0 @@
#!/usr/bin/env node
// Splits a pre-split site/index.html (one file: HTML, CSS and JS) into the src/ layout.
//
// This is how src/ was made, and it stays around for work that was started before the split: a branch
// or pull request that still edits site/index.html. scripts/legacy/port-branch.js uses it to carry those
// edits over to src/ (see CONTRIBUTING.md, "Your branch still edits site/index.html?").
//
// node scripts/legacy/split-index-html.js INDEX_HTML OUT_DIR writes OUT_DIR/index.html and partials
//
// The cut points are found by content, not line numbers, so the same rules split any version from around
// the split (1.33.x–1.34.x). Comments directly above a cut point travel with the code below them.
const fs = require('node:fs');
const path = require('node:path');
// [partial, first line of it]. Each regex is looked for after the previous cut.
const CSS = [
['styles/00-base.css', /^\/\* Layout: full-bleed/],
['styles/10-hud.css', /^\/\* HUD \*\/$/],
['styles/20-drawers.css', /^\/\* drawers \*\/$/],
['styles/30-toasts.css', /^\/\* toasts \*\/$/],
['styles/40-modal.css', /^\/\* modal \*\/$/],
['styles/50-tablet.css', /^\/\* Tablets in landscape/],
['styles/60-phone.css', /^\/\* =+ PHONES/],
];
const JS = [
['game/00-core/10-language.js', /^\/\* =+ LANGUAGE/],
['game/00-core/20-analytics.js', /^\/\* =+ ANALYTICS/],
['game/10-catalog/10-economy.js', /^\/\* =+ CONSTANTS/],
['game/10-catalog/20-routers.js', /^const RG=\[/],
['game/10-catalog/30-supply-chain.js', /^\/\* -+ Supply chain/],
['game/10-catalog/40-ports.js', /^\/\* Ports are finite/],
['game/10-catalog/50-dark-fiber.js', /^\/\/ dark fiber & optical gear/],
['game/10-catalog/60-reach-and-subsea.js', /^\/\* Reach \(#17/],
['game/20-world/10-projection.js', /^\/\* =+ WORLD/],
['game/20-world/20-landmasses.js', /^const LANDS_LL=/],
['game/20-world/30-coastline.js', /^\/\/ Drawn coastline/],
['game/20-world/40-city-coords.js', /^const CITY_LL=/],
['game/20-world/50-cities.js', /^const CITIES=\[/],
['game/20-world/60-cables.js', /^const CABLES=\[/],
['game/30-networks/10-networks.js', /^\/\* =+ NETWORKS/],
['game/30-networks/20-rival-exchanges.js', /^\/\* Rival exchanges/],
['game/30-networks/30-long-tail.js', /^\/\* The long tail/],
['game/30-networks/40-traffic-shares.js', /^const NET=Object\.fromEntries/],
['game/40-progress/10-businesses.js', /^\/\* =+ BUSINESSES/],
['game/40-progress/20-goals.js', /^\/\* =+ GOALS/],
['game/50-state.js', /^\/\* =+ STATE/],
['game/60-features/10-banks.js', /^\/\* =+ BANKS & LOANS/],
['game/60-features/20-scenarios.js', /^\/\* Seeded games/],
['game/60-features/30-conferences.js', /^\/\* -+ conference season/],
['game/60-features/40-tutorial.js', /^\/\* -+ guided first game/],
['game/60-features/50-traceroute.js', /^\/\* -+ traceroute and looking glass/],
['game/60-features/60-share-card.js', /^\/\* -+ share card/],
['game/60-features/70-scenario-progress.js', /^function scnTick\(/],
['game/60-features/80-new-game.js', /^function newGame\(/],
['game/70-rules/10-helpers.js', /^\/\* =+ HELPERS/],
['game/70-rules/20-exchanges.js', /^\/\* Australian exchanges follow/],
['game/70-rules/30-pnis.js', /^\/\* -+ PNIs with the big networks/],
['game/70-rules/40-peering-inbox.js', /^\/\* -+ The peering inbox/],
['game/70-rules/50-peering-policy.js', /^\/\* Big networks sometimes refuse/],
['game/70-rules/60-de-kicks.js', /^\/\* DE-KICKS Group/],
['game/70-rules/70-sold-out.js', /^\/\* Sold out:/],
['game/70-rules/80-hot-ports-and-rank.js', /^const HOT=/],
['game/80-simulation/10-dijkstra.js', /^\/\* =+ SIMULATION/],
['game/80-simulation/20-routescript.js', /^\/\* -+ RouteScript/],
['game/80-simulation/30-compute.js', /^const LABS=new Map/],
['game/80-simulation/40-billing.js', /^function p95\(/],
['game/80-simulation/50-sanitize.js', /^const own=/],
['game/80-simulation/60-requirements.js', /^const GRACE_DAYS=/],
['game/80-simulation/70-customers-and-events.js', /^function bizSf\(/],
['game/80-simulation/80-geography-and-latency.js', /^function cnOk\(/],
['game/80-simulation/90-sites-and-service.js', /^const RT=\{/],
['game/85-incidents/10-incidents-and-ddos.js', /^\/\* -+ failures & events/],
['game/85-incidents/20-failures.js', /^function fireFailure\(/],
['game/85-incidents/30-events.js', /^function fireEvent\(/],
['game/88-days/10-day-tick.js', /^\/\* -+ daily tick/],
['game/88-days/20-badges.js', /^const RARITY=/],
['game/90-actions/00-actions.js', /^\/\* =+ ACTIONS/],
['game/90-actions/90-action-helpers.js', /^function landTrenches\(/],
['game/91-save.js', /^\/\* =+ SAVE/],
['game/92-audio.js', /^\/\* =+ AUDIO/],
['game/93-ui/10-dom.js', /^\/\* =+ DOM RENDER/],
['game/93-ui/20-phone.js', /^\/\* =+ PHONE =/],
['game/93-ui/30-install.js', /^\/\* =+ INSTALL/],
['game/93-ui/40-hud-and-panels.js', /^function fitHud\(/],
['game/93-ui/50-city-panel.js', /^function cityPanel\(/],
['game/93-ui/60-decommission.js', /^\/\* Decommissioning POPs/],
['game/93-ui/70-link-panels.js', /^const portMo=/],
['game/94-dashboard/10-progress.js', /^\/\* -+ scenario and level progress/],
['game/94-dashboard/20-meet-a-network.js', /^\/\* -+ where to meet a network/],
['game/94-dashboard/30-customers.js', /^\/\* -+ customers overview/],
['game/94-dashboard/40-connections.js', /^\/\* -+ connections overview/],
['game/94-dashboard/50-lease-swaps.js', /^\/\* Leased lines you could swap/],
['game/94-dashboard/60-dashboard.js', /^function dashTabs\(/],
['game/94-dashboard/70-bank.js', /^function loanSummary\(/],
['game/94-dashboard/80-hint.js', /^function renderHint\(/],
['game/95-modals/10-toasts.js', /^\/\* -+ toasts & modals/],
['game/95-modals/20-notifications.js', /^\/\* -+ notifications:/],
['game/95-modals/30-modal-and-names.js', /^function openModal\(/],
['game/95-modals/40-title.js', /^function showTitle\(/],
['game/95-modals/50-release-notes.js', /^\/\* In-app notes stay short/],
['game/95-modals/60-help.js', /^function showHelp\(/],
['game/95-modals/70-link-modal.js', /^function openLinkModal\(/],
['game/95-modals/80-own-cable.js', /^\/\* Your own subsea cable/],
['game/95-modals/90-fiber-modals.js', /^function dfModalBody\(/],
['game/96-map/10-canvas.js', /^\/\* =+ CANVAS/],
['game/96-map/20-land-and-clouds.js', /^function rng\(seed\)/],
['game/96-map/30-settings.js', /^function i18nDom\(/],
['game/96-map/40-level-of-detail.js', /^\/\* Level of detail/],
['game/96-map/50-link-geometry.js', /^\/\* Parallel waves on the same cable/],
['game/96-map/60-draw.js', /^function draw\(now\)/],
['game/96-map/70-world-layer.js', /^\/\* The land is never drawn/],
['game/96-map/80-cities.js', /^const LBLW=/],
['game/96-map/90-input.js', /^\/\* -+ hit tests & input/],
['game/96-map/95-clicks.js', /^\/\* -+ click delegation/],
['game/99-loop.js', /^\/\* =+ LOOP/],
];
// Moves a cut up over the comment directly above it, so a comment stays with the code it describes.
function liftOverComments(lines, i, floor) {
for (;;) {
const prev = lines[i - 1];
if (i - 1 <= floor || prev === undefined) return i;
if (/^\/\//.test(prev)) { i--; continue; }
if (/\*\/\s*$/.test(prev)) {
// A block comment ending just above: find the "/*" line it starts on, with no other "*/" in between.
let j = i - 1;
while (j > floor && !/^\/\*/.test(lines[j])) j--;
if (j > floor && !lines.slice(j, i - 1).some((l) => l.includes('*/'))) { i = j; continue; }
}
return i;
}
}
// Cuts lines[from, to) into [file, text] pairs by the spec.
function cut(lines, from, to, spec, what) {
// Older versions lack some later sections: a part whose marker is missing is left out, and its code (if
// any) stays in the part before it. The first part of each section is required.
const found = [];
let at = from;
for (const [file, re] of spec) {
let i = at;
while (i < to && !re.test(lines[i])) i++;
if (i >= to) {
if (!found.length) throw new Error(`${what}: no line matches ${re} (for ${file})`);
continue;
}
found.push([file, found.length ? liftOverComments(lines, i, found[found.length - 1][1]) : from]);
at = i + 1;
}
return found.map(([file, s], k) => [file, lines.slice(s, k + 1 < found.length ? found[k + 1][1] : to).map((l) => l + '\n').join('')]);
}
function split(html) {
if (html.includes('\r')) html = html.replace(/\r\n/g, '\n');
const lines = html.split('\n');
const find = (re, from = 0) => { const i = lines.findIndex((l, k) => k >= from && re.test(l)); if (i < 0) throw new Error(`no line matches ${re}`); return i; };
const styleOpen = find(/^<style>$/), styleClose = find(/^<\/style>$/, styleOpen);
// The game script is the last inline <script>, opened with 'use strict'.
const gameOpen = find(/^'use strict';$/), gameClose = find(/^<\/script>$/, gameOpen);
const files = [
...cut(lines, styleOpen + 1, styleClose, CSS, 'styles'),
...cut(lines, gameOpen + 1, gameClose, JS, 'game'),
];
const shell = [
...lines.slice(0, styleOpen + 1), '<!-- @include styles -->',
...lines.slice(styleClose, gameOpen + 1), '<!-- @include game -->',
...lines.slice(gameClose),
].join('\n');
return [['index.html', shell], ...files];
}
module.exports = { split };
if (require.main === module) {
const [input, out] = process.argv.slice(2);
if (!input || !out) { console.error('usage: split-index-html.js INDEX_HTML OUT_DIR'); process.exit(2); }
const parts = split(fs.readFileSync(input, 'utf8'));
// The post-split tidying (see transforms.js) is part of the layout, so ported work lines up with src/.
const { transform } = require('./transforms');
for (const [file, text] of transform(parts)) {
const p = path.join(out, file);
fs.mkdirSync(path.dirname(p), { recursive: true });
fs.writeFileSync(p, text);
}
console.log(`Split ${input} into ${parts.length} files under ${out}/`);
}

View file

@ -1,120 +0,0 @@
// Tidying applied right after the split, to cut down merge conflicts. Each one keeps behaviour the same
// and only changes where code sits or how a literal is laid out. They run as part of
// split-index-html.js, so work from older branches lines up with src/ when it is ported.
//
// 1. The ACT map (every player action) becomes one file per area under game/90-actions/: the first file
// declares `const ACT={…}` and the others add to it with Object.assign. Two people adding actions in
// different areas no longer touch the same lines.
// 2. Coordinate tables that lived on one very long line (CITY_LL, CITY_NUDGE, LANDS_LL) get one entry per
// line, CITY_LL and CITY_NUDGE sorted by id: adding a city no longer edits a 4,000-character line
// that everyone else is editing too.
// 3. Translations are keyed by labels, not by English text (labels.js): tr('pnis.delivery_month') with the
// English in src/i18n/en.js, inlined into the page by an `<!-- @include i18n -->` line in the shell.
// [file, first action in it]. A group runs until the next group's first action.
const ACT_GROUPS = [
['game/90-actions/10-interface.js', 'speed'],
['game/90-actions/20-pops-transit-ix.js', 'buildPop'],
['game/90-actions/30-route-script-and-tools.js', 'teEdit'],
['game/90-actions/40-sites-peering-caches.js', 'addSite'],
['game/90-actions/50-customers.js', 'advertise'],
['game/90-actions/60-links.js', 'upLink'],
['game/90-actions/70-dashboard-lists.js', 'custGo'],
['game/90-actions/80-security-and-china.js', 'applyCn'],
['game/90-actions/85-routing-and-routers.js', 'via'],
['game/90-actions/87-fiber-and-hardware.js', 'dfMode'],
['game/90-actions/89-game-and-settings.js', 'randomName'],
];
function splitActions(text) {
const lines = text.split('\n');
if (lines[lines.length - 1] === '') lines.pop();
const open = lines.indexOf('const ACT={'), close = lines.lastIndexOf('};');
if (open < 0 || close < open) throw new Error('90-actions: no `const ACT={ … };` block');
// Old versions without the action-helpers cut keep that code here; it stays after the last group.
const after = lines.slice(close + 1);
const keyAt = (k) => lines.findIndex((l, i) => i > open && i < close && l.startsWith(` ${k}:`));
// A group whose first action does not exist (yet, in an older version) is left out.
const groups = ACT_GROUPS.map(([file, k], g) => [file, g ? keyAt(k) : 0]).filter(([, i]) => i >= 0);
const starts = groups.map(([, i]) => i);
if (starts.some((s, i) => i && s <= starts[i - 1])) throw new Error('90-actions: actions are out of the expected order');
return groups.map(([file], g) => {
const from = g ? starts[g] : 0, to = g + 1 < starts.length ? starts[g + 1] : close;
const body = lines.slice(from, to);
const out = g ? ['Object.assign(ACT,{', ...body, '});'] : [...body, '};'];
if (g === groups.length - 1) out.push(...after);
return [file, out.join('\n') + '\n'];
});
}
// The top-level entries of an array or object literal source "a,b,c" (no brackets around it).
function entries(src) {
const out = [];
let depth = 0, q = null, start = 0;
for (let i = 0; i < src.length; i++) {
const c = src[i];
if (q) { if (c === '\\') i++; else if (c === q) q = null; continue; }
if (c === '"' || c === "'" || c === '`') q = c;
else if ('[{('.includes(c)) depth++;
else if (']})'.includes(c)) depth--;
else if (c === ',' && depth === 0) { out.push(src.slice(start, i).trim()); start = i + 1; }
}
if (depth || q) throw new Error('unbalanced literal');
const last = src.slice(start).trim();
if (last) out.push(last);
return out;
}
const idOf = (e) => e.match(/^["']?([\w$]+)["']?\s*:/)[1];
const byId = (a, b) => (idOf(a) < idOf(b) ? -1 : idOf(a) > idOf(b) ? 1 : 0);
// `HEAD{entries}TAIL` on one line → HEAD, one entry per line, TAIL. Lines that don't match stay as they are.
function oneLine(text, re, { sort = false, indent = ' ' } = {}) {
return text.split('\n').map((l) => {
const m = re.exec(l);
if (!m) return l;
let es = entries(m[2]);
if (sort) {
// Sorting is only safe without duplicate keys (with duplicates, the last one wins).
const ids = es.map(idOf);
if (new Set(ids).size !== ids.length) throw new Error(`duplicate keys in ${m[1]}`);
es = es.slice().sort(byId);
}
return [m[1], ...es.map((e) => indent + e + ','), m[3]].join('\n');
}).join('\n');
}
function tidy(parts) {
const out = [];
for (const [file, text] of parts) {
if (file === 'game/90-actions/00-actions.js') out.push(...splitActions(text));
else if (file === 'game/20-world/40-city-coords.js') out.push([file, oneLine(text, /^(const CITY_LL=\{)(.*)(\};)$/, { sort: true })]);
else if (file === 'game/20-world/50-cities.js') out.push([file, oneLine(text, /^(const CITY_NUDGE=\{)(.*)(\};)$/, { sort: true })]);
else if (file === 'game/20-world/20-landmasses.js') {
out.push([file, oneLine(oneLine(text, /^(const LANDS_LL=\[)(.*)(\];)$/), /^(LANDS_LL\.push\()(.*)(\);)$/)]);
} else out.push([file, text]);
}
return out;
}
const EN_HEADER = `// English: the text of every label the game uses (in tr(), trn() and N_() calls in src/, and data-i18n in src/index.html).
// Inlined into the page at build. One entry per line, sorted by label; plurals are {"one":…,"other":…}.
// Add or change text with scripts/i18n-add.js, check with npm run i18n:check.
`;
// All the tidying, plus labels. `known` maps English text to the labels src/ already has, so text that
// exists today keeps its label (default: the current src/i18n/en.js). Returns the parts and the labels used.
function transformFull(parts, known) {
const D = require('../lib/dict');
const { labelize, knownFrom } = require('./labels');
if (!known) known = knownFrom(require('node:fs').existsSync(D.fileOf('en')) ? D.read('en').dict : {});
const { parts: labelled, en, labels } = labelize(tidy(parts), known);
const out = labelled.map(([file, text]) => file === 'index.html'
? [file, text.replace('<!-- @include game -->', '<!-- @include i18n -->\n<!-- @include game -->')] : [file, text]);
out.push(['i18n/en.js', D.format('en', EN_HEADER, Object.fromEntries(en))]);
return { parts: out, labels };
}
const transform = (parts, known) => transformFull(parts, known).parts;
module.exports = { transform, transformFull, tidy, entries };

View file

@ -1,52 +0,0 @@
// Shrinks labels for the shipped page (docs/adr/0003-translations-by-label.md, "Performance").
//
// In src/ a label is readable: tr('pnis.delivery_2_to_6_weeks'). Shipped like that, every label would
// sit in the page twice (in the code and as a key in the inlined English), about 20% more page after
// compression. So the build gives each label a short id ('a', 'b', … '2kq'), in the code, in the
// static markup, in the inlined English and in every translation file, and the page ends up about the
// size it was when the English text itself was the key.
//
// Labels passed to N_() are kept whole: those are the ones the game stores (in saves)
// and shows later, and an id would mean something else in the next release.
const { CALL } = require('../legacy/labels');
const D = require('./dict');
const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/;
const EN_OPEN = '(window.I18N=window.I18N||{}).en={';
// {map: label → id for every label that gets one, kept: labels that stay whole}.
function plan(html, en) {
const kept = new Set();
for (const m of html.matchAll(CALL)) if (m[1] === 'N_') kept.add(m[2].slice(1, -1));
const map = new Map();
let n = 0;
for (const l of Object.keys(en).sort(D.cmp)) if (!kept.has(l)) map.set(l, (n++).toString(36));
return { map, kept };
}
const rekey = (dict, map) => Object.fromEntries(Object.entries(dict).map(([k, v]) => [map.get(k) || k, v]));
// The page and the dictionaries with short ids. `dicts` is {lang: dict} for the translations.
function compile(html, en, dicts) {
const { map } = plan(html, en);
// English: the inlined dictionary, swapped whole.
const a = html.indexOf(EN_OPEN), b = html.indexOf('\n};\n', a);
if (a < 0 || b < 0) throw new Error('compile-labels: the inlined English dictionary is missing from the page');
const head = html.lastIndexOf('\n', a) + 1;
let out = html.slice(0, head) + D.format('en', '', rekey(en, map)) + html.slice(b + 4);
// Code: the first argument of tr() and trn(); N_() keeps its label.
out = out.replace(CALL, (m, fn, lit) => {
if (fn === 'N_') return m;
const l = lit.slice(1, -1);
return map.has(l) ? m.replace(lit, `'${map.get(l)}'`) : m;
});
// Static markup.
out = out.replace(/ data-i18n(-aria-label|-title)?="([^"]+)"/g, (m, attr, l) => (map.has(l) ? ` data-i18n${attr || ''}="${map.get(l)}"` : m));
const left = [...out.matchAll(/(?<![\w$.])(tr|trn)\(\s*'([^']*)'/g)].map((m) => m[2]).filter((l) => LABEL.test(l) && !map.has(l) && !(l in en));
if (left.length) throw new Error(`compile-labels: labels with no English: ${[...new Set(left)].slice(0, 5).join(', ')}`);
const compiled = {};
for (const [lang, d] of Object.entries(dicts)) compiled[lang] = rekey(d, map);
return { html: out, dicts: compiled, map };
}
module.exports = { compile, plan };

View file

@ -1,49 +0,0 @@
// Reads and writes the dictionaries: English in src/i18n/en.js, translations in site/i18n/<lang>.js.
// Each maps a label to its text, or for plurals to {"one": …, "other": …}.
//
// Every dictionary is kept in one canonical layout: the header comment, then one `"label":"Text",`
// entry per line, sorted by label. Sorted entries spread new strings across the file instead of
// piling them up at the end, so two pull requests that each add strings rarely touch the same lines.
// `npm run i18n:check` reports a dictionary that is out of order; `npm run i18n:fix` puts it back.
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
// English lives with the source (it is inlined into the page); translations are static files in site/i18n/.
const DIR = path.join(__dirname, '..', '..', 'site', 'i18n');
const EN = path.join(__dirname, '..', '..', 'src', 'i18n', 'en.js');
const fileOf = (lang) => (lang === 'en' ? EN : path.join(DIR, `${lang}.js`));
const langs = () => fs.readdirSync(DIR).filter((f) => f.endsWith('.js')).map((f) => path.basename(f, '.js')).sort();
// Plain code-unit order: the same on every machine, whatever its locale.
const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
function parse(text, lang) {
const window = {};
vm.runInNewContext(text, { window });
return (window.I18N || {})[lang] || {};
}
function read(lang) {
const text = fs.readFileSync(fileOf(lang), 'utf8');
const open = text.indexOf(`(window.I18N=window.I18N||{}).${lang}={`);
if (open < 0) throw new Error(`${lang}.js: missing the (window.I18N=window.I18N||{}).${lang}={ line`);
return { text, header: text.slice(0, open), dict: parse(text, lang) };
}
function format(lang, header, dict) {
const keys = Object.keys(dict).sort(cmp);
return `${header}(window.I18N=window.I18N||{}).${lang}={\n${keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(dict[k])},\n`).join('')}};\n`;
}
// True when the file is already in the canonical layout.
function tidy(lang) {
const { text, header, dict } = read(lang);
return text === format(lang, header, dict);
}
function write(lang, dict, header = read(lang).header) {
fs.writeFileSync(fileOf(lang), format(lang, header, dict));
}
module.exports = { DIR, EN, fileOf, langs, read, write, format, tidy, parse, cmp };

View file

@ -1,216 +0,0 @@
// Runs inside a game page (scripts/route-fuzz.js loads two: main's and this checkout's).
// The driver picks every move with its own seeded random numbers and sends the same calls to both pages, so the pages
// stay in lockstep; this file only offers what a player could do now (buttons on screen, POPs, cities) and digests what
// routing gave, as strings the driver compares.
(() => {
const DENY = new Set(['animSet', 'cont', 'exportSave', 'importGo', 'importPick', 'install', 'langSet', 'mapSet', 'menu', 'mute', 'newgame', 'phonePlay', 'phoneSpeed',
'prefSet', 'pzShare', 'resetAsk', 'settings', 'settingsClose', 'share', 'shareDl', 'shareGo', 'slotBack', 'slotDel', 'slotDelGo', 'slotExport', 'slotMenu',
'slotRetry', 'slotSpace', 'slotSwitch', 'slotTake', 'soundSet', 'speed', 'start', 'toTitle', 'traceCopy', 'updateLater', 'updateNow', 'vpSet', 'wsShare',
// Leave the game or open what is not this game: the title screen, menus of other modes, AI helpers that fetch.
'closePanel', 'puzzleMenu', 'puzzleDoor', 'scnMenu', 'startScn', 'startWeekly', 'pzStart', 'pzArStart', 'arMenu', 'teSlop', 'help', 'helpClose', 'keepPlaying',
'logOpen', 'pitchSkip', 'pitchGo', 'feedback', 'tutSkip', 'tutNext']);
const sig = (b) => b.act + ' ' + JSON.stringify(b.args);
const btns = (root) => (root ? [...root.querySelectorAll('[data-act]')] : []).filter((b) => !b.disabled && !DENY.has(b.dataset.act) && typeof ACT[b.dataset.act] === 'function')
.map((b) => { let args = {}; try { args = JSON.parse(b.dataset.args || '{}'); } catch (e) {} return { act: b.dataset.act, args }; });
const modalOpen = () => !$('modal').hidden;
const errs = [];
const call = (act, args) => {
try { const r = ACT[act](args || {}); if (r && typeof r.then === 'function') r.catch((e) => errs.push(act + ': ' + e.message)); return ''; } catch (e) { return act + ': ' + (e && e.message); }
};
const fixClock = (t) => { Date.now = () => t; };
// ---------- starts ----------
const homes = () => CITIES.filter((c) => homeOk(c.id)).map((c) => c.id);
// Home cities with rules of their own: China, Korea, Russia, Australia, the Philippines, islands and far places.
const special = () => CITIES.filter((c) => homeOk(c.id) && (c.cn || c.kr || c.ru || ['AU', 'PH', 'NZ', 'JP', 'ID', 'IS', 'FJ', 'PF', 'MU', 'MV', 'CL', 'ZA', 'BR', 'IN', 'SG', 'HK', 'TW', 'KR', 'CN'].includes(c.cc))).map((c) => c.id);
const lists = () => ({ homes: homes(), special: special(), scn: SCN.map((s) => s.id), pz: PZ.map((p) => p.id), ar: AR_RUNS.map((r) => r.id) });
const settle = () => { UI.started = true; UI.pitched = true; UI.speed = 0; if (UI.pendGame) ACT.pitchSkip(); closeModal(); if (S && !pzOn()) compute(); renderAll(); };
const start = ({ kind, id, city, preset, seed, name }) => {
if (window.__reseed) window.__reseed(seed);
fixClock(1.7e12 + seed * 1000);
UI.pitched = true; UI.pendGame = null;
if (pzOn()) pzLeave();
if (kind === 'normal') beginGame(name, city, { mode: 'normal', preset });
else if (kind === 'sandbox') beginGame(name, city, { mode: 'sandbox', rules: { chaos: preset } });
else if (kind === 'scenario') { const sc = SCN.find((x) => x.id === id); beginGame(name, sc.city, { scn: sc }); }
else if (kind === 'weekly') { const wk = weekly(); beginGame(name, wk.city, { scn: wk, seed: wk.seed }); }
else if (kind === 'puzzle') pzBegin(pzDef(id));
else if (kind === 'architect') arBegin(arRunDef(id));
// A saved network (the big fixture): loaded and migrated as an import is, with its incidents and events still on.
else if (kind === 'save') { S = migrate(JSON.parse(window.__fzSave)); }
settle();
return { mode: S.mode, home: S.home, puzzle: pzOn() };
};
// ---------- what a player could do now ----------
// The nearest cities, and those a cable lands from here (subsea seats, IRUs and own cables start there).
const near = (c, n) => CITIES.filter((x) => x.id !== c).map((x) => [x.id, kmBetween(c, x.id)]).sort((a, b) => a[1] - b[1]).slice(0, n).map((x) => x[0])
.concat(CABLE_PAIRS.filter((p) => p.a === c || p.b === c).slice(0, 4).map((p) => (p.a === c ? p.b : p.a)));
const state = () => {
const pops = Object.keys(S.pops), nb = new Set();
for (const p of pops.slice(0, 12)) for (const c of near(p, 8)) if (!S.pops[c]) nb.add(c);
return { pops, near: [...nb], cities: CITIES.length, links: S.links.map((l) => l.id), day: S.day, puzzle: pzOn(), modal: modalOpen(), lost: !!S.lost,
clock: !!rule('clock'), core: S.core ? S.core.lv : 0, nets: NET_IDS.length, transit: S.transit.map((t) => t.id), pni: S.pni.map((p) => p.id), biz: S.biz.map((b) => b.id), offers: (S.offers || []).map((o) => o.id) };
};
// The buttons of one place on screen, after opening it.
const screen = (w) => {
if (w.where === 'modal') return btns($('modal'));
if (w.where === 'city') { UI.sel = { type: 'city', id: w.city }; UI.tab = w.tab; renderAll(); return btns($('panel')); }
// The city names in a link panel's header open the city (#196); older pages have plain text there. They only change
// the view, so neither page offers them, and both stay in lockstep.
if (w.where === 'link') { if (!S.links.some((l) => l.id === w.id)) return []; UI.sel = { type: 'link', id: w.id }; renderAll(); const P = $('panel'); for (const h of P.querySelectorAll('.ph h2 [data-act]')) h.removeAttribute('data-act'); return btns(P); }
if (w.where === 'dash') { $('dash').hidden = false; UI.dtab = w.tab; renderDash(); const b = btns($('dash')); return b; }
if (w.where === 'left') {
UI.left = w.tab; UI.leftOpen = true; renderLeft(); let b = btns($('leftBody'));
if (w.tab !== 'noc') return b;
// The backbone, Auto-TE and DDoS settings moved from the NOC tab into the Routing & DDoS modal: offer them here on
// both pages, in one order, so main's page (settings in the tab) and this one (behind the button) stay in lockstep.
if (typeof routingBody === 'function' && b.some((x) => x.act === 'routingOpen')) { const d = document.createElement('div'); d.innerHTML = routingBody(); b = b.filter((x) => x.act !== 'routingOpen').concat(btns(d)); }
// The traceroute moved into that modal too, and Connections left the tab (it is in the dashboard): drop it on both pages.
b = b.filter((x) => x.act !== 'connOpen');
return b.sort((x, y) => (sig(x) < sig(y) ? -1 : sig(x) > sig(y) ? 1 : 0));
}
if (w.where === 'openLink') { if (!S.pops[w.a]) return []; openLinkModal(w.a, w.b); return modalOpen() ? btns($('modal')) : []; }
return [];
};
const press = (b) => { const e = call(b.act, b.args); return e; };
const close = () => { if (modalOpen()) closeModal(); $('dash').hidden = true; };
// ---------- things a player does with no button handy here ----------
const RS = ['spill at 80%', 'spill at 60%', 'protect customers', 'blackhole ddos'];
const script = (rules) => {
const L = [];
for (const r of rules) {
const [k, a, b] = r;
const net = NETS[a % NETS.length], t = S.transit.length ? NET[S.transit[a % S.transit.length].net] : net;
const pops = Object.keys(S.pops), l = S.links.length ? S.links[a % S.links.length] : null;
if (k === 0) L.push(RS[a % RS.length]);
else if (k === 1) L.push(`${b % 2 ? 'prefer' : 'avoid'} ${['pni', 'ix', 'transit'][b % 3]} for ${net.name.toLowerCase()}`);
else if (k === 2) L.push(`cap transit ${t.name.toLowerCase()} at ${10 + (b % 50)} gbps`);
else if (k === 3) L.push(`${b % 2 ? 'prefer' : 'avoid'} transit ${t.name.toLowerCase()}`);
else if (k === 4) L.push(`prepend transit ${t.name.toLowerCase()} ${1 + (b % 3)}`);
else if (k === 5 && pops.length) L.push(`drain ${CITY[pops[a % pops.length]].name.toLowerCase()}`);
else if (k === 6 && l) L.push(`avoid link ${CITY[l.a].name.toLowerCase()}-${CITY[l.b].name.toLowerCase()}`);
}
return L.join('\n');
};
const poke = (p) => {
const [k, a, b] = p;
if (k === 'te') { if (!S.te) return 'no te'; S.te.script = script(a); S.te.on = !!b; S.core = S.core || { lv: 0, run: 0 }; after(); return S.te.script; }
if (k === 'teOff') { if (S.te) { S.te.on = false; after(); } return ''; }
if (k === 'core') { if (S.core) { const v = a % (S.core.lv + 1); return call('coreSet', { v }); } return ''; }
if (k === 'fail') { S.nextFail = S.day + 1; return ''; }
if (k === 'event') { S.nextEvent = S.day + 1; return ''; }
if (k === 'cash') { S.cash += a; after(); return ''; }
// One level up from the level the game reads (lvl(): S.lvl, or 1 when a page never wrote it down).
if (k === 'lvl') { S.lvl = Math.min(LEVELS.length, (S.lvl || 1) + 1); after(); return ''; }
// Events that move routes, as the game's own events set them.
if (k === 'ev') {
const n = NETS[a % NETS.length].id;
if (b === 0) S.ev.leak = { net: n, until: S.day + 3 };
else if (b === 1) S.ev.rpki = { nets: [n, NETS[(a * 7) % NETS.length].id], until: S.day + 3 };
else if (b === 2) S.ev.depeer = S.day + 3;
else if (b === 3) { const x = Object.keys(S.ixp); if (x.length) { S.ev.ixdown = S.ev.ixdown || {}; S.ev.ixdown[x[a % x.length]] = S.day + 2; } }
else if (b === 4 && S.links.length) S.links[a % S.links.length].cut = S.day + 2;
else if (b === 5 && S.transit.length) S.transit[a % S.transit.length].down = S.day + 2;
// After an update brings networks: the courtesy route to them (sanitize() sets it on load).
else if (b === 7) S.grace = { until: S.day + 4, nets: [n, NETS[(a * 13) % NETS.length].id, NETS[(a * 31) % NETS.length].id], fresh: 0 };
else if (b === 8) S.krExit = S.day + 2;
else if (b === 6) { const p = Object.keys(S.pops); if (p.length > 1) S.pops[p[1 + (a % (p.length - 1))]].down = S.day + 2; }
after(); return '';
}
return 'unknown poke';
};
/* Actions on what the network already has, with arguments a button somewhere would give (some sit in collapsed
lists, or on screens the walker rarely reaches): one list of calls, the driver picks one. */
const direct = () => {
const o = [], add = (act, args) => { if (typeof ACT[act] === 'function') o.push({ act, args }); };
const pops = Object.keys(S.pops), PR = ['high', 'low', 'normal'];
for (const t of S.transit) { add('setPref', { kind: 't', id: t.id, v: PR[(t.id.length + S.day) % 3] }); add('setCarry', { id: t.id, on: !t.carry }); add('lagT', { id: t.id, d: (S.day % 3) ? 1 : -1 }); add('cancelTransit', { id: t.id, ok: true }); add('togglePrem', { id: t.id }); add('cleanPipe', { id: t.id }); }
for (const p of S.pni) { add('setPref', { kind: 'p', id: p.id, v: PR[(p.id.length + S.day) % 3] }); add('lagP', { id: p.id, d: (S.day % 3) ? 1 : -1 }); add('cancelPni', { id: p.id, ok: true }); add('sacrif', { id: p.id }); }
for (const x of Object.keys(S.ixp)) { add('setPref', { kind: 'ix', id: x, v: PR[(x.length + S.day) % 3] }); add('lagIx', { city: x, d: (S.day % 3) ? 1 : -1 }); add('peerAll', { city: x }); add('rs', { city: x }); add('cancelIx', { city: x, sure: true, ok: true });
for (const n of ixMembers(x).slice(0, 30)) add(ixSessions(x).has(n) ? 'unpeer' : 'peer', { city: x, net: n }); }
for (const c of pops) {
for (const x of ixIdsIn(c)) if (S.ixp[x] === undefined) add('buyIx', { city: x, tier: S.day % 3 });
for (const n of NETS) if (n.pops.includes(c)) { if (S.day % 2 === 0 || n.cache) add('pni', { city: c, net: n.id, tier: n.id.length % 3 }); if (n.cache) add('cache', { city: c, net: n.id }); }
for (const n of NETS) if (sellsAt(n, c) && (n.id.length + S.day) % 4 === 0) add('buyTransit', { city: c, net: n.id, tier: (S.day >> 2) % 3 });
add('addRouter', { city: c }); add('upRouter', { city: c, g: 1 + (S.day % 4) }); if (!ixName(c) && !CITY[c].cn) add('foundIx', { city: c }); add('launchBB', { city: c }); add('addSite', { city: c });
}
for (const c of S.caches) add('rmCache', { id: c.id });
for (const l of S.links) { add('setStandby', { id: l.id, on: !l.standby }); add('setMetric', { id: l.id, v: ['backup', 'avoid', 'prefer', 'normal'][(l.id.length + S.day) % 4] }); add('upLink', { id: l.id, tier: (S.day % 4) }); add('rmLink', { id: l.id }); add('addParallel', { id: l.id }); }
for (const b of S.offers || []) add('accept', { id: b.id });
for (const b of S.biz) add('dropBiz', { id: b.id });
for (const l of S.loanOffers || []) add('takeLoan', { id: l.id });
for (const l of S.loans || []) add('repayLoan', { id: l.id });
return o;
};
// ---------- time ----------
const day = () => { if (S.lost || !rule('clock')) return 'no clock'; if (modalOpen()) closeModal(); try { dayTick(); } catch (e) { return 'dayTick: ' + e.message; } return ''; };
// ---------- digests ----------
// Everything routing produced: R in full (with every link's R.ef), the flows (R.fl), and what the PNI lists read.
// An attack's record names its attack by id (as rwPack does): the attack itself is game state, compared with S.
const rj = (v) => JSON.stringify(v, (k, x) => (k === 'attack' && x && typeof x === 'object' ? x.id : x));
const routing = () => {
if (!R) return 'noR';
const r = rj(R), fl = R.fl ? JSON.stringify(R.fl) : '';
let pf = '';
if (typeof pniFlows === 'function' && S && !pzOn()) for (const c of Object.keys(S.pops).slice(0, 4)) try { pf += c + JSON.stringify(pniFlows(c)); } catch (e) { pf += c + 'E' + e.message; }
return r + '\n' + fl + '\n' + pf;
};
const parts = () => { const o = {}; if (!R) return o; for (const k of Object.keys(R)) o[k] = rj(R[k]); o.fl = R.fl ? JSON.stringify(R.fl) : ''; return o; };
// A field only this checkout's game has (a new feature's state, on S or on its customers and offers) cannot match main
// yet: the driver passes those (drop) and they are left out; every field both games have must still match.
// The intern's state two levels deep (ops.on.sales, ops.wk.rev): a standing order one game has and the other retired.
// Compared as a reload makes it (migrate(), keys in order): the same game, whichever way each version writes the
// fields it fills in anyway (main may create a record without the defaults a reload gives it, in another order).
// One reload judges both: the driver passes the base page's live state (sLive) through this checkout's migrate()
// (sDigest(drop, json)), so a repair only one version's reload makes (main's re-aimed an attack whose customer left
// during the day) is no divergence. That reload runs with this page's own S in scope (sanitize reads S.rules through
// rule()): pages in lockstep have the same, and a difference in the rules shows up in the fields they decide. A POP without a router model plays the basic one (RG[p.rgen||0]): that is written
// down first, so the reload does not guess one from its ports (a free upgrade a page from before canonical state got).
// Puzzles are never saved: as they are. The rules stay as they are too: both pages may have set them alike (noIp4),
// and a base that does not know a rule would drop it on the way.
const sortK = (v) => (Array.isArray(v) ? v.map(sortK) : v && typeof v === 'object' ? Object.keys(v).sort().reduce((o, k) => ((o[k] = sortK(v[k])), o), {}) : v);
const sLive = () => JSON.stringify(S === undefined ? null : S);
const sOf = (json) => { const live = JSON.parse(json); if (!live || !S || pzOn() || live.mode === 'puzzle') return live; const u0 = uidN, r0 = S.rng;
try {
for (const c of Object.keys(live.pops || {})) if (live.pops[c] && live.pops[c].rgen === undefined) live.pops[c].rgen = 0;
const rules = live.rules === undefined ? undefined : JSON.parse(JSON.stringify(live.rules));
const s = migrate(live); s.rules = rules; return sortK(s);
} finally { uidN = u0; S.rng = r0; } };
const sNow = () => sOf(sLive());
const opsPaths = (s = sNow()) => { const O = s.ops, out = []; if (!O || typeof O !== 'object') return out;
for (const k of Object.keys(O)) { out.push(k); const v = O[k]; if (v && typeof v === 'object' && !Array.isArray(v)) for (const j of Object.keys(v)) out.push(k + '.' + j); } return out; };
const sKeys = () => { const s = sNow(); return { top: Object.keys(s), items: [...new Set([...(s.biz || []), ...(s.offers || [])].flatMap((x) => Object.keys(x)))], ops: opsPaths(s), orders: typeof OPSK === 'object' ? Object.keys(OPSK) : [] }; };
const opsDrop = (s, ops) => { const o = {}; for (const k of Object.keys(s.ops)) { if (ops.includes(k)) continue; const v = s.ops[k];
if (v && typeof v === 'object' && !Array.isArray(v)) { const w = {}; for (const j of Object.keys(v)) if (!ops.includes(k + '.' + j)) w[j] = v[j]; o[k] = w; } else o[k] = v; } return o; };
// json: a live state to judge (the other page's, from sLive); without it, this page's own.
const sDrop = (drop, json) => { const s = json === undefined ? sNow() : sOf(json); if (!s || typeof s !== 'object' || !drop || (!drop.top.length && !drop.items.length && !(drop.ops || []).length)) return s; const o = {};
for (const k of Object.keys(s)) if (!drop.top.includes(k)) o[k] = k === 'ops' && s.ops && (drop.ops || []).length ? opsDrop(s, drop.ops) : s[k];
for (const k of ['biz', 'offers']) if (Array.isArray(o[k])) o[k] = o[k].map((x) => { const y = {}; for (const f of Object.keys(x)) if (!drop.items.includes(f)) y[f] = x[f]; return y; });
return o; };
const sDigest = (drop, json) => JSON.stringify(sDrop(drop, json));
const sParts = (drop, json) => { const s = sDrop(drop, json), o = {}; if (s && typeof s === 'object') for (const k of Object.keys(s)) o[k] = JSON.stringify(s[k]); return o; };
/* After a move: what the move routed (a), routing again from the same state (b: on this checkout's page the kept
tables are used), and routing from that state with the cache off (c: RC.on=false where there is an RC). b and c
route from the same previous R; c's R is kept, as a plain compute would. */
const check = () => {
if (!S || pzOn() && !R) return { a: routing() };
const a = routing(), prior = R, keep = UI.rkR === prior;
compute(); const b = routing();
R = prior; const rc = typeof RC !== 'undefined';
if (rc) RC.on = false;
try { compute(); } finally { if (rc) RC.on = true; }
const c = routing();
if (keep) UI.rkR = R;
return { a, b, c };
};
const acts = () => Object.keys(ACT);
// Scarce IPv4 off (#150, rule ip4), the same rules object with its keys in the same order on both pages: the driver calls
// it only while the base has no such rule, so the pages play the same game until it lands.
const noIp4 = () => { if (S && S.rules) { const { ip4, mods, ...r } = S.rules; S.rules = { ...r, ip4: false, mods }; } };
window.__fz = { acts, direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sLive, sDigest, sParts, check, errs, modalOpen, noIp4 };
})();

View file

@ -1,155 +0,0 @@
// The benchmark panel that scripts/gpu-bench.js adds to the game page. It runs in your own browser, so it measures your
// graphics card: the save is loaded, then each scenario plays for a few seconds with the 2D map and with the WebGL
// tubes, and the frames are timed as they really reach the screen (requestAnimationFrame). Results show in the panel
// and go back to the terminal that started the server. Nothing is saved: the page's save() is switched off.
// What each number is: the frame rate and p95 frame are the cadence of requestAnimationFrame (what you see); draw() is
// the main thread's time to build and submit a frame (CPU only: the card may still be drawing when it returns); GPU is
// the card's own time for a WebGL frame, from EXT_disjoint_timer_query_webgl2 where the browser offers it (read back
// frames later, never waited for, and thrown away when the card says its timing was disturbed).
(() => {
const CFG = window.__BENCH__ || {}, QS = new URLSearchParams(location.search);
const SECS = CFG.secs || 6, WARM = CFG.warm ?? 1500, SETTLE = CFG.settleMs || 5000, SEED = CFG.seed || 777;
const SCEN = [
{ id: 'x1-far', label: 'Map at x1, zoomed out (0.6)', speed: 1, z: 0.6 },
{ id: 'x1-mid', label: 'Map at x1 (zoom 1.4)', speed: 1, z: 1.4 },
{ id: 'x1-near', label: 'Map at x1, zoomed in (3.2)', speed: 1, z: 3.2 },
{ id: 'pan', label: 'Panning at x1 (zoom 1.4)', speed: 1, z: 1.4, pan: true },
{ id: 'x8', label: 'Game at x8 (zoom 1.4)', speed: 8, z: 1.4 },
];
// ?only=gl or ?only=2d runs one renderer; ?scen=x1-mid,pan runs only those scenarios; ?reps=3 runs each one three
// times (the renderers take turns going first, and the table shows the medians); ?dpr=2 below.
const ONLY = QS.get('only'), PICK = QS.get('scen'), REPS = Math.max(1, Math.min(9, +QS.get('reps') || CFG.reps || 1));
if (PICK) SCEN.splice(0, SCEN.length, ...SCEN.filter((s) => PICK.split(',').includes(s.id)));
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const box = document.createElement('div');
box.style.cssText = 'position:fixed;top:8px;left:50%;transform:translateX(-50%);z-index:100000;background:rgba(30,38,64,.94);color:#fff;font:13px/1.4 system-ui,sans-serif;padding:12px 14px;border-radius:12px;max-width:94vw;max-height:80vh;overflow:auto;box-shadow:0 6px 24px rgba(0,0,0,.35)';
box.innerHTML = '<b>Series of Tubes · GPU benchmark</b><div id="bst" style="margin:6px 0">Loading…</div><button id="bgo" disabled style="font:inherit;padding:6px 12px;border-radius:8px;border:0;background:#22C47A;color:#fff;font-weight:700;cursor:pointer">Start</button> <button id="bcp" hidden style="font:inherit;padding:6px 12px;border-radius:8px;border:0;background:#FF4F9A;color:#fff;font-weight:700;cursor:pointer">Copy results</button><div id="bout"></div>';
const st = (t) => { box.querySelector('#bst').textContent = t; };
let SAVE = null, MD = '', TRIAL = 0;
// Ends what the last trial left running before the next one starts, so nothing of one lands on the other: the clock
// stops, its frame callback is cancelled (measure() does that, and TRIAL turns away one already queued), and a day
// still being routed in the worker is waited for. Its answer runs dayPost() on the old save; one that never comes is
// dropped (rwDone() ignores an answer to no job). Then the clock's leftovers are cleared.
async function settle() {
UI.speed = 0; TRIAL++;
const t0 = performance.now();
while (RW.job && performance.now() - t0 < SETTLE) await sleep(10);
if (RW.job) { console.warn('[bench] the route worker did not answer: its day is dropped'); RW.job = null; }
acc = 0; animT = 0;
}
// The save again, with the same random numbers every time (S.rng makes Math.random() follow it, as in a scenario).
function fresh() {
S = migrate(JSON.parse(SAVE)); S.rng = SEED; UI.started = true; UI.pitched = true; UI.sel = null; UI.anim = 'on'; applyAnim();
closeModal(); compute(); renderAll();
const h = CITY[S.home] || CITIES[0]; cam.x = h.x; cam.y = h.y;
}
async function reset() { await settle(); fresh(); }
const q = (s, x) => (s.length ? s[Math.min(s.length - 1, Math.floor(s.length * x))] : 0);
async function measure(sc, hz, r) {
await reset(); cam.z = sc.z; UI.speed = sc.speed; WL.key = null;
const trial = TRIAL;
await sleep(WARM);
const fr = [], dr = [], gpu = [], pend = [], day0 = S.day; let last = 0, stop = false, hidden = false, long = 0, panX = cam.x, raf = 0, glF = 0, flatF = 0, disjoint = 0;
// The card's own time, where the browser lets us read it: a timer around each WebGL draw(), read when it is ready.
const gl = r === 'gl' ? GLX.gl : null; let tq = null; try { tq = gl && gl.getExtension('EXT_disjoint_timer_query_webgl2'); } catch (e) { /* none */ }
const poll = () => { while (pend.length) { const x = pend[0]; if (!gl.getQueryParameter(x, gl.QUERY_RESULT_AVAILABLE)) break; pend.shift();
const ns = gl.getQueryParameter(x, gl.QUERY_RESULT); gl.deleteQuery(x); if (gl.getParameter(tq.GPU_DISJOINT_EXT)) disjoint++; else gpu.push(ns / 1e6); } };
const D0 = draw;
draw = function (t) { let x = null; if (tq && GLX.gl === gl && pend.length < 16) { x = gl.createQuery(); gl.beginQuery(tq.TIME_ELAPSED_EXT, x); }
const a = performance.now();
try { return D0(t); } finally { dr.push(performance.now() - a); if (x) { gl.endQuery(tq.TIME_ELAPSED_EXT); pend.push(x); } if (GLX.shown) glF++; else flatF++; } };
let po = null; try { po = new PerformanceObserver((l) => { long += l.getEntries().length; }); po.observe({ type: 'longtask' }); } catch (e) { /* not in this browser */ }
// Frames slower than three refreshes, with the day they fell on and their draw(): where the stutters are.
const t00 = performance.now(), slow = [];
const tick = (t) => { if (stop || trial !== TRIAL) return;
if (last) { fr.push(t - last); if (t - last > 50) slow.push({ at: Math.round(t - t00), ms: Math.round(t - last), day: S.day, draw: +(dr[dr.length - 1] || 0).toFixed(1) }); } last = t; if (document.hidden) hidden = true;
if (sc.pan) { panX += 0.18 * (t - (tick.p || t)) / cam.z; cam.x = panX; tick.p = t; }
if (tq) poll();
raf = requestAnimationFrame(tick); };
raf = requestAnimationFrame(tick);
const t0 = performance.now(); await sleep(SECS * 1000); stop = true; cancelAnimationFrame(raf); const T = (performance.now() - t0) / 1000;
draw = D0; if (po) po.disconnect(); UI.speed = 0;
if (tq) { poll(); for (const x of pend) gl.deleteQuery(x); }
const s = fr.slice().sort((a, b) => a - b), d = dr.slice().sort((a, b) => a - b), g = gpu.slice().sort((a, b) => a - b), budget = 1000 / hz;
return { fps: +(fr.length / T).toFixed(1), p50: +q(s, 0.5).toFixed(1), p95: +q(s, 0.95).toFixed(1), p99: +q(s, 0.99).toFixed(1), max: +q(s, 1).toFixed(1),
dropped: +(100 * fr.filter((x) => x > budget * 1.5).length / Math.max(1, fr.length)).toFixed(1),
drawMs: +(d.reduce((a, x) => a + x, 0) / Math.max(1, d.length)).toFixed(2), drawP95: +q(d, 0.95).toFixed(2),
gpuMs: g.length ? +(g.reduce((a, x) => a + x, 0) / g.length).toFixed(2) : null, gpuP95: g.length ? +q(g, 0.95).toFixed(2) : null, gpuN: g.length, disjoint,
// Which map really drew the frames: a WebGL run that fell back to 2D (or a 2D run on the card) is not what it says.
drawn: glF && flatF ? 'mixed' : glF ? 'gl' : flatF ? '2d' : 'none', glFrames: glF, flatFrames: flatF,
daysPerSec: +((S.day - day0) / T).toFixed(2), longTasks: long, hidden, drawMax: +q(d, 1).toFixed(1), slow };
}
// Several runs of one scenario: the median of each number; the flags and the stutters of all of them.
function merge(ms) {
if (ms.length === 1) return ms[0];
const o = {}, med = (a) => { const s = a.slice().sort((x, y) => x - y); return s[(s.length - 1) >> 1]; };
for (const k of Object.keys(ms[0])) {
const v = ms.map((m) => m[k]);
o[k] = k === 'slow' ? v.flat() : k === 'drawn' ? [...new Set(v)].join('+') : typeof v[0] === 'boolean' ? v.some(Boolean) : v.every((x) => typeof x === 'number') ? med(v) : v[0];
}
o.runs = ms.length; return o;
}
async function refresh() {
const a = []; let l = 0; await new Promise((r) => { const f = (t) => { if (l) a.push(t - l); l = t; if (a.length < 90) requestAnimationFrame(f); else r(); }; requestAnimationFrame(f); });
a.sort((x, y) => x - y); return Math.round(1000 / a[a.length >> 1]);
}
function table(res, env) {
const gpu = res.gl && SCEN.some((sc) => res.gl[sc.id] && res.gl[sc.id].gpuMs != null);
const rows = SCEN.map((sc) => { const a = res['2d'] && res['2d'][sc.id], b = res.gl && res.gl[sc.id];
const f = (m, k, u = '') => (m && m[k] != null ? `${m[k]}${u}` : '-');
return `| ${sc.label} | ${f(a, 'fps')} | ${f(b, 'fps')} | ${f(a, 'p95', ' ms')} | ${f(b, 'p95', ' ms')} | ${f(a, 'drawMs', ' ms')} | ${f(b, 'drawMs', ' ms')} |${gpu ? ` ${f(b, 'gpuMs', ' ms')} |` : ''}`; });
// A run is only what it says if its frames were drawn by the map it names.
const off = []; for (const [r, want] of [['2d', '2d'], ['gl', 'gl']]) for (const sc of SCEN) { const m = res[r] && res[r][sc.id]; if (m && m.drawn !== want && m.drawn !== 'none') off.push(`${sc.label} (${r === 'gl' ? 'WebGL' : '2D'}: ${m.flatFrames} frames in 2D, ${m.glFrames} on the card)`); }
return [`**${env.gpu || 'unknown GPU'}** · ${env.ua}`, `${env.w}×${env.h} at ${env.dpr}× · ${env.hz} Hz screen · ${env.cores} threads · ${env.save}${env.reps > 1 ? ` · median of ${env.reps} runs` : ''}`, '',
`| Scenario | 2D fps | WebGL fps | 2D p95 frame | WebGL p95 frame | 2D draw() | WebGL draw() |${gpu ? ' WebGL GPU |' : ''}`,
`|---|--:|--:|--:|--:|--:|--:|${gpu ? '--:|' : ''}`, ...rows,
'', `<sub>fps and p95 frame: requestAnimationFrame's cadence (p95: the slowest 5% of frames). draw(): CPU time on the main thread to build and submit a frame; the card may still be working when it returns, so it is not the cost of drawing.${gpu ? ' WebGL GPU: the card\'s own time per frame (EXT_disjoint_timer_query_webgl2).' : ' No GPU timer in this browser: the card\'s own time is not measured.'}${env.invalid ? ' ⚠️ The tab was hidden during a run: those numbers are not valid.' : ''}</sub>`,
...(off.length ? ['', `⚠️ Not drawn by the map they name: ${off.join('; ')}.`] : [])].join('\n');
}
async function run() {
const go = box.querySelector('#bgo'); go.disabled = true;
save = () => {};
// An incident pauses the game (autoPause): the clock must keep running for the timings to mean anything.
autoPause = () => false;
await reset(); st('Measuring the screen refresh…'); await sleep(500);
const hz = await refresh();
const want0 = GLX.want, glOk = mapGl(true, false) && glInit(); const env = { gpu: GLX.gpu, ua: navigator.userAgent.replace(/^Mozilla\/5\.0 /, ''), w: innerWidth, h: innerHeight, dpr: devicePixelRatio, hz, cores: navigator.hardwareConcurrency, save: `${Object.keys(S.pops).length} POPs · ${S.links.length} links`, reps: REPS };
mapGl(false, false);
const rends = (glOk ? ['2d', 'gl'] : ['2d']).filter((x) => !ONLY || x === ONLY), all = {};
// Scenario by scenario, both renderers in turn, the first one changing every time: neither always runs on a cold or
// a tired browser.
let n = 0;
for (let rep = 0; rep < REPS; rep++) for (const [i, sc] of SCEN.entries()) for (const r of (rep + i) % 2 ? rends.slice().reverse() : rends) {
mapGl(r === 'gl', false); n++;
st(`${r === 'gl' ? 'WebGL' : '2D'} · ${sc.label}${REPS > 1 ? ` · run ${rep + 1}/${REPS}` : ''} (${SECS}s, ${n}/${REPS * SCEN.length * rends.length})… keep this tab in front`);
const m = await measure(sc, hz, r); ((all[r] = all[r] || {})[sc.id] = all[r][sc.id] || []).push(m); if (m.hidden) env.invalid = true;
}
const res = { '2d': null, gl: null };
for (const r of Object.keys(all)) { res[r] = {}; for (const id of Object.keys(all[r])) res[r][id] = merge(all[r][id]); }
mapGl(want0, false); await reset();
MD = table(res, env);
st(glOk ? 'Done. The results are also in the terminal.' : 'Done (no WebGL2 here: 2D only).');
box.querySelector('#bout').innerHTML = '<pre style="white-space:pre-wrap;font:11px/1.35 ui-monospace,monospace;margin:8px 0 0">' + MD.replace(/<\/?sub>/g, '').replace(/&/g, '&amp;').replace(/</g, '&lt;') + '</pre>';
box.querySelector('#bcp').hidden = false; go.disabled = false; go.textContent = 'Run again';
try { await fetch('/__bench/results', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ env, res, md: MD }) }); } catch (e) { /* the panel has them */ }
}
// tests/gpu-bench.test.js drives the pieces without the panel.
if (CFG.expose) { window.__bench = { settle, reset, measure, merge, table, setSave: (s) => { SAVE = s; } }; return; }
addEventListener('load', async () => {
document.body.appendChild(box);
while (typeof migrate !== 'function' || typeof GLX === 'undefined') await sleep(50);
// A software renderer is measured too here (the game itself keeps the 2D map on one); the table names the renderer.
GLX.soft = true;
// ?dpr=2 draws the map as a screen of that density would (a 4K screen's pixels, measured on a smaller one).
const DPRQ = +QS.get('dpr'); if (DPRQ > 0) { Object.defineProperty(window, 'devicePixelRatio', { get: () => DPRQ }); resize(); WL.key = null; }
await sleep(800);
try { SAVE = JSON.stringify((await (await fetch('/__bench/save.json')).json()).S || null); } catch (e) { st('Could not load the save: ' + e); return; }
if (SAVE === 'null') { st('The save file has no game in it.'); return; }
const runs = SCEN.length * (ONLY ? 1 : 2) * REPS;
st(`Ready: ${SCEN.length} scenarios × ${ONLY ? 1 : 2} renderers${REPS > 1 ? ` × ${REPS}` : ''}, about ${Math.ceil(runs * (SECS + 3) / 60)} minutes. Keep this tab in front and do not touch the map.`);
const go = box.querySelector('#bgo'); go.disabled = false; go.onclick = () => run().catch((e) => st('Failed: ' + (e && e.stack || e)));
box.querySelector('#bcp').onclick = () => navigator.clipboard.writeText(MD).then(() => st('Copied.'), () => st('Copy failed: select the table instead.'));
if (/[?&]auto\b/.test(location.search)) go.onclick();
});
})();

View file

@ -1,5 +0,0 @@
// A value as a JavaScript literal, safe to paste into code that is eval'd or into an inline <script>: JSON, with the
// characters that could end a script tag or break a string (<, >, /, U+2028, U+2029) written as \u escapes.
const ESC = /[<>\/\u2028\u2029]/g;
const lit = (v) => { const s = JSON.stringify(v); return s === undefined ? 'undefined' : s.replace(ESC, (c) => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0')); };
module.exports = { lit };

View file

@ -1,64 +0,0 @@
// The MCP server's browser session: the game in the player's tab, over the agent relay (scripts/lib/relay-client.js),
// never a game of this process. The page owns the game (start, saves, seed), the clock (its Settings) and its windows;
// the tools are the page's own facade (src/agent/, TUBES.call), called with ctx.relay, so the same tools play
// the same way as the headless session (scripts/lib/mcp-game.js), with the player's rules on top.
const { load } = require('../../tests/harness');
const { pageCall } = require('./mcp-game');
const { createRelaySession } = require('./relay-client');
// Days the player watches take their time: an advance may run for minutes on a big network.
const ADVANCE_MS = 10 * 60 * 1000;
// The sections of the contract a tab and this checkout must agree on. mode and clock are the live session's own.
const CONTRACT = ['commands', 'view', 'session', 'drafts', 'denied', 'domains', 'state', 'results'];
// This checkout's contract, as a tab built from it would serve it over the relay.
let LOCAL = null;
function localSchema() {
if (LOCAL) return LOCAL;
const g = load({ agent: true });
LOCAL = pageCall(g, 'schema', {}, { relay: true });
if (g.errors.length) throw new Error(`the page assembled from src/ reported errors: ${g.errors.join('; ')}`);
g.dom.window.close();
return LOCAL;
}
// The sections in which a live tab's contract differs from this checkout's: a stale tab keeps names but may have
// changed arguments, domains or docs, so the comparison is deep.
const drift = (live, local = localSchema()) => CONTRACT.filter((k) => JSON.stringify(live && live[k]) !== JSON.stringify(local[k]));
function createBrowserSession(opts = {}) {
const relay = createRelaySession(opts);
const session = {
mode: 'browser', relay,
async tool(name, args = {}) {
const r = await relay.call(name, args, { ms: name === 'advance' ? Math.max(relay.config.callMs, ADVANCE_MS) : undefined });
if (r.refused) throw new Error(r.refused);
return r.value;
},
call(name, args) { return session.tool(name, args); },
headless() { throw new Error('Not in the player\'s browser: the game there is the player\'s to start, load and save.'); },
loadSave() { return session.headless(); },
info() { return { transport: 'relay', relay: relay.url }; },
errors() { return []; },
close() { return relay.close(); },
// Wait for a page on the relay (up to waitMs), then check that it serves this checkout's contract.
// Resolves {ok:true}, or {ok:false, why} for the server to say and stop on.
async ready({ waitMs = 90000, onWait } = {}) {
const deadline = Date.now() + waitMs;
let said = false, why = 'no answer';
for (;;) {
const r = await relay.call('schema', {});
if (!r.refused && r.value) {
const d = drift(r.value);
return d.length ? { ok: false, stale: d, why: `the game page in the browser disagrees with the code on disk (${d.join(', ')})` } : { ok: true };
}
why = r.refused || why;
if (Date.now() >= deadline) return { ok: false, why: `no game page answered on the relay (${relay.url}): ${why}` };
if (!said && onWait) { said = true; onWait(); }
await new Promise((res) => setTimeout(res, 1000));
}
},
};
return session;
}
module.exports = { createBrowserSession, drift, localSchema, CONTRACT };

View file

@ -1,283 +0,0 @@
// The game behind the MCP server (scripts/mcp.js), in one of two places. Headless (createSession): one game page of its
// own, the development page from src/ (with the agent facade, src/agent/), loaded in jsdom as the tests load it
// (tests/harness.js: seeded, no animation loop), with scripts/lib/mcp-headless.js added to start, load and export games.
// In the browser (scripts/lib/mcp-browser.js): the game in the player's tab, over the agent relay. Either way every
// other tool is the page's own facade (TUBES.call), so both play the same game the same way.
//
// TOOLS is the list the server offers; each says which sessions it works in (modes), and run() gets the session and
// the tool's arguments and returns JSON, or a promise of it (the browser answers over a socket).
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('../../tests/harness');
const HEADLESS_JS = fs.readFileSync(path.join(__dirname, 'mcp-headless.js'), 'utf8');
const ACT_DIRS = ['90-actions', '94-dashboard', '96-map'].map((d) => path.join(__dirname, '..', '..', 'src', 'game', d));
// The arguments of the actions the command tables do not type (the drafts), read from their source
// (`dfSrc:({v})=>`): in the page the actions are wrapped for puzzle mode, so their own parameter lists are not visible.
let ACT_ARGS = null;
function actArgs() {
if (ACT_ARGS) return ACT_ARGS;
ACT_ARGS = {};
const re = /(?:^|[\s,{])([A-Za-z]\w*):\s*(?:async\s*)?\(\s*\{([^}]*)\}\s*(?:=\s*\{\s*\}\s*)?\)\s*=>/g;
for (const [dir, f] of ACT_DIRS.flatMap((d) => fs.readdirSync(d).filter((f) => f.endsWith('.js')).sort().map((f) => [d, f]))) {
const src = fs.readFileSync(path.join(dir, f), 'utf8');
for (const m of src.matchAll(re)) if (!ACT_ARGS[m[1]]) ACT_ARGS[m[1]] = m[2].split(',').map((a) => a.split('=')[0].trim()).filter(Boolean);
}
return ACT_ARGS;
}
const MAX_INLINE_SAVE = 200000;
const CLOCKS = ['agent', 'realtime'];
const DEFAULT_PACE_MS = 60000;
// One call into a jsdom page's facade, as JSON both ways: nothing but plain data crosses.
function pageCall(g, tool, args = {}, ctx) {
const w = g.dom.window;
w.__mcpTool = tool; w.__mcpArgs = JSON.parse(JSON.stringify(args)); w.__mcpCtx = ctx || null;
return JSON.parse(g.ev('JSON.stringify(TUBES.call(__mcpTool,__mcpArgs,__mcpCtx))') || 'null');
}
// Where load_save and export_save may touch files. stdio (saveDir undefined): anywhere, as the operator's own client
// asks. Over HTTP the client may be another machine: nowhere (null), or only under one directory, symlinks included.
function savePath(s, p, write) {
if (s.saveDir === undefined) return path.resolve(p);
if (s.saveDir === null) throw new Error('This server takes saves as JSON only: give json instead of path (the server can allow a directory with --save-dir).');
const root = s.saveDir, full = path.resolve(root, String(p));
let real;
try { real = write ? path.join(fs.realpathSync(path.dirname(full)), path.basename(full)) : fs.realpathSync(full); } catch (e) { throw new Error(`${p}: no such file or directory under the save directory`); }
if (!real.startsWith(root + path.sep)) throw new Error(`${p} is outside the save directory.`);
if (write && fs.existsSync(real) && fs.lstatSync(real).isSymbolicLink()) throw new Error(`${p} is a symbolic link: write to a plain file.`);
return real;
}
// opts.clock: 'agent' (time moves with advance) or 'realtime' (the session runs a day every opts.paceMs, and tools can
// only wait). opts.seed, opts.file as tests/harness.js takes them (a file must be a development page: it carries the
// facade). opts.saveDir: see savePath.
function createSession(opts = {}) {
const clock = CLOCKS.includes(opts.clock) ? opts.clock : 'agent';
const paceMs = Math.max(10, Math.floor(+opts.paceMs) || DEFAULT_PACE_MS);
let game = null, timer = null;
const boot = () => {
const g = load({ seed: opts.seed || 12345, file: opts.file, agent: true });
g.ev(HEADLESS_JS);
g.headless = (fn, ...args) => { g.dom.window.__mcpArgs = JSON.parse(JSON.stringify(args)); return JSON.parse(g.ev(`JSON.stringify(__mcpHeadless.${fn}(...window.__mcpArgs))`) || 'null'); };
g.headless('setClock', clock, paceMs, clock === 'realtime');
g.headless('newGame', { city: 'fra', name: 'Scratch Networks', preset: 'oncall' });
// A running clock: the server keeps the time, one day per pace, whatever the tools do (as the player's tab does).
if (clock === 'realtime') {
timer = setInterval(() => { try { g.ev('apiTick()'); } catch (e) { g.errors.push(String(e && e.message || e)); } }, paceMs);
if (timer.unref) timer.unref();
}
return g;
};
const session = {
mode: 'headless', clock, paceMs: clock === 'realtime' ? paceMs : 0, saveDir: opts.saveDir,
get game() { return game || (game = boot()); },
// The page's own tools (TUBES.call), answered at once.
tool(name, args) { return pageCall(session.game, name, args); },
call(name, args) { return session.tool(name, args); },
headless(fn, ...args) { return session.game.headless(fn, ...args); },
// Text into the page without building a giant eval string (saves run to megabytes).
loadSave(txt) { session.game.dom.window.__mcpSave = txt; return JSON.parse(session.game.ev('JSON.stringify(__mcpHeadless.loadSave(window.__mcpSave))')); },
info() { return { transport: 'jsdom', clock, ...(clock === 'realtime' ? { paceMs } : {}) }; },
errors() { return game ? game.errors.slice() : []; },
close() { if (timer) clearInterval(timer); timer = null; },
};
return session;
}
// A value or a promise of one, the same way: headless tools answer at once, the browser's over a socket.
const then = (v, f) => (v && typeof v.then === 'function' ? v.then(f) : f(v));
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const str = (description, extra = {}) => ({ type: 'string', description, ...extra });
const num = (description, extra = {}) => ({ type: 'number', description, ...extra });
const bool = (description) => ({ type: 'boolean', description });
const obj = (properties = {}, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
const SECTIONS = ['mode', 'clock', 'commands', 'view', 'session', 'drafts', 'denied', 'domains', 'state', 'results'];
const WHERE = ['modal', 'bank', 'dash', 'panel', 'left', 'puzzle'];
const BOTH = ['headless', 'browser'], HEADLESS = ['headless'];
// A page tool, passed straight through: the MCP tool's arguments are the facade's.
const page = (name) => (s, a) => s.tool(name, a);
// wait: a running clock's days, read off the page until enough have passed (or something needs an answer).
async function waitDays(s, a) {
const days = Math.max(1, Math.min(365, Math.floor(+a.days) || 1)), maxMs = Math.max(1, Math.min(600, +a.maxSeconds || 120)) * 1000;
const c0 = await s.tool('clock', {});
if (c0.mode !== 'realtime') throw new Error('The clock here is yours and stands still between calls: use advance to move it.');
const t0 = Date.now(), poll = Math.max(10, Math.min(250, (c0.paceMs || 1000) / 4));
let c = c0, stop = null;
if (!c0.running) stop = 'the clock is not running (no game, a puzzle, or the network is bankrupt)';
while (!stop) {
await sleep(poll);
c = await s.tool('clock', {});
if (c.day >= c0.day + days) break;
if (c.lost) stop = 'bankrupt';
else if (c.question && !c0.question) stop = 'a window opened';
else if (Date.now() - t0 >= maxMs) stop = 'maxSeconds passed';
}
const since = await s.tool('since', { day: c0.day, cash: c0.cash, inc: c0.incidents });
return { ...since, daysAsked: days, stoppedBecause: stop, waitedSeconds: Math.round((Date.now() - t0) / 100) / 10 };
}
const TOOLS = [
{
name: 'new_game', modes: HEADLESS,
description: 'Start a new network, replacing the current one. Presets: soft (Best Effort, the gentlest: no DDoS, no cable ships, no conferences, instant PNIs, patient customers, a rescue loan instead of game over), freeze (Change Freeze, gentle), oncall (On-call, the classic game), bgp (BGP at 3 a.m., harsh), sandbox (endless money, every level; chaos sets how often things break, default none). Seeded, so the same seed and the same moves give the same game. Scenarios, puzzles and architect runs start with act (startScn, pzStart, pzArStart).',
inputSchema: obj({ city: str('Home city: id (fra) or name (Frankfurt). Default Frankfurt.'), name: str('Network name (24 characters at most). Default: a random pun.'),
preset: str('Rules preset', { enum: ['soft', 'freeze', 'oncall', 'bgp', 'sandbox'] }), seed: num('Random seed, default 12345.'),
asn: num('Your own AS number, as the title screen takes it. Default: a free one.'), chaos: str('Sandbox only: how often things break. Default none.', { enum: ['none', 'calm', 'normal', 'spicy'] }) }),
run: (s, a) => s.headless('newGame', a),
},
{
name: 'load_save', modes: HEADLESS,
description: 'Load a saved game: a file exported from the game (Menu → Export save, the series-of-tubes-*.json from a bug report) or a raw save, as a path or as JSON text. Old saves are migrated exactly as the game does.',
inputSchema: obj({ path: str('Path to a .json save file.'), json: str('The save itself, as JSON text.') }),
run: (s, a) => {
if (!a.path === !a.json) throw new Error('Give either path or json.');
const txt = a.path ? fs.readFileSync(savePath(s, a.path, false), 'utf8') : a.json;
return s.loadSave(txt);
},
},
{
name: 'export_save', modes: HEADLESS,
description: 'Export the current game as a save file the real game can import (Menu → Import save). Writes it to path, or returns it when it is small.',
inputSchema: obj({ path: str('Where to write the .json file.') }),
run: (s, a) => {
const txt = s.headless('exportSave', require('../../package.json').version);
if (a.path) { const f = savePath(s, a.path, true); fs.writeFileSync(f, txt); return { wrote: f, bytes: Buffer.byteLength(txt) }; }
if (txt.length > MAX_INLINE_SAVE) throw new Error(`The save is ${txt.length} characters; give a path to write it to.`);
return JSON.parse(txt);
},
},
{
name: 'status', modes: BOTH,
description: 'The network at a glance: date, cash, monthly revenue and costs by kind, level, tier and why it is not Tier 1 yet, the current goal, traffic, reach, counts, POPs and open incidents.',
inputSchema: obj(),
run: page('status'),
},
{
name: 'advance', modes: BOTH,
description: 'With the agent\'s clock (schema mode.clock "agent"): run the game forward day by day, as the game loop does. Stops early when a window opens (then read it with screen and answer it with click or act; decision says when it is a question with options) or the network goes bankrupt. Returns what happened: log, toasts, new incidents, cash, and how long each simulated day took. With a running clock it is an error: use wait.',
inputSchema: obj({ days: num('Days to run, 1 to 3650. Default 1.') }),
run: page('advance'),
},
{
name: 'wait', modes: BOTH,
description: 'With a running clock (schema mode.clock "realtime"): days pass on their own at a fixed pace and nobody can stop them. wait returns once that many have passed, or earlier when a window asks a question, the network goes bankrupt or maxSeconds of real time are up. Returns what happened meanwhile: log, new incidents, cash. With the agent\'s clock it is an error: use advance.',
inputSchema: obj({ days: num('Days to wait for, 1 to 365. Default 1.'), maxSeconds: num('Give up after this much real time, 1 to 600. Default 120.') }),
run: (s, a) => waitDays(s, a),
},
{
name: 'network', modes: BOTH,
description: 'Everything about one network (a carrier, eyeball network, CDN…): type, peering policy and what it asks for, traffic share, transit price, PoPs, exchanges, upstreams and customer cone, whether Tier 1 needs it, and for you: demand, how its traffic leaves you (egress by kind), your PNIs and sessions with it, and how to move it to peering.',
inputSchema: obj({ network: str('Id (dtk), name (Doitsche Telekomm) or ASN.') }, ['network']),
run: page('network'),
},
{
name: 'city', modes: BOTH,
description: 'One city: country, exchanges and their member counts, data center, who sells transit there and at what price, the networks present, the cables that land there, and your POP if you have one.',
inputSchema: obj({ city: str('Id (fra) or name (Frankfurt).') }, ['city']),
run: page('city'),
},
{
name: 'find', modes: BOTH,
description: 'Search cities, networks, cables and exchanges by name, id or ASN. Use it to get the ids other tools and actions take.',
inputSchema: obj({ query: str('Part of a name, an id or an ASN.'), kind: str('Only this kind', { enum: ['city', 'network', 'cable', 'exchange'] }) }, ['query']),
run: page('find'),
},
{
name: 'traceroute', modes: BOTH,
description: 'The game\'s looking glass: the path traffic takes from one of your POPs to a network (which exit wins and why, with the AS path) or to another of your POPs (prefix it city:).',
inputSchema: obj({ from: str('One of your POPs: id or name.'), to: str('A network (id, name or ASN), or city:<one of your POPs>.') }, ['from', 'to']),
run: page('traceroute'),
},
{
name: 'peering_check', modes: BOTH,
description: 'Would this network peer with you, and if not, why not? Checks a PNI at each of your POPs where it is, and a session at each exchange you are on where it is a member, with the game\'s own reasons (traffic it wants, paid peering, the Tier 1 club…).',
inputSchema: obj({ network: str('Id, name or ASN.'), city: str('Only this city.'), via: str('Only this way', { enum: ['pni', 'ix'] }) }, ['network']),
run: page('peering_check'),
},
{
name: 'hot_spots', modes: BOTH,
description: 'Where it hurts: the fullest links, transit ports and PNIs, the transit bill by carrier, and the networks with the most traffic still over transit, each with the cheapest way to peer with it.',
inputSchema: obj({ limit: num('How many of each, default 10.') }),
run: page('hot_spots'),
},
{
name: 'schema', modes: BOTH,
description: 'The typed contract act checks against: which session this is (mode: headless or the player\'s browser, and whose clock), every game command with its arguments, their domains and a description, which ones dry-run, decide or confirm; view commands; session actions (scenarios, puzzles, runs); drafts (inputs another command reads); what is not available and why; the argument domains; and a field-by-field reference of state and results. Give section for one part.',
inputSchema: obj({ section: str('One part only', { enum: SECTIONS }) }),
run: (s, a) => then(s.tool('schema', a), (v) => (!a.section ? { ...v, mode: { ...v.mode, ...s.info() } } : a.section === 'mode' ? { ...v, ...s.info() } : v)),
},
{
name: 'catalog', modes: BOTH,
description: 'The game\'s reference tables, which the argument domains point at: CITIES, NETS, CABLES, PORT, LT, OPT, DF_SYS, FAB, INTERNS, OPSK, CHARTERS, SCN, BANKS… plus three made for you: conferences (the upcoming calendar with the keys confGo and confSponsor take), TE_RECIPES (each RouteScript recipe with its script, ready for teDeploy) and BADGES (as the badge wall shows them). Omit name for the list of tables with their sizes.',
inputSchema: obj({ name: str('One table; omit for the list.') }),
run: page('catalog'),
},
{
name: 'state', modes: BOTH,
description: 'The saved game itself as JSON, the same object the game saves: offers, loan offers, links, ports, PNIs, customers, the intern, events… with their ids. schema section "state" documents each field; in the player\'s browser the dice (the seed, the days of the next failure and event) are held back. Give a path (pops.fra, links, loanOffers, biz.3, links.<id>): the whole state of a big network is hundreds of KB.',
inputSchema: obj({ path: str('Dotted path: a key, an array index or an entity id per step.') }),
run: page('state'),
},
{
name: 'results', modes: BOTH,
description: 'The game\'s last traffic computation (R), rebuilt after every action and every day: load per link, use per port, demand and served per city, egress per network, monthly cost and revenue by kind, latency, reach. schema section "results" documents each field. Give a path (load, cost, netEg.ggl).',
inputSchema: obj({ path: str('Dotted path.') }),
run: page('results'),
},
{
name: 'ui', modes: BOTH,
description: 'The view state actions read and write (the selection, the pending link pair, the drafts of the link, fiber and cable windows, the RouteScript draft, confirmations), without render caches. For working out why an action did what it did.',
inputSchema: obj(),
run: page('ui'),
},
{
name: 'actions', modes: BOTH,
description: 'Every action act can run, with its arguments (? marks an optional one), e.g. buildPop(city), buyTransit(city,net,tier), buildLink(a,b,tier,cable?,route?,premiumCrossing?). Port tiers: 0 = 10G, 1 = 100G, 2 = 400G, 3 = 800G. Exchanges are given as city=<exchange id>. schema has each one\'s argument domains and what it does.',
inputSchema: obj(),
run: (s) => then(s.tool('actions', {}), ({ typed, drafts }) => {
const a = actArgs();
return [...Object.entries(typed).map(([k, sig]) => `${k}(${sig})`), ...drafts.map((k) => (a[k] ? `${k}(${a[k].join(',')})` : k))].sort();
}),
},
{
name: 'act', modes: BOTH,
description: 'Do something in the game: run one action with its arguments (see actions and schema). Arguments are checked first (a wrong id or value is an error that lists what fits); the action then runs as the game runs it: windows that take typed text are filled in (renameGo, teDeploy, teCheck, metricSet), multi-step builds take their choices as arguments (buildLink, orderDf, orderCable, decomGo), and confirmations are given (rmLink, cancelTransit…). outcome says what happened: applied (something changed), rejected (the game said no, see toasts), no_effect (nothing changed and nothing was said), shown (a view or draft: only the screen changed), decision (a window asks a question: answer with one of decision.options or closeModal; other game commands wait), quote (dryRun), stopped (bankrupt). charged is what the money gate took; cashChange also counts goal rewards. With dryRun, a game command is priced with the game\'s own helpers and nothing happens. In the player\'s browser, a window the player opened stays theirs: you play behind it.',
inputSchema: obj({ action: str('Action name, e.g. buildPop (view. prefixes are accepted).'), command: str('Same as action.'), args: { type: 'object', description: 'Its arguments, e.g. {"city":"ams"}.' },
dryRun: bool('Price it and check it can be done: {setup, monthly, days, blocked}. Nothing happens.') }),
run: page('act'),
},
{
name: 'screen', modes: BOTH,
description: 'What the player sees, as text with numbered buttons for click: the open window, else the bank or the NOC dashboard when open, else the side panel, else the puzzle box. where picks one: modal, bank, dash, panel, left (the left drawer: goals, deals, noc or nets) or puzzle. open lists what is showing. Long text comes in pages: textMore says the offset of the next one. Lists the game acts on when they change come with their options; click them with a value.',
inputSchema: obj({ where: str('Which surface', { enum: WHERE }), offset: num('Start the text here (from textMore).') }),
run: page('screen'),
},
{
name: 'panel', modes: BOTH,
description: 'Open the side panel of a city or a link, a network in the network list, or a tab of the left drawer (goals, deals: offers and loans, noc, nets), optionally on a tab (a city has cust, up, peer, infra…), and show it as text with numbered buttons.',
inputSchema: obj({ city: str('City id or name.'), link: str('Link id (from status, hot_spots or state links).'), network: str('Network id or name.'), tab: str('Tab id, as the tab buttons name it.'),
left: str('A tab of the left drawer', { enum: ['goals', 'deals', 'noc', 'nets'] }) }),
run: page('panel'),
},
{
name: 'click', modes: BOTH,
description: 'Press a numbered button from the last screen, panel or act result, as a player\'s click does: with the button\'s own arguments, so confirmations arm first and windows step on as in the game. For a list (it has options), give value.',
inputSchema: obj({ button: num('The button\'s n.'), value: str('For a list: the option to pick.') }, ['button']),
run: page('click'),
},
{
name: 'open_link', modes: BOTH,
description: 'Open the build window for a link (a leased wave, dark fiber or your own cable) from one of your POPs to any city, to compare the routes and sizes it offers; then click through it. act buildLink, orderDf and orderCable do the same in one call.',
inputSchema: obj({ from: str('One of your POPs.'), to: str('Any city.') }, ['from', 'to']),
run: page('open_link'),
},
];
const toolsFor = (mode) => TOOLS.filter((t) => t.modes.includes(mode));
module.exports = { createSession, TOOLS, toolsFor, actArgs, pageCall, savePath, CLOCKS, DEFAULT_PACE_MS };

View file

@ -1,36 +0,0 @@
// Runs inside the MCP server's own game page (scripts/lib/mcp-game.js), in the game's global scope, after the page has
// loaded: the half of a session only that page has. It starts, loads and exports games, which in a player's browser
// are the player's alone, so it is not part of any page. Everything else a tool does goes through the page's own
// facade (window.TUBES, src/agent/).
(() => {
// Out of the way of the game: no sheet of a previous game, no title screen or pitch, the clock left to the server.
const settle = () => { UI.started = true; UI.pitched = true; UI.speed = 0; if (UI.pendGame) ACT.pitchSkip(); closeModal(); API_SHEET = null; compute(); renderAll(); };
const newGame = ({ city = 'fra', name, preset = 'oncall', seed, asn, chaos } = {}) => {
const c = apiCityOf(city).id;
if (!homeOk(c)) apiFail(`${apiCityName(c)} cannot be a home city.`);
if (!['soft', 'freeze', 'oncall', 'bgp', 'sandbox'].includes(preset)) apiFail('preset is one of soft, freeze, oncall, bgp, sandbox');
if (asn !== undefined && !asnOk(+asn)) apiFail(`AS${asn} cannot be yours: it is reserved, private or another network's. Leave asn out for a free one.`);
if (chaos !== undefined && preset !== 'sandbox') apiFail('chaos is the sandbox\'s dial: give preset "sandbox" with it.');
if (chaos !== undefined && !own(CHAOS, chaos)) apiFail(`chaos is one of ${Object.keys(CHAOS).join(', ')}.`);
if (seed !== undefined && window.__reseed) window.__reseed(Math.max(1, Math.floor(+seed) || 1));
if (UI.pendGame) UI.pendGame = null;
UI.pitched = true;
const nm = String(name || randomNetworkName()).slice(0, 24), was = UI.asnTxt;
// beginGame takes the ASN typed on the title screen.
UI.asnTxt = asn !== undefined ? String(+asn) : '';
try { beginGame(nm, c, preset === 'sandbox' ? { mode: 'sandbox', rules: { chaos: chaos || 'none' } } : { mode: 'normal', preset }); } finally { UI.asnTxt = was; }
settle();
return apiStatus();
};
const loadSave = (txt) => {
const r = parseSave(txt);
if (r.err) apiFail(apiText(r.err));
S = migrate(JSON.parse(JSON.stringify(r.s)));
settle();
return { savedBy: r.ver, ...apiStatus() };
};
const exportSave = (version) => JSON.stringify({ app: 'series-of-tubes', version: /^\d/.test(APP_VERSION) ? APP_VERSION : version, exported: new Date().toISOString(), S: packSave(S) });
// The server's clock: the agent's (advance), or a running one it ticks itself (apiTick) at paceMs.
const setClock = (mode, paceMs, running) => { API_CLK = { mode, paceMs: mode === 'realtime' ? paceMs : 0, running: !!running }; };
window.__mcpHeadless = { newGame, loadSave, exportSave, setClock };
})();

View file

@ -1,650 +0,0 @@
// What a page of a server-run network may ask the session server to do, as plain data, and the envelope check every
// request body passes before anything reaches a game (docs: the server-sim design, sections 5.8-5.9 and 10).
// Shared by the realm (scripts/lib/mp-sim-realm.js), the host (scripts/lib/mp-sim.js) and the page's own copies
// (src/game/98-server-play/40-acts.js), which tests hold equal to these tables. Plain data only: no game code here,
// and nothing here is ever evaluated.
//
// Every ACT is in exactly one of SEND, ASK, VOTE, LOCAL or PUZZLE (tests/mp-sim-contract.test.js names the act and this
// file when one is not). SEND is the agent's API_CMD minus the pz* acts and teCheck, traceRun, closeModal, plus
// connCancel, pieRename and tutSkip: a test derives it again, so nobody counts it by hand.
'use strict';
// Acts that change the game: the page sends them, the server runs them as a click (ACT[act](args)).
const SEND = [
'accept',
'acceptFix',
'ad',
'addCh',
'addGen',
'addPair',
'addRouter',
'addSite',
'applyCn',
'bstdApply',
'bstdSet',
'buildLink',
'buildPop',
'buildScrub',
'buyIx',
'buyNni',
'buySat',
'buySpare',
'buyTE',
'buyTransit',
'buyVxc',
'cache',
'cacheSite',
'callBank',
'cancelIx',
'cancelPni',
'cancelTransit',
'cancelVxc',
'charter',
'cleanPipe',
'confGo',
'confSponsor',
'connCancel',
'coreLab',
'coreSet',
'coreUp',
'crews',
'ddosAuto',
'ddosEngage',
'ddosTest',
'decline',
'declineLoan',
'decomGo',
'demoAsk',
'dkAccept',
'dkHaggle',
'dkOptOut',
'dkStay',
'dkWalk',
'downIx',
'downP',
'downT',
'dropBiz',
'fixInc',
'foundIx',
'hackback',
'hwLock',
'ip4Back',
'ip4Buy',
'ip4Lease',
'ip4Nat',
'ip4Nat64',
'ip4Out',
'ip4Return',
'ip4Sell',
'ip6Go',
'ip6Stop',
'lagIx',
'lagNni',
'lagP',
'lagT',
'launchBB',
'layShip',
'listFiber',
'metricMode',
'metricSet',
'mkBanana',
'mktCfg',
'mktHold',
'mktRoute',
'myIxUp',
'opsCap',
'opsFire',
'opsFloor',
'opsHire',
'opsNewPop',
'opsParam',
'opsPop',
'opsToggle',
'opsTpl',
'orderCable',
'orderDf',
'pathAuto',
'pathMove',
'pathPin',
'peer',
'peerAll',
'peerPol',
'pieAnt',
'pieBid',
'pieDish',
'pieExim',
'pieFactory',
'pieFound',
'pieLaunch',
'pieLic',
'pieName',
'piePad',
'pieRd',
'pieRename',
'pieSafe',
'pieSpatPick',
'pni',
'pniAll',
'pniChase',
'popStdClear',
'popStdSet',
'ptAll',
'ptApply',
'ptSave',
'regen',
'renameGo',
'renewLet',
'renewMatch',
'renewMeet',
'repayLoan',
'rmCache',
'rmCh',
'rmLink',
'rmNni',
'rmRouter',
'rmScrub',
'rmSite',
'rs',
'rtbh',
'sacrif',
'salesAuto',
'salesFire',
'salesHire',
'salesMin',
'salesRen',
'salesVp',
'satSize',
'scrubMode',
'scrubUp',
'seaRush',
'seatBuy',
'seatNo',
'sellSpare',
'setCarry',
'setChCount',
'setMetric',
'setPref',
'setRoute',
'setStandby',
'siteSet',
'spares',
'subUpgrade',
'takeLoan',
'teClear',
'teDeploy',
'teToggle',
'teleBuild',
'teleLeo',
'teleLeoRm',
'teleRm',
'teleTrk',
'togglePrem',
'tutSkip',
'unlistFiber',
'unpeer',
'unrtbh',
'upLink',
'upRouter',
'upSys',
'upVxc',
'utilityCaches',
'utilityKit',
'utilityKitAll',
'utilityKitNew',
'utilityPeers',
'utilityRouteServers',
'wispRm',
'wispSat',
'wispSatRm',
'wispSatSize',
'wispSpur',
'xpBuild',
'xpCh',
];
// What-ifs the server answers with the window they open, putting the game back as it was (5.9).
const ASK = ['linkCheck', 'teCheck', 'teSlop'];
// The clock's buttons: on a server network they are a vote for the session's speed (4.5).
const VOTE = ['phonePlay', 'phoneSpeed', 'speed'];
// The page runs these itself: views, drafts, settings, slots, session acts, teOpt.
const LOCAL = [
'addParallel',
'animSet',
'bank',
'bankClose',
'bstdOpen',
'chaosSet',
'chartToggle',
'closeModal',
'closePanel',
'cnPrem',
'connCity',
'connF',
'connFor',
'connNet',
'connOpen',
'connSort',
'cont',
'custCity',
'custF',
'custGo',
'custOpen',
'custSort',
'dash',
'dashClose',
'dashLink',
'dashSort',
'dashTab',
'decomOpen',
'decomToggle',
'dfMode',
'dfSrc',
'dfSys',
'exportSave',
'findGo',
'findLink',
'findOpen',
'focusCity',
'goConn',
'goEgress',
'help',
'helpClose',
'importGo',
'importPick',
'install',
'ip4Open',
'ip4Pick',
'keepPlaying',
'keys',
'langSet',
'leaseSwap',
'leftTab',
'linkTo',
'listMore',
'logAll',
'logOpen',
'mapSet',
'marketOpen',
'meetGo',
'menu',
'modeSet',
'models',
'mpBack',
'mpChat',
'mpCopyLink',
'mpDoor',
'mpJoin',
'mpKeep',
'mpLeave',
'mpLeaveAsk',
'mpNewer',
'mpOpen',
'mpShare',
'mpStart',
'mute',
'netClear',
'netFilter',
'netFind',
'netFocus',
'netOnly',
'newgame',
'nocWindow',
'offerStep',
'openVxc',
'opsCity',
'opsOpen',
'ownCab',
'pathOpen',
'phoneTab',
'pickHome',
'pickStart',
'pieCity',
'pieGlobeNight',
'pieGovOpen',
'pieHi',
'pieIns',
'pieLas',
'pieOpen',
'pieSpatOpen',
'pieTab',
'pitchSkip',
'pniAllOpen',
'pniAllSize',
'pniFilter',
'pniGrp',
'pniSort',
'popGo',
'popStep',
'popsReg',
'popsSort',
'prefSet',
'presetSet',
'puzzleDoor',
'puzzleMenu',
'randomName',
'rename',
'resetAsk',
'route',
'routingOpen',
'salesOpen',
'satOpen',
'scenarios',
'seaDesign',
'seaPackage',
'selLink',
'settings',
'settingsClose',
'share',
'shareDl',
'shareGo',
'slotBack',
'slotDel',
'slotDelGo',
'slotExport',
'slotMenu',
'slotRetry',
'slotSpace',
'slotSwitch',
'slotTake',
'soundSet',
'start',
'startScn',
'startWeekly',
'tab',
'tailTog',
'teBack',
'teClose',
'teEdit',
'teExample',
'teHelp',
'teOpt',
'teRecipe',
'themeSet',
'toTitle',
'toggleLeft',
'trace',
'traceCopy',
'traceMode',
'traceRun',
'updateLater',
'updateNow',
'utilities',
'utilityPick',
'via',
'vpSet',
'whatsNewShow',
'wispOpen',
'wsShare',
'xfer',
'xferFile',
'xferLink',
'xferPaste',
'xferRecv',
'xferShare',
'xpOpen',
'zoomStep',
];
// Puzzles never run on the server: they stay on the device, like everything that starts with pz.
const PUZZLE = [
'pzAddPar',
'pzArAll',
'pzArGo',
'pzArNext',
'pzArSkip',
'pzArStart',
'pzCity',
'pzDiv',
'pzFinish',
'pzLeave',
'pzLink',
'pzLinkTo',
'pzLook',
'pzMkSkip',
'pzMonkey',
'pzPop',
'pzReset',
'pzRetry',
'pzRmLink',
'pzRmPop',
'pzRoute',
'pzRtAdd',
'pzRtModel',
'pzRtRm',
'pzShare',
'pzStart',
'pzTab',
'pzTier',
'pzUndo',
'pzVia',
'pzWeekly',
];
/* Two-click buttons: the first click arms the button on the page (a view change), only the second is sent, with
confirmed:true. 'arg': the act takes ok:1 and runs at once. Anything else: the key the first click writes to
UI.confirm, as a template over the act's args ({id} is String(args.id)); the server sets UI.confirm to it and runs the
act once. */
const CONFIRM = {
cancelIx: 'arg',
cancelPni: 'arg',
cancelTransit: 'arg',
cancelVxc: '{id}',
connCancel: 'cc:{k}:{id}',
dkOptOut: 'dk{city}{n}',
dropBiz: '{id}',
ip4Sell: '{id}',
opsFire: 'opsFire',
repayLoan: '{id}',
rmLink: '{id}',
rmScrub: 'scrub:{city}',
rmSite: 'site{city}',
salesFire: 'salesFire',
teleLeoRm: 'leo:{city}',
teleRm: 'tele:{city}',
wispRm: 'wz:{z}',
wispSatRm: 'wsat:{z}',
};
// The UI.confirm key a preset act's first click writes (null for 'arg' acts and acts that do not confirm).
const SRV_ARM = Object.fromEntries(Object.entries(CONFIRM).filter(([, v]) => v !== 'arg'));
function armKey(act, args) {
const t = Object.prototype.hasOwnProperty.call(SRV_ARM, act) ? SRV_ARM[act] : null;
return t === null ? null : t.replace(/\{(\w+)\}/g, (m, k) => String(args && args[k] !== undefined ? args[k] : ''));
}
/* The UI drafts an act reads, and the only UI keys a request may set (its ui object). Types are checked here; the realm
checks the values against the game's catalogs (cities, CABLES, DF_SYS, SEA_DESIGNS, the route picker's values). */
const DRAFTS = {
buildLink: ['pending', 'route', 'via', 'cnPrem'],
decomGo: ['decom'],
orderCable: ['pending', 'seaDesign', 'seaterminal', 'seaengineering'],
orderDf: ['pending', 'dfSrc', 'dfSys'],
pieLaunch: ['pieIns', 'pieLas'],
teDeploy: ['slop'],
};
// pair: {a, b}, two different city-like ids; id: a short id string; ids: an array of at most 200 of them (a Set in the game).
const DRAFT_TYPES = {
cnPrem: 'boolean',
decom: 'ids',
dfSrc: ['lease', 'build', 'cable'],
dfSys: 'id',
pending: 'pair',
pieIns: 'boolean',
pieLas: 'boolean',
route: 'string',
seaDesign: 'id',
seaengineering: 'boolean',
seaterminal: 'boolean',
slop: 'boolean',
via: 'string',
};
// Args longer than the envelope's 64 characters: their own cap (the game cuts the texts shorter itself).
const TEXT = {
metricSet: { v: 16 },
// A pinned path's cities, comma-separated: a long path is longer than 64 characters.
pathPin: { via: 1024 },
pieRename: { name: 64 },
renameGo: { name: 64 },
teCheck: { script: 4000 },
teDeploy: { script: 4000 },
utilityCaches: { quote: 1024 },
// An express's spans, as link ids joined by ',' (up to XP_HOPS = 6 ids of about 10 characters).
xpBuild: { via: 256 },
};
/* Acts that charge a total the player saw in a window, planned again at the click: the arg that carries what the window
showed. The game refuses a different one ("The quote changed"); the server also refuses a request without it.
'quote' is the plan's key (a string), any other name the total (a number). pniAll: the exact total (fixed prices, so
the total names the plan). bstdApply: the plan's key, plus its total q, which may drift 1% (hardware prices move
daily under the market rule). utilityKit, utilityKitAll, acceptFix, ptApply, ptAll: the total, within 1% (each prices
routers, so a day's drift moves it; ptApply's "Mark it" sends 0). utilityCaches: the list of boxes. */
const QUOTE = {
acceptFix: 'cost',
bstdApply: 'quote',
pniAll: 'q',
ptAll: 'cost',
ptApply: 'cost',
utilityCaches: 'quote',
utilityKit: 'cost',
utilityKitAll: 'cost',
};
/* The windows a request's ctx.win may name: the one the page has open when the click came from inside it. The game asks
which window is open by its class and by a marker inside it (pieRe: class 'pie'; bstdShown: [data-sheet="bstd"];
routingRefresh: [data-routing]; charter), so the realm's stand-in has to be that window, or a redraw on the server
opens another one. c: its class (#modal's className); sel: the marker inside #modalCard, if it has one; ui: the view
state it draws from that only the page holds (set by LOCAL acts: the intern window's POP, the pie window's tab and
POP), each checked against the game in the realm. The page names the first entry, in this order, whose c is the open
window's class and whose sel (when it has one) matches inside it; a window none names is sent as ctx.modal alone. */
const WINDOWS = {
bstd: { c: 'ops', sel: '[data-sheet="bstd"]' },
routing: { c: '', sel: '[data-routing]' },
charter: { c: 'charter' },
ops: { c: 'ops', ui: ['opsCity'] },
pie: { c: 'pie', ui: ['pieCity', 'pieTab'] },
};
const ID_RE = /^[a-z0-9]{8,16}$/, SIM_RE = /^[0-9a-f]{12}$/, KEY_RE = /^[A-Za-z][A-Za-z0-9]{0,15}$/, VIEW_RE = /^[a-z0-9]{1,16}$/, SHORT_RE = /^[A-Za-z0-9_.:|~-]{1,40}$/;
const SPEEDS = [0, 0.5, 1, 2, 4, 8];
// The viewport a request's ctx may set on the realm, in CSS pixels: checkEnvelope clamps ctx.w and ctx.h into it.
const VIEW_MIN = 200, VIEW_MAX = 4000;
const PREFS = ['pauseFurious', 'pauseIncident', 'warnUnhappy'];
const SETS = { SEND: new Set(SEND), ASK: new Set(ASK), CONFIRM: new Set(Object.keys(CONFIRM)) };
const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
const plain = (o) => !!o && typeof o === 'object' && !Array.isArray(o) && (Object.getPrototypeOf(o) === Object.prototype || Object.getPrototypeOf(o) === null);
const prim = (v, cap) => v === null || typeof v === 'boolean' || (typeof v === 'number' && Number.isFinite(v)) || (typeof v === 'string' && v.length <= cap);
// Keys a request object may never carry, whatever the regex says; nor values, where a value names something: written
// through as a key (S.pops[city]), they reach a prototype, and any name Object.prototype has ('toString', 'valueOf')
// reads as something there. Free text (TEXT) may say them.
const BAD_KEY = new Set(['__proto__', 'constructor', 'prototype']);
const badVal = (v) => (typeof v === 'string' ? BAD_KEY.has(v) || v in Object.prototype : Array.isArray(v) ? v.some(badVal) : !!v && typeof v === 'object' && Object.keys(v).some((k) => BAD_KEY.has(k) || badVal(v[k])));
function bad(error, code = 400, extra = {}) { return { ok: false, code, error, ...extra }; }
function checkArgs(act, args) {
if (!plain(args)) return 'args must be an object';
const keys = Object.keys(args);
if (keys.length > 12) return 'too many args';
const caps = own(TEXT, act) ? TEXT[act] : {};
for (const k of keys) {
if (!KEY_RE.test(k) || BAD_KEY.has(k)) return `bad arg name ${JSON.stringify(k).slice(0, 40)}`;
const v = args[k], cap = own(caps, k) ? caps[k] : 64;
if (!own(caps, k) && badVal(v)) return `bad arg ${k}`;
if (Array.isArray(v)) { if (v.length > 64 || !v.every((x) => prim(x, 64))) return `bad arg ${k}`; continue; }
if (!prim(v, cap)) return `bad arg ${k}`;
}
if (own(QUOTE, act)) { const q = args[QUOTE[act]]; if (QUOTE[act] === 'quote' ? typeof q !== 'string' : !(typeof q === 'number' && Number.isFinite(q))) return `${act} needs the quoted ${QUOTE[act]}`; }
return null;
}
function checkDraft(k, v) {
const t = DRAFT_TYPES[k];
if (badVal(v)) return false;
if (Array.isArray(t)) return t.includes(v);
if (t === 'boolean') return typeof v === 'boolean';
if (t === 'string') return typeof v === 'string' && v.length <= 64;
if (t === 'id') return typeof v === 'string' && SHORT_RE.test(v);
// Two different places: the game's own drag never opens a link from a city to itself.
if (t === 'pair') return plain(v) && Object.keys(v).length === 2 && typeof v.a === 'string' && typeof v.b === 'string' && SHORT_RE.test(v.a) && SHORT_RE.test(v.b) && v.a !== v.b;
if (t === 'ids') return Array.isArray(v) && v.length <= 200 && v.every((x) => typeof x === 'string' && SHORT_RE.test(x));
return false;
}
function checkCtx(c) {
if (!plain(c)) return 'ctx must be an object';
for (const k of Object.keys(c)) {
const v = c[k];
if (k === 'sel') { if (v !== null && !(plain(v) && Object.keys(v).length === 2 && (v.type === 'city' || v.type === 'link') && typeof v.id === 'string' && SHORT_RE.test(v.id))) return 'bad ctx.sel'; }
else if (k === 'tab' || k === 'left') { if (v !== null && !(typeof v === 'string' && VIEW_RE.test(v))) return `bad ctx.${k}`; }
else if (k === 'modal' || k === 'coarse') { if (typeof v !== 'boolean') return `bad ctx.${k}`; }
// The page sends its innerWidth/innerHeight as they are: a 5120-px monitor, or a desktop zoomed out, is wider than
// anything the layout tells apart (isPhone() and the like only ask whether it is under about 760). Clamped, not refused.
else if (k === 'w' || k === 'h') { if (!(typeof v === 'number' && Number.isFinite(v) && v > 0 && v <= 1e5)) return `bad ctx.${k}`; c[k] = Math.min(VIEW_MAX, Math.max(VIEW_MIN, v)); }
// The open window, by name, with its view state (WINDOWS): {k, ui?}.
else if (k === 'win') {
const W = plain(v) && typeof v.k === 'string' && own(WINDOWS, v.k) ? WINDOWS[v.k] : null;
if (!W || !Object.keys(v).every((x) => x === 'k' || x === 'ui')) return 'bad ctx.win';
if (v.ui !== undefined && !(plain(v.ui) && Object.keys(v.ui).every((u) => (W.ui || []).includes(u) && (v.ui[u] === null || (typeof v.ui[u] === 'string' && SHORT_RE.test(v.ui[u]) && !badVal(v.ui[u])))))) return 'bad ctx.win.ui';
}
else return `unknown ctx.${String(k).slice(0, 20)}`;
}
return null;
}
const bool = (v) => v === undefined || typeof v === 'boolean';
/* The envelope of one request body, before anything reaches a game. kind: 'act' | 'ask' | 'vote' | 'here' | 'prefs'.
opts.sim: the server's build id; a request built by another one answers 409 {old:true}. Returns {ok:true} or
{ok:false, code (400 or 409), error, old?}. Only shapes are checked here; what the ids name is the realm's to check.
One repair, in place: ctx.w and ctx.h (any finite width up to 100000) are clamped into VIEW_MIN–VIEW_MAX, so the
realm only ever sees a viewport in that range. */
function checkEnvelope(kind, body, opts = {}) {
if (!plain(body)) return bad('the body must be a JSON object');
const keys = Object.keys(body);
const only = (allowed) => { for (const k of keys) if (!allowed.includes(k)) return `unknown field ${JSON.stringify(k).slice(0, 40)}`; return null; };
const simOk = () => {
if (typeof body.sim !== 'string' || !SIM_RE.test(body.sim)) return bad('sim must be the page\'s build id');
if (opts.sim && body.sim !== opts.sim) return bad('this page is from another build', 409, { old: true });
return null;
};
if (kind === 'act' || kind === 'ask') {
const e = only(kind === 'act' ? ['rid', 'dev', 'sim', 'act', 'args', 'ui', 'confirmed', 'ctx'] : ['rid', 'dev', 'sim', 'act', 'args', 'ctx']);
if (e) return bad(e);
if (typeof body.rid !== 'string' || !ID_RE.test(body.rid)) return bad('bad rid');
if (typeof body.dev !== 'string' || !ID_RE.test(body.dev)) return bad('bad dev');
const s = simOk(); if (s) return s;
if (typeof body.act !== 'string' || !(kind === 'act' ? SETS.SEND : SETS.ASK).has(body.act)) return bad(`${kind} ${JSON.stringify(String(body.act).slice(0, 40))} is not one the server runs`);
const a = checkArgs(body.act, body.args === undefined ? {} : body.args); if (a) return bad(a);
if (body.ui !== undefined) {
if (kind !== 'act' || !plain(body.ui)) return bad('bad ui');
const allowed = own(DRAFTS, body.act) ? DRAFTS[body.act] : [];
for (const k of Object.keys(body.ui)) if (!allowed.includes(k) || !checkDraft(k, body.ui[k])) return bad(`bad ui.${String(k).slice(0, 20)}`);
}
if (body.confirmed !== undefined && (body.confirmed !== true || !SETS.CONFIRM.has(body.act))) return bad('confirmed only goes with a two-click act');
if (body.ctx !== undefined) { const c = checkCtx(body.ctx); if (c) return bad(c); }
return { ok: true };
}
if (kind === 'vote') {
const e = only(['speed', 'sim']); if (e) return bad(e);
const s = simOk(); if (s) return s;
if (body.speed !== null && !SPEEDS.includes(body.speed)) return bad('bad speed');
return { ok: true };
}
if (kind === 'here') {
const e = only(['dev', 'hidden', 'hold', 'idle', 'away', 'view']); if (e) return bad(e);
if (typeof body.dev !== 'string' || !ID_RE.test(body.dev)) return bad('bad dev');
if (!['hidden', 'hold', 'idle', 'away'].every((k) => bool(body[k]))) return bad('bad flag');
if (body.view !== undefined) {
const v = body.view;
if (v !== null && !(plain(v) && Object.keys(v).every((k) => (k === 'link' || k === 'peer') && (v[k] === null || (typeof v[k] === 'string' && SHORT_RE.test(v[k])))))) return bad('bad view');
}
return { ok: true };
}
if (kind === 'prefs') {
const e = only(['prefs', 'lang']); if (e) return bad(e);
if (body.prefs !== undefined && !(plain(body.prefs) && Object.keys(body.prefs).every((k) => PREFS.includes(k) && typeof body.prefs[k] === 'boolean'))) return bad('bad prefs');
if (body.lang !== undefined && !(typeof body.lang === 'string' && /^[a-z]{2}(-[A-Za-z]{2,4})?$/.test(body.lang))) return bad('bad lang');
return { ok: true };
}
return bad(`unknown kind ${String(kind).slice(0, 20)}`);
}
// Body size caps per kind, in bytes (section 10), for the host's readJson.
const BODY_MAX = { act: 16384, ask: 8192, here: 2048, prefs: 1024, vote: 256 };
module.exports = { SEND, ASK, VOTE, LOCAL, PUZZLE, CONFIRM, SRV_ARM, armKey, DRAFTS, DRAFT_TYPES, TEXT, QUOTE, WINDOWS, SPEEDS, PREFS, VIEW_MIN, VIEW_MAX, BODY_MAX, checkEnvelope };

View file

@ -1,271 +0,0 @@
// The server-run engine (the server-sim design, sections 4.2-4.3): a small pool of worker threads (mp-sim-worker.js),
// each holding the vm realms (mp-sim-realm.js) of the sessions placed on it, behind a promise API. The session host
// (scripts/lib/mp-sim.js) keeps the clock, presence and votes, and asks this for days, actions, what-ifs and pulls.
// tests/lib/mp-sim-fake-engine.js has the same API with canned answers.
//
// const engine = createEngine({workers: 2, heapMb: 1536, root, log, maxOwn: 4, onLost});
// engine.load(code, [{nid, env?, begin?, lang, prefs, rng?}]) → [{t:'loaded', nid, epoch, day, lost, saved?} |
// {t:'loaded', nid, err}], one per network, in order. env: the checkpoint envelope {s, uidN, rt, last,
// day} (s: the save text; rt: what the realm needs besides it to play on exactly as before, opaque
// here: route memory, R's routing point, key order, the sales desk's memory); begin: {name, home,
// preset, asn, mp, tut, day?} builds a new network, checkpointed at once (saved); day is the
// session's date, where it begins (absent or 0: the session's first day). A network that comes
// without a save, whose save does not load, or that cannot begin answers err: broken (4.7), and
// the others load. A load of a network that is loaded replaces its realm (a failed one leaves none).
// engine.day(code, {d, speed, last, alone:[nid], nets:[nid], mute}) → {t:'dayDone', code, d, nets:{[nid]: {day, lost,
// pause?, err?, retried?, ms}}}. Each network in sorted order; one that failed twice answers err and
// its day as it was, and is broken from then on (no more days; actions answer 'stopped'). One
// calendar for the session: the host (T3) checks that every network's day here is d, lost and
// broken networks excepted; the engine does not.
// engine.act(code, nid, msg) → {t:'actDone', nid, epoch, rid, outcome, why?, v, upd, ms} (upd: the update with the
// result, version v; null when stopped) | {t:'err', code, nid, rid, what:'timeout'|'throw', msg}
// engine.ask(code, nid, msg) → {t:'askDone', nid, rid, modal?, ui?, err?, ms} (neither modal nor err: the what-if
// opened nothing) | {t:'err', …}
// engine.pull(code, nid, {snap, views}) → {t:'pulled', nid, epoch, v, upd?, snap?, subs?, ms}. snap is the realm's
// half of a snapshot: snapWith(snap, {clock, roster, since}) makes the stream event.
// ms: the worker's time for the call (the mark, the realm, the update), without the wait behind other calls: what
// the host's rate limit of worker time counts (section 10).
// engine.sub(code, nid, {views}) → {t:'subbed', nid, epoch, v, subs}; engine.greet(code, nid) → a pulled
// engine.prefs(code, nid, {prefs}) → undefined (or the {t:'err'} of a realm that failed);
// engine.save(code, nid) → {t:'saved', nid, txt, uidN, rt, day, lost}; engine.card(code, nid) → {t:'card', nid, card}
// engine.unload(code, nid?) → {t:'unloaded', code, nid?}; engine.has(code, nid) → whether that network has a realm
// engine.stats() → {workers, realms, sessions} (not a promise); engine.mem() → each pool worker's heap and rss
// engine.close() → stops the workers
// engine.simId the build id this engine's game belongs to (SIM_ID of the multiplayer page from the same src/). The
// game text is read once, here: every worker, also one started after an exit, runs that game, and
// a src/ that does not compile makes createEngine throw.
//
// Rejections: a call for a network that is not loaded (code 'NO_REALM'), a malformed call (code 'ERR': a load that
// names no network, or one twice, changes nothing), every call pending on a worker that exits (out of memory, a crash):
// Error('worker exited'), code 'EXIT', and every call while no worker can start (code 'SIM_DOWN', 503 for the host).
// Every call is answered or rejected; none waits for ever.
// Lost networks. A worker that exits takes the realms of every session on it, also of those with no call pending, and
// the worker drops a network whose realm cannot be built again after a failure. Such a network answers NO_REALM: for a
// network the host believes loaded, NO_REALM means "load it again from its checkpoint" (4.7). opts.onLost(code, nids,
// why) says it as it happens ('exit', or the worker's reason).
// Blame. An exit counts against the session the worker was running (a call or a step that crashed or overflowed it),
// else against those whose load was under way, else against every session it held; a worker that never started
// blames nobody. A session with two exits against it within an hour gets a worker of its own (at most opts.maxOwn of
// them, 4 by default: past that it is given up); when that one exits too, its loads reject with code 'GAVE_UP' until
// the engine is made again (the server restarts). A worker that exits before it is ready is started again after a
// pause that doubles; after 5 such starts in a row the engine is down (SIM_DOWN). A session stays on its worker while
// a load of it is under way, so an unload and a load sent back to back (a language change) land on the same worker.
// Epochs: every realm load mints one (a load, a begin, the fresh realm after a timeout); loaded, pulled, actDone and
// subbed carry the realm's current one. Versions are the realm's: only a pull (or an action's own pull) makes one.
//
// Tests only, with createEngine({test: {seed, now, step} | true}): engine.eval(code, nid, src) runs code in a realm
// ({value} | {error} | {timeout, epoch}); engine.kill(i) ends pool worker i, engine.killOf(code) the worker of that
// session; engine.workerOf(code) is its pool index (-1: none, or its own), engine.dedicated(code) whether it has a
// worker of its own, engine.running(i) the session pool worker i is running as far as the engine knows.
// opts.test.startFail: no worker starts; opts.startBackoffMs: the first pause before starting one again (1000).
'use strict';
const path = require('node:path');
const vm = require('node:vm');
const { Worker } = require('node:worker_threads');
const page = require('./page');
const { gameSource } = require('./mp-sim-realm');
const FILE = path.join(__dirname, 'mp-sim-worker.js');
const HOUR = 3600e3;
/* The stream event of a snapshot: the realm's half (S, r, keep, epoch, v, now) with the host's (clock, roster,
since), joined as text: the realm's 270 KB are never parsed again. */
function snapWith(snap, { clock, roster, since }) {
if (typeof snap !== 'string' || !snap.endsWith('}')) throw new Error('snapWith: not a snapshot');
return snap.slice(0, -1) + ',"clock":' + JSON.stringify(clock) + ',"roster":' + JSON.stringify(roster) + ',"since":' + JSON.stringify(since) + '}';
}
function createEngine(opts = {}) {
if (!vm.constants || vm.constants.DONT_CONTEXTIFY === undefined) {
throw new Error(`server-run play needs Node 22.8 or newer (vm.constants.DONT_CONTEXTIFY); this is ${process.version}`);
}
const N = Math.max(1, Math.floor(+opts.workers || 2));
const heapMb = Math.max(64, Math.floor(+opts.heapMb || 1536));
const maxOwn = Math.max(0, Math.floor(opts.maxOwn !== undefined ? +opts.maxOwn || 0 : 4));
const backoff = Math.max(1, +opts.startBackoffMs || 1000);
const log = typeof opts.log === 'function' ? opts.log : () => {};
const lostTo = (code, nids, why) => { if (typeof opts.onLost === 'function' && nids.length) try { opts.onLost(code, nids, why); } catch (e) { log('error', 'mp-sim: onLost threw: ' + (e && e.message)); } };
const test = opts.test || null;
// The game, read once, here: a src/ that does not compile throws now, and every worker runs the game simId names.
const root = opts.root || page.ROOT, src = gameSource({ root, page: opts.page });
try { new vm.Script(src, { filename: 'game.js' }); } catch (e) { throw new Error(`mp-sim: the game in ${path.join(root, 'src')} does not compile: ${e.message}`); }
const simId = page.simId(page.assemble({ src: path.join(root, 'src'), mp: true }).html);
const W = { root: opts.root, page: opts.page, src, simId, test, strict: opts.strict !== undefined ? !!opts.strict : process.env.SIM_STRICT === '1', timeouts: opts.timeouts };
let seq = 0, closed = false, down = null, fails = 0;
const DOWN = () => Object.assign(new Error(`server-run play is down: ${down}`), { code: 'SIM_DOWN' });
const CLOSED = () => Object.assign(new Error('engine closed'), { code: 'CLOSED' });
// Why no call can go out now: closed, or down (else null).
const shut = () => (closed ? CLOSED() : down ? DOWN() : null);
const pool = [], own = new Map(), placed = new Map(), exits = new Map(), gaveUp = new Set();
// A worker's realms (sessions: code → its loaded nids), and for placement the networks of its loads under way too
// (loading: code → how many).
const size = (w) => [...w.sessions.values()].reduce((a, b) => a + b.size, 0);
const count = (w) => size(w) + [...w.loading.values()].reduce((a, b) => a + b, 0);
function spawn(dedicated = false) {
const w = { worker: null, pending: new Map(), sessions: new Map(), loading: new Map(), dedicated, dead: false, ready: false, fatal: null, running: null };
w.worker = new Worker(FILE, { workerData: { mpSim: W }, resourceLimits: { maxOldGenerationSizeMb: heapMb } });
w.worker.on('message', (m) => {
if (m.log) { log(m.log[0], m.log[1]); return; }
if (m.fatal) { w.fatal = String(m.fatal).split('\n')[0].slice(0, 300); return; }
if (m.ready) { w.ready = true; fails = 0; return; }
// The session it runs from now until its next reply: whose doing an exit then is.
if ('run' in m) { w.running = m.run; return; }
if (m.lost) { const s = w.sessions.get(m.lost.code); if (s) s.delete(m.lost.nid); lostTo(m.lost.code, [m.lost.nid], m.lost.why); return; }
w.running = null;
const p = w.pending.get(m.id);
if (!p) return;
w.pending.delete(m.id);
// An idle worker does not keep the process alive; one with calls pending does.
if (!w.pending.size) w.worker.unref();
if (m.ok) p.ok(m.reply);
else p.no(Object.assign(new Error(m.error.message), { code: m.error.code }));
});
w.worker.on('error', (e) => log('error', 'mp-sim worker failed: ' + (e && e.message)));
w.worker.on('exit', (c) => died(w, c));
w.worker.unref();
return w;
}
function died(w, c) {
if (w.dead) return;
w.dead = true;
// Whose exit it is: the session it was running (a call or a step that crashed or overflowed it), else those whose
// load was under way, else every session it held; nobody's when it never started. The others lose their realms
// (the host loads them again) without an exit against them.
const held = new Set([...w.sessions.keys(), ...w.loading.keys()]);
const blamed = new Set(!w.ready ? [] : w.running && held.has(w.running) ? [w.running] : w.loading.size ? w.loading.keys() : held);
const e = Object.assign(new Error('worker exited'), { code: 'EXIT', exitCode: c });
for (const p of w.pending.values()) p.no(e);
w.pending.clear();
const t = Date.now();
for (const code of held) {
if (placed.get(code) === w) placed.delete(code);
lostTo(code, [...(w.sessions.get(code) || [])], 'exit');
if (!blamed.has(code)) continue;
if (w.dedicated) { gaveUp.add(code); own.delete(code); log('error', `mp-sim: session ${code} took down its own worker too; not loading it again until a restart`); continue; }
exits.set(code, (exits.get(code) || []).filter((x) => t - x < HOUR).concat(t));
}
w.sessions.clear(); w.loading.clear();
for (const [k, x] of own) if (x === w) own.delete(k);
if (closed) return;
const i = pool.indexOf(w);
if (!w.ready) {
// It never started (the game does not run in a worker): not again at once, but after a pause that doubles; after
// 5 such starts in a row, server-run play is down until the engine is made again.
if (++fails >= 5) { if (!down) { down = w.fatal || `a worker exited before it started (code ${c})`; log('error', `mp-sim: no worker can start (${down}); server-run play is down until a restart`); } return; }
log('warn', `mp-sim: a worker could not start (${w.fatal || 'code ' + c}); trying again in ${backoff * 2 ** (fails - 1)} ms`);
if (i >= 0) setTimeout(() => { if (!closed && !down && pool[i] === w) pool[i] = spawn(); }, backoff * 2 ** (fails - 1)).unref();
return;
}
log('warn', `mp-sim: a worker exited (code ${c}); its sessions load again from their checkpoints`);
if (i >= 0) pool[i] = spawn();
}
for (let i = 0; i < N; i++) pool.push(spawn());
// The worker of a session: where it is, else the pool's least loaded one (or one of its own, after two exits).
function workerOf(code, create) {
let w = placed.get(code);
if (w && !w.dead) return w;
if (!create) return null;
if (down) throw DOWN();
if (gaveUp.has(code)) throw Object.assign(new Error(`session ${code} kept failing its worker`), { code: 'GAVE_UP' });
if ((exits.get(code) || []).filter((x) => Date.now() - x < HOUR).length >= 2) {
if (own.size >= maxOwn) {
gaveUp.add(code);
log('error', `mp-sim: session ${code} keeps failing its worker, and ${own.size} sessions have workers of their own already; not loading it again until a restart`);
throw Object.assign(new Error(`session ${code} kept failing its worker`), { code: 'GAVE_UP' });
}
w = spawn(true); own.set(code, w);
} else {
const live = pool.filter((x) => !x.dead);
if (!live.length) throw Object.assign(new Error('no worker is up yet: try again'), { code: 'SIM_DOWN' });
w = live.reduce((a, b) => (count(b) < count(a) ? b : a));
}
placed.set(code, w);
return w;
}
function send(w, m) {
if (closed) return Promise.reject(CLOSED());
if (!w || w.dead) return Promise.reject(Object.assign(new Error('worker exited'), { code: 'EXIT' }));
const id = ++seq;
return new Promise((ok, no) => {
if (!w.pending.size) w.worker.ref();
w.pending.set(id, { ok, no });
// A message that cannot be sent (not cloneable) is a malformed call, and nothing waits for its answer.
try { w.worker.postMessage({ id, ...m }); } catch (e) { w.pending.delete(id); if (!w.pending.size) w.worker.unref(); no(Object.assign(new Error(String((e && e.message) || e)), { code: 'ERR' })); }
});
}
const noRealm = (code, nid) => Promise.reject(Object.assign(new Error(`no realm ${code}/${nid}`), { code: 'NO_REALM' }));
const to = (code, nid, m) => { const x = shut(); if (x) return Promise.reject(x); const w = workerOf(code, false); return w ? send(w, { code, nid, ...m }) : noRealm(code, nid); };
const mine = (w, code) => { let s = w.sessions.get(code); if (!s) w.sessions.set(code, s = new Set()); return s; };
const engine = {
simId,
load(code, nets) {
{ const x = shut(); if (x) return Promise.reject(x); }
if (!Array.isArray(nets) || !nets.length) return Promise.reject(Object.assign(new Error('load: give the networks to load'), { code: 'ERR' }));
let w;
try { w = workerOf(code, true); } catch (e) { return Promise.reject(e); }
// Under way: the session is on this worker from now (an exit meanwhile counts against it, and its placement holds).
const n = nets.length, done = () => { const k = (w.loading.get(code) || 0) - n; if (k > 0) w.loading.set(code, k); else w.loading.delete(code); };
w.loading.set(code, (w.loading.get(code) || 0) + n);
return send(w, { t: 'load', code, nets }).then((r) => {
done();
const s = mine(w, code);
for (const l of r) if (!l.err) s.add(l.nid); else s.delete(l.nid);
return r;
}, (e) => { done(); throw e; });
},
day(code, { d, speed = 1, last = 1, alone = [], nets = [], mute = false } = {}) {
{ const x = shut(); if (x) return Promise.reject(x); }
const w = workerOf(code, false);
if (!w) return Promise.reject(Object.assign(new Error(`no session ${code} here`), { code: 'NO_REALM' }));
return send(w, { t: 'day', code, d, speed, last, alone, nets, mute });
},
act(code, nid, msg) { return to(code, nid, { t: 'act', msg }); },
ask(code, nid, msg) { return to(code, nid, { t: 'ask', msg }); },
pull(code, nid, { snap = false, views } = {}) { return to(code, nid, { t: 'pull', snap: !!snap, ...(views ? { views } : {}) }); },
sub(code, nid, { views = [] } = {}) { return to(code, nid, { t: 'sub', views }); },
prefs(code, nid, { prefs } = {}) { return to(code, nid, { t: 'prefs', prefs }).then((r) => (r && r.t === 'err' ? r : undefined)); },
greet(code, nid) { return to(code, nid, { t: 'greet' }); },
save(code, nid) { return to(code, nid, { t: 'save' }); },
card(code, nid) { return to(code, nid, { t: 'card' }); },
unload(code, nid) {
if (closed) return Promise.reject(CLOSED());
const w = workerOf(code, false);
if (!w) return Promise.resolve({ t: 'unloaded', code, ...(nid !== undefined ? { nid } : {}) });
return send(w, { t: 'unload', code, ...(nid !== undefined ? { nid } : {}) }).then((r) => {
const s = w.sessions.get(code);
if (s) { if (nid === undefined) s.clear(); else s.delete(nid); }
// Gone from here, unless a load of it sent after this unload is under way.
if ((!s || !s.size) && !w.loading.has(code)) { w.sessions.delete(code); if (placed.get(code) === w) placed.delete(code); }
// A worker of its own with nothing on it and nothing pending is done (with a call pending it would never answer).
if (w.dedicated && !w.dead && !w.sessions.size && !w.loading.size && !w.pending.size) { if (own.get(code) === w) own.delete(code); w.dead = true; w.worker.terminate(); }
return r;
});
},
has(code, nid) { const w = placed.get(code), s = w && !w.dead && w.sessions.get(code); return !!(s && s.has(nid)); },
mem() { return Promise.all(pool.filter((w) => !w.dead).map((w) => send(w, { t: 'mem' }))); },
stats() {
const ws = [...pool, ...own.values()].filter((w) => !w.dead);
return { workers: ws.length, realms: ws.reduce((a, w) => a + size(w), 0), sessions: ws.reduce((a, w) => a + w.sessions.size, 0) };
},
close() {
closed = true;
const ws = [...pool, ...own.values()];
return Promise.all(ws.map((w) => (w.dead ? null : w.worker.terminate()))).then(() => undefined);
},
snapWith,
};
if (test) {
engine.eval = (code, nid, src, ms) => to(code, nid, { t: 'eval', src: String(src), ...(ms ? { ms } : {}) });
engine.kill = (i = 0) => { const w = pool[i]; if (w && !w.dead) w.worker.terminate(); };
engine.killOf = (code) => { const w = placed.get(code); if (w && !w.dead) w.worker.terminate(); };
engine.workerOf = (code) => pool.indexOf(placed.get(code));
engine.dedicated = (code) => !!(placed.get(code) && placed.get(code).dedicated);
engine.running = (i = 0) => (pool[i] ? pool[i].running : null);
}
return engine;
}
module.exports = { createEngine, snapWith };

View file

@ -1,565 +0,0 @@
// One network of a server session, run by the game's own code in a vm realm (the server-sim design, section 4.1).
// The realm is a vm context made with DONT_CONTEXTIFY, so it has its own intrinsics (a prototype polluted in one realm
// stays there) and runs at full speed. Into it go, in order: the prelude below (DOM stand-ins that record what the
// game writes and reads back, no-op timers that count, the network's language), the network's dictionary
// (site/i18n/<lang>.js, not English), the game script, and the epilogue (the srv… functions: what the server asks of a
// network, and the rebinds that turn toasts, sounds, windows and the like into effects, "fx", for the page).
//
// The worker (mp-sim-worker.js) calls into a realm only through call()/raw(): the input goes in as one JSON string
// (globalThis.__in), the answer comes back as one string, and no object crosses between host and realm. An answer is
// a JSON header, optionally followed by more parts, each on its own line (JSON text never holds a raw newline):
// srvPull answers `{"v":3,"parts":["upd","snap"]}\n<upd JSON>\n<snap JSON>`, ready to write to a stream.
// A call that throws inside the realm answers {"srvErr": stack}; a call after which the realm's built-ins are not what
// they were at load (a prototype written through) answers {"srvErr", "polluted":1}, and the realm must not be used for
// play again; a call that runs over its time limit throws ERR_SCRIPT_EXECUTION_TIMEOUT here, and the realm must not be
// used for play again either (a timeout skips finally blocks).
//
// gameSource({root, page}) the game script (the largest inline <script> of the assembled page)
// dictSource(lang, root) the source dictionary of a language, or null for English
// prelude(opts), EPILOGUE the realm's own code around the game, as plain strings
// compileCode({root, page, src, simId}) {game, epilogue, simId} as vm.Scripts, once per process (a worker); src and
// simId: the game text and build id the engine read once (every worker runs the same)
// new Realm({code, lang, dict, test, log, nid}) a realm, the game loaded; .call(name, input, ms), .raw(...)
// parts(text) [header, ...parts] of an answer
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const { assemble, simId, ROOT } = require('./page');
const ACTS = require('./mp-sim-acts');
/* The page whose game a realm runs: the plain one (design 4.1), never a multiplayer build's page. That one also holds
the server-play client (src/game/98-server-play/), whose rebinds of after, toast and save are for a page that shows
a server's network; inside the server's own realm they would have to be switched off one by one. The build id
(SIM_ID) still names the multiplayer page, which holds this game and its client both. */
const REALM_PAGE = Object.freeze({ dev: false, mp: false });
function gameSource({ root = ROOT, page = REALM_PAGE } = {}) {
const html = assemble({ src: path.join(root, 'src'), dev: !!page.dev, mp: !!page.mp }).html;
let best = '';
html.replace(/<script>([\s\S]*?)<\/script>/g, (m, s) => { if (s.length > best.length) best = s; return m; });
if (!best.includes('function dayTick')) throw new Error('mp-sim-realm: no game script in the assembled page');
return best;
}
const LANG_RE = /^[a-z]{2}$/;
function dictSource(lang, root = ROOT) {
if (!lang || lang === 'en') return null;
if (!LANG_RE.test(lang)) throw new Error(`mp-sim-realm: bad language ${JSON.stringify(String(lang).slice(0, 20))}`);
const f = path.join(root, 'site', 'i18n', lang + '.js');
if (!fs.existsSync(f)) throw new Error(`mp-sim-realm: no dictionary for ${lang}`);
return fs.readFileSync(f, 'utf8');
}
/* The realm's stand-ins (start: probe/srv-engine/common.js prelude({mode:'record'}), which kept S byte-identical to
jsdom over 30 big-network days). opts.seed: a test's seeded Math.random under the game's own seeded wrapper (the
harness's generator, so a realm and a test page draw the same numbers); opts.now: a test's pinned Date.now, moved on
by opts.step at every day. Without them the realm has its own Math.random and the real clock. */
function prelude({ lang = 'en', seed = null, now = null, step = 2500, test = false } = {}) {
const L = JSON.stringify(LANG_RE.test(lang) ? lang : 'en');
return `'use strict';
globalThis.self=globalThis;self.window=self;self.__TUBES_WORKER__=1;self.__TUBES_TEST__=true;
{const hn=__hostNow;self.performance={now:()=>hn(),mark(){},measure(){},timeOrigin:0};}
{const hl=__hostLog,f=l=>(...a)=>{try{hl(l,a.map(x=>x&&x.stack?x.stack:String(x)).join(' '));}catch(e){}};self.console={log:f('log'),info:f('info'),warn:f('warn'),error:f('error'),debug:f('debug'),trace:f('debug')};}
// No timers in a realm: nothing may run outside the worker's handling of a message. Calls are counted (the timer audit).
self.__SRV_T={n:0,at:${test ? '[]' : 'null'}};
{const t=k=>function(){__SRV_T.n++;if(__SRV_T.at&&__SRV_T.at.length<50)__SRV_T.at.push(k+': '+String(new Error().stack).split('\\n').slice(2,7).join(' < '));return 0;};
for(const k of ['setTimeout','setInterval','requestAnimationFrame','queueMicrotask','setImmediate','requestIdleCallback'])self[k]=t(k);
for(const k of ['clearTimeout','clearInterval','cancelAnimationFrame','clearImmediate','cancelIdleCallback'])self[k]=()=>{};}
${seed == null ? '' : `{let r=${(+seed | 0) || 12345};Math.random=()=>{r=(r*16807)%2147483647;return r/2147483647;};}`}
${now == null ? '' : `{let t=${+now};Date.now=()=>t;self.__srvClock=v=>{if(typeof v==='number')t=v;return t;};self.__srvStep=${+step || 0};}`}
const _n=new Proxy(function(){},{get:(t,k)=>k===Symbol.toPrimitive?()=>0:k==='then'?undefined:_n,apply:()=>_n,construct:()=>_n,set:()=>true});
const _store=()=>{const m=new Map();return {getItem:k=>m.has(String(k))?m.get(String(k)):null,setItem(k,v){m.set(String(k),String(v));},removeItem(k){m.delete(String(k));},clear(){m.clear();},key:i=>[...m.keys()][i]??null,get length(){return m.size;}};};
const _ent={amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:'\\u00a0',middot:'\\u00b7',times:'\\u00d7',rarr:'\\u2192',larr:'\\u2190',hellip:'\\u2026',mdash:'\\u2014',ndash:'\\u2013',bull:'\\u2022',deg:'\\u00b0',euro:'\\u20ac',thinsp:'\\u2009'};
const _txt=h=>String(h).replace(/<[^>]*>/g,'').replace(/&(#x[0-9a-f]+|#\\d+|[a-z]+);/gi,(m,e)=>e[0]==='#'?String.fromCodePoint(e[1]==='x'||e[1]==='X'?parseInt(e.slice(2),16):+e.slice(1)):(e in _ent?_ent[e]:m));
// Elements keep innerHTML, hidden and value, and answer textContent and firstElementChild from what was written; they
// have no children (morphKids would loop for ever on the inert proxy's endless nextSibling).
const _el=(tag,init)=>{const t={tagName:String(tag||'div').toUpperCase(),_h:'',hidden:true,value:'',firstChild:null,lastChild:null,nextSibling:null,previousSibling:null,parentNode:null,children:[],childNodes:[],attributes:[],...init};
return new Proxy(t,{get(o,k){if(k==='innerHTML')return o._h;if(k==='textContent')return _txt(o._h);
if(k==='firstElementChild'){const m=/^\\s*<([a-zA-Z][a-zA-Z0-9]*)\\b[^>]*>([\\s\\S]*?)<\\/\\1>/.exec(o._h);return m?_el(m[1],{_h:m[2]}):null;}
if(k==='querySelector'||k==='querySelectorAll')return s=>_q(o._h,s,k==='querySelectorAll');if(k==='classList')return _cls(o);
if(k in o)return o[k];return _n;},
set(o,k,v){if(k==='innerHTML')o._h=String(v);else if(k==='textContent')o._h=String(v).replace(/[&<>]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;'})[c]);else o[k]=v;return true;}});};
// Which window is open, as the game asks it (pieRe, bstdShown, routingRefresh, the sea survey: a class, or a [data-x] /
// [data-x="v"] marker inside the card), is answered from what was written, never with the inert proxy, which would say
// every window is open. Other selectors match nothing; matches carry their data-* attributes. (closest() stays inert:
// a stand-in has no ancestors, and the page's own start asks one for its chip.)
const _cls=o=>{const g=()=>String(o.className||'').split(/\\s+/).filter(Boolean),p=a=>{o.className=a.join(' ');};
return new Proxy({contains:c=>g().includes(String(c)),add:(...c)=>p([...new Set([...g(),...c.map(String)])]),remove:(...c)=>{const x=c.map(String);p(g().filter(y=>!x.includes(y)));},
toggle:(c,f)=>{c=String(c);const on=f===undefined?!g().includes(c):!!f;p(on?[...new Set([...g(),c])]:g().filter(y=>y!==c));return on;}},{get:(t,k)=>k in t?t[k]:_n});};
const _cc=x=>x.replace(/-([a-z])/g,(q,c)=>c.toUpperCase());
const _ds=a=>{const d=Object.create(null);a.replace(/\\sdata-([a-z0-9-]+)(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+)))?/gi,(m,k,x,y,z)=>{d[_cc(k.toLowerCase())]=_txt(x??y??z??'');return m;});return d;};
const _q=(h,sel,all)=>{const m=/^\\[data-([a-z0-9-]+)(?:=(?:"([^"]*)"|'([^']*)'|([^\\]"']*)))?\\]$/i.exec(String(sel).trim()),out=[];
if(m){const k=_cc(m[1].toLowerCase()),v=m[2]??m[3]??m[4],re=/<([a-zA-Z][a-zA-Z0-9]*)(\\s[^>]*)?>/g;let t;
while((t=re.exec(h))){const d=_ds(t[2]||'');if(Object.hasOwn(d,k)&&(v===undefined||d[k]===v)){out.push(_el(t[1],{dataset:d}));if(!all)break;}}}
return all?out:out[0]||null;};
const _byId=new Map();
const _doc=new Proxy({},{get(o,k){if(k==='createElement')return tag=>_el(tag);if(k==='getElementById')return id=>{if(!_byId.has(id))_byId.set(id,_el('div',{id}));return _byId.get(id);};return _n;},set:()=>true});
self.__srvEl=_byId;self.__srvCoarse=false;
for(const [k,v] of Object.entries({document:_doc,localStorage:_store(),sessionStorage:_store(),innerWidth:1024,innerHeight:768,devicePixelRatio:1,
matchMedia:q=>({matches:/pointer:\\s*coarse/.test(String(q))?!!self.__srvCoarse:false,addEventListener(){},removeEventListener(){},addListener(){},removeListener(){}}),
Image:_n,Audio:_n,AudioContext:undefined,webkitAudioContext:undefined,screen:_n,visualViewport:_n,history:_n,getComputedStyle:_n,ResizeObserver:_n,MutationObserver:_n,IntersectionObserver:_n,Path2D:_n,scrollTo(){},
SOT_LANG:${L},SOT_LANGS:{en:'English',it:'Italiano',pt:'Português',fr:'Français',es:'Español',de:'Deutsch'},I18N:{},
location:{href:'https://server.invalid/',protocol:'https:',hostname:'server.invalid',host:'server.invalid',origin:'https://server.invalid',search:'',hash:'',pathname:'/',reload(){},replace(){},assign(){}},
addEventListener(){},removeEventListener(){},dispatchEvent(){return true;},
// Nothing reaches out of a realm: no channels, sockets or requests (fetch never settles), no workers.
BroadcastChannel:undefined,WebSocket:undefined,EventSource:undefined,Worker:undefined,fetch:()=>new Promise(()=>{}),
navigator:{language:${L},languages:[${L}],userAgent:'tubes-server',onLine:true,maxTouchPoints:0,hardwareConcurrency:1,vibrate:()=>false}}))
Object.defineProperty(self,k,{value:v,writable:true,configurable:true,enumerable:true});
`;
}
/* The epilogue: the server's side of a network, in the game's global scope. It only uses the game's own functions and
the tables of mp-sim-acts.js, written in as data. Everything a page needs to know comes out as fx or in the answers. */
const TABLES = JSON.stringify({ SEND: ACTS.SEND, ASK: ACTS.ASK, CONFIRM: ACTS.CONFIRM, DRAFTS: ACTS.DRAFTS, DRAFT_TYPES: ACTS.DRAFT_TYPES, PREFS: ACTS.PREFS, TEXT: ACTS.TEXT, WINDOWS: ACTS.WINDOWS });
const EPILOGUE = `'use strict';
const SIMT=${TABLES},SIM_SEND=new Set(SIMT.SEND),SIM_ASK=new Set(SIMT.ASK),SIM_KEEP=new Set(['badge','modal']);
const SIM_RNEVER=new Set(['ef','fl','efp','flc','efg','egDesc','l2route','bbF','peered','cityBlocked']);
const SIM_DRAFT=Object.keys(SIMT.DRAFT_TYPES);
// The realm's own memory: epoch and version of what it sent (5.10), the last keys sent, the fx and actions since the
// last pull, the marks, and what the running call saw (a window opened or closed, a refusal toast, an auto-pause).
const SIMR={epoch:'',v:0,seen:false,base:null,rSent:null,fx:[],acts:[],floats:0,alone:false,last:1,pause:false,modal:null,closed:false,bad:false,
mark:null,markK:null,markRt:null,strict:false};
const srvOwn=(o,k)=>Object.prototype.hasOwnProperty.call(o,k);
const srvOut=(h,...p)=>[JSON.stringify(h),...p].join('\\n');
function srvLog(t){console.warn(String(t).slice(0,600));}
/* The realm's built-ins as the game left them at load. A click that writes through a prototype (a city named
__proto__ or constructor) changes them, and every for…in, the game's and this file's, would carry that from then on.
The trampoline checks after every call; a realm whose built-ins changed is replaced like one that timed out. */
const srvFp=(()=>{const n=Object.getOwnPropertyNames,L=[Object,Object.prototype,Array,Array.prototype,Function.prototype,String.prototype,Number.prototype,Boolean.prototype,Map.prototype,Set.prototype];
return ()=>{for(const k in {})return 'Object.prototype.'+k;for(const k in [])return 'Array.prototype.'+k;return L.map(o=>n(o).length).join(',');};})();
const SIM_FP0=srvFp();
function srvDirty(){const f=srvFp();return f===SIM_FP0?'':/^(Object|Array)\\./.test(f)?f:'a built-in has a new property';}
// Strings no arg names: written through as a key, they reach a prototype. Free text (TEXT) may say them.
const SIM_BADV=new Set(['__proto__','constructor','prototype']);
const srvBadV=v=>typeof v==='string'?SIM_BADV.has(v):Array.isArray(v)?v.some(srvBadV):!!v&&typeof v==='object'&&Object.keys(v).some(k=>SIM_BADV.has(k)||srvBadV(v[k]));
const srvBadArgs=(act,a)=>{const t=srvOwn(SIMT.TEXT,act)?SIMT.TEXT[act]:{};return Object.keys(a).some(k=>SIM_BADV.has(k)||(!srvOwn(t,k)&&srvBadV(a[k])));};
/* fx: a ring of 200; when it overflows, the oldest go first, but badges and windows (win, lose) stay, at most 32. */
function srvFx(f){const q=SIMR.fx;q.push(f);
if(q.length>200){const i=q.findIndex(x=>!SIM_KEEP.has(x[0]));q.splice(i>=0?i:0,1);}
if(SIM_KEEP.has(f[0])){let n=0;for(const x of q)if(SIM_KEEP.has(x[0]))n++;if(n>32)q.splice(q.findIndex(x=>SIM_KEEP.has(x[0])),1);}}
// At most 60 in one update: floaters go first, then sounds and the like, then the oldest toasts; windows, badges,
// pauses and the chaos monkey's last word stay.
function srvCap(fx){if(fx.length<=60)return fx;let out=fx;
for(const k of ['floater','sfx','haptic','track','mk','told','toast']){let over=out.length-60;if(over<=0)break;
out=out.filter(f=>{if(over>0&&f[0]===k&&!(k==='mk'&&f[1]&&f[1].e==='end')){over--;return false;}return true;});}
return out.length>60?out.slice(-60):out;}
/* ---- capture: what the page shows, as fx (design 4.1's table) ---- */
toast=function(h,k='',a=[],o=null){if(S)logNote(h,k,a,o);if(k==='bad')SIMR.bad=true;srvFx(['toast',{h:String(h),k:String(k),a:Array.isArray(a)?a:[],o:o||null,tick:!!UI.tick}]);};
sfx=function(n){srvFx(['sfx',String(n)]);};
haptic=function(n){srvFx(['haptic',+n||12]);};
floater=function(x,y,t,c){if(SIMR.floats>=40)return;SIMR.floats++;srvFx(['floater',[+x||0,+y||0,String(t),String(c)]]);};
track=function(n,once){srvFx(['track',[String(n),!!once]]);};
// Alone, an auto-pause pauses the world (the host stops the clock after the day) and its toast's Resume votes for the
// speed it ran at; with others it does not pause, and the page offers a vote instead.
// Alone it stops this realm's clock too, as the page's does: a second auto-pause that day finds it paused (srvDay sets
// the speed again before the next day).
autoPause=function(){if(!S||!UI.speed)return false;SIMR.pause=true;srvFx(['pause',1]);if(!SIMR.alone)return false;UI.resumeSpeed=UI.lastSpeed=SIMR.last;UI.speed=0;return true;};
openModal=function(h,c=''){SIMR.modal={h:String(h),c:String(c||'')};const m=$('modal');m.className=String(c||'');m.hidden=false;$('modalCard').innerHTML=String(h);};
{const c0=closeModal;closeModal=function(){c0();SIMR.closed=true;};}
showWin=function(){srvFx(['modal','win']);};
showLose=function(){srvFx(['modal','lose']);};
showBaronWin=function(){srvFx(['modal','baron']);};
{const s0=mkStart,r0=mkRun,e0=mkEnd;
mkStart=function(c){s0(c);srvFx(['mk',{e:'start',c:String(c)}]);};
mkRun=function(l,dur,bad){r0(l,dur,bad);srvFx(['mk',{e:'run',link:l&&l.id!==undefined?String(l.id):null,felt:!!bad}]);};
mkEnd=function(ok,bye){e0(ok,bye);srvFx(['mk',{e:'end',ok:!!ok,bye:!!bye}]);};}
{const b0=checkBadges;checkBadges=function(){const a0=S&&S.ach?{...S.ach}:{},p0=S&&S.achP?{...S.achP}:{};b0();
if(S&&S.achP)for(const id of Object.keys(S.achP))if(a0[id]===undefined||p0[id]!==S.achP[id])srvFx(['badge',{id,v:String(S.achP[id])}]);};}
// Never shown here, and linkPanel would drop a selection it cannot find; the page keeps its own.
renderPanel=function(){};renderLeft=function(){};
// Checkpoints are the engine's (UI.slot is null anyway).
save=function(){};
// This realm is the server: a server network is never shown here.
srvOn=function(){return false;};
UI.clockLocked=true;UI.started=true;UI.pitched=true;UI.speed=1;
/* ---- S as top-level keys, R as the page gets it ---- */
function srvKeyJson(){const o=Object.create(null);for(const k of Object.keys(S)){const j=JSON.stringify(S[k]);if(j!==undefined)o[k]=j;}return o;}
function srvJoin(K){let t='{',f=true;for(const k in K){t+=(f?'':',')+JSON.stringify(k)+':'+K[k];f=false;}return t+'}';}
// Slim R (5.5): rwPack's view without the flow tables, routing's own inputs and what goes on demand; the top 4 networks
// per transit port, the top 8 over all of them, numbers to 6 significant digits. Packed once per R object.
const srvR6=(k,v)=>typeof v==='number'&&!Number.isInteger(v)&&Number.isFinite(v)?+v.toPrecision(6):v;
function srvSlimR(){const c=SIM_RTXT.get(R);if(c)return c;const o={};
for(const k in R){if(SIM_RNEVER.has(k))continue;o[k]=k==='ddos'?R.ddos.map(m=>({...m,attack:m.attack?m.attack.id:null,ports:null})):R[k];}
const tn={};for(const id in o.tNet)tn[id]=Object.fromEntries(Object.entries(o.tNet[id]).sort((a,b)=>b[1]-a[1]).slice(0,4));o.tNet=tn;
o.tTop8=transitTop(S.transit.map(t=>t.id),8);
const t=JSON.stringify(o,srvR6);SIM_RTXT.set(R,t);return t;}
const SIM_RTXT=new WeakMap();
/* ---- rt (4.1, 4.6): what a fresh realm needs besides the save to go on exactly as this one ---- */
// The route memory: what compute() reads of the R before it (R.load, R.l2route, R.efg cut to the scenic circuits' keys).
function srvRtOut(r){const efg={},E=r&&r.efg;
if(E)for(const id in E){const t=E[id]&&E[id].t;if(!t||!t.g)continue;const g=[],v=[];for(const [k,s] of t.g)if(String(k).startsWith('l2:')){g.push([k,v.length]);v.push(+t.v[s]);}if(g.length)efg[id]={g,v};}
return {load:(r&&r.load)||{},l2route:(r&&r.l2route)||{},efg};}
function srvRtIn(rt){const r=emptyR();if(!rt||typeof rt!=='object')return r;
if(rt.load&&typeof rt.load==='object')r.load=rt.load;if(rt.l2route&&typeof rt.l2route==='object')r.l2route=rt.l2route;
if(rt.efg&&typeof rt.efg==='object'){const o={};for(const id of Object.keys(rt.efg)){const t=rt.efg[id];if(t&&Array.isArray(t.g)&&Array.isArray(t.v))o[id]={g:new Map(t.g),v:t.v};}
Object.defineProperty(r,'efg',{value:rwEfgIn(o)});}
return r;}
/* The routing point. R after a day is the R of the day's last routing, which ran before the day's end changed S (bills,
moods, customers who left or signed) and started from the memory of the R before it. compute() of the saved S, even
from R's own memory, gives another R, and the next day reads it (eyeball growth, the peering share): a network
restored that way drifts from its first day on. So every compute() keeps, for the R it makes, S as it routed it (one
JSON per top-level key, 0.8 ms big) and the memory it started from. rt carries that point (pt: the memory, at: the
keys that changed since, gone: the keys S did not have then), and a fresh realm routes that S again from that memory:
the same R (srvReroute). Trials route and put R back: their points go with their R. */
const SIM_RIN=new WeakMap();
{const c0=compute;compute=function(){const k=S?srvKeyJson():null,rt=JSON.stringify(srvRtOut(R)),v=c0.apply(this,arguments);if(k)SIM_RIN.set(R,{k,rt});return v;};}
// The sales desk's memory (39-sales-auto.js): the offers it tried, which wait a week before it tries them again. It is
// not in S; rt carries the entries of offers still on the table (no other can count again).
function srvSlOut(){const t=UI.slTried;if(!t||t.s!==S||!t.m)return [];const ids=new Set(S.offers.map(o=>o.id));return [...t.m].filter(e=>ids.has(e[0]));}
function srvSlIn(sl){const m=new Map();if(Array.isArray(sl))for(const e of sl.slice(0,1000))if(Array.isArray(e)&&typeof e[0]==='string'&&Number.isInteger(e[1]))m.set(e[0],e[1]);UI.slTried=m.size?{s:S,m}:null;}
/* Key order: a reload gives some keys back with their keys in another order (a customer's defaults go last, the intern's
week tally comes back in its own order, and the week's report lists it in that order). At a checkpoint rt carries the
live text of each such key (ord, srvGate's round trip: ≈ 8 ms big, once per checkpoint), and a fresh realm takes it
only where it holds what sanitize() made of the save (srvSame): only the order comes from it. */
function srvOrdOut(txt,K){const u0=uidN,r0=S.rng;let B;
try{B=migrate(JSON.parse(txt));}catch(e){srvLog('checkpoint: the save does not load: '+String(e&&e.message||e));return '{}';}finally{uidN=u0;S.rng=r0;}
const o=[];for(const k in K)if(srvOwn(B,k)&&JSON.stringify(B[k])!==K[k])o.push(JSON.stringify(k)+':'+K[k]);return '{'+o.join(',')+'}';}
function srvOrdIn(o){if(!o||typeof o!=='object'||Array.isArray(o))return;for(const k of Object.keys(o))if(srvOwn(S,k)&&srvSame(o[k],S[k]))S[k]=o[k];}
// rt as JSON text: R's own route memory, its routing point against S as K holds it (when R was routed here), ord when
// given, and the desk's memory sl.
function srvRtText(r,K,ord,sl,rk){const p=K&&SIM_RIN.get(r);let t=JSON.stringify(srvRtOut(r)).slice(0,-1);
if(p){const at=[],gone=[];for(const k in p.k)if(K[k]!==p.k[k])at.push(JSON.stringify(k)+':'+p.k[k]);for(const k in K)if(!srvOwn(p.k,k))gone.push(k);
t+=',"pt":'+p.rt.slice(0,-1)+',"at":{'+at.join(',')+'},"gone":'+JSON.stringify(gone)+'}';}
return t+(ord?',"ord":'+ord:'')+(rk?',"rk":true':'')+',"sl":'+JSON.stringify(sl||[])+'}';}
// rk: R is the routing of S as it is (routeIfChanged's memory, UI.rk and UI.rkR, against K: routeKey() is the join of
// K without RK_SKIP). A fresh realm given it skips the routing of a click that changes nothing routing reads, as this
// one would; without it that click routes again, and compute() is not always a fixed point.
const srvRkOk=(r,K,rk,rkR)=>{if(!K||rkR!==r||typeof rk!=='string')return false;let t='{',f=true;for(const k in K){if(RK_SKIP.has(k))continue;t+=(f?'':',')+JSON.stringify(k)+':'+K[k];f=false;}return t+'}'===rk;};
const srvKeysOf=s=>{const o=JSON.parse(s),K=Object.create(null);for(const k of Object.keys(o)){const j=JSON.stringify(o[k]);if(j!==undefined)K[k]=j;}return K;};
// The S of a routing point (pt), one JSON per key: the loaded S with the keys of at put back and those of gone left out.
function srvAtK(pt){if(!pt||typeof pt!=='object'||!pt.at||typeof pt.at!=='object'||Array.isArray(pt.at)||!Array.isArray(pt.gone))return null;
const K=srvKeyJson();for(const k of Object.keys(pt.at))K[k]=JSON.stringify(pt.at[k]);for(const k of pt.gone)if(typeof k==='string')delete K[k];return K;}
// R as the routing point gives it: that S routed from that memory, then the loaded S again (R's attacks found in it).
function srvReroute(pt){const K=srvAtK(pt);if(!K)return false;const S1=S,u0=uidN;
try{S=JSON.parse(srvJoin(K));R=srvRtIn(pt);compute();}
catch(e){srvLog('routing the checkpoint again failed: '+String(e&&e.stack||e));return false;}
finally{S=S1;uidN=u0;}
srvAttacks();return true;}
// R with its point, when it came whole (rpack): a checkpoint before its next routing still carries the point.
function srvPointIn(r,pt){const K=srvAtK(pt);if(K)SIM_RIN.set(r,{k:K,rt:JSON.stringify({load:pt.load||{},l2route:pt.l2route||{},efg:pt.efg||{}})});}
// R's attacks are its only references into S (rwPack): looked up again in a new S.
function srvAttacks(){if(!R||!Array.isArray(R.ddos))return;const as=ddosAll(S,false);for(const x of R.ddos)if(x.attack)x.attack=as.find(a=>a.id===x.attack.id)||null;}
// mark: rt of the marked R against the marked S (a day's mark has it at once); else of R against S now.
function srvRt(inp){const m=inp?JSON.parse(inp):{},k=SIMR.mark;
if(!m.mark){const K=srvKeyJson();return srvRtText(R,K,'',srvSlOut(),srvRkOk(R,K,UI.rk,UI.rkR));}
if(SIMR.markRt)return SIMR.markRt;
if(!k)return srvRtText(R,null,'',[]);
const K=SIMR.markK||srvKeysOf(k.s);return srvRtText(k.R,K,'',k.sl,srvRkOk(k.R,K,k.ui.rk,k.ui.rkR));}
/* R itself, whole, for the fresh realm that replaces this one after a timeout (routing it again from its point costs a
routing; the old realm still answers), the way the route worker sends it (rwPack/rwUnpack), as text: Maps, Sets, typed
arrays and non-finite numbers tagged. A checkpoint carries the point instead: 20 KB gzip, where R is 375 KB. */
const SIM_TA=new Set(['Float64Array','Float32Array','Int32Array','Uint32Array','Int16Array','Uint16Array','Int8Array','Uint8Array','Uint8ClampedArray']);
const srvEnc=(k,v)=>typeof v==='number'&&!Number.isFinite(v)?{__n:String(v)}:v instanceof Map?{__m:[...v]}:v instanceof Set?{__s:[...v]}:ArrayBuffer.isView(v)&&SIM_TA.has(v.constructor.name)?{__t:v.constructor.name,a:Array.from(v)}:v;
const srvDec=(k,v)=>!v||typeof v!=='object'||Array.isArray(v)?v:'__n' in v?Number(v.__n):'__m' in v?new Map(v.__m):'__s' in v?new Set(v.__s):'__t' in v&&SIM_TA.has(v.__t)?new self[v.__t](v.a):v;
function srvRPack(inp){const m=inp?JSON.parse(inp):{},r=m.mark&&SIMR.mark?SIMR.mark.R:R;if(!r||!r.efp||!r.flc)return '';const {o,p}=rwPack(r);return JSON.stringify({o,p},srvEnc);}
function srvSetPrefs(p){if(!p||typeof p!=='object')return;for(const k of SIMT.PREFS)if(typeof p[k]==='boolean')PREFS[k]=p[k];}
/* The window the page has open (ctx.modal; ctx.win names it, mp-sim-acts.js WINDOWS): the stand-in #modal is that
window as the game asks it (its class, its marker), with the view state it draws from (checked here). No win: no
window, or one nothing asks about. The view state of an earlier request never stays. */
const SIM_WINUI=[...new Set(Object.values(SIMT.WINDOWS).flatMap(w=>w.ui||[]))];
const SIM_WINOK={opsCity:v=>srvOwn(S.pops,v),pieCity:v=>srvOwn(S.pops,v),pieTab:v=>PIE_TABS.includes(v)};
function srvWin(c){const w=c&&c.win&&typeof c.win==='object'?c.win:null,W=w&&typeof w.k==='string'&&srvOwn(SIMT.WINDOWS,w.k)?SIMT.WINDOWS[w.k]:null,m=$('modal');
for(const k of SIM_WINUI)delete UI[k];
m.hidden=!((c&&c.modal===true)||W);m.className=W?W.c:'';$('modalCard').innerHTML=W&&W.sel?'<div '+W.sel.slice(1,-1)+'></div>':'';
if(W&&W.ui&&w.ui&&typeof w.ui==='object')for(const k of W.ui){const v=w.ui[k];if(typeof v==='string'&&srvOwn(SIM_WINOK,k)&&SIM_WINOK[k](v))UI[k]=v;}}
function srvWinOff(){const m=$('modal');m.hidden=true;m.className='';$('modalCard').innerHTML='';}
function srvFresh(epoch){SIMR.epoch=String(epoch||'');SIMR.v=0;SIMR.seen=false;SIMR.fx=[];SIMR.acts=[];SIMR.floats=0;SIMR.rSent=new WeakRef(R);SIMR.base=srvKeyJson();SIMR.mark=null;SIMR.markK=null;SIMR.markRt=null;
UI.sel=null;UI.confirm=null;UI.pending=null;UI.started=true;UI.pitched=true;UI.clockLocked=true;srvWinOff();}
/* srvLoad: a network from its save (a checkpoint, or the mark of a realm that timed out) and its rt: S in its live key
order, R routed again from its routing point, the desk's memory; then the days to come are the ones the old realm
had. A realm that replaces one that timed out gets the old realm's R itself when it could still pack it (rpack); live:
the save is the old realm's own S as text (a mark), key order and all. An rt without a point (an older checkpoint)
seeds R with its memory before compute(), the way the route worker does: close, not always the same. A damaged rt
never breaks a save that loads: R is routed from nothing then (close, logged). fx: the fx a fresh realm takes over
from the one it replaces (srvFxOut). Only a server network loads: a Normal game with the session's marks (S.mp.sim;
a local save is stamped on its way in, 5.2), else the load fails with the reason. */
function srvLoad(inp){const m=JSON.parse(inp),rt=m.rt&&typeof m.rt==='object'?m.rt:{};SIMR.strict=!!m.strict;
S=migrate(JSON.parse(m.save));
{const no=S.mode!=='normal'||S.scn?'server networks are Normal games':!S.mp||S.mp.sim!==1?'not a server network (S.mp.sim)':'';if(no)throw new Error('srvLoad: '+no);}
if(typeof S.rng!=='number')S.rng=(m.rng|0)||1;
if(Number.isInteger(m.uidN)&&m.uidN>0)uidN=m.uidN;
srvSetPrefs(m.prefs);
// A test's pinned clock goes on where the realm this one replaces had it.
if(self.__srvClock&&typeof m.clock==='number')__srvClock(m.clock);
srvOrdIn(m.live?JSON.parse(m.save):rt.ord);
if(typeof m.rpack==='string'&&m.rpack){const x=JSON.parse(m.rpack,srvDec);R=rwUnpack(x.o,x.p);UI.hotMap=hotByCity();srvPointIn(R,rt.pt);}
else if(!srvReroute(rt.pt)){try{R=srvRtIn(rt);compute();}catch(e){srvLog('the route memory does not load ('+String(e&&e.message||e).slice(0,200)+'): routed from nothing');R=emptyR();compute();}}
if(rt.rk===true){UI.rk=routeKey();UI.rkR=R;}
srvSlIn(rt.sl);
srvFresh(m.epoch);
if(m.fx&&typeof m.fx==='object'&&Array.isArray(m.fx.fx)){SIMR.fx=m.fx.fx.filter(f=>Array.isArray(f)&&typeof f[0]==='string').slice(-200);SIMR.floats=Math.min(40,Math.max(0,m.fx.floats|0));}
// Whatever a loaded network says before its first snapshot (days nobody watched) is older than that snapshot: the
// first pull handles it like any (5.11). Only a new network's welcome waits for its first page (srvBegin).
SIMR.seen=true;
return JSON.stringify({day:S.day,lost:!!S.lost});}
const srvClockNow=()=>self.__srvClock?{clock:__srvClock()}:{};
// srvBegin: a new network of a server session (T1's beginState, then the server's own marks and the welcome). b.day: the
// session's date, where the network begins (one calendar for the session; 0 or none: its first day).
function srvBegin(inp){const m=JSON.parse(inp),b=m.begin||{};SIMR.strict=!!m.strict;
if(typeof b.home!=='string'||!homeOk(b.home))throw new Error('srvBegin: '+String(b.home).slice(0,20)+' cannot be a home city');
if(!b.mp||typeof b.mp!=='object')throw new Error('srvBegin: no session');
const D=b.day===undefined?0:b.day;
if(!Number.isInteger(D)||D<0||D>1e7)throw new Error('srvBegin: '+String(b.day).slice(0,20)+' is no start day');
srvSetPrefs(m.prefs);UI.pitched=true;
beginState(String(b.name||'').slice(0,24)||randomNetworkName(),b.home,{mode:'normal',preset:b.preset,mp:b.mp,asn:Number(b.asn),day:D});
if(!S.mp)throw new Error('srvBegin: the session did not take');
S.mp.sim=1;S.tut=b.tut?0:null;compute();srvFresh(m.epoch);
// The welcome: in S.log, and an fx that waits for the first update after the first snapshot (srvPullParts).
beginHello();
return JSON.stringify({day:S.day,lost:!!S.lost});}
function srvPrefs(inp){const m=JSON.parse(inp);srvSetPrefs(m.prefs);return '{}';}
/* srvMark: the restore point of the next day (day) or action (keys: one JSON per top-level key, whose join is the same
string, kept for the action's own comparison). The worker keeps the string, uidN and a day's rt too, to build a fresh
realm if this one times out. */
function srvMark(inp){const m=inp?JSON.parse(inp):{};let s,K=null;
if(m.keys||m.day){K=srvKeyJson();s=srvJoin(K);}else s=JSON.stringify(S);
SIMR.markK=m.keys?K:null;const sl=srvSlOut();
SIMR.mark={s,uidN,rng:S.rng,R,sl,...srvClockNow(),fx:SIMR.fx.slice(),floats:SIMR.floats,ui:{sel:UI.sel,tab:UI.tab,left:UI.left,confirm:UI.confirm,pending:UI.pending,rk:UI.rk,rkR:UI.rkR}};
// As text: nothing the day does reaches it.
const rtJ=m.day?srvRtText(R,K,'',sl,srvRkOk(R,K,UI.rk,UI.rkR)):'';SIMR.markRt=rtJ||null;const h=JSON.stringify({uidN,day:S.day,...srvClockNow()});
return (rtJ?h.slice(0,-1)+',"rt":'+rtJ+'}':h)+'\\n'+s;}
/* srvRestore: back to the mark, in place (after a throw: the finally blocks ran). S is parsed back only when it
changed, so the S object stays on every normal path; R is the marked object, its attacks looked up again in a parsed
S; the sales desk's memory is the marked one (a failed day may have added to it). (The design rebuilt R from route
memory after a failed day; that R is close, not the same: tests/mp-sim-determinism.) */
function srvRestore(inp){const k=SIMR.mark;if(!k)return '{"none":1}';
let parsed=false;if(JSON.stringify(S)!==k.s){S=JSON.parse(k.s);parsed=true;}
uidN=k.uidN;S.rng=k.rng;if(self.__srvClock&&typeof k.clock==='number')__srvClock(k.clock);
// R: the marked object. A day or an action routes into a new R (compute() never writes to the one it starts from),
// so the marked one is still the R the network had: route memory and compute() would only give one close to it.
R=k.R;if(parsed)srvAttacks();
UI.hotMap=hotByCity();UI.slTried=k.sl.length?{s:S,m:new Map(k.sl)}:null;
Object.assign(UI,k.ui);SIMR.fx=k.fx.slice();SIMR.floats=k.floats;SIMR.modal=null;SIMR.closed=false;srvWinOff();
return JSON.stringify({parsed});}
// The fx a fresh realm takes over from this one: the mark's after a failed call (its own fx are dropped, 4.3), else
// (a read that ran out of time) all of them. Badges and windows wait for a page for days; a timeout does not lose them.
function srvFxOut(inp){const m=inp?JSON.parse(inp):{},k=SIMR.mark;return JSON.stringify(m.mark&&k?{fx:k.fx,floats:k.floats}:{fx:SIMR.fx,floats:SIMR.floats});}
/* srvDay: one day of this network, as the page runs it (dayTick, then the day's end render), then the tutorial. mute:
a catch-up day, whose fx are dropped (badges and windows stay). */
function srvDay(inp){const m=inp?JSON.parse(inp):{};
if(!S||S.lost)return JSON.stringify({day:S?S.day:0,lost:true});
SIMR.alone=!!m.alone;SIMR.last=[0.5,1,2,4,8].includes(m.last)?m.last:1;SIMR.pause=false;
UI.speed=[0.5,1,2,4,8].includes(m.speed)?m.speed:1;UI.clockLocked=true;UI.started=true;
if(self.__srvClock&&self.__srvStep)__srvClock(__srvClock()+__srvStep);
const n0=SIMR.fx.length;
dayTick();UI.ticking=true;try{renderHUD();}finally{UI.ticking=false;}
tutAdvance();
if(m.mute)SIMR.fx=SIMR.fx.slice(0,n0).concat(SIMR.fx.slice(n0).filter(f=>SIM_KEEP.has(f[0])));
// Tests (SIM_STRICT): live S after a day is what a reload makes of it, every key (T1's canonical state).
if(SIMR.strict){const bad=srvGate(null).bad;if(bad.length)throw new Error('sanitize would repair day '+S.day+': '+bad.join(', '));}
// Done: the marked R (and its flow tables) need not stay alive until the next mark.
SIMR.mark=null;
return JSON.stringify({day:S.day,lost:!!S.lost,...(SIMR.pause?{pause:true}:{})});}
/* The sanitize gate (5.8 step 6): the keys an action changed must come through the save path as they are. Never adopts
the repaired copy (a new S without compute() would leave R's attacks pointing into the old one). keys null: all. */
const srvSortK=v=>Array.isArray(v)?v.map(srvSortK):v&&typeof v==='object'?Object.keys(v).sort().reduce((o,k)=>(v[k]!==undefined&&(o[k]=srvSortK(v[k])),o),Object.create(null)):v;
const srvSame=(a,b)=>{const x=JSON.stringify(a),y=JSON.stringify(b);return x===y||JSON.stringify(srvSortK(a))===JSON.stringify(srvSortK(b));};
function srvGate(keys){const u0=uidN,r0=S.rng;
try{const txt=JSON.stringify(packSave(S)),a=JSON.parse(txt),b=JSON.parse(JSON.stringify(packSave(migrate(JSON.parse(txt)))));
const ks=keys||[...new Set([...Object.keys(a),...Object.keys(b)])];return {bad:ks.filter(k=>!srvSame(a[k],b[k])),len:txt.length};}
finally{uidN=u0;S.rng=r0;}}
/* ---- actions (5.8) ---- */
const srvSel=v=>v&&typeof v==='object'&&typeof v.id==='string'&&(v.type==='city'?isCity(v.id):v.type==='link'?S.links.some(l=>l.id===v.id):false)?{type:v.type,id:v.id}:null;
function srvView(c){c=c&&typeof c==='object'?c:{};
innerWidth=Number.isFinite(c.w)?c.w:1024;innerHeight=Number.isFinite(c.h)?c.h:768;self.__srvCoarse=!!c.coarse;}
function srvArm(act,args){const t=SIMT.CONFIRM[act];return t.replace(/\\{(\\w+)\\}/g,(m,k)=>String(args&&args[k]!==undefined?args[k]:''));}
// The drafts an act reads, from the request, each checked against the game's catalogs; anything else is wiped first, so
// nothing of an earlier request leaks into this one. A bad one: the reason; the act does not run.
function srvDrafts(act,ui,args){for(const k of SIM_DRAFT){if(k==='pending')UI.pending=null;else delete UI[k];}
const allowed=SIMT.DRAFTS[act]||[];
for(const k of Object.keys(ui||{})){if(!allowed.includes(k))return 'draft '+k+' is not '+act+'\\'s';const v=ui[k];
if(k==='pending'){if(!v||typeof v!=='object'||!isCity(v.a)||!isCity(v.b)||v.a===v.b)return 'pending names no two places';UI.pending={a:v.a,b:v.b};}
else if(k==='route'){if(typeof v!=='string'||!/^(|same|diverse|t:[A-Za-z0-9_.:|~-]{1,40})$/.test(v))return 'bad route';UI.route=v;}
else if(k==='via'){if(!(v===''||v==='land'||(typeof v==='string'&&CABLES.some(c=>c.id===v))))return 'bad via';UI.via=v;}
else if(k==='dfSrc'){if(!['lease','build','cable'].includes(v))return 'bad dfSrc';UI.dfSrc=v;}
else if(k==='dfSys'){if(typeof v!=='string'||!srvOwn(DF_SYS,v))return 'bad dfSys';UI.dfSys=v;}
else if(k==='seaDesign'){if(typeof v!=='string'||!srvOwn(SEA_DESIGNS,v))return 'bad seaDesign';UI.seaDesign=v;}
else if(k==='decom'){if(!Array.isArray(v))return 'bad decom';UI.decom=new Set(v.filter(isCity).slice(0,200));}
else if(k==='slop'){if(typeof v!=='boolean')return 'bad slop';if(v&&typeof args.script==='string')UI.slop=args.script.slice(0,4000);}
else{if(typeof v!=='boolean')return 'bad '+k;UI[k]=v;}}
return null;}
function srvAct(inp){const m=JSON.parse(inp),act=String(m.act),ent={rid:String(m.rid),dev:String(m.dev),ui:{}};
if(!S||S.lost)return srvOut({outcome:'stopped',v:SIMR.v});
const args=m.args&&typeof m.args==='object'&&!Array.isArray(m.args)?m.args:{};
let outcome,why;const K0=SIMR.markK;
const done=(o,w)=>{outcome=o;why=w;};
if(!SIM_SEND.has(act)||!srvOwn(ACT,act)||typeof ACT[act]!=='function')done('rejected','not an act the server runs');
else if(srvBadArgs(act,args)||srvBadV(m.ui))done('rejected','an arg names a built-in');
else{const w=srvDrafts(act,m.ui,args);
if(w)done('rejected',w);
else{const c=m.ctx&&typeof m.ctx==='object'?m.ctx:{};
UI.sel=srvSel(c.sel);if(typeof c.tab==='string')UI.tab=c.tab;if(typeof c.left==='string')UI.left=c.left;srvView(c);srvWin(c);
let a2=args;UI.confirm=null;
if(m.confirmed===true&&srvOwn(SIMT.CONFIRM,act)){if(SIMT.CONFIRM[act]==='arg')a2={...args,ok:1};else UI.confirm=srvArm(act,args);}
const sent={sel:UI.sel,tab:UI.tab,left:UI.left,confirm:UI.confirm};
SIMR.modal=null;SIMR.closed=false;SIMR.bad=false;
let err=null;try{ACT[act](a2);tutAdvance();}catch(e){err=e;}
if(err){srvRestore('{}');srvLog('act '+act+' threw: '+String(err&&err.stack||err));done('error','the game threw: '+String(err&&err.message||err).slice(0,200));}
else{const K=srvKeyJson(),ch=[];for(const k in K)if(!K0||K0[k]!==K[k])ch.push(k);if(K0)for(const k in K0)if(!(k in K))ch.push(k);
if(!ch.length)done(SIMR.bad?'rejected':'no_effect');
else if(SIMR.bad&&ch.every(k=>k==='log'))done('rejected');
else{const g=srvGate(ch);let len=0,len0=0;for(const k in K)len+=K[k].length;if(K0)for(const k in K0)len0+=K0[k].length;
if(g.bad.length){srvRestore('{}');srvLog('sanitize would repair '+act+': '+g.bad.join(', '));done('error','sanitize would repair '+act+': '+g.bad.join(', '));}
else if(g.len>4194304||len-len0>262144){srvRestore('{}');srvLog('size guard: '+act);done('error','the network would grow too big');}
else done('applied');}
if(outcome!=='error'){for(const k of ['sel','tab','left','confirm'])if(JSON.stringify(UI[k]??null)!==JSON.stringify(sent[k]??null))ent.ui[k]=UI[k]??null;
if(SIMR.closed)ent.ui.closed=1;if(SIMR.modal)ent.ui.modal=SIMR.modal;}}}}
srvWinOff();SIMR.mark=null;SIMR.markK=null;SIMR.acts.push(ent);
const p=srvPullParts({});
return srvOut({outcome,...(why?{why}:{}),v:SIMR.v},p.upd);}
/* ---- asks (5.9): what-ifs that open a window and put everything back ---- */
function srvAsk(inp){const m=JSON.parse(inp),k=SIMR.mark,act=String(m.act),out={};
if(!SIM_ASK.has(act)||!srvOwn(ACT,act))return JSON.stringify({err:'not a what-if the server answers'});
const args=m.args&&typeof m.args==='object'&&!Array.isArray(m.args)?m.args:{},td=UI.teDraft,sl=UI.slop,fx0=SIMR.fx.slice(),fl=SIMR.floats,hot=UI.hotMap;
if(srvBadArgs(act,args))return JSON.stringify({err:'an arg names a built-in'});
srvView(m.ctx);srvWin(m.ctx);SIMR.modal=null;
try{ACT[act](args);}catch(e){out.err='the game threw: '+String(e&&e.message||e).slice(0,200);srvLog('ask '+act+' threw: '+String(e&&e.stack||e));}
if(SIMR.modal)out.modal=SIMR.modal;
if(act==='teCheck'||act==='teSlop'){out.ui={teDraft:typeof UI.teDraft==='string'?UI.teDraft:null};if(act==='teSlop')out.ui.slop=typeof UI.slop==='string'?UI.slop:null;}
R=k.R;UI.hotMap=hot;uidN=k.uidN;S.rng=k.rng;
if(JSON.stringify(S)!==k.s){srvLog('ask '+act+' changed the game: put back');srvRestore('{}');}
else Object.assign(UI,k.ui);
SIMR.mark=null;UI.teDraft=td;UI.slop=sl;SIMR.fx=fx0;SIMR.floats=fl;SIMR.modal=null;srvWinOff();
return JSON.stringify(out);}
/* ---- pulls (5.3-5.6, 5.10): the only place the version moves ---- */
function srvSubs(views){const o={};if(!Array.isArray(views))return o;
for(const w of views.slice(0,16)){if(!w||typeof w!=='object')continue;
if(typeof w.link==='string'){const l=S.links.find(x=>x.id===w.link),ef={},egd={};
if(l){const k=edgeKey(l),rec=R.ef&&R.ef[k];if(rec){ef[k]=rec;for(const e in rec.eg||{})if(R.egDesc&&R.egDesc[e])egd[e]=R.egDesc[e];}}
o['link:'+w.link]={ef,egd};}
if(typeof w.peer==='string'&&isCity(w.peer))o['peer:'+w.peer]={pf:{[w.peer]:S.pops[w.peer]?pniFlows(w.peer):{}}};}
return o;}
function srvPullParts(m,K){K=K||srvKeyJson();const now=Date.now();
// The first snapshot of an epoch, before any update: nobody holds anything of this realm yet, so there is no update to
// make; what happened meanwhile (a new network's welcome) waits for the first one, which that page will get.
if(m.snap&&!SIMR.seen){SIMR.seen=true;SIMR.base=K;SIMR.rSent=new WeakRef(R);
return {upd:'',snap:'{"t":"snap","epoch":'+JSON.stringify(SIMR.epoch)+',"v":'+SIMR.v+',"now":'+now+',"S":'+srvJoin(K)+',"r":'+srvSlimR()+',"keep":[]}',subs:m.views?srvSubs(m.views):null};}
const B=SIMR.base||Object.create(null),s=[],del=[];
for(const k in K)if(B[k]!==K[k])s.push(k);for(const k in B)if(!(k in K))del.push(k);
const rNew=!SIMR.rSent||SIMR.rSent.deref()!==R,fx=SIMR.fx,acts=SIMR.acts;let upd='';
if(s.length||del.length||rNew||fx.length||acts.length){const from=SIMR.v,v=++SIMR.v;
let t='{"t":"upd","from":'+from+',"v":'+v+',"now":'+now+',"day":'+S.day+',"s":{'+s.map(k=>JSON.stringify(k)+':'+K[k]).join(',')+'}';
if(del.length)t+=',"del":'+JSON.stringify(del);
if(rNew)t+=',"r":'+srvSlimR();
const cf=srvCap(fx);if(cf.length)t+=',"fx":'+JSON.stringify(cf);
if(acts.length)t+=',"acts":'+JSON.stringify(acts);
upd=t+'}';SIMR.base=K;SIMR.rSent=new WeakRef(R);SIMR.fx=[];SIMR.acts=[];SIMR.floats=0;SIMR.seen=true;}
let snap='';
// A snapshot at the same version: what the host adds (clock, roster, since) it adds to this text itself.
if(m.snap){const keep=fx.filter(f=>SIM_KEEP.has(f[0])).slice(-32);
snap='{"t":"snap","epoch":'+JSON.stringify(SIMR.epoch)+',"v":'+SIMR.v+',"now":'+now+',"S":'+srvJoin(K)+',"r":'+srvSlimR()+',"keep":'+JSON.stringify(keep)+'}';
SIMR.base=K;SIMR.rSent=new WeakRef(R);}
return {upd,snap,subs:m.views?srvSubs(m.views):null};}
function srvPull(inp){const m=inp?JSON.parse(inp):{},p=srvPullParts(m),parts=[],h={v:SIMR.v,parts};
if(p.upd)parts.push('upd');if(p.snap)parts.push('snap');if(p.subs)h.subs=p.subs;
return srvOut(h,...(p.upd?[p.upd]:[]),...(p.snap?[p.snap]:[]));}
function srvSub(inp){const m=inp?JSON.parse(inp):{};return JSON.stringify({v:SIMR.v,subs:srvSubs(m.views)});}
// The one-shots a page says when a network opens (the courtesy route, Australia's prices): they change S, so the
// server says them, as fx of the next update.
function srvGreet(inp){bootNotes();return srvPull(inp);}
// A checkpoint: the save and its rt, ord included.
function srvSave(){const txt=JSON.stringify(packSave(S)),K=srvKeyJson(),h=JSON.stringify({uidN,day:S.day,lost:!!S.lost,...srvClockNow()});
return h.slice(0,-1)+',"rt":'+srvRtText(R,K,srvOrdOut(txt,K),srvSlOut(),srvRkOk(R,K,UI.rk,UI.rkR))+'}\\n'+txt;}
function srvCard(){return JSON.stringify({card:mpCard()});}
`;
// The realm API: one precompiled trampoline per name. Input in __in, a string out; a throw comes back as {srvErr}, and
// changed built-ins as {srvErr, polluted}. The unchecked ones only read what a fresh realm needs from one that is done
// (its save, rt, R and fx): the worker's recovery after a timeout or a pollution.
const API = ['srvLoad', 'srvBegin', 'srvPrefs', 'srvMark', 'srvRestore', 'srvRt', 'srvRPack', 'srvFxOut', 'srvDay', 'srvAct', 'srvAsk', 'srvPull', 'srvSub', 'srvGreet', 'srvSave', 'srvCard'];
const PEEK = ['srvRt', 'srvRPack', 'srvFxOut', 'srvSave'];
let TRAMP = null, TRAMP0 = null;
const tramp = (n, check) => new vm.Script(`(()=>{let r;try{r=${n}(globalThis.__in);}catch(e){r=JSON.stringify({srvErr:String(e&&e.stack||e).slice(0,4000)});}`
+ (check ? `const d=srvDirty();return d?JSON.stringify({srvErr:'the built-ins of the realm changed: '+d,polluted:1}):r;})()` : 'return r;})()'), { filename: `srv-${n}.js` });
const tramps = (check = true) => (check ? TRAMP || (TRAMP = Object.fromEntries(API.map((n) => [n, tramp(n, true)])))
: TRAMP0 || (TRAMP0 = Object.fromEntries(PEEK.map((n) => [n, tramp(n, false)]))));
// Tests only (createEngine({test})): run a piece of code in a realm, answer its value as JSON.
const EVAL = new vm.Script('(()=>{const f=new Function(globalThis.__in);const v=f();return v===undefined?"null":JSON.stringify(v);})()', { filename: 'srv-test-eval.js' });
/* The game, the epilogue and the build id, compiled once per process. The engine passes the game text and its build
id (read once, in the main thread), so a worker started later runs the game the engine names, whatever src/ holds by
then; without them they are read from root. */
function compileCode({ root = ROOT, page = REALM_PAGE, src = null, simId: id = null } = {}) {
if (!vm.constants || vm.constants.DONT_CONTEXTIFY === undefined) {
throw new Error(`server-run play needs Node 22.8 or newer (vm.constants.DONT_CONTEXTIFY); this is ${process.version}`);
}
const game = typeof src === 'string' && src ? src : gameSource({ root, page });
return {
game: new vm.Script(game, { filename: 'game.js' }),
epilogue: new vm.Script(EPILOGUE, { filename: 'srv-epilogue.js' }),
simId: id || simId(assemble({ src: path.join(root, 'src'), mp: true }).html),
root,
};
}
const DICTS = new Map();
function dictScript(lang, root) {
const k = root + '|' + lang;
if (!DICTS.has(k)) { const s = dictSource(lang, root); DICTS.set(k, s ? new vm.Script(s, { filename: `i18n-${lang}.js` }) : null); }
return DICTS.get(k);
}
class Realm {
/* code: compileCode()'s; lang: the network's language; test: {seed, now, step} for tests; log(level, text). */
constructor({ code, lang = 'en', test = null, log = () => {}, loadMs = 30000 }) {
const t0 = performance.now();
const ctx = vm.createContext(vm.constants.DONT_CONTEXTIFY);
ctx.__hostNow = () => performance.now();
let n = 0, w0 = 0;
// The realm's console, rate-limited: 20 lines, then one a second.
ctx.__hostLog = (lvl, txt) => { const t = Date.now(); if (n > 20 && t - w0 < 1000) return; if (t - w0 >= 1000) { w0 = t; n = Math.min(n, 20); } n++; log(lvl, String(txt).slice(0, 2000)); };
// A language this server has no dictionary for plays in English (the page falls back the same way), not broken.
let d = null;
if (LANG_RE.test(lang) && lang !== 'en') { try { d = dictScript(lang, code.root); } catch (e) { log('warn', `no dictionary for ${lang}: English`); } }
this.lang = d ? lang : 'en';
new vm.Script(prelude({ lang: this.lang, test: !!test, ...(test || {}) }), { filename: 'srv-prelude.js' }).runInContext(ctx, { timeout: loadMs });
if (d) d.runInContext(ctx, { timeout: loadMs });
code.game.runInContext(ctx, { timeout: loadMs });
code.epilogue.runInContext(ctx, { timeout: loadMs });
// The no-op timers the page's own start called (two canvas resizes) are not a simulation's.
new vm.Script('__SRV_T.n=0;if(__SRV_T.at)__SRV_T.at.length=0;').runInContext(ctx);
this.ctx = ctx;
this.ms = performance.now() - t0;
}
// The answer as the realm gave it (a string). Throws ERR_SCRIPT_EXECUTION_TIMEOUT past ms. check false: one of PEEK,
// whatever the built-ins are now (recovery only).
raw(name, input, ms = 1000, check = true) {
const s = tramps(check)[name];
if (!s) throw new Error(`mp-sim-realm: no realm call ${name}`);
this.ctx.__in = input === undefined ? '' : JSON.stringify(input);
try { const r = s.runInContext(this.ctx, { timeout: ms }); return typeof r === 'string' ? r : ''; } finally { this.ctx.__in = ''; }
}
// The header parsed, plus the parts that follow it.
call(name, input, ms) { return parts(this.raw(name, input, ms)); }
// Tests only.
eval(src, ms = 5000) {
this.ctx.__in = String(src);
try { const r = EVAL.runInContext(this.ctx, { timeout: ms }); return JSON.parse(r); } finally { this.ctx.__in = ''; }
}
}
// [header (parsed), ...parts (strings)] of a realm's answer.
function parts(text) {
const t = String(text);
const i = t.indexOf('\n');
if (i < 0) return [JSON.parse(t || '{}')];
const rest = t.slice(i + 1).split('\n');
return [JSON.parse(t.slice(0, i)), ...rest];
}
const isTimeout = (e) => !!e && e.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT';
module.exports = { REALM_PAGE, gameSource, dictSource, prelude, EPILOGUE, API, compileCode, Realm, parts, isTimeout };

View file

@ -1,408 +0,0 @@
// A worker thread of the server-run engine (the server-sim design, section 4.2): it compiles the game once, holds the
// realms of the sessions placed on it (every network of a session in one worker), and answers the host's messages.
//
// Order. Messages run one at a time, in arrival order per network. A session's day is one task per network, in sorted
// network order, with a turn for other messages between two networks: an action for network X lands between days of
// other networks, never inside X's own day. The networks of a day are fixed when it starts. Loads, new networks and
// unloads of a session wait for its day; actions for a network that is still loading wait for it. Every message is
// answered: a load that names no network (or one twice), or a day whose lists are not lists, is refused whole and
// changes nothing; a network in a load that has no save, or whose save does not load, answers err (broken) and the
// others load. Nothing a message holds, and nothing a step throws, takes the worker down.
//
// Failures. Every realm call has a time limit (a day 2 s, an action 1 s, a what-if 3 s, a pull or a save 1 s). Before
// a day or an action the realm is marked (its S as text, uidN, the dice, and for a day its rt: route memory and routing
// point), and the worker keeps the mark. A mark changes nothing: one that fails leaves the realm as it was, and one
// that runs out of time has the realm built again from its own save, never from an older mark (that would undo what
// came after it). A call that throws has run its finally blocks: the realm goes back to the mark in place. A call that
// times out has not (vm skips them), and one after which the realm's built-ins changed (a prototype written through)
// left them changed: such a realm is never called again for play. A fresh one is built from the mark, with a new
// epoch, and takes over the fx the mark held. A failed day runs once more; failing again, the network is broken at its
// state before the day. When not even a fresh realm can be built, the network is dropped: its calls answer NO_REALM,
// and the engine is told ({lost}), so the host loads it again from its checkpoint (4.7).
//
// The worker → host replies are the shapes of tests/lib/mp-sim-shape.js checkWorker(), sent as {id, ok, reply} (or
// {id, ok:false, error}) for the engine to match its promises; logs go up as {log:[level, text]}, a dropped network as
// {lost:{code, nid, why}}, and before each job or step that runs a realm {run: code}, the session it runs (the engine
// forgets it at the next reply): a worker that dies then is that session's doing.
'use strict';
const { isMainThread, parentPort, workerData } = require('node:worker_threads');
const crypto = require('node:crypto');
const v8 = require('node:v8');
const { compileCode, Realm, isTimeout, parts } = require('./mp-sim-realm');
const TIMEOUTS = { day: 2000, act: 1000, ask: 3000, pull: 1000, save: 1000, mark: 1000, small: 1000, load: 30000 };
const now = () => performance.now();
const MSG = (e) => String((e && (e.stack || e.message)) || e).slice(0, 2000);
const LINE = (e) => String((e && e.message) || e).split('\n')[0].slice(0, 300);
const msOf = (t0) => +(now() - t0).toFixed(2);
/* opts: {root, page, src, simId, test: {seed, now, step} | true | null, strict, timeouts, log(level, text), post(message)}. */
function createCore(opts = {}) {
const code = compileCode({ root: opts.root, page: opts.page, src: opts.src, simId: opts.simId });
const T = { ...TIMEOUTS, ...(opts.timeouts || {}) };
const test = opts.test ? (typeof opts.test === 'object' ? opts.test : {}) : null;
const log = opts.log || (() => {});
const post = opts.post || (() => {});
const realms = new Map(), sessions = new Map(), jobs = [];
let epochN = 0, pumping = false, turn = 0;
const key = (c, n) => c + '/' + n;
const epochOf = () => crypto.randomBytes(4).toString('hex') + (++epochN).toString(36);
const session = (c) => { let s = sessions.get(c); if (!s) sessions.set(c, s = { code: c, day: null, load: null }); return s; };
const running = (c) => post({ run: c });
/* ---- realms ---- */
function build(nid, lang) {
return new Realm({ code, lang, test: test && { seed: test.seed, now: test.now, step: test.step }, loadMs: T.load,
log: (lvl, txt) => log(lvl === 'log' || lvl === 'info' || lvl === 'debug' ? 'info' : 'warn', `[${nid}] ${txt}`) });
}
// A realm call: [header, ...parts]; a throw inside the realm comes back as {srvErr}, a timeout throws. A realm whose
// built-ins changed is marked polluted: the caller replaces it.
const call = (e, name, input, ms) => { const r = e.realm.call(name, input, ms); if (r[0] && r[0].polluted) e.polluted = true; return r; };
// What a fresh realm takes from one that is done (its save, rt, R, fx), whatever its built-ins are now.
const peek = (e, name, input, ms) => (e.realm ? parts(e.realm.raw(name, input, ms, false)) : [{ srvErr: 'gone' }]);
/* A fresh realm in place of one that is done (timed out, polluted, or could not go back in place), from {s, uidN, rt,
live}: same network, new epoch, versions from 0, the fx the old one held (the mark's, or after a read all of them).
R comes from the old realm, which still answers after a timeout: the marked R (mark) or its current one, packed
whole; when it cannot (or is polluted), or that R does not load, R is routed again from rt's routing point. The old
realm is never called again, even when this throws. */
function rebuild(e, from, mark = true) {
if (!from || typeof from.s !== 'string') { e.realm = null; throw new Error('rebuilding the realm failed: nothing to build from'); }
let rpack = null, fx = null;
if (!e.polluted) try { const s = e.realm && e.realm.raw('srvRPack', { mark }, T.load, false); if (typeof s === 'string' && s.startsWith('{"o"')) rpack = s; } catch (x) { /* gone */ }
try { const [h] = peek(e, 'srvFxOut', { mark }, T.small); if (h && Array.isArray(h.fx)) fx = h; } catch (x) { /* gone */ }
e.realm = null;
const epoch = epochOf();
const load = (rp) => {
const r = build(e.nid, e.lang);
const [h] = r.call('srvLoad', { save: from.s, uidN: from.uidN, rt: from.rt, rpack: rp, fx, live: !!from.live, prefs: e.prefs, epoch, strict: !!opts.strict, clock: from.clock }, T.load);
if (h.srvErr) throw new Error(h.srvErr);
return [r, h];
};
let r, h;
try { [r, h] = load(rpack); } catch (x) {
if (!rpack) throw new Error('rebuilding the realm failed: ' + LINE(x));
log('warn', `[${e.nid}] R as it was did not load (${LINE(x)}): routed again`);
rpack = null;
try { [r, h] = load(null); } catch (y) { throw new Error('rebuilding the realm failed: ' + LINE(y)); }
}
e.realm = r; e.polluted = false; e.epoch = epoch; e.v = 0; e.day = h.day; e.lost = h.lost;
log('warn', `[${e.nid}] realm rebuilt (epoch ${epoch}${rpack ? '' : ', R routed again'})`);
}
// The network cannot go on: dropped (later calls answer NO_REALM), and the engine tells the host (4.7).
function lose(e, why) {
e.realm = null; e.broken = true;
if (realms.get(key(e.code, e.nid)) === e) realms.delete(key(e.code, e.nid));
log('error', `[${e.nid}] dropped, its realm could not be built again: ${why}`);
post({ lost: { code: e.code, nid: e.nid, why: String(why).slice(0, 300) } });
}
// A recovery: true when the network has a realm to play on again, else it is dropped.
const recover = (e, f) => { try { f(); return true; } catch (x) { lose(e, LINE(x)); return false; } };
const gone = (e) => (e.realm ? '' : '; the network was dropped: load it again');
// The rt of the old realm's mark, if it still answers; else the last day's, whose routing point belongs to that day's
// S: with another mark only its route memory counts (a close R).
function markRt(e) {
try { const [h] = peek(e, 'srvRt', { mark: true }, 200); if (h && !h.srvErr && h.load) return h; } catch (x) { /* gone */ }
return e.dayMark ? (e.dayMark === e.mark ? e.dayMark.rt : { ...e.dayMark.rt, pt: undefined, rk: undefined }) : null;
}
// The restore point of the next day or action. A failed mark throws {mark:true} and changed nothing applied; one that
// ran out of time has the realm built again from its own save first (or the network dropped).
function mark(e, input) {
e.mark = null;
if (input.day) e.dayMark = null;
let h, s;
try { [h, s] = call(e, 'srvMark', input, T.mark); } catch (x) {
if (!isTimeout(x)) throw x;
recover(e, () => rebuildAfterRead(e));
throw Object.assign(new Error(`marking the network took longer than ${T.mark} ms`), { mark: true, timeout: true });
}
if (h.srvErr) {
if (e.polluted) recover(e, () => rebuildAfterRead(e));
throw Object.assign(new Error('marking the network failed: ' + LINE(h.srvErr)), { mark: true });
}
const m = { s, uidN: h.uidN, rt: h.rt || null, day: h.day, clock: h.clock, live: true };
if (input.day) e.dayMark = m;
e.mark = m;
return m;
}
// After a throw: back to the mark in place; if even that fails (or the realm is polluted), a fresh realm from the mark.
function restore(e, input) {
if (!e.polluted) {
try { const [h] = call(e, 'srvRestore', input, T.small); if (!h.srvErr) return; log('warn', `[${e.nid}] restore failed: ${h.srvErr}`); }
catch (x) { log('warn', `[${e.nid}] restore failed: ${LINE(x)}`); }
}
rebuild(e, { ...e.mark, rt: input.day ? e.mark.rt : markRt(e) });
}
// A call that changed nothing applied and timed out (or left the realm polluted): the fresh realm starts from the
// realm's own save. When even that cannot be read, this throws: never an older mark.
function rebuildAfterRead(e) {
let from = null;
try { const [h, txt] = peek(e, 'srvSave', undefined, T.save); if (!h.srvErr && typeof txt === 'string') from = { s: txt, uidN: h.uidN, rt: h.rt, clock: h.clock }; } catch (x) { /* gone */ }
if (!from) { e.realm = null; throw new Error('rebuilding the realm failed: its save could not be read'); }
rebuild(e, from, false);
}
/* ---- the handlers: each returns the reply (or throws, which the engine turns into a rejection) ---- */
const errReply = (m, what, msg) => ({ t: 'err', code: m.code, nid: m.nid, ...(m.msg && m.msg.rid ? { rid: m.msg.rid } : {}), what, msg: String(msg).slice(0, 500) });
function loadOne(c, n) {
const e = realms.get(key(c, n.nid));
try {
if (!n.begin && !(n.env && typeof n.env === 'object' && typeof n.env.s === 'string')) throw new Error('no save to load');
e.realm = build(n.nid, n.lang);
e.lang = e.realm.lang;
const epoch = epochOf();
// begin: {name, home, preset, asn, mp, tut, day?}, passed on untouched (srvBegin checks it; day: the session's date).
const [h] = n.begin
? call(e, 'srvBegin', { begin: n.begin, prefs: n.prefs, epoch, strict: !!opts.strict }, T.load)
: call(e, 'srvLoad', { save: n.env.s, uidN: n.env.uidN, rt: n.env.rt, prefs: n.prefs, rng: n.rng, epoch, strict: !!opts.strict }, T.load);
if (h.srvErr) throw new Error(h.srvErr);
Object.assign(e, { epoch, v: 0, day: h.day, lost: h.lost, loading: false });
const out = { t: 'loaded', nid: n.nid, epoch, day: h.day, lost: h.lost };
if (n.begin) out.saved = saved(e);
return out;
} catch (x) {
if (realms.get(key(c, n.nid)) === e) realms.delete(key(c, n.nid));
log('warn', `[${n.nid}] did not load: ${MSG(x)}`);
return { t: 'loaded', nid: n.nid, err: isTimeout(x) ? 'the network took too long to load' : LINE(x) };
}
}
function saved(e) {
const [h, txt] = call(e, 'srvSave', undefined, T.save);
if (h.srvErr) { if (e.polluted) recover(e, () => rebuildAfterRead(e)); throw new Error(h.srvErr); }
return { t: 'saved', nid: e.nid, txt, uidN: h.uidN, rt: h.rt, day: h.day, lost: h.lost };
}
// One network's day, with its mark, one retry, and broken after a second failure.
function dayOne(e, m) {
const t0 = now(), d0 = e.day;
const input = { speed: m.speed, last: m.last, alone: m.alone.includes(e.nid), mute: !!m.mute };
let err = null;
for (let i = 0; i < 2 && e.realm; i++) {
try {
mark(e, { day: true });
const [h] = call(e, 'srvDay', input, T.day);
if (h.srvErr) throw new Error(h.srvErr);
e.day = h.day; e.lost = h.lost;
return { day: h.day, lost: h.lost, ...(h.pause ? { pause: true } : {}), ...(i ? { retried: true } : {}), ms: msOf(t0) };
} catch (x) {
err = x;
log('warn', `[${e.nid}] day ${d0 + 1} failed (${x.mark ? 'mark' : isTimeout(x) ? 'timeout' : e.polluted ? 'polluted' : 'throw'}${i ? ', again' : ''}): ${MSG(x)}`);
// A failed mark changed nothing (the realm is as it was, built again from its own save, or dropped). Else back
// to this attempt's mark: in place after a throw, a fresh realm after a timeout or a pollution.
if (!x.mark && !recover(e, () => { if (isTimeout(x) || e.polluted) rebuild(e, e.dayMark); else restore(e, { day: true }); })) break;
}
}
e.broken = true;
return { day: e.day, lost: !!e.lost, err: (isTimeout(err) ? 'timeout: ' : '') + LINE(err) + gone(e), retried: true, ms: msOf(t0) };
}
// An action or a what-if: its mark, the call, and the way back when it fails.
function marked(m, e, name, input, ms, what) {
try { mark(e, input); } catch (x) { if (!x.mark) throw x; return [errReply(m, x.timeout ? 'timeout' : 'throw', x.message + gone(e))]; }
let r;
try { r = call(e, name, m.msg, ms); } catch (x) {
if (!isTimeout(x)) throw x;
recover(e, () => rebuild(e, { ...e.mark, rt: markRt(e) }));
return [errReply(m, 'timeout', `the ${what} took longer than ${ms} ms` + gone(e))];
}
if (r[0].srvErr) { recover(e, () => (e.polluted ? rebuild(e, { ...e.mark, rt: markRt(e) }) : restore(e, {}))); return [errReply(m, 'throw', r[0].srvErr + gone(e))]; }
return r;
}
const H = {
act(m, e) {
if (e.broken || e.lost) return { t: 'actDone', nid: m.nid, epoch: e.epoch, rid: m.msg.rid, outcome: 'stopped', v: e.v, upd: null };
const t0 = now(), [h, upd] = marked(m, e, 'srvAct', { keys: true }, T.act, 'action');
if (h.t === 'err') return h;
e.v = h.v;
if (h.outcome === 'stopped') e.lost = true;
return { t: 'actDone', nid: m.nid, epoch: e.epoch, rid: m.msg.rid, outcome: h.outcome, ...(h.why ? { why: h.why } : {}), v: h.v, upd: upd || null, ms: msOf(t0) };
},
ask(m, e) {
if (e.broken || e.lost) return { t: 'askDone', nid: m.nid, rid: m.msg.rid, err: 'stopped' };
const t0 = now(), [h] = marked(m, e, 'srvAsk', {}, T.ask, 'what-if');
if (h.t === 'err') return h;
return { t: 'askDone', nid: m.nid, rid: m.msg.rid, ...h, ms: msOf(t0) };
},
pull(m, e) { return pulled(m, e, 'srvPull', { snap: !!m.snap, views: m.views }); },
greet(m, e) { return pulled(m, e, 'srvGreet', {}); },
sub(m, e) {
return guarded(m, e, () => { const [h] = call(e, 'srvSub', { views: m.views || [] }, T.pull); if (h.srvErr) return errReply(m, 'throw', h.srvErr); return { t: 'subbed', nid: m.nid, epoch: e.epoch, v: h.v, subs: h.subs }; });
},
save(m, e) { return guarded(m, e, () => saved(e)); },
card(m, e) { return guarded(m, e, () => { const [h] = call(e, 'srvCard', undefined, T.small); if (h.srvErr) return errReply(m, 'throw', h.srvErr); return { t: 'card', nid: m.nid, card: h.card || null }; }); },
prefs(m, e) { if (m.prefs) e.prefs = { ...e.prefs, ...m.prefs }; return guarded(m, e, () => { const [h] = call(e, 'srvPrefs', { prefs: m.prefs }, T.small); return h.srvErr ? errReply(m, 'throw', h.srvErr) : null; }); },
// Tests only: a piece of code in the realm, its value back.
eval(m, e) {
if (!test) throw new Error('eval is for tests');
try { return { value: e.realm.eval(m.src, m.ms || 5000) }; }
catch (x) { if (isTimeout(x)) { recover(e, () => rebuildAfterRead(e)); return { timeout: true, epoch: e.epoch }; } return { error: MSG(x) }; }
},
};
function pulled(m, e, name, input) {
return guarded(m, e, () => {
const t0 = now(), [h, ...p] = call(e, name, input, T.pull);
if (h.srvErr) return errReply(m, 'throw', h.srvErr);
e.v = h.v;
const o = { t: 'pulled', nid: m.nid, epoch: e.epoch, v: h.v };
(h.parts || []).forEach((k, i) => { o[k] = p[i]; });
if (h.subs) o.subs = h.subs;
o.ms = msOf(t0);
return o;
});
}
// A call that changes nothing applied: after a timeout (or a pollution) the realm is built again from its own save.
function guarded(m, e, f) {
let r;
try { r = f(); } catch (x) {
if (!isTimeout(x)) { if (e.polluted && e.realm) recover(e, () => rebuildAfterRead(e)); throw x; }
recover(e, () => rebuildAfterRead(e));
return errReply(m, 'timeout', `${m.t} took too long` + gone(e));
}
if (e.polluted && e.realm) recover(e, () => rebuildAfterRead(e));
return r;
}
/* ---- the queue ---- */
const SESSION_OPS = new Set(['load', 'unload', 'day']);
function runnable(j, i) {
const s = sessions.get(j.code);
if (SESSION_OPS.has(j.t)) {
if (s && (s.day || s.load)) return false;
for (let k = 0; k < i; k++) if (jobs[k].code === j.code) return false;
return true;
}
for (let k = 0; k < i; k++) if (jobs[k].code === j.code && SESSION_OPS.has(jobs[k].t) && jobs[k].t !== 'day') return false;
// A network that is loading waits for its load; one marked loading with no load under way (none can be: a guard)
// waits for nothing, so start() answers NO_REALM.
const e = realms.get(key(j.code, j.nid));
return !e || !e.loading || !(s && s.load);
}
function reply(j, r) { post({ id: j.id, ok: true, reply: r === undefined ? null : r }); }
function fail(j, x) { post({ id: j.id, ok: false, error: { message: String((x && x.message) || x), code: (x && x.code) || 'ERR' } }); }
function runJob() {
for (let i = 0; i < jobs.length; i++) {
const j = jobs[i];
if (!runnable(j, i)) continue;
jobs.splice(i, 1);
try { start(j); } catch (x) { fail(j, x); }
return true;
}
return false;
}
const strings = (a) => [...new Set(a.filter((n) => typeof n === 'string'))];
function start(j) {
if (j.t === 'mem') { const h = v8.getHeapStatistics(), mu = process.memoryUsage(); return reply(j, { heapUsed: h.used_heap_size, heapTotal: h.total_heap_size, external: h.external_memory, rss: mu.rss, realms: realms.size }); }
if (j.t === 'load') {
// The whole call first, with no side effects: a malformed one is refused and leaves every realm as it was. A
// network without a save to load (or a begin) is only that network's problem: loadOne answers it broken.
const nets = Array.isArray(j.nets) ? j.nets : [], seen = new Set();
if (!nets.length) throw new Error('load: give the networks to load');
for (const n of nets) {
if (!n || typeof n !== 'object' || typeof n.nid !== 'string' || !n.nid) throw new Error('load: each network needs a nid');
if (seen.has(n.nid)) throw new Error(`load: ${n.nid.slice(0, 40)} is there twice`);
seen.add(n.nid);
}
const s = session(j.code);
for (const n of nets) realms.set(key(j.code, n.nid), { code: j.code, nid: n.nid, lang: n.lang || 'en', prefs: n.prefs || {}, loading: true, realm: null, epoch: '', v: 0, day: 0, lost: false, broken: false, polluted: false, mark: null, dayMark: null });
s.load = { j, i: 0, out: [] };
return;
}
if (j.t === 'day') {
// The lists as lists (of network ids), or the day is refused whole; speed and last the realm checks itself.
for (const k of ['nets', 'alone']) if (j[k] !== undefined && !Array.isArray(j[k])) throw new Error(`day: ${k} must be a list`);
j.alone = strings(j.alone || []);
const s = session(j.code);
const order = strings(j.nets || []).sort().filter((n) => { const e = realms.get(key(j.code, n)); return e && !e.loading && !e.broken && !e.lost; });
s.day = { j, order, i: 0, out: {} };
return;
}
if (j.t === 'unload') {
for (const [k, e] of [...realms]) if (e.code === j.code && (j.nid === undefined || e.nid === j.nid)) realms.delete(k);
if (![...realms.values()].some((e) => e.code === j.code)) sessions.delete(j.code);
return reply(j, { t: 'unloaded', code: j.code, ...(j.nid !== undefined ? { nid: j.nid } : {}) });
}
const e = realms.get(key(j.code, j.nid));
if (e && e.loading) { realms.delete(key(j.code, j.nid)); log('error', `[${j.nid}] marked loading with no load under way: dropped`); }
if (!e || e.loading || !e.realm) throw Object.assign(new Error(`no realm ${key(j.code, j.nid)}`), { code: 'NO_REALM' });
const h = H[j.t];
if (!h) throw new Error(`unknown message ${j.t}`);
running(j.code);
return reply(j, h(j, e));
}
// One step of a session's load (one network) or day (one network). A throw answers the whole call, never the worker.
function runStep() {
const ss = [...sessions.values()].filter((s) => s.load || s.day);
if (!ss.length) return false;
const s = ss[turn++ % ss.length];
if (s.load) {
const L = s.load;
try {
const n = L.j.nets[L.i++];
if (n) { running(s.code); L.out.push(loadOne(L.j.code, n)); }
if (L.i >= L.j.nets.length) { s.load = null; reply(L.j, L.out); }
} catch (x) {
s.load = null;
for (const n of L.j.nets.slice(L.i)) { const e = n && realms.get(key(L.j.code, n.nid)); if (e && e.loading) realms.delete(key(L.j.code, n.nid)); }
log('error', `mp-sim worker: a load of ${s.code} failed: ${MSG(x)}`);
fail(L.j, x);
}
return true;
}
const D = s.day;
try {
const nid = D.order[D.i++];
const e = nid && realms.get(key(D.j.code, nid));
if (e && !e.broken && !e.lost && e.realm) {
running(s.code);
try { D.out[nid] = dayOne(e, D.j); } catch (x) {
e.broken = true;
log('error', `[${nid}] the day could not run: ${MSG(x)}`);
D.out[nid] = { day: e.day, lost: !!e.lost, err: 'the day could not run: ' + LINE(x), retried: false, ms: 0 };
}
}
if (D.i >= D.order.length) { s.day = null; reply(D.j, { t: 'dayDone', code: D.j.code, d: D.j.d, nets: D.out }); }
} catch (x) {
s.day = null;
log('error', `mp-sim worker: a day of ${s.code} failed: ${MSG(x)}`);
fail(D.j, x);
}
return true;
}
/* Turns: a message and a step of a session's load or day, in alternation. The worker goes on only while something ran:
what a job waits for (a load, a day, an earlier job of its session) is itself a job or a step that runs, so a pass
where nothing could run means nothing will until a message comes (handle() kicks). If a job were still waiting
then, nothing could ever free it: it is answered, not left pending, and the worker does not spin on it. */
let flip = false;
function pump() {
pumping = false;
flip = !flip;
try {
if (flip ? runJob() || runStep() : runStep() || runJob()) return kick();
if (!jobs.length) return;
const j = jobs.shift();
log('error', `mp-sim worker: ${j.t} for ${key(j.code, j.nid)} waited for nothing that could come; answered`);
fail(j, new Error(`${j.t} could not run`));
} catch (x) { log('error', `mp-sim worker: ${MSG(x)}`); }
kick();
}
function kick() { if (!pumping) { pumping = true; setImmediate(pump); } }
return {
handle(m) { jobs.push(m); kick(); },
stats: () => ({ realms: realms.size, sessions: sessions.size, jobs: jobs.length }),
simId: code.simId,
};
}
if (!isMainThread && workerData && workerData.mpSim) {
const W = workerData.mpSim;
const post = (m) => parentPort.postMessage(m);
const log = (level, text) => post({ log: [level, text] });
process.on('unhandledRejection', (e) => log('warn', 'unhandled rejection in a realm: ' + MSG(e)));
let core;
try {
// Tests only: a worker that cannot start (the engine backs off, then stops trying).
if (W.test && W.test.startFail) throw new Error('injected: the game does not start');
core = createCore({ ...W, log, post });
} catch (e) { post({ fatal: MSG(e) }); process.exit(1); }
parentPort.on('message', (m) => core.handle(m));
post({ ready: true, simId: core.simId });
}
module.exports = { createCore, TIMEOUTS };

View file

@ -1,448 +0,0 @@
// The multiplayer API (docs/MULTIPLAYER.md): sessions players share by a short code, each player's save kept on the
// server, and a small public card per player for the session's leaderboard and feed. Plain node:http, no dependencies.
// scripts/mp-server.js runs it on its own (optionally serving the built site too); npm run dev -- --mp mounts it in the
// dev server. It is never part of the page or of site/: the page only talks to it when the build stamped MP_API.
//
// Storage: one JSON file per session (DIR/<CODE>.json: settings, players, cards, feed) and one file per player's save
// (DIR/<CODE>.<pid>.save), kept apart so a card push never rewrites a dozen saves. Writes go to a temporary file and are
// renamed into place, one session at a time, in order. A session code is checked against CODE_RE before it ever becomes
// part of a file name, and so is a player id.
const fs = require('node:fs');
const path = require('node:path');
const net = require('node:net');
const crypto = require('node:crypto');
// Crockford's base32 (no I, L, O or U): codes read aloud or typed from a phone do not get mixed up.
const ALPHA = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
const CODE_RE = /^[0-9A-HJKMNP-TV-Z]{6}$/;
const PID_RE = /^[a-z0-9]{8}$/;
const TOKEN_RE = /^[0-9a-f]{64}$/;
const PRESETS = ['soft', 'freeze', 'oncall', 'bgp'];
const PPOL = ['open', 'selective', 'closed'];
const TIERS = ['t1', 't2', 't3'];
const ASN_LO = 200000, ASN_HI = 214999;
const COLORS = ['#ff4f9a', '#3a86ff', '#ffbe0b', '#2ec4b6', '#8338ec', '#fb5607', '#06d6a0', '#e63946', '#118ab2', '#8ac926', '#b5179e', '#6c757d'];
const MAX_SAVE = 4 * 1024 * 1024; // characters of save text ('gz:'+base64 or JSON)
const LIMIT = { small: 16 * 1024, save: MAX_SAVE + 64 * 1024 };
const SAVE_MS = 120000; // a save's body must arrive within this, or the upload is cut (it holds one of few places)
const FEED_MAX = 100, CHAT_MAX = 200;
const DAY = 86400000;
// "k7q-2xd", "K7Q 2XD", even "k7q2xo": the code itself, or null. I, L and O are read as 1, 1 and 0, as Crockford meant.
function normCode(s) {
if (typeof s !== 'string' || s.length > 20) return null;
const c = s.toUpperCase().replace(/[\s-]/g, '').replace(/[IL]/g, '1').replace(/O/g, '0');
return CODE_RE.test(c) ? c : null;
}
const showCode = (c) => c.slice(0, 3) + '-' + c.slice(3);
const randCode = () => { const b = crypto.randomBytes(6); let s = ''; for (const x of b) s += ALPHA[x & 31]; return s; };
const randPid = () => crypto.randomBytes(4).toString('hex');
const sha = (t) => crypto.createHash('sha256').update(t).digest();
// Text from players: no control or bidi-override characters, none of <>&"'` (the page escapes everything anyway), one
// space between words, at most max characters (whole characters, never half an emoji).
function cleanText(v, max) {
if (typeof v !== 'string') return '';
const s = v.replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩<>&"'`]/g, '').replace(/\s+/g, ' ').trim();
return Array.from(s).slice(0, max).join('').trim();
}
const cleanChat = (v) => {
if (typeof v !== 'string') return '';
const s = v.replace(/[\u0000-\u001f\u007f-\u009f‎‏‪-‮⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim();
return Array.from(s).slice(0, CHAT_MAX).join('').trim();
};
const num = (v, lo, hi, d = 0) => { v = +v; if (!Number.isFinite(v)) return d; return Math.min(hi, Math.max(lo, v)); };
const int = (v, lo, hi, d = 0) => Math.round(num(v, lo, hi, d));
// Only the first few times max entries are even looked at: a card padded with copies costs no more than an honest one.
const ids = (v, re, max) => {
if (!Array.isArray(v)) return [];
const out = new Set();
for (const x of v.slice(0, max * 4)) { if (typeof x === 'string' && re.test(x)) out.add(x); if (out.size >= max) break; }
return [...out];
};
const CITY_RE = /^[a-z0-9]{2,8}$/, IX_RE = /^[a-z0-9~_-]{1,16}$/, NET_RE = /^[a-z0-9]{1,12}$/;
/* A player's public card: only these fields, numbers clamped, ids only in their shape (the page checks them against its
catalogs again: this is other players' data there). Name and AS number come from the server, never from the card. */
function cleanCard(c) {
if (!c || typeof c !== 'object' || Array.isArray(c)) return null;
const links = [];
if (Array.isArray(c.links)) for (const l of c.links.slice(0, 1200)) {
if (!Array.isArray(l) || typeof l[0] !== 'string' || typeof l[1] !== 'string' || !CITY_RE.test(l[0]) || !CITY_RE.test(l[1]) || l[0] === l[1]) continue;
links.push([l[0], l[1], num(l[2], 0, 1e7)]);
if (links.length >= 300) break;
}
return {
day: int(c.day, 0, 1e7), tier: TIERS.includes(c.tier) ? c.tier : 't3', t1: c.t1 === true, lvl: int(c.lvl, 0, 99),
pops: ids(c.pops, CITY_RE, 500), links, ix: ids(c.ix, IX_RE, 500), transit: ids(c.transit, NET_RE, 64),
ppol: PPOL.includes(c.ppol) ? c.ppol : 'open', reach: num(c.reach, 0, 1), peak: num(c.peak, 0, 1e9), served: num(c.served, 0, 1e9),
cust: int(c.cust, 0, 1e7), rev: num(c.rev, -1e13, 1e13), cashB: int(c.cashB, -1, 20), score: num(c.score, 0, 1e15),
};
}
/* Small in-memory rate limits: at most n events per window for one key (an address, a player). Keys are kept in the
order they were last seen, so the ones nobody used for a whole window go from the front, a few at a time, and above
cap keys the oldest go too: memory stays bounded and no call ever walks the whole map. */
function limiter(n, ms, cap = 20000) {
const m = new Map();
const live = (k, now) => { const a = m.get(k); return a ? a.filter((t) => now - t < ms) : []; };
return {
// Counts one more, unless the key is already at its limit.
ok(k, now) {
const a = live(k, now), ok = a.length < n;
if (ok) a.push(now);
m.delete(k); m.set(k, a);
for (const [x, v] of m) { if (m.size > cap || !v.length || now - v[v.length - 1] >= ms) m.delete(x); else break; }
return ok;
},
full: (k, now) => live(k, now).length >= n,
size: () => m.size,
};
}
/* The address a limit counts against. One IPv6 customer (a phone, a home, a server) usually holds a whole /64, so an
IPv6 address counts as its /64; an IPv4 address mapped into IPv6 counts as itself. null: not an address. */
function addrKey(a) {
a = String(a || '').trim();
if (a.startsWith('[')) a = a.slice(1, a.indexOf(']') >>> 0);
const z = a.indexOf('%'); if (z >= 0) a = a.slice(0, z);
const m4 = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(a); if (m4) a = m4[1];
const v = net.isIP(a);
if (v === 4) return a;
if (v !== 6) return null;
const [h, t] = a.toLowerCase().split('::'), head = h ? h.split(':') : [], tail = t ? t.split(':') : [];
// The groups :: stands for (a dotted IPv4 at the end is two of them).
const n = head.length + tail.length + (tail.length && tail[tail.length - 1].includes('.') ? 1 : 0);
const g = t === undefined ? head : [...head, ...Array(8 - n).fill('0'), ...tail];
return g.slice(0, 4).map((x) => parseInt(x, 16).toString(16)).join(':') + '::/64';
}
class HttpError extends Error { constructor(status, msg, extra) { super(msg); this.status = status; this.extra = extra; } }
const fail = (status, msg, extra) => { throw new HttpError(status, msg, extra); };
// The request body as JSON, refusing it as soon as it is longer than max bytes (never buffered beyond that). A body that
// has not arrived within ms is cut off: it would hold its place (and its memory) for as long as the sender likes.
function readJson(req, max, ms = 30000) {
return new Promise((resolve, reject) => {
const ct = String(req.headers['content-type'] || '');
if (!/^application\/json\b/i.test(ct)) { req.resume(); return reject(new HttpError(415, 'send JSON (content-type: application/json)')); }
const len = +req.headers['content-length'];
if (len > max) { req.resume(); return reject(new HttpError(413, 'too large')); }
let parts = [], n = 0, done = false;
const stop = (e) => { if (done) return; done = true; clearTimeout(tm); parts = null; reject(e); };
const tm = setTimeout(() => { stop(new HttpError(408, 'too slow')); req.destroy(); }, ms);
req.on('data', (b) => {
if (done) return;
n += b.length;
if (n > max) { stop(new HttpError(413, 'too large')); req.resume(); return; }
parts.push(b);
});
req.on('end', () => {
if (done) return; done = true; clearTimeout(tm);
let j;
try { const t = Buffer.concat(parts).toString('utf8'); parts = null; j = JSON.parse(t); } catch (e) { return reject(new HttpError(400, 'bad JSON')); }
if (!j || typeof j !== 'object' || Array.isArray(j)) return reject(new HttpError(400, 'expected a JSON object'));
resolve(j);
});
req.on('error', () => stop(new HttpError(400, 'request failed')));
req.on('close', () => { if (!req.complete) stop(new HttpError(400, 'request failed')); });
});
}
function send(res, status, body) {
if (res.headersSent) { try { res.end(); } catch (e) { /* gone */ } return; }
const txt = JSON.stringify(body);
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'content-length': Buffer.byteLength(txt) });
res.end(txt);
}
/* createMp({dir, base, maxSessions, maxPlayers, pruneDays, trustProxy, verbose, log, now, ...limits}): the API.
handle(req, res) answers anything under base (default /api/mp) and returns true, or returns false for everything else. */
function createMp(o = {}) {
const dir = path.resolve(o.dir || 'mp-data');
const base = (o.base || '/api/mp').replace(/\/+$/, '');
const maxSessions = o.maxSessions || 1000, maxPlayers = o.maxPlayers || 12, pruneDays = o.pruneDays || 60;
const now = o.now || Date.now, log = o.log || ((s) => console.log(s));
fs.mkdirSync(dir, { recursive: true });
const file = (code) => path.join(dir, code + '.json');
const saveFile = (code, pid) => path.join(dir, `${code}.${pid}.save`);
const cache = new Map(), chains = new Map(), soon = new Map();
let codes = new Set(), tmpN = 0;
const HOUR = 3600000, MIN = 60000;
const createRate = limiter(o.createPerHour || 10, HOUR), joinRate = limiter(o.joinPerHour || 60, HOUR);
// However many addresses ask, the server fills up slowly: a full server takes days, not minutes.
const createAll = limiter(o.sessionsPerHour || 100, HOUR);
const chatRate = limiter(6, 30000), chatGap = limiter(1, 1000);
// Wrong codes, counted per address: guessing codes runs out long before it finds one.
const missRate = limiter(o.missesPerHour || 120, HOUR);
// A player's pushes. The game sends a save at most every 15 seconds and a card with it, so these never touch it; they
// stop one player from keeping the disk busy rewriting their session.
const saveRate = limiter(o.savesPerMinute || 20, MIN), cardRate = limiter(o.cardsPerMinute || 60, MIN);
// Saves being uploaded: one per player, a few per address, a few more on the whole server. Each can hold megabytes.
const up = new Set(), upAddr = new Map(), maxUploads = o.maxUploads || 16, maxUploadsAddr = o.maxUploadsPerAddress || 4;
// Atomic: write a temporary file next to it, then rename over the old one.
const writeAtomic = async (f, txt) => {
const tmp = `${f}.${process.pid}.${++tmpN}.tmp`;
await fs.promises.writeFile(tmp, txt);
await fs.promises.rename(tmp, f);
};
// One session's writes happen one after another, in the order they were asked for.
const queue = (code, job) => {
const p = (chains.get(code) || Promise.resolve()).then(job, job);
const q = p.catch((e) => { log(`[mp] writing ${code} failed: ${e.message}`); });
chains.set(code, q);
q.then(() => { if (chains.get(code) === q) chains.delete(code); });
return p;
};
// A session that is gone (its last player left) is never written again, whatever was still on its way.
const persist = (s) => {
const tm = soon.get(s.code); if (tm) { clearTimeout(tm); soon.delete(s.code); }
s.touched = now();
if (s.dead) return Promise.resolve();
return queue(s.code, () => s.dead ? null : writeAtomic(file(s.code), JSON.stringify(s)));
};
// Cards change often and matter little: their session is written a moment later, once for all of that moment's.
const persistSoon = (s) => {
s.touched = now();
if (s.dead || soon.has(s.code)) return;
const tm = setTimeout(() => { soon.delete(s.code); persist(s); }, o.persistMs ?? 2000);
if (tm.unref) tm.unref();
soon.set(s.code, tm);
};
function scan() { codes = new Set(); for (const f of fs.readdirSync(dir)) { const m = /^([0-9A-Z]{6})\.json$/.exec(f); if (m && CODE_RE.test(m[1])) codes.add(m[1]); } }
// Sessions nobody touched for pruneDays go, with their saves; so do leftovers of interrupted writes.
function prune() {
const cut = now() - pruneDays * DAY; let n = 0;
for (const f of fs.readdirSync(dir)) {
const p = path.join(dir, f);
let st; try { st = fs.statSync(p); } catch (e) { continue; }
if (!st.isFile()) continue;
if (f.endsWith('.tmp') && st.mtimeMs < now() - 3600000) { fs.rmSync(p, { force: true }); continue; }
const m = /^([0-9A-Z]{6})\.json$/.exec(f);
const live = m && cache.get(m[1]);
if (m && CODE_RE.test(m[1]) && st.mtimeMs < cut && !(live && live.touched >= cut)) { drop(m[1]); n++; }
}
for (const f of fs.readdirSync(dir)) { const m = /^([0-9A-Z]{6})\.[a-z0-9]{8}\.save$/.exec(f); if (m && !fs.existsSync(file(m[1]))) fs.rmSync(path.join(dir, f), { force: true }); }
scan();
return n;
}
function drop(code) {
const s = cache.get(code); if (s) s.dead = true;
const tm = soon.get(code); if (tm) { clearTimeout(tm); soon.delete(code); }
for (const f of fs.readdirSync(dir)) if (f === code + '.json' || (f.startsWith(code + '.') && f.endsWith('.save'))) fs.rmSync(path.join(dir, f), { force: true });
cache.delete(code); codes.delete(code);
}
function load(code) {
if (!CODE_RE.test(code)) return null;
if (cache.has(code)) return cache.get(code);
if (!codes.has(code)) return null;
let s = null;
try { s = JSON.parse(fs.readFileSync(file(code), 'utf8')); } catch (e) { return null; }
if (!s || s.code !== code || !Array.isArray(s.players)) return null;
// A hand-edited or damaged file: players without an id or a token hash cannot be anyone.
s.players = s.players.filter((p) => p && typeof p === 'object' && PID_RE.test(p.pid) && typeof p.th === 'string');
for (const p of s.players) if (!p.hit || typeof p.hit !== 'object') p.hit = { t1: !!(p.card && p.card.t1), t2: !!(p.card && (p.card.t1 || p.card.tier !== 't3')) };
if (!Array.isArray(s.feed)) s.feed = [];
cache.set(code, s);
return s;
}
prune();
// The client's address, as the limits count it (see addrKey); behind your own proxy, the one it added last.
const ipOf = (req) => {
if (o.trustProxy) { const x = String(req.headers['x-forwarded-for'] || '').split(',').map((v) => v.trim()).filter(Boolean); const k = x.length && addrKey(x[x.length - 1]); if (k) return k; }
return addrKey(req.socket.remoteAddress) || '?';
};
// The player this request's token belongs to, or null. Compares hashes of the same length, in constant time, even for
// a player who is not there.
function player(req, s) {
const m = /^Bearer ([a-z0-9]{8})\.([0-9a-f]{64})$/.exec(String(req.headers.authorization || ''));
if (!m) return null;
const p = s.players.find((x) => x.pid === m[1]);
const want = p && /^[0-9a-f]{64}$/.test(p.th) ? Buffer.from(p.th, 'hex') : Buffer.alloc(32), got = sha(m[2]);
return crypto.timingSafeEqual(want, got) && p ? p : null;
}
const authed = (p) => { if (!p) fail(401, 'unauthorized'); p.seen = now(); return p; };
// Still there after waiting for a body or a write: the player may have left meanwhile, or the session gone with them.
const still = (s, p) => !s.dead && cache.get(s.code) === s && (!p || s.players.includes(p));
const event = (s, k, p, extra) => { s.feed.push({ k, pid: p.pid, name: p.name, at: now(), ...extra }); if (s.feed.length > FEED_MAX) s.feed.splice(0, s.feed.length - FEED_MAX); };
const roster = (s) => ({
code: s.code, title: s.title, preset: s.preset, seed: s.seed, created: s.created,
players: s.players.map((p) => ({ pid: p.pid, name: p.name, asn: p.asn, color: p.color, card: p.card, seen: p.seen, joined: p.joined })),
feed: s.feed,
});
// A card can tell the feed something, once per player: reaching Tier 2, and Tier 1 (the first one in the session gets
// the headline). A network that drops out and comes back is not news again.
function applyCard(s, p, c) {
const hit = p.hit || (p.hit = {});
if (c.t1 && !hit.t1) { hit.t1 = hit.t2 = true; if (!s.first) { s.first = p.pid; event(s, 't1first', p); } else event(s, 't1', p); }
else if (c.tier === 't2' && !hit.t2) { hit.t2 = true; event(s, 't2', p); }
p.card = c;
}
function newPlayer(s, body, ip) {
const net = body.net && typeof body.net === 'object' ? body.net : {};
const name = cleanText(net.name, 32);
if (!name) fail(400, 'name your network');
const home = typeof net.home === 'string' && CITY_RE.test(net.home) ? net.home : null;
if (!home) fail(400, 'pick a home city');
let pid; do pid = randPid(); while (s.players.some((p) => p.pid === pid));
const token = crypto.randomBytes(32).toString('hex');
const avoid = new Set((Array.isArray(body.avoid) ? body.avoid.slice(0, 64) : []).filter((a) => Number.isInteger(a)));
for (const p of s.players) avoid.add(p.asn);
let asn; do asn = ASN_LO + crypto.randomInt(ASN_HI - ASN_LO + 1); while (avoid.has(asn));
const color = COLORS.find((c) => !s.players.some((p) => p.color === c)) || COLORS[s.players.length % COLORS.length];
const p = { pid, name, home, asn, color, th: sha(token).toString('hex'), joined: now(), seen: now(), card: null, sv: null, hit: {} };
s.players.push(p);
event(s, 'join', p);
return { code: s.code, pid, token, seed: s.seed, asn, preset: s.preset, color, title: s.title };
}
// The save as stored: its text alone (the number and time are in the session). Files from before that were wrapped.
const readSave = async (code, pid) => {
const t = await fs.promises.readFile(saveFile(code, pid), 'utf8');
if (t.startsWith('{"seq":')) { try { const j = JSON.parse(t); if (typeof j.data === 'string') return j.data; } catch (e) { /* a save after all */ } }
return t;
};
// A save upload holds a place until it is done: one per player, a few per address and on the whole server.
function upTake(key, ip) {
if (up.has(key)) fail(429, 'a save of yours is still on its way');
if (up.size >= maxUploads || (upAddr.get(ip) || 0) >= maxUploadsAddr) fail(503, 'busy: try again in a moment', { busy: true });
up.add(key); upAddr.set(ip, (upAddr.get(ip) || 0) + 1);
return () => { up.delete(key); const n = (upAddr.get(ip) || 1) - 1; if (n > 0) upAddr.set(ip, n); else upAddr.delete(ip); };
}
async function route(req, res, url) {
const rest = url.pathname.slice(base.length);
const t = now(), ip = ipOf(req), M = req.method;
if (rest === '/sessions') {
if (M !== 'POST') fail(405, 'method not allowed');
const body = await readJson(req, LIMIT.small);
if (codes.size >= maxSessions) fail(503, 'the server is full: no new sessions for now');
if (!createRate.ok(ip, t)) fail(429, 'too many new sessions from here: try again later');
if (!createAll.ok('*', t)) fail(503, 'the server is full: no new sessions for now');
const preset = PRESETS.includes(body.preset) ? body.preset : null;
if (!preset) fail(400, 'unknown rules preset');
let code; do code = randCode(); while (codes.has(code));
const s = { v: 1, code, title: cleanText(body.title, 40), preset, seed: crypto.randomBytes(4).readInt32LE(0), created: t, touched: t, first: null, players: [], feed: [] };
const out = newPlayer(s, body, ip);
codes.add(code); cache.set(code, s);
await persist(s);
return send(res, 201, out);
}
const m = /^\/sessions\/([^/]{1,32})(\/[a-z]+)?$/.exec(rest);
if (!m) fail(404, 'not found');
const sub = m[2] || '';
let raw = ''; try { raw = decodeURIComponent(m[1]); } catch (e) { /* not a code */ }
const code = normCode(raw), s = code && load(code);
// A player of this very session, with their token, is never held up by somebody else's wrong codes from the same
// address. Everyone else is: a wrong code and a wrong token get the same answer then, so it says nothing either.
const me = s ? player(req, s) : null;
if (!me && missRate.full(ip, t)) fail(429, 'too many wrong codes from here: try again later');
if (sub === '/join' && M === 'POST' && !joinRate.ok(ip, t)) fail(429, 'too many joins from here: try again later');
if (!s) { missRate.ok(ip, t); fail(404, 'no such session'); }
if (sub === '/join') {
if (M !== 'POST') fail(405, 'method not allowed');
const body = await readJson(req, LIMIT.small);
if (!still(s)) fail(404, 'no such session');
if (s.players.length >= maxPlayers) fail(409, 'this session is full', { full: true });
const out = newPlayer(s, body, ip);
await persist(s);
return send(res, 200, out);
}
if (sub === '') {
if (M !== 'GET') fail(405, 'method not allowed');
authed(me);
return send(res, 200, roster(s));
}
if (sub === '/card') {
if (M !== 'PUT') fail(405, 'method not allowed');
const p = authed(me);
if (!cardRate.ok(code + '.' + p.pid, t)) fail(429, 'too many cards: slow down');
const body = await readJson(req, LIMIT.small);
if (!still(s, p)) fail(401, 'unauthorized');
const c = cleanCard(body.card);
if (!c) fail(400, 'bad card');
applyCard(s, p, c);
persistSoon(s);
return send(res, 200, roster(s));
}
if (sub === '/save') {
if (M === 'GET') {
const p = authed(me);
if (!p.sv) fail(404, 'no save yet');
let data; try { data = await readSave(code, p.pid); } catch (e) { fail(404, 'no save yet'); }
return send(res, 200, { seq: p.sv.seq, at: p.sv.at, data });
}
if (M !== 'PUT') fail(405, 'method not allowed');
const p = authed(me), key = code + '.' + p.pid;
const free = upTake(key, ip);
try {
if (!saveRate.ok(key, t)) fail(429, 'too many saves: slow down');
const body = await readJson(req, LIMIT.save, o.saveMs || SAVE_MS);
if (!still(s, p)) fail(401, 'unauthorized');
const seq = body.seq, data = body.data;
if (!Number.isSafeInteger(seq) || seq < 1) fail(400, 'seq must be a positive integer');
if (typeof data !== 'string' || !data.length) fail(400, 'no save data');
if (data.length > MAX_SAVE) fail(413, 'save too large');
if (!(data.startsWith('gz:') || data.startsWith('{'))) fail(400, 'not a save');
const card = body.card === undefined ? undefined : cleanCard(body.card);
if (card === null) fail(400, 'bad card');
const old = p.sv;
// Another device of the same player saved a newer game: never overwrite it unless the player says so.
if (old && seq <= old.seq && body.force !== true) fail(409, 'a newer save is on the server', { seq: old.seq, at: old.at });
const at = num(body.at, 0, 1e15, t), sq = old && seq <= old.seq ? old.seq + 1 : seq;
// The session says it has this save only once the save is on disk.
await queue(code, () => writeAtomic(saveFile(code, p.pid), data));
if (!still(s, p)) fail(401, 'unauthorized');
p.sv = { seq: sq, at, size: data.length };
if (card) applyCard(s, p, card);
await persist(s);
return send(res, 200, { ok: true, seq: sq, at, roster: roster(s) });
} finally { free(); }
}
if (sub === '/feed') {
if (M !== 'POST') fail(405, 'method not allowed');
const p = authed(me), body = await readJson(req, LIMIT.small);
if (!still(s, p)) fail(401, 'unauthorized');
const text = cleanChat(body.text);
if (!text) fail(400, 'say something');
if (!chatGap.ok(code + p.pid, t) || !chatRate.ok(code + p.pid, t)) fail(429, 'slow down a little');
event(s, 'chat', p, { text });
await persist(s);
return send(res, 200, roster(s));
}
if (sub === '/me') {
if (M !== 'DELETE') fail(405, 'method not allowed');
const p = authed(me);
s.players = s.players.filter((x) => x !== p);
await queue(code, () => fs.promises.rm(saveFile(code, p.pid), { force: true }));
if (!s.players.length) { s.dead = true; await queue(code, async () => drop(code)); return send(res, 200, { ok: true }); }
event(s, 'leave', p);
await persist(s);
return send(res, 200, { ok: true });
}
fail(404, 'not found');
}
function handle(req, res) {
let url;
try { url = new URL(req.url, 'http://x'); } catch (e) { return false; }
if (url.pathname !== base && !url.pathname.startsWith(base + '/')) return false;
const t0 = Date.now();
res.on('finish', () => { if (o.verbose) log(`${new Date().toISOString()} ${ipOf(req)} ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - t0}ms`); });
route(req, res, url).catch((e) => {
// A body nobody read (refused before it was needed) is drained, so the client still gets its answer.
if (!req.complete && !req.destroyed) req.resume();
if (e instanceof HttpError) return send(res, e.status, { error: e.message, ...(e.extra || {}) });
log(`[mp] ${req.method} ${url.pathname}: ${e && e.stack || e}`);
send(res, 500, { error: 'server error' });
});
return true;
}
// Everything written before the process goes, sessions waiting for their moment too.
const flush = () => { for (const code of [...soon.keys()]) { const s = cache.get(code); if (s) persist(s); else { clearTimeout(soon.get(code)); soon.delete(code); } } return Promise.all([...chains.values()]); };
return { handle, prune, flush, dir, base, sessions: () => codes.size, uploads: () => up.size };
}
module.exports = { createMp, cleanCard, cleanText, normCode, showCode, addrKey, limiter, CODE_RE, PRESETS, MAX_SAVE };

View file

@ -1,136 +0,0 @@
// Assembles the game page from src/: src/index.html is the shell, and every line that is exactly
// `<!-- @include DIR -->` is replaced by the files under src/DIR, concatenated in path order.
// The result is the same single, self-contained index.html the game has always shipped: one request,
// no module loader, no runtime cost. See docs/ARCHITECTURE.md ("Source layout") and docs/adr/.
//
// A line `<!-- @include-dev DIR -->` is the same, but only in the development page (dev: true): the
// tools' side of the game (src/agent/, the agent facade the MCP server drives) for npm run dev, the
// MCP server's own page and the tests that ask for it. Everywhere else the line is dropped whole, so
// the page players get is exactly what it would be without it (docs/adr/0004-dev-only-code.md).
//
// The server-run play of a multiplayer build (src/game/98-server-play/ and src/styles/43-server-play.css) is only in a
// page assembled with mp: true, which MP_API=… npm run build asks for; every other page, the one players get on
// GitHub Pages included, has none of it.
//
// node scripts/lib/page.js [-o FILE] the page as it ships (stdout by default)
// node scripts/lib/page.js --source [-o FILE] assembled only, labels as in src/ (what tests use)
// node scripts/lib/page.js --source --dev [-o FILE] the development page: with src/agent/ (what npm run dev serves)
// node scripts/lib/page.js --mp [--source] [-o FILE] a multiplayer build's page: with the server-play client
// node scripts/lib/page.js --ref origin/main -o FILE the page as it ships at a git ref
//
// --ref uses that commit's own assembler, so it keeps working when this file changes; refs from before
// the split (when the page was site/index.html) are read as they are.
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { execFileSync } = require('node:child_process');
const ROOT = path.join(__dirname, '..', '..');
const INCLUDE = /^<!-- @include(-dev)? ([\w./-]+) -->$/;
// Parts of src/ only a multiplayer build's page has (paths as the line map names them; a trailing / is a folder).
const MP_ONLY = ['game/98-server-play/', 'styles/43-server-play.css'];
const mpOnly = (f) => MP_ONLY.some((p) => (p.endsWith('/') ? f.startsWith(p) : f === p));
// Every file under dir, as paths relative to dir with '/' separators, in a stable order
// (plain code-unit comparison, so the order never depends on the machine's locale).
function listFiles(dir, rel = '') {
const out = [];
for (const e of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
if (e.name.startsWith('.')) continue;
const r = rel ? rel + '/' + e.name : e.name;
if (e.isDirectory()) out.push(...listFiles(dir, r));
else out.push(r);
}
return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
}
// The partials that make up one include, in order: [{file, text}]. Without mp, the multiplayer-only ones are left out.
function partials(src, dir, mp = true) {
const base = path.join(src, dir);
if (!fs.existsSync(base)) throw new Error(`@include ${dir}: no such directory under ${path.relative(ROOT, src) || '.'}`);
return listFiles(base).filter((r) => mp || !mpOnly(dir + '/' + r)).map((r) => {
const file = path.join(base, r);
const text = fs.readFileSync(file, 'utf8');
if (text.includes('\r')) throw new Error(`${path.relative(ROOT, file)}: use LF line endings`);
if (text && !text.endsWith('\n')) throw new Error(`${path.relative(ROOT, file)}: must end with a newline`);
if (/^<\/(script|style)/im.test(text)) throw new Error(`${path.relative(ROOT, file)}: must not close its <script>/<style>`);
return { file: dir + '/' + r, text };
});
}
// The assembled page as a string, plus a map of which output line came from which source file.
// dev: also the @include-dev parts (the development page); without it, their lines are left out entirely.
// mp: also the multiplayer-only parts (MP_ONLY); without it, those files are left out entirely.
function assemble({ src = path.join(ROOT, 'src'), dev = false, mp = false } = {}) {
const shell = fs.readFileSync(path.join(src, 'index.html'), 'utf8');
const out = [], map = [];
let line = 1;
const lines = shell.split('\n');
lines.forEach((l, i) => {
const m = INCLUDE.exec(l);
if (!m) {
out.push(l + (i < lines.length - 1 ? '\n' : ''));
line++;
return;
}
if (m[1] && !dev) return;
for (const p of partials(src, m[2], mp)) {
const n = p.text.split('\n').length - 1;
map.push({ file: p.file, from: line, to: line + n - 1 });
out.push(p.text);
line += n;
}
});
return { html: out.join(''), map };
}
// Which source file (and line in it) an assembled-page line comes from: for stack traces and errors.
function locate(map, line) {
const m = map.find((x) => line >= x.from && line <= x.to);
return m ? { file: m.file, line: line - m.from + 1 } : { file: 'index.html (shell)', line };
}
// The page at a git ref: that commit's src/ through its own assembler, or site/index.html before the split.
function assembleRef(ref, cwd = ROOT) {
const git = (...a) => execFileSync('git', a, { cwd, encoding: 'utf8', maxBuffer: 1 << 28, stdio: ['ignore', 'pipe', 'pipe'] });
const has = (p) => { try { git('cat-file', '-e', `${ref}:${p}`); return true; } catch { return false; } };
if (!has('src/index.html')) return git('show', `${ref}:site/index.html`);
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-ref-'));
try {
const tar = execFileSync('git', ['archive', '--format=tar', ref, 'src', 'scripts'], { cwd, maxBuffer: 1 << 28 });
execFileSync('tar', ['-x', '-C', tmp], { input: tar });
return execFileSync(process.execPath, [path.join(tmp, 'scripts', 'lib', 'page.js')], { cwd: tmp, encoding: 'utf8', maxBuffer: 1 << 28 });
} finally { fs.rmSync(tmp, { recursive: true, force: true }); }
}
// The page as it ships: assembled, with labels shrunk to short ids (compile-labels.js). Not version-stamped.
// `dicts` ({lang: label-keyed dictionary}) come back with the same ids. mp: a multiplayer build's page.
function shipped(dicts = {}, { mp = false } = {}) {
const D = require('./dict');
return require('./compile-labels').compile(assemble({ mp }).html, D.read('en').dict, dicts);
}
/* The build id of server-run play (SIM_ID): the first 12 hex digits of sha256 of the multiplayer page as assembled from
src/, labels as written (game and server-play client together, so a change to either is a new id). The build stamps
it into MP pages and version.json; the session server works it out from its own src/ and refuses pages of another. */
function simId(html = assemble({ mp: true }).html) {
return require('node:crypto').createHash('sha256').update(html).digest('hex').slice(0, 12);
}
// The shipped page written to a file, for tools that need a path (perf in a real browser, base vs head).
function pageFile(file = path.join(os.tmpdir(), `tubes-page-${process.pid}.html`)) {
fs.writeFileSync(file, shipped().html);
return file;
}
module.exports = { assemble, assembleRef, shipped, simId, pageFile, locate, listFiles, MP_ONLY, ROOT };
if (require.main === module) {
const args = process.argv.slice(2);
const opt = (k) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : null; };
const mp = args.includes('--mp');
const html = opt('--ref') ? assembleRef(opt('--ref')) : args.includes('--source') ? assemble({ dev: args.includes('--dev'), mp }).html : shipped({}, { mp }).html;
const out = opt('-o');
if (out) { fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true }); fs.writeFileSync(out, html); }
else process.stdout.write(html);
}

View file

@ -1,89 +0,0 @@
// Puzzle tools (the weekly generator, the puzzle tests): build a puzzle network straight into a headless game, judge
// it with the game's own star code, and search for the cheapest build that earns three stars.
//
// A build is a list of links [a, b, via, tier, same]: via is 'land' or a cable id, tier an index into LT, and `same`
// (k > 0) puts an overland link in the k-th trench already on that pair (otherwise a further one takes a diverse
// route, +40%). Routers
// are not part of the search: each POP gets the cheapest models that carry its busiest moment (across every single
// cut), its ports and its biggest wave, which is what any sensible player would buy for that build.
// Runs inside the page.
function page() {
window.pzsReset = () => { S.pops = {}; S.links = []; S.pairMet = {}; for (const b of S.biz) b.route = 'normal'; UI.pzEv = null; };
window.pzsLink = (a, b, via, tier, same) => {
const r = pzRoutes(a, b).find((x) => x.via === via); if (!r) throw new Error(`no route ${via} for ${a}-${b}`);
for (const c of [a, b]) if (!S.pops[c]) S.pops[c] = pzNewPop(c);
// `same` k > 0: in the k-th overland trench on this pair; 0: a trench of its own (diverse, unless it is the first).
const tr = !r.sub ? [...new Set(S.links.filter((l) => edgeKey(l) === edgeKey({ a, b }) && !l.cable).map((l) => l.trench))] : [], sm = same && tr[same - 1], div = !!(tr.length && sm !== tr[0]), id = uid();
S.links.push({ id, a, b, kind: 'wave', border: false, premium: false, tier, km: r.km, sub: r.sub, cable: r.cab, mo: pzMo(r, tier, div), mult: r.f * (div ? DIVERSE : 1), trench: r.cab ? 'cab:' + r.cab : sm || id, cut: 0, day: 0 });
};
// The cheapest routers for POP c: enough ports, a model that lights its biggest wave, and capacity for its peak.
window.pzsRouters = (c, peak) => {
const used = portsUsed(c), lt = Math.max(0, ...S.links.filter((l) => l.a === c || l.b === c).map((l) => l.tier)); let best = null;
for (const g of PZ_RG) for (let rt = 1; rt <= 6; rt++) { const M = RG[g]; if (M.maxLT < lt || M.ports * rt < used - 1e-9 || M.cap * rt < peak - 1e-6) continue;
const cost = pzRtCost(g, rt); if (!best || cost < best.cost) best = { g, rt, cost }; }
return best;
};
// Judge the build on routers big enough for anything, then price the routers it really needs. With those, routing
// is the same (no router is ever full), so the stars are too.
window.pzsJudge = () => {
const BIG = RG.findIndex((r) => r.n === 'Arrrhipster 7800R'), keep = {};
for (const c in S.pops) { keep[c] = [S.pops[c].rgen, S.pops[c].routers]; S.pops[c].rgen = BIG; S.pops[c].routers = 1; }
UI.pzEv = null; const b0 = S.pz.budget; S.pz.budget = 0; const e = pzEval(); S.pz.budget = b0; UI.pzEv = null;
const rt = {}; let spend = 0, bad = false;
for (const c in S.pops) { const r = pzsRouters(c, e.peak[c] || 0); if (!r) { bad = true; continue; } rt[c] = [r.g, r.rt]; spend += r.cost + pzPopCost(c); S.pops[c].rgen = keep[c][0]; S.pops[c].routers = keep[c][1]; }
for (const l of S.links) spend += l.mo * PZ_YEAR;
return { one: e.goal && !bad, three: e.goal && e.n1 && !bad, spend, rt };
};
window.pzsApplyRt = (rt) => { for (const c in rt) { S.pops[c].rgen = rt[c][0]; S.pops[c].routers = rt[c][1]; } UI.pzEv = null; };
}
const install = (ev) => { if (ev("typeof pzsJudge!=='function'")) ev(`(${page.toString()})()`); };
const key = (L) => JSON.stringify(L);
// Steps that are not links set what a player sets in the panels: ['@route', flow, 'fast'] a circuit's path,
// ['@met', a, b, 'avoid'] a pair's metric. The search keeps them as they are.
const step = ([a, b, v, t, s]) => a === '@route' ? `S.biz.find(x=>x.id===pzFlowId(${b})).route='${v}';` : a === '@met' ? `(S.pairMet=S.pairMet||{})[edgeKey({a:'${b}',b:'${v}'})]='${t}';`
: `pzsLink('${a}','${b}','${v}',${t},${s || 0});`;
function judge(ev, L) {
return JSON.parse(ev(`pzsReset();${L.map(step).join('')}JSON.stringify(pzsJudge())`));
}
// Every link option between the given cities: each route, at tiers up to maxTier.
function options(ev, cities, maxTier, noSub) {
const out = [];
for (let i = 0; i < cities.length; i++) for (let j = i + 1; j < cities.length; j++) {
const [a, b] = [cities[i], cities[j]];
const rs = JSON.parse(ev(`JSON.stringify(pzRoutes('${a}','${b}').map(r=>({via:r.via,sub:r.sub,ok:[0,1,2,3].map(t=>!subWaveWhy(t,r.km,r.sub))})))`));
for (const r of rs) { if (noSub && r.sub) continue; for (let t = 0; t <= maxTier; t++) if (r.ok[t]) { out.push([a, b, r.via, t, 0]); if (!r.sub) { out.push([a, b, r.via, t, 1]); out.push([a, b, r.via, t, 2]); } } }
}
return out;
}
// Local search from a 3-star build: drop a link, shrink one, move one to another route, put it in the first trench
// or out of it, or swap one link for another option, while it is cheaper and still three stars.
function improve(ev, start, opts = {}) {
const memo = new Map(), J = (L) => { const k = key(L); if (!memo.has(k)) memo.set(k, judge(ev, L)); return memo.get(k); };
let cur = start.map((x) => x.slice()), cj = J(cur);
if (!cj.three) throw new Error('the starting build does not earn three stars');
const routes = {}, via = (a, b) => { const k = a < b ? a + '|' + b : b + '|' + a; if (!routes[k]) routes[k] = JSON.parse(ev(`JSON.stringify(pzRoutes('${a}','${b}').map(r=>r.via))`)); return routes[k]; };
const opt = opts.options || [];
for (let round = 0; round < 60; round++) {
const nb = [];
for (let i = 0; i < cur.length; i++) {
const w = (x) => { const L = cur.slice(); L[i] = x; return L; }, [a, b, v, t, s] = cur[i];
if (a[0] === '@') continue;
nb.push(cur.filter((_, k) => k !== i));
if (t > 0) nb.push(w([a, b, v, t - 1, s]));
for (const v2 of via(a, b)) if (v2 !== v) nb.push(w([a, b, v2, t, 0]));
if (v === 'land') for (const s2 of [0, 1, 2]) if (s2 !== (s || 0)) nb.push(w([a, b, v, t, s2]));
}
if (opts.swap) for (const o of opt) for (let i = 0; i < cur.length; i++) { if (cur[i][0][0] === '@') continue; const L = cur.slice(); L[i] = o; nb.push(L); }
let best = null;
for (const L of nb) { const j = J(L); if (j.three && j.spend < cj.spend - 1 && (!best || j.spend < best.j.spend)) best = { L, j }; }
if (!best && opts.add) for (const o of opt) for (let i = 0; i < cur.length; i++) for (let k = i + 1; k < cur.length; k++) {
if (cur[i][0][0] === '@' || cur[k][0][0] === '@') continue;
const L = [...cur.filter((_, x) => x !== i && x !== k), o], j = J(L); if (j.three && j.spend < cj.spend - 1 && (!best || j.spend < best.j.spend)) best = { L, j }; }
if (!best) break;
cur = best.L; cj = best.j;
}
return { links: cur, ...cj };
}
module.exports = { install, judge, options, improve };

View file

@ -1,72 +0,0 @@
// The tool side of the agent relay (scripts/agent/relay.js), for the MCP server's browser session
// (scripts/lib/mcp-browser.js). The game runs in the player's browser, never in this process, connected to the relay
// from Settings. The relay rides the server that serves the page, same port, path /agent (npm run dev, 8080 unless
// told otherwise), so host and port say where the page is served, nothing else. A call travels
// tool → relay → page → TUBES.call and back.
const WebSocket = require('ws');
// A healthy page answers in milliseconds, and a page that goes away has its calls answered at once (by the relay, or
// by the close handler below), so this only catches a page that hangs. Days the player watches take longer: a call
// can ask for more time of its own.
const CALL_MS = 30000;
function createRelaySession(opts = {}) {
const cfg = {
host: typeof opts.host === 'string' && opts.host ? opts.host : '127.0.0.1',
port: +opts.port || 8080, // the port the game page is served on: the relay rides it
callMs: +opts.callMs > 0 ? +opts.callMs : CALL_MS,
};
const url = `ws://${cfg.host.includes(':') && !cfg.host.startsWith('[') ? `[${cfg.host}]` : cfg.host}:${cfg.port}/agent`;
let ws = null, connecting = null, id = 0, page = false;
const pending = new Map();
function connect() {
if (ws && ws.readyState === 1) return Promise.resolve();
if (connecting) return connecting;
connecting = new Promise((res, rej) => {
const w = new WebSocket(url);
let done = false;
const finish = (e) => { if (done) return; done = true; connecting = null; e ? rej(e) : res(); };
w.on('open', () => { w.send(JSON.stringify({ kind: 'auth', role: 'tool' })); finish(); });
w.on('error', (e) => finish(new Error(`relay ${url}: ${e.message}`)));
w.on('close', () => {
if (ws === w) { ws = null; page = false; }
// The socket died with calls in flight: answer them here too, so no tool waits out its timeout on a
// connection that is already gone (the relay answers for a dead page).
for (const [k, p] of [...pending]) { pending.delete(k); clearTimeout(p.t); p.res({ error: `relay ${url}: connection closed before the game page answered` }); }
if (!done) finish(new Error(`relay ${url}: connection closed`));
});
w.on('message', (d) => {
let m; try { m = JSON.parse(String(d)); } catch { return; }
if (!m || typeof m !== 'object') return;
if (m.kind === 'presence') { page = !!m.page; return; }
if (m.kind === 'result' && m.id !== undefined) { const p = pending.get(m.id); if (p) { pending.delete(m.id); clearTimeout(p.t); p.res(m); } }
});
ws = w;
});
return connecting;
}
// One call: {refused} when it could not be answered (no relay, no page, a timeout) or the page's tool threw,
// else {value}. dayBefore/dayAfter: the game day the page saw around it.
async function call(tool, args = {}, o = {}) {
try { await connect(); } catch (e) { return { refused: e.message, value: null }; }
const k = 't' + (++id), ms = +o.ms > 0 ? +o.ms : cfg.callMs;
const m = await new Promise((res) => {
const t = setTimeout(() => { pending.delete(k); res({ error: `no answer from the game page in ${ms / 1000} s (is the tab stuck?)` }); }, ms);
pending.set(k, { res, t });
ws.send(JSON.stringify({ kind: 'call', id: k, tool, args }));
});
if (m.error) return { refused: m.error, value: null, dayBefore: m.dayBefore, dayAfter: m.dayAfter };
return { refused: null, value: m.value === undefined ? null : m.value, dayBefore: m.dayBefore, dayAfter: m.dayAfter };
}
return {
config: cfg, url, call, connect,
get page() { return page; },
async close() { try { ws && ws.close(1000); } catch {} },
};
}
module.exports = { createRelaySession, CALL_MS };

View file

@ -1,217 +0,0 @@
// Differential games (scripts/route-fuzz.js, tests/route-fuzz.test.js): two game pages in one process, a base page
// (main's) and this checkout's, play the same seeded game move for move. After every move and every day both must
// have routed identically (all of R, R.fl, R.ef, the PNI lists), and this checkout must route the same with the
// routing cache (RC) on and off. The whole game state S must match too, so the two games stay in lockstep.
// Every move is picked here, from what the base page offers right now, with the game's seed: the seed alone
// replays a game.
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('../../tests/harness');
const FUZZ_JS = fs.readFileSync(path.join(__dirname, 'fuzz-page.js'), 'utf8');
function openPage(file, label) {
const g = load({ seed: 1, file });
g.ev(FUZZ_JS);
g.label = label;
g.call = (fn, ...args) => {
g.dom.window.__fzA = JSON.parse(JSON.stringify(args));
const out = g.ev(`JSON.stringify(__fz.${fn}(...window.__fzA))`);
return out === undefined ? undefined : JSON.parse(out);
};
return g;
}
// mulberry32: the driver's own numbers, apart from the pages' Math.random.
function rng(seed) {
let a = seed >>> 0;
const f = () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
f.int = (n) => Math.floor(f() * n);
f.pick = (a) => a[f.int(a.length)];
// A button by its action's weight (w), then any button of that action: 38 transit sellers count as one choice.
f.wp = (a, w) => { const g = new Map(); for (const x of a) { const l = g.get(x.act); if (l) l.push(x); else g.set(x.act, [x]); }
const ks = [...g.keys()]; let s = 0; for (const k of ks) s += w(g.get(k)[0]); let t = f() * s;
for (const k of ks) { t -= w(g.get(k)[0]); if (t < 0) return f.pick(g.get(k)); } return f.pick(g.get(ks[ks.length - 1])); };
f.w = (o) => { let s = 0; for (const k in o) s += o[k]; let x = f() * s; for (const k in o) { x -= o[k]; if (x < 0) return k; } return Object.keys(o)[0]; };
return f;
}
// The first key of two {key: json} maps that differs, with a short look at where.
function firstDiff(A, B) {
const keys = [...new Set([...Object.keys(A), ...Object.keys(B)])];
const out = [];
for (const k of keys) {
if (A[k] === B[k]) continue;
const a = A[k] || '', b = B[k] || '';
let i = 0; while (i < a.length && a[i] === b[i]) i++;
out.push({ key: k, at: i, base: a.slice(Math.max(0, i - 80), i + 120), head: b.slice(Math.max(0, i - 80), i + 120) });
if (out.length >= 4) break;
}
return out;
}
const DTABS = ['overview', 'cust', 'conn', 'traffic', 'infra', 'lease'];
const TABS = ['cust', 'up', 'peer', 'links'];
const LEFT = ['nets', 'noc', 'deals', 'goals'];
const PRESETS = ['freeze', 'oncall', 'bgp'];
// How often a button is pressed against the others on screen: what changes the network often, looking around rarely.
const BUILD = /^(buy\w*|pni\w*All|pni|peer|peerAll|unpeer|cache|cacheSite|rmCache|buildLink|buildPop|launchBB|accept|decline|dropBiz|pathMove|pathPin|pathAuto|takeLoan|repayLoan|lag[TPI]x?|setPref|setCarry|setStandby|setMetric|togglePrem|cleanPipe|sacrif|rs|foundIx|myIxUp|addRouter|rmRouter|upRouter|addSite|rmSite|siteSet|decomToggle|rmLink|upLink|addParallel|cancel\w*|upVxc|buyNni|rmNni|buildScrub|scrubUp|rmScrub|addGen|regen|addCh|rmCh|addPair|upSys|spares|layShip|crews|fixInc|seaPackage|subUpgrade|orderCable|orderDf|ownCab|opsHire|opsToggle|opsParam|opsCap|opsPop|opsTpl|opsNewPop|popStdSet|coreSet|teRecipe|dkOptOut|dkStay|utility\w*|listFiber|unlistFiber|leaseSwap|custGo|confGo|confSponsor|seatBuy|charter|cnPrem|applyCn|ad|ddosAuto|pz(Pop|RmPop|Link|AddPar|Tier|RmLink|RtAdd|RtRm|RtModel|Route|Via|Div)|setRoute|route|via|metricSet)$/;
const UIACT = /^(tab|dashTab|leftTab|\w*Sort|\w*Filter|pniGrp|trace\w*|focusCity|findGo|selLink|dashLink|logAll|tailTog|listMore|netFocus|netFilter|meetGo|phoneTab|dashClose|connF|connCity|connNet|connFor|custF|custCity|popGo|popsReg|opsOpen|decomOpen|linkCheck|pathOpen)$/;
const DW = { launchBB: 4, accept: 4, buyTransit: 3, pni: 3, buyIx: 3, setPref: 4, cache: 2, peerAll: 2, setCarry: 2, takeLoan: 2 };
const weight = (b) => (BUILD.test(b.act) ? 8 : UIACT.test(b.act) ? 0.3 : 1);
/* One game. pages: {base, head}. Returns {seed, start, moves, days, log, div} where div is the first divergence (or null).
opts: moves (count, default 50 to 200 by seed), maxDays per day-move, onMove(i, move) */
function playGame(pages, seed, opts = {}) {
const { base, head } = pages;
// A badge only this checkout has would unlock in its game alone, and an unlock writes a log line, which shifts every
// id made after it: the comparison is about routing, so the new badges are taken off this checkout's page.
if (!pages.badges && base !== head) {
const ids = base.ev('JSON.stringify(BADGES.map((b)=>b.id))');
head.ev(`{const keep=new Set(${ids});for(let i=BADGES.length-1;i>=0;i--)if(!keep.has(BADGES[i].id))BADGES.splice(i,1);}`);
pages.badges = true;
}
const r = rng(seed * 2654435761);
const both = (fn, ...a) => [base.call(fn, ...a), head.call(fn, ...a)];
const L = base.call('lists');
const log = [], acts = {};
let div = null, days = 0;
const note = (m) => { log.push(m); };
const fail = (where, info) => { if (!div) div = { seed, where, move: log.length, last: log.slice(-6), ...info }; };
const same = (where, a, b) => { if (JSON.stringify(a) !== JSON.stringify(b)) fail(where, { base: a, head: b }); };
// Compare everything: routing on both pages (a: the move's, b: again, c: cache off) and the game state.
const compare = (where) => {
const [x, y] = both('check');
for (const k of ['a', 'b', 'c']) if (x[k] !== y[k]) { fail(where + ': routing (' + k + ') base vs head', { diff: firstDiff(base.call('parts'), head.call('parts')) }); return false; }
if (y.b !== y.c) { fail(where + ': head cached vs uncached', { diff: 'R from the kept tables differs from a fresh route' }); return false; }
// Fields only this checkout's game has are left out on both sides (see sKeys in fuzz-page.js), and so is the state of a
// standing order only one of them has (one this checkout retired, or added).
const [k1, k2] = both('sKeys'), drop = { top: k2.top.filter((k) => !k1.top.includes(k)), items: k2.items.filter((k) => !k1.items.includes(k)),
ops: [...k1.ops.filter((k) => !k2.ops.includes(k)), ...k2.ops.filter((k) => !k1.ops.includes(k))] };
// Both states as this checkout's reload makes them (see sLive in fuzz-page.js).
const [j1, j2] = both('sLive'), s1 = head.call('sDigest', drop, j1), s2 = head.call('sDigest', drop, j2);
if (s1 !== s2) { fail(where + ': game state S', { diff: firstDiff(head.call('sParts', drop, j1), head.call('sParts', drop, j2)) }); return false; }
return true;
};
// The start.
const kind = opts.save ? 'save' : r.w({ normal: 44, sandbox: 14, scenario: 20, weekly: 3, puzzle: 11, architect: 8 });
if (opts.save) for (const p of [base, head]) p.dom.window.__fzSave = opts.save;
const home = r() < 0.4 ? r.pick(L.special) : r.pick(L.homes);
const st = { kind, seed: (seed % 2147483646) + 1, name: 'Fuzz ' + seed, city: home,
preset: kind === 'sandbox' ? r.pick(['none', 'calm', 'normal', 'spicy']) : r.pick(PRESETS),
id: kind === 'scenario' ? r.pick(L.scn) : kind === 'puzzle' ? r.pick(L.pz) : kind === 'architect' ? r.pick(L.ar) : undefined };
const [s0, s1] = both('start', st);
// A base without scarce IPv4 (#150) plays the classic game: both pages switch the rule off. Once it is on main, both play it.
if (!base.call('acts').includes('ip4Buy')) both('noIp4');
same('start', s0, s1);
note('start ' + JSON.stringify(st));
// A normal game signs its charter first: a popup on newer pages (which seeded pages skip), a card on older ones. Both
// sign the classic one at once, so neither shows charter buttons the other has not, and the game plays as it did.
if (kind === 'normal') { const [c0, c1] = both('press', { act: 'charter', args: { k: 'global' } }); same('charter', c0, c1); }
if (!div) compare('start');
// A screen's buttons on both pages; the same list or a divergence.
// Buttons for actions main's page does not have (a new feature's) are left out: the driver only presses what both have.
// So are the switches and dials of a standing order this checkout retired (main's sheet still shows them), and a
// dashboard tab main's page does not have yet.
let baseActs = null, retired = null, baseTabs = null;
const screen = (w) => { const [a0, b0] = both('screen', w); baseActs = baseActs || new Set(base.call('acts'));
if (!retired) { const [o1, o2] = both('sKeys'); retired = new Set(o1.orders.filter((k) => !o2.orders.includes(k))); }
const a = Array.isArray(a0) ? a0.filter((x) => !(/^ops/.test(x.act) && retired.has(x.args && x.args.k))) : a0;
// Args only this checkout's buttons carry (the total or plan a window shows: pniAll's q, bstdApply's quote) are left
// out as well: the driver presses the base's button, which both pages take as before.
if (!baseTabs) baseTabs = new Set(JSON.parse(base.ev('JSON.stringify(DTABS)')));
const b = Array.isArray(b0) ? b0.filter((x) => baseActs.has(x.act) && !(x.act === 'dashTab' && x.args && !baseTabs.has(x.args.k))).map((x, i) => { const y = Array.isArray(a) && a[i] && a[i].act === x.act ? a[i].args : null;
return y && x.args && typeof x.args === 'object' && typeof y === 'object' ? { act: x.act, args: Object.fromEntries(Object.entries(x.args).filter(([k]) => k in y)) } : x; }) : b0;
same('buttons of ' + JSON.stringify(w), a, b); return a || []; };
const press = (b, where) => { acts[b.act] = (acts[b.act] || 0) + 1; const [e1, e2] = both('press', b); same('press ' + where, e1, e2); note(where + ' ' + b.act + JSON.stringify(b.args) + (e1 ? ' !' + e1 : '')); };
// Answer whatever window opened, a few levels deep, then close it.
const modal = (bias) => {
for (let k = 0; k < 4 && !div; k++) {
if (!base.call('modalOpen')) return;
let bs = screen({ where: 'modal' });
if (bias) { const pref = bs.filter((b) => bias.test(b.act)); if (pref.length && r() < 0.7) bs = pref; }
const real = bs.filter((b) => !/^(closeModal|x)$/.test(b.act));
if (!real.length || r() < 0.12) break;
press(r.wp(real, weight), ' modal');
if (!div) compare('modal button');
}
both('close');
};
const N = opts.moves || 50 + (seed % 151);
for (let i = 0; i < N && !div; i++) {
const s = base.call('state');
if (s.lost) { note('bankrupt'); break; }
const mv = r.w(s.puzzle ? { city: 40, openLink: 30, link: 15, modal: 5 } : { city: 22, direct: 22, openLink: 13, link: 5, dash: 5, left: 3, poke: 8, day: s.clock ? 20 : 0, build: 4 });
if (opts.onMove) opts.onMove(i, mv);
if (mv === 'city' || mv === 'build') {
const city = mv === 'build' || !s.pops.length || r() < 0.3 ? (s.near.length ? r.pick(s.near) : r.pick(L.homes)) : r.pick(s.pops);
const tab = r.pick(TABS);
let bs = screen({ where: 'city', city, tab });
if (mv === 'build') { const p = bs.filter((b) => /^(buildPop|launchBB|opsNewPop|popStdSet)$/.test(b.act)); if (p.length) bs = p; }
if (bs.length) press(r.wp(bs, weight), `city ${city}/${tab}`);
if (!div) compare('city button');
modal();
} else if (mv === 'openLink') {
if (!s.pops.length) continue;
const a = r.pick(s.pops), b = r() < 0.75 && s.near.length ? r.pick(s.near) : r() < 0.5 && s.pops.length > 1 ? r.pick(s.pops) : r.pick(L.homes);
const bs = screen({ where: 'openLink', a, b });
note(`openLink ${a}-${b} (${bs.length})`);
if (bs.length) {
// Pick a route or a kind first sometimes (dark fiber, subsea seat, own cable...), then build.
const opt = bs.filter((x) => !/^(buildLink|closeModal)$/.test(x.act));
if (opt.length && r() < 0.4) { press(r.pick(opt), ' link option'); if (!div) compare('link option'); }
modal(/^(buildLink|pzLink|seaPackage|layShip|buyVxc|dfSys|seaDesign)$/);
} else both('close');
if (!div) compare('openLink');
} else if (mv === 'link') {
if (!s.links.length) continue;
const id = r.pick(s.links);
const bs = screen({ where: 'link', id });
if (bs.length) press(r.wp(bs, weight), 'link ' + id);
if (!div) compare('link button');
modal();
} else if (mv === 'dash' || mv === 'left') {
const w = mv === 'dash' ? { where: 'dash', tab: r.pick(DTABS) } : { where: 'left', tab: r.pick(LEFT) };
const bs = screen(w);
if (bs.length) press(r.wp(bs, weight), mv + ' ' + w.tab);
both('close');
if (!div) compare(mv + ' button');
modal();
} else if (mv === 'direct') {
const [a, b] = both('direct');
same('direct calls', a, b);
if (a.length) press(r.wp(a, (x) => DW[x.act] || (/^(cancel|rm|drop|unpeer)/.test(x.act) ? 0.4 : 1)), 'direct');
if (!div) compare('direct');
modal();
} else if (mv === 'modal') {
modal();
} else if (mv === 'poke') {
const k = r.w({ te: 3, teOff: 1, core: 2, fail: 2, event: 3, cash: 3, lvl: 2, ev: 4 });
let p;
if (k === 'te') { const rules = []; for (let j = 0, n = 1 + r.int(4); j < n; j++) rules.push([r.int(7), r.int(1000), r.int(1000)]); p = [k, rules, r() < 0.85]; }
else p = [k, k === 'cash' ? r.int(3e7) : r.int(1e6), r.int(9)];
const [e1, e2] = both('poke', p);
same('poke', e1, e2);
note('poke ' + JSON.stringify(p));
if (!div) compare('poke ' + k);
} else if (mv === 'day') {
const n = 1 + r.int(opts.maxDays || 12);
note('days ' + n);
for (let d = 0; d < n && !div; d++) {
const [e1, e2] = both('day');
same('day', e1, e2);
days++;
if (!div) compare('day ' + d);
// A window that opened over the day (an offer, a loan, a crisis) gets an answer.
if (!div && base.call('modalOpen')) modal();
}
}
}
return { seed, start: st, moves: log.length, days, log, div, acts, errors: [...base.errors, ...head.errors] };
}
module.exports = { openPage, playGame, rng };

View file

@ -1,54 +0,0 @@
// The reference player for weekly scenarios (scripts/weekly-scenario.js). It plays inside the real game, headless,
// through the game's own actions (ACT.*, openLinkModal + buildLink), as a careful human would: broadband, transit and
// an exchange port at home on day 0, a NOC intern on standing orders for transit and routers, then the generator's
// plan one step at a time whenever the bank allows it, upgrading any wave that runs hot. It never reads the goal, so the
// same seed and plan always play the same game, and the generator can calibrate a goal from what it reached.
const { lit } = require('./js-literal');
const BOT = String.raw`(()=>{
const B=window.__wsBot={};
const cheapNet=(c,avoid)=>NETS.filter(n=>n.price&&sellsAt(n,c)&&!avoid.includes(n.id)&&!S.transit.some(t=>t.city===c&&t.net===n.id)).sort((a,b)=>a.price*netMult(a,c)-b.price*netMult(b,c))[0];
const reserve=()=>Math.max(60000,1.5*(R.costMo||0));
const can=x=>S.cash>=x+reserve();
const quiet=f=>{const t=window.toast;window.toast=()=>{};try{f();}finally{window.toast=t;}};
function link(a,b,tier,via){UI.via=via||null;UI.route=null;openLinkModal(a,b);ACT.buildLink({tier});closeModal();return S.links.some(l=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a));}
function ix(c){if(!S.pops[c])return;for(const x of (B.plan&&B.plan.allIx?ixIdsIn(c):[c])){if(!ixName(x)||S.ixp[x]!==undefined)continue;ACT.buyIx({city:x,tier:1,signed:true});if(S.ixp[x]!==undefined&&!S.rs[x])ACT.rs({city:x});}}
// Before a big event: transit enough for the event on top of the usual peak, and routers that can take it.
function prep(E){const c=E.city,need=(S.stats.peak||R.served||0)*1.2+E.g*1.15;let cap=()=>S.transit.filter(t=>t.city===c).reduce((a,t)=>a+PORT[t.tier].g*(t.n||1),0);
for(let k=0;k<12&&cap()<need;k++){const t=S.transit.filter(t=>t.city===c).sort((a,b)=>PORT[a.tier].g*(a.n||1)-PORT[b.tier].g*(b.n||1))[0];if(!t)break;const c0=cap();
if(t.tier<PORT.length-1&&PORT[t.tier+1].g>=need/4&&portOk(c,t.tier+1))ACT.buyTransit({city:c,net:t.net,tier:t.tier+1});else ACT.lagT({id:t.id,d:1});if(cap()===c0)break;}
for(let k=0;k<4;k++){const p=S.pops[c];if(!p||(p.routers||1)>=RMAX)break;const r0=p.routers||1;ACT.addRouter({city:c});if((p.routers||1)===r0)break;}}
B.start=(plan)=>{B.plan=plan;B.i=0;const c=S.scn.home||plan.home;quiet(()=>{
ACT.launchBB({city:c});
if(!scnRule('noTransit')){const n=cheapNet(c,plan.avoid||[]);if(n)ACT.buyTransit({city:c,net:n.id,tier:1});if(plan.tr2){const m=cheapNet(c,plan.avoid||[]);if(m)ACT.buyTransit({city:c,net:m.id,tier:1});}}
ix(c);if(plan.scrub)ACT.buildScrub({city:c,tier:plan.scrub});});};
B.day=()=>{const P=B.plan,d=S.day;if(!P)return;quiet(()=>{
// A month in, with the first bills paid: the intern keeps transit and routers ahead of the traffic.
if(d===30&&opsCanHire()&&!opsHired()&&rule('clock')){ACT.opsHire({id:'kevin'});closeModal();if(opsHired())for(const k of ['transit','routers','repair'])if(!S.ops.on[k])ACT.opsToggle({k});closeModal();}
if(d%7===0)for(const l of S.links){if(l.kind!=='wave'||l.tier>=LT.length-1||(R.load[l.id]||0)<LT[l.tier].g*0.7)continue;const nm=Math.round(waveMo(l.km,l.sub,l.tier+1)*(l.mult||1));if(can(nm))ACT.upLink({id:l.id,tier:l.tier+1});}
if(P.event&&d>=P.event.day-21&&d<P.event.day&&d%7===0)prep(P.event);
const s=P.steps[B.i];if(!s)return;
if(s.k==='hop'){const [a,b,t,via]=s.v;if(!S.pops[a])return;const est=(S.pops[b]?0:popCost(b))+waveMo(kmBetween(a,b),isSub(a,b),t)*2+(P.bb?bbCost(b):0);if(!can(est))return;
// Big waves need big routers at both ends: the POP first, then the routers, then the wave.
if(!waveOk(a,b,t)){if(!S.pops[b])ACT.buildPop({city:b});for(const c of [a,b])for(let k=0;k<4&&S.pops[c]&&!waveOk(a,b,t);k++){const g0=S.pops[c].rgen||0;ACT.upRouter({city:c});if((S.pops[c].rgen||0)===g0)break;}}
if(!link(a,b,t,via)){B.i++;return;}if(P.bb&&!S.pops[b].bb)ACT.launchBB({city:b});if(P.ix)ix(b);B.i++;}
else if(s.k==='ix'){if(can(30000)){ix(s.v);B.i++;}}
else if(s.k==='tr'){if(can(40000)&&!scnRule('noTransit')){const n=cheapNet(s.v,P.avoid||[]);if(n)ACT.buyTransit({city:s.v,net:n.id,tier:1});B.i++;}}
else B.i++;});};
})()`;
const install = (ev) => { if (!ev('!!window.__wsBot')) ev(BOT); };
// Plays a weekly scenario file from day 0: the plan steps once a day, until the goal is met (when stop) or the days
// run out. Returns the day the goal was first met (or null), what the goal measure read each day, and the end state.
function play(ev, file, plan, { days, stop = true, measure = 'wsMeasure()' } = {}) {
install(ev);
ev(`localStorage.removeItem('sot-wkscn');wsBegin(${lit(file)},'Ref');if(UI.pendGame)ACT.pitchSkip();UI.speed=0;closeModal()`);
if (ev('!!(S.scn&&S.scn.wk)') !== true) throw new Error('the game would not start this scenario');
ev(`__wsBot.start(${lit(plan)})`);
const won0 = ev('wsOk()'), n = days || ev('S.scn.days');
// Each day: the bot moves, the day ticks (scnTick records a win), and we note the measure.
const out = JSON.parse(ev(`(()=>{const m=[];let won=null;for(let i=0;i<${n};i++){__wsBot.day();dayTick();closeModal();m.push(+(${measure}).toFixed(3));if(won===null&&S.scn.done)won=S.scn.done;if(won!==null&&${stop})break;if(S.lost)break;}return JSON.stringify({won,m,lost:!!S.lost,day:S.day,cash:Math.round(S.cash)});})()`));
return { won0, ...out };
}
module.exports = { BOT, install, play };

View file

@ -1,77 +0,0 @@
// The reference player for the handmade scenarios (tests/scenarios-playtest.test.js), the sibling of scenario-bot.js
// (which plays the weekly ones). It plays inside the real game, headless, through the game's own actions, one plan
// step at a time whenever the bank allows it, plus the upkeep a careful human does every week: hot waves a size up, hot
// transit and exchange ports a LAG member, new peers at every exchange, routers before they fill.
//
// A plan is a list of steps, each [op, ...args]:
// ['bb', c] POP and broadband ['tr', c, tier] the cheapest transit there ['ix', c, tier] every exchange
// ['pop', c] a POP only ['link', a, b, tier, cable] a wave (routers upgraded first, a swap a day)
// ['hire', orders, params] the NOC intern on standing orders, as soon as the level allows ('sales': the CEO signs deals)
// ['wait', day] until that day ['served', g] until g Gbps are served ['prep', c, g] capacity for an event
// ['scrub', c, tier] a scrubbing center ['pnis'] a PNI with every unreached network that takes one
// ['pni', c, net, tier] one PNI with that network there ['last', c] transit there only as a last resort
// ['loans'] take every loan the banks offer, from now on (the cheese plans)
const { lit } = require('./js-literal');
const REF = String.raw`(()=>{
const Q=window.__ref={log:[]};
const quiet=f=>{const t=window.toast;window.toast=()=>{};try{return f();}finally{window.toast=t;}};
Q.reserve=()=>Math.max(40000,1.3*(R.costMo||0));
Q.can=x=>S.cash>=x+Q.reserve();
Q.cheap=c=>NETS.filter(n=>n.price&&sellsAt(n,c)&&!(Q.avoid||[]).includes(n.id)&&!S.transit.some(t=>t.city===c&&t.net===n.id)).sort((a,b)=>a.price*netMult(a,c)-b.price*netMult(b,c))[0];
Q.pop=c=>{if(!S.pops[c])ACT.buildPop({city:c});return !!S.pops[c];};
Q.bb=c=>{Q.pop(c);if(S.pops[c]&&!S.pops[c].bb)ACT.launchBB({city:c});return !!(S.pops[c]&&S.pops[c].bb);};
Q.tr=(c,tier=1)=>{Q.pop(c);const n=Q.cheap(c);if(!n)return true;ACT.buyTransit({city:c,net:n.id,tier});return true;};
Q.last=c=>{for(const t of S.transit)if(t.city===c)ACT.setPref({kind:'t',id:t.id,v:'low'});return true;};
Q.ix=(c,tier=1)=>{if(!S.pops[c])return false;for(const x of ixIdsIn(c)){if(!ixName(x))continue;if(S.ixp[x]===undefined)ACT.buyIx({city:x,tier,signed:true});if(S.ixp[x]===undefined)continue;if(!S.rs[x])ACT.rs({city:x});ACT.peerAll({city:x});}return true;};
// A wave: big waves need big routers at both ends, and a router swap takes a day, so the step waits (null) until they fit.
Q.link=(a,b,tier=1,via)=>{for(const c of [a,b])Q.pop(c);if(!S.pops[a]||!S.pops[b])return false;
for(const c of [a,b])for(let k=0;k<4&&!waveOk(a,b,tier);k++){const g0=S.pops[c].rgen||0;ACT.upRouter({city:c});if((S.pops[c].rgen||0)===g0)break;}
if(!waveOk(a,b,tier))return null;const n0=S.links.length;UI.via=via||null;UI.route=null;openLinkModal(a,b);ACT.buildLink({tier});closeModal();return S.links.length>n0;};
Q.hire=(orders,par)=>{Q.wantHire=[orders||['transit','routers','repair'],par||{}];return true;};
Q.hire0=(orders,par)=>{if(!opsCanHire()||!Q.can(20000))return false;if(!opsHired()){ACT.opsHire({id:'kevin'});closeModal();}if(!opsHired())return false;
// Deals are the sales desk's: 'sales' puts the CEO there (free, and he signs what the old sales order signed) and lets him sign.
for(const k of orders)if(k==='sales'){if(!slP()&&salesCanHire())ACT.salesHire({id:'ceo'});if(slP()&&!S.slAuto.on)ACT.salesAuto();}else if(!S.ops.on[k])ACT.opsToggle({k});for(const k in par)for(const [p,v] of Object.entries(par[k]))for(let i=0;i<8&&opsP(k,p)!==v;i++)ACT.opsParam({k,p});closeModal();return true;};
Q.pnis=(tier=0)=>{for(const n of NETS.filter(n=>!R.reachable[n.id]).sort((a,b)=>NSH[b.id]-NSH[a.id])){const b=pniBatch(n.id,tier);if(!b||!b.orders.length||!Q.can(b.cost))continue;ACT.pniAll({net:n.id,tier});}return true;};
Q.pni=(c,net,tier=0)=>{if(!S.pni.some(p=>p.city===c&&p.net===net))ACT.pni({city:c,net,tier});closeModal();return S.pni.some(p=>p.city===c&&p.net===net);};
Q.scrub=(c,tier=0)=>{ACT.buildScrub({city:c,tier});return true;};
Q.loans=()=>{Q.loan=true;return true;};
Q.served=g=>R.served>=g||null;
Q.wait=d=>S.day>=d||null;
// Before an event: transit for the event on top of the usual peak, and routers that can take it.
Q.prep=(c,g)=>{const need=(S.stats.peak||R.served||0)*1.2+g*1.15,cap=()=>S.transit.filter(t=>t.city===c).reduce((a,t)=>a+PORT[t.tier].g*(t.n||1),0);
for(let k=0;k<12&&cap()<need;k++){const t=S.transit.filter(t=>t.city===c).sort((a,b)=>PORT[a.tier].g*(a.n||1)-PORT[b.tier].g*(b.n||1))[0];if(!t)break;const c0=cap();
if(t.tier<PORT.length-1&&PORT[t.tier+1].g>=need/4&&portOk(c,t.tier+1))ACT.buyTransit({city:c,net:t.net,tier:t.tier+1});else ACT.lagT({id:t.id,d:1});
if(cap()===c0){if(t.tier<PORT.length-1&&!portOk(c,t.tier+1))ACT.upRouter({city:c});else break;}}
for(let k=0;k<4;k++){const p=S.pops[c];if(!p||(p.routers||1)>=RMAX)break;const r0=p.routers||1;ACT.addRouter({city:c});if((p.routers||1)===r0)break;}return true;};
Q.est={pop:c=>S.pops[c]?0:popCost(c),bb:c=>(S.pops[c]?0:popCost(c))+bbCost(c),tr:()=>20000,pni:()=>20000,ix:()=>25000,hire:()=>0,scrub:(c,t)=>SCRUB_TIERS[t||0].cost,
link:(a,b,t)=>(S.pops[a]?0:popCost(a))+(S.pops[b]?0:popCost(b))+waveMo(kmBetween(a,b),isSub(a,b),t)*2+20000};
Q.upkeep=()=>{
for(const l of S.links){if(l.kind!=='wave'||l.tier>=LT.length-1||linkDown(l)||(R.load[l.id]||0)<LT[l.tier].g*0.75)continue;
if(!waveOk(l.a,l.b,l.tier+1))for(const c of [l.a,l.b])if(!waveOk(l.a,l.b,l.tier+1)&&Q.can(80000))ACT.upRouter({city:c});
if(Q.can(Math.round(waveMo(l.km,l.sub,l.tier+1)*(l.mult||1))*2))ACT.upLink({id:l.id,tier:l.tier+1});}
for(const x in S.ixp)if(!(S.myIx&&S.myIx[x]))ACT.peerAll({city:x});
if(!(opsHired()&&S.ops.on.transit))for(const t of S.transit.slice()){const u=(R.useT&&R.useT[t.id])||0,cap=lagCap(PORT[t.tier].g,t.n);if(u<cap*0.75)continue;
if((t.n||1)<2||t.tier>=PORT.length-1||!portOk(t.city,t.tier+1)){if(Q.can(PORT[t.tier].setup+20000))ACT.lagT({id:t.id,d:1});if(lagCap(PORT[t.tier].g,t.n)===cap&&Q.can(80000))ACT.upRouter({city:t.city});}
else if(Q.can(PORT[t.tier+1].setup+30000))ACT.buyTransit({city:t.city,net:t.net,tier:t.tier+1});}
for(const x in S.ixp){if(S.myIx&&S.myIx[x])continue;const u=(R.useIx&&R.useIx[x])||0;if(u>=lagCap(PORT[S.ixp[x]].g,(S.ixn||{})[x])*0.75&&Q.can(30000))ACT.lagIx({city:x,d:1});}
if(!(opsHired()&&S.ops.on.routers))for(const c in S.pops){if((R.nodeLoad[c]||0)/(R.nodeCap[c]||nodeCap(c)||1)>0.8&&Q.can(80000)){if((S.pops[c].routers||1)<2)ACT.addRouter({city:c});else ACT.upRouter({city:c});}}};
Q.step=()=>{for(let k=0;k<6;k++){const s=Q.steps[Q.i];if(!s)return;const [op,...a]=s;
if(Q.est[op]&&!Q.can(Q.est[op](...a)))return;const ok=Q[op](...a);if(ok===null)return;Q.log.push(S.day+' '+op+' '+a.join(',')+(ok?'':' (failed)'));Q.i++;}};
Q.day=()=>quiet(()=>{if(Q.wantHire&&Q.hire0(...Q.wantHire)){Q.log.push(S.day+' hired');Q.wantHire=null;}
if(Q.loan)for(const o of (S.loanOffers||[]).slice())ACT.takeLoan({id:o.id});closeModal();
Q.step();if(S.day%7===0)Q.upkeep();});
Q.start=(steps,o={})=>quiet(()=>{Q.steps=steps;Q.i=0;Q.avoid=o.avoid||[];Q.step();});
})()`;
// Starts scenario `id` (with `seed`, or its own), plays `plan` for up to `days` days (default: the scenario's), and
// returns the day it was won (or null), whether the network went broke, and the end state.
function play(ev, id, plan, { seed, days, avoid } = {}) {
ev(`localStorage.removeItem('sot-scn');beginGame('Ref',SCN.find(x=>x.id==='${id}').city,{scn:SCN.find(x=>x.id==='${id}')${seed ? ',seed:' + seed : ''}});if(UI.pendGame)ACT.pitchSkip();UI.speed=0;closeModal()`);
if (ev('typeof __ref') === 'undefined') ev(REF);
ev(`__ref.start(${lit(plan)},${lit({ avoid })})`);
const n = days || ev('S.scn.days');
return JSON.parse(ev(`(()=>{let won=null;for(let i=0;i<${n};i++){__ref.day();dayTick();closeModal();if(S.scn.done){won=S.scn.done;break;}if(S.lost||S.scn.failed)break;}
return JSON.stringify({won,lost:!!S.lost,day:S.day,limit:S.scn.days,cash:Math.round(S.cash),served:Math.round(R.served)});})()`));
}
module.exports = { REF, play };

View file

@ -1,18 +0,0 @@
// A node:test reporter that writes how long each test file took, as JSON {"tests/x.test.js": seconds}, to its
// destination. scripts/test.js adds it next to the usual output with --timings FILE; CI merges the parts' files
// into tests/durations.json, which the next run splits its parts by.
const path = require('node:path');
module.exports = async function* timings(source) {
const sec = {};
for await (const { type, data } of source) {
// Top-level tests only: their durations include their subtests.
if ((type === 'test:pass' || type === 'test:fail') && data.nesting === 0 && data.file && data.details) {
const f = path.relative(process.cwd(), data.file).split(path.sep).join('/');
sec[f] = (sec[f] || 0) + (data.details.duration_ms || 0) / 1000;
}
}
const out = {};
for (const f of Object.keys(sec).sort()) out[f] = Math.round(sec[f] * 10) / 10;
yield JSON.stringify(out, null, 1) + '\n';
};

View file

@ -1,240 +0,0 @@
#!/usr/bin/env node
// Series of Tubes as an MCP server: an AI client can play, inspect and debug the game through typed tools, in one of
// two sessions: headless, a game of its own loaded from this checkout's src/ (scripts/lib/mcp-game.js), or the game in
// the player's browser tab over the agent relay (scripts/lib/mcp-browser.js). It speaks MCP through the official SDK
// (@modelcontextprotocol/server), over stdio or over HTTP. Nothing is hosted: this is a local tool, like npm run dev,
// and the game page players get does not change.
//
// node scripts/mcp.js # stdio, headless, the agent's clock (advance)
// node scripts/mcp.js --clock realtime # a clock that runs on its own (--pace ms per day; wait)
// node scripts/mcp.js --browser # the player's tab, through the relay npm run dev hosts
// node scripts/mcp.js --http 7777 # Streamable HTTP on http://127.0.0.1:7777/mcp (with any of the above)
// node scripts/mcp.js --http 0.0.0.0:7777 # the same on every interface: anyone who can reach it can play
//
// claude mcp add seriesoftubes -- node /path/to/seriesoftubes/scripts/mcp.js
// claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp
//
// stdout carries only protocol messages in stdio mode; anything else goes to stderr.
const crypto = require('node:crypto');
const fs = require('node:fs');
const http = require('node:http');
const os = require('node:os');
const path = require('node:path');
const { McpServer, fromJsonSchema, createMcpHandler, validateHostHeader, validateOriginHeader, localhostAllowedHostnames, localhostAllowedOrigins } = require('@modelcontextprotocol/server');
const { createSession, toolsFor, CLOCKS, DEFAULT_PACE_MS } = require('./lib/mcp-game');
const { version } = require('../package.json');
const READ = 'Read with status, network, city, find, traceroute, peering_check and hot_spots, or raw with state, results and catalog; schema is the typed contract of every action, and its mode section says which session this is. Change things with act (arguments are checked, outcome says what happened, dryRun prices a move first), or with screen, panel and click, which show the game\'s own panels and windows as text with numbered buttons.';
const CLOCK = {
agent: 'Time moves only with advance.',
realtime: 'The clock runs on its own, a day at a fixed pace, and you cannot stop it: decide while it runs, and use wait to let days pass.',
};
const instructions = (mode, clock) => mode === 'browser'
? `Series of Tubes is a cartoon game about building an internet backbone: POPs in cities, links between them, transit, exchanges, PNIs, customers. You are playing the game in the player's own browser tab while they watch: the game, its saves and its settings are theirs, and so is any window they open (you play behind it). ${READ} The player picks the clock in Settings: either it runs on its own at a pace and you use wait, or it is yours and you use advance (schema mode.clock says which).`
: `Series of Tubes is a cartoon game about building an internet backbone: POPs in cities, links between them, transit, exchanges, PNIs, customers. A game is always loaded (a fresh On-call game in Frankfurt until you start or load another). ${READ} ${CLOCK[clock]} Games are seeded: the same seed and moves give the same game.
To look into a bug report: load_save with the attached save, then status, hot_spots, and advance with timings.`;
const INSTRUCTIONS = instructions('headless', 'agent');
const MCP_PATH = '/mcp';
const usage = () => `Usage: node scripts/mcp.js [options]
(no options) headless over stdio: a game of its own, from this checkout's src/; the client starts this process
--clock agent|realtime headless: who moves time (default agent: advance; realtime: a day every --pace ms, and wait)
--pace MS headless, realtime clock: real milliseconds per simulated day (default ${DEFAULT_PACE_MS})
--seed N headless: the random seed of the first game (default 12345)
--browser the game in the player's browser instead, over the agent relay (Settings → Agent API)
--relay-host HOST browser: where npm run dev serves the page; the relay rides it (default 127.0.0.1)
--relay-port N browser: the port it serves the page on (default 8080)
--page-wait-ms N browser: how long to wait for a game page to connect (default 90000)
--call-ms N browser: how long one tool call may wait for the page (default 30000)
--http [HOST:]PORT Streamable HTTP at http://HOST:PORT${MCP_PATH} instead (HOST defaults to 127.0.0.1)
--token-file FILE HTTP: require "Authorization: Bearer <the file's contents>" (or set SOT_MCP_TOKEN)
--allow-host NAME HTTP: also accept this Host name (repeatable), e.g. for a tunnel or a LAN name
--save-dir DIR HTTP: load_save and export_save may read and write files under DIR (otherwise no files)
--help`;
// Valueless flags are true; repeated ones collect; --kebab-case becomes camelCase.
function parseArgs(argv) {
const out = {};
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (!a.startsWith('--')) continue;
const k = a.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase()), v = argv[i + 1];
const val = v === undefined || v.startsWith('--') ? true : (i++, v);
out[k] = k in out ? [].concat(out[k], val) : val;
}
return out;
}
// Tool calls run one at a time, in the order they arrived, from every client: one game, one move at a time.
function serial() {
let chain = Promise.resolve();
return (f) => { const p = chain.then(f); chain = p.catch(() => {}); return p; };
}
// One MCP server definition over the game session: the SDK asks for a fresh one per connection (stdio) or per request
// (HTTP); they all share the session and its queue.
function serverFactory(session) {
const queue = serial(), tools = toolsFor(session.mode || 'headless'), text = instructions(session.mode || 'headless', session.clock || 'agent');
const schemas = new Map(tools.map((t) => [t.name, fromJsonSchema(t.inputSchema)]));
return () => {
const server = new McpServer({ name: 'seriesoftubes', title: 'Series of Tubes', version }, { capabilities: { tools: {} }, instructions: text });
for (const tool of tools) {
server.registerTool(tool.name, { description: tool.description, inputSchema: schemas.get(tool.name) }, (args) => queue(async () => {
try {
const out = await tool.run(session, args || {});
const errs = session.errors();
return { content: [{ type: 'text', text: JSON.stringify(out, null, 1) }], ...(errs.length ? { _meta: { pageErrors: errs.slice(-5) } } : {}) };
} catch (e) {
return { content: [{ type: 'text', text: String(e && e.message || e) }], isError: true };
}
}));
}
return server;
};
}
// --http [HOST:]PORT, with IPv6 hosts in brackets ([::1]:7777).
function parseListen(v) {
const s = String(v === true ? '' : v);
const m = /^(?:\[([^\]]+)\]|([^:]+)):(\d+)$/.exec(s) || /^()()(\d+)$/.exec(s);
// Port 0 picks a free one (the banner says which).
if (!m || +m[3] > 65535) throw new Error(`--http takes [HOST:]PORT, e.g. 7777 or 0.0.0.0:7777, not "${s}"`);
return { host: m[1] || m[2] || '127.0.0.1', port: +m[3] };
}
const isLoopback = (h) => h === 'localhost' || h === '::1' || /^127\.\d+\.\d+\.\d+$/.test(h);
const isWildcard = (h) => h === '0.0.0.0' || h === '::';
const bracket = (h) => (h.includes(':') && !h.startsWith('[') ? `[${h}]` : h);
// The names a request's Host may carry: this machine by loopback, the address the server is bound to (every local
// address when bound to all of them), and names the operator allowed. Anything else is a name someone else's DNS
// points here (DNS rebinding) and is refused.
function allowedHosts(host, extra = []) {
const out = new Set([...localhostAllowedHostnames(), ...extra.map(String)]);
if (isWildcard(host)) for (const list of Object.values(os.networkInterfaces())) for (const a of list || []) out.add(bracket(a.address.split('%')[0]));
else out.add(bracket(host));
return [...out];
}
// Constant-time token check (hashing first makes the lengths equal, so the length does not leak either).
const sameToken = (a, b) => crypto.timingSafeEqual(crypto.createHash('sha256').update(String(a)).digest(), crypto.createHash('sha256').update(String(b)).digest());
// The HTTP side: Host and Origin checked on every request (browsers cannot be talked into driving the game from a
// website), the token when there is one, then the SDK's Streamable HTTP handler.
function createHttpServer(factory, { host, allow = [], token = null } = {}) {
const { toNodeHandler } = require('@modelcontextprotocol/node');
const handle = toNodeHandler(createMcpHandler(factory));
const hosts = allowedHosts(host, allow), origins = localhostAllowedOrigins();
const deny = (res, code, message, headers = {}) => {
res.writeHead(code, { 'content-type': 'application/json', ...headers });
res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32000, message } }));
};
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname !== MCP_PATH) return deny(res, 404, `The MCP endpoint is ${MCP_PATH}.`);
const h = validateHostHeader(req.headers.host, hosts);
if (!h.ok) return deny(res, 403, `Host not allowed: ${h.message}. Use an address of this machine, or start the server with --allow-host.`);
const o = validateOriginHeader(req.headers.origin, origins);
if (!o.ok) return deny(res, 403, 'Origin not allowed: a web page may not drive this server.');
if (token) {
const auth = String(req.headers.authorization || '').trim(), sp = auth.search(/\s/);
const given = sp > 0 && auth.slice(0, sp).toLowerCase() === 'bearer' ? auth.slice(sp + 1).trim() : '';
if (!given || !sameToken(given, token)) return deny(res, 401, 'A bearer token is required.', { 'www-authenticate': 'Bearer realm="seriesoftubes"' });
}
handle(req, res);
});
// advance over thousands of days on a big network takes minutes; Node's default would cut it off at five.
server.requestTimeout = 30 * 60 * 1000;
return server;
}
function readToken(args) {
if (args.tokenFile) {
const t = fs.readFileSync(path.resolve(String(args.tokenFile)), 'utf8').trim();
if (!t) throw new Error(`${args.tokenFile} is empty`);
return t;
}
return process.env.SOT_MCP_TOKEN ? String(process.env.SOT_MCP_TOKEN).trim() || null : null;
}
async function main() {
const args = parseArgs(process.argv.slice(2));
if (args.help) { console.error(usage()); process.exit(0); }
const say = (m) => console.error(`[series-of-tubes] ${m}`);
const die = (m) => { console.error(`error: ${m}`); process.exit(1); };
// The game page logs nothing to stdout, but a stray console.log anywhere must not break the stdio protocol.
console.log = console.info = (...a) => console.error(...a);
const flag = (k) => `--${k.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase())}`;
if (!args.http) for (const k of ['tokenFile', 'allowHost', 'saveDir']) if (args[k] !== undefined) die(`${flag(k)} is an --http option`);
if (args.browser) {
for (const k of ['clock', 'pace', 'seed', 'saveDir']) if (args[k] !== undefined) die(`${flag(k)} is the headless session's: in the browser the player owns the game and sets the clock in Settings`);
} else {
for (const k of ['relayHost', 'relayPort', 'pageWaitMs', 'callMs']) if (args[k] !== undefined) die(`${flag(k)} is a --browser option`);
if (args.clock !== undefined && !CLOCKS.includes(args.clock)) die(`--clock is one of ${CLOCKS.join(', ')}`);
}
if (!args.http) {
const { serveStdio } = require('@modelcontextprotocol/server/stdio');
const session = open(args);
serveStdio(serverFactory(session));
const shutdown = () => { try { session.close(); } catch {} process.exit(0); };
process.stdin.on('close', shutdown);
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
// stdio has one client, which needs the page: without one, it is better told by the server stopping.
started(session, args, say, true);
return;
}
let listen, token;
try { listen = parseListen(args.http); token = readToken(args); } catch (e) { die(e.message); }
// Over HTTP the client may be another machine: files only under --save-dir, never anywhere on this one.
let saveDir = null;
if (args.saveDir !== undefined) {
try { saveDir = fs.realpathSync(path.resolve(String(args.saveDir))); } catch (e) { die(`--save-dir ${args.saveDir}: ${e.message}`); }
if (!fs.statSync(saveDir).isDirectory()) die(`--save-dir ${args.saveDir} is not a directory`);
}
const session = open(args, { saveDir });
const server = createHttpServer(serverFactory(session), { host: listen.host, allow: [].concat(args.allowHost || []), token });
server.on('error', (e) => die(`could not listen on ${bracket(listen.host)}:${listen.port}: ${e.message}`));
server.listen(listen.port, listen.host, () => {
const ad = server.address(), at = `${bracket(ad.address)}:${ad.port}`;
say(`MCP server ${version} on http://${at}${MCP_PATH} (one game, shared by every client; calls run one at a time)`);
say(token ? 'a bearer token is required' : 'no token: anything that can reach this address may play');
if (!isLoopback(listen.host) && !token) say(`WARNING: bound to ${listen.host}, beyond this machine, without a token. Set SOT_MCP_TOKEN or --token-file to require one.`);
if (session.mode === 'headless') say(saveDir ? `load_save and export_save files: under ${saveDir}` : 'load_save and export_save take JSON only (no files: --save-dir DIR allows some)');
started(session, args, say, false);
});
const shutdown = () => { try { session.close(); } catch {} server.close(() => process.exit(0)); };
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
}
// The session the flags ask for: headless (with its clock), or the player's browser over the relay.
function open(args, extra = {}) {
if (args.browser) {
const { createBrowserSession } = require('./lib/mcp-browser');
return createBrowserSession({ host: args.relayHost, port: args.relayPort, callMs: args.callMs });
}
return createSession({ clock: args.clock, paceMs: args.pace, seed: +args.seed || undefined, ...extra });
}
// What the session is, said once it is up. In the browser the handshake is answered at once; the page may arrive
// later, and must be built from this checkout. Over stdio a missing or stale page stops the server (its one client
// is better told so); over HTTP the server stays up and says why its tools fail.
function started(session, args, say, stopOnFail) {
if (session.mode !== 'browser') {
say(`MCP server ${version}: headless, ${session.clock === 'realtime' ? `a running clock, a day every ${session.paceMs} ms` : 'the agent\'s clock'}`);
return;
}
say(`MCP server ${version}: the player's browser, over the relay ${session.relay.url}`);
session.ready({ waitMs: +args.pageWaitMs || 90000, onWait: () => say(`waiting for the game page on the relay (${session.relay.url})...`) }).then((r) => {
if (r.ok) { say('the game page serves this checkout\'s contract: ready'); return; }
say(r.why);
if (r.stale) say('Its tab is older than this checkout: reload the page in the browser (npm run dev assembles it from src/ on every request).');
else say('Turn agent mode on in the game (Settings → Agent API), which connects it to the relay. The page must come from npm run dev, which hosts the relay (the deployed seriesoftub.es has none), opened by address (http://localhost or http://127.0.0.1, or the IP it is bound to), not a DNS name, which the relay refuses.');
if (stopOnFail) process.exit(1);
});
}
if (require.main === module) main();
module.exports = { serverFactory, createHttpServer, serial, parseArgs, parseListen, allowedHosts, instructions, INSTRUCTIONS, MCP_PATH };

View file

@ -1,117 +0,0 @@
#!/usr/bin/env node
// The multiplayer server for a self-hosted Series of Tubes (docs/MULTIPLAYER.md). The public game at seriesoftub.es
// is GitHub Pages only and has no multiplayer: this is for your own copy, built with MP_API=/api/mp npm run build.
// Plain node:http, no dependencies. It answers the API under /api/mp and, with --site, serves the built game too, so
// one process can sit behind a reverse proxy.
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const { createMp } = require('./lib/mp');
const HELP = `Series of Tubes multiplayer server
node scripts/mp-server.js [options] (npm run mp -- [options])
--port N port to listen on (default 8090, or $PORT)
--host H address to bind (default 127.0.0.1: put a reverse proxy in front)
--data DIR where sessions and saves are kept (default ./mp-data, created if missing)
--site DIR also serve the built game from DIR (e.g. _site from MP_API=/api/mp npm run build)
--base PATH the API's path (default /api/mp; the page's MP_API must match)
--prune-days N sessions nobody touched for N days are deleted at startup and daily (default 60)
--max-sessions N at most N sessions on this server (default 1000)
--max-players N at most N players per session (default 12, at most 12)
--create-per-hour N new sessions one address may start per hour (default 10; an IPv6 address counts as its /64)
--sessions-per-hour N new sessions on the whole server per hour (default 100)
--trust-proxy take the client's address from X-Forwarded-For (only behind your own reverse proxy)
--verbose log one line per API request (never tokens)
--help this text
Storage: DIR/<CODE>.json per session and DIR/<CODE>.<pid>.save per player's save. Back up DIR.
API (JSON; every call but create and join needs Authorization: Bearer <pid>.<token>):
POST /api/mp/sessions {net:{name,home},preset,title?} start a session
POST /api/mp/sessions/:code/join {net:{name,home}} join one
GET /api/mp/sessions/:code roster, cards and feed
PUT /api/mp/sessions/:code/card {card} your public card
PUT /api/mp/sessions/:code/save {seq,at,data,card?,force?} your save (409 when the server has a newer one)
GET /api/mp/sessions/:code/save your save
POST /api/mp/sessions/:code/feed {text} a chat line
DELETE /api/mp/sessions/:code/me leave
`;
const argv = process.argv.slice(2);
if (argv.includes('--help') || argv.includes('-h')) { process.stdout.write(HELP); process.exit(0); }
const die = (m) => { console.error(`error: ${m}`); process.exit(2); };
const KNOWN = new Set(['--port', '--host', '--data', '--site', '--base', '--prune-days', '--max-sessions', '--max-players', '--create-per-hour', '--sessions-per-hour', '--trust-proxy', '--verbose', '--help', '-h']);
for (const a of argv) if (a.startsWith('-') && !KNOWN.has(a)) die(`unknown option ${a} (see --help)`);
const opt = (k) => { const i = argv.indexOf(k); if (i < 0) return null; const v = argv[i + 1]; if (v === undefined || v.startsWith('--')) die(`${k} needs a value`); return v; };
const pos = (k, d, max = 1e9) => { const v = opt(k); if (v === null) return d; const n = +v; if (!Number.isInteger(n) || n < 1 || n > max) die(`${k} wants a whole number from 1 to ${max}`); return n; };
const PORT = pos('--port', +process.env.PORT || 8090, 65535);
const HOST = opt('--host') || '127.0.0.1';
const DATA = path.resolve(opt('--data') || 'mp-data');
const SITE = opt('--site') ? path.resolve(opt('--site')) : null;
const BASE = opt('--base') || '/api/mp';
// A path, never "//host/..." (which a browser reads as another host).
if (!/^\/(?!\/)[A-Za-z0-9/_-]*[A-Za-z0-9_-]$/.test(BASE)) die('--base must be a path like /api/mp');
if (SITE && !fs.statSync(SITE, { throwIfNoEntry: false })?.isDirectory()) die(`--site ${SITE} is not a directory`);
if (SITE && !fs.existsSync(path.join(SITE, 'index.html'))) die(`--site ${SITE} has no index.html (run npm run build first)`);
const mp = createMp({
dir: DATA, base: BASE, pruneDays: pos('--prune-days', 60), maxSessions: pos('--max-sessions', 1000),
maxPlayers: pos('--max-players', 12, 12), createPerHour: pos('--create-per-hour', 10), sessionsPerHour: pos('--sessions-per-hour', 100),
trustProxy: argv.includes('--trust-proxy'), verbose: argv.includes('--verbose'),
});
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json',
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml',
'.webmanifest': 'application/manifest+json', '.woff2': 'font/woff2', '.jpg': 'image/jpeg', '.webp': 'image/webp' };
// The page, the service worker and the files that change between releases are always checked; the rest may be cached.
const FRESH = /(^|\/)(index\.html|404\.html|sw\.js|version\.json)$|\/weekly\//;
// What is at p, or null: a path the file system cannot even look at (too long, a loop of links...) is not there either.
const stat = (p) => { try { return fs.statSync(p, { throwIfNoEntry: false }) || null; } catch (e) { return null; } };
const isFile = (p) => { const st = stat(p); return !!(st && st.isFile()); };
// The built site, like GitHub Pages serves it: / is index.html, a missing file is 404.html, nothing outside SITE.
function serveSite(req, res) {
if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405, { allow: 'GET, HEAD' }); return res.end(); }
let rel;
try { rel = decodeURIComponent(new URL(req.url, 'http://x').pathname); } catch (e) { rel = null; }
let file = null;
if (rel !== null && !rel.includes('\0')) {
if (rel.endsWith('/')) rel += 'index.html';
const p = path.resolve(SITE, '.' + path.posix.normalize('/' + rel));
if (p.startsWith(SITE + path.sep)) { const st = stat(p); if (st && st.isFile()) file = p; else if (st && st.isDirectory() && isFile(path.join(p, 'index.html'))) file = path.join(p, 'index.html'); }
}
const status = file ? 200 : 404;
if (!file) file = path.join(SITE, '404.html');
if (!isFile(file)) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); return res.end('Not found'); }
const r = path.relative(SITE, file).split(path.sep).join('/');
res.writeHead(status, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': FRESH.test('/' + r) ? 'no-cache' : 'public, max-age=3600', 'x-content-type-options': 'nosniff' });
if (req.method === 'HEAD') return res.end();
fs.createReadStream(file).on('error', () => res.destroy()).pipe(res);
}
const server = http.createServer((req, res) => {
try {
if (mp.handle(req, res)) return;
if (SITE) return serveSite(req, res);
res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' });
res.end('{"error":"not found"}');
} catch (e) {
// One line, never a stack: whatever went wrong, a request should not be able to fill the log.
console.error(`[mp] ${req.method} ${String(req.url).slice(0, 200)}: ${e && e.message}`);
if (!res.headersSent) res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' });
res.end('{"error":"server error"}');
}
});
server.on('clientError', (e, socket) => { try { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); } catch (_) { /* gone */ } });
server.on('error', (e) => { console.error(`error: could not listen on ${HOST}:${PORT}: ${e.message}`); process.exit(1); });
server.listen(PORT, HOST, () => {
const ad = server.address(), at = `${ad.family === 'IPv6' ? `[${ad.address}]` : ad.address}:${ad.port}`;
console.log(`Series of Tubes multiplayer: http://${at}${BASE} (data in ${DATA}, ${mp.sessions()} sessions${SITE ? `, serving ${SITE}` : ''})`);
});
setInterval(() => { try { mp.prune(); } catch (e) { console.error(`[mp] pruning failed: ${e.message}`); } }, 86400000).unref();
const shutdown = () => { server.close(); mp.flush().finally(() => process.exit(0)); setTimeout(() => process.exit(0), 3000).unref(); };
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);

View file

@ -1,127 +0,0 @@
#!/usr/bin/env node
// Performance benchmark on a very large network (tests/fixtures/big-network.json).
//
// node scripts/perf-bench.js time this checkout
// node scripts/perf-bench.js --base-ref origin/main compare main with this checkout (builds main's page)
// node scripts/perf-bench.js --base OLD.html compare a built page (e.g. a release's) with this checkout
// node scripts/perf-bench.js --base OLD.html --md out.md --summary "$GITHUB_STEP_SUMMARY"
// node scripts/perf-bench.js --save my-export.json --base OLD.html a player's save (plain or exported from the menu)
// node scripts/perf-bench.js --base OLD.html --browser also in real Chromium, as a desktop and as a phone
//
// Both versions load the same save in one process and are timed in alternating turns, so a busy machine slows
// them equally. Each number is the median of several runs. It also says whether both versions route the save's
// traffic identically, which catches unintended gameplay changes in a "pure speed" PR.
// Headless (jsdom, a recording canvas): it measures our JavaScript, not the browser's painting. --browser adds the
// same workloads in Chromium (scripts/perf-browser.js), where DOM work, layout and canvas drawing are real.
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('../tests/harness');
const args = process.argv.slice(2);
const opt = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };
const ROOT = path.join(__dirname, '..');
const page = require('./lib/page');
const { lit } = require('./lib/js-literal');
// Pages as files: the browser run opens them from disk.
const HEAD = opt('--head', null) || page.pageFile();
const BASE = opt('--base', null) || (opt('--base-ref', null) && (() => {
const f = path.join(require('node:os').tmpdir(), `tubes-base-${process.pid}.html`);
fs.writeFileSync(f, page.assembleRef(opt('--base-ref', null)));
return f;
})());
const RUNS = +opt('--runs', 15);
// A plain save, or a file from the in-game "Export save", which wraps it as {app, version, exported, S}.
const RAW = JSON.parse(fs.readFileSync(opt('--save', path.join(ROOT, 'tests', 'fixtures', 'big-network.json')), 'utf8'));
const SAVE = JSON.stringify(RAW && RAW.app === 'series-of-tubes' && RAW.S ? RAW.S : RAW);
// What we time. Each body runs inside the game page; panels render two selections in turn, so nothing can be
// skipped as "unchanged" and every run does the same work.
const METRICS = [
['compute', 'Routing: compute()', 'compute()'],
['day', 'One game day: dayTick()', 'S.nextFail=S.day+99;S.nextEvent=S.day+99;dayTick()'],
['action', 'An action: after()', 'after()'],
['panels', 'Side panel and left list', "for(const f of [true,false]){UI.sel={type:'city',id:f?'fra':'ams'};UI.tab=f?'peer':'up';UI.left=f?'nets':'noc';UI.leftOpen=true;renderPanel();renderLeft();}"],
['dash', 'NOC dashboard tabs', "$('dash').hidden=false;for(const k of ['overview','conn','traffic','infra','cust']){UI.dtab=k;renderDash();}$('dash').hidden=true"],
['map', 'Map at three zoom levels', "for(const z of [1,3.2,7]){cam.x=CITY.fra.x;cam.y=CITY.fra.y;cam.z=z;draw(0);}"],
// The NOC intern runs every order, every day: one shift, its recomputes included (hired here if the save has none).
['ops', "The NOC intern's shift: opsDay()", "if(!S.ops.intern){S.ops.intern='tracy';S.ops.hired=S.day;for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;for(const k in S.ops.cap)S.ops.cap[k]=0;}S.cash=1e9;opsDay(S.day)"],
// A day as it is played: its routing in the route worker, and only the time it holds the page counted (what a player
// feels as a hitch). Chromium only: jsdom has no Worker. See perf-browser.js.
['play', 'One game day in play: page time only', null, { play: true }],
];
function open(file) {
const { ev, errors } = load({ file, seed: 777 });
ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();renderAll();`);
const time = (body) => ev(`(()=>{const t=performance.now();${body};return performance.now()-t;})()`);
// What the network carries, to tell a pure speed-up from a change in how traffic is routed.
const outcome = () => ev(`(()=>{compute();const r=[R.served,R.demand,R.reach,R.peered,JSON.stringify(R.egT),...Object.keys(R.citySrv).sort().map(c=>R.citySrv[c]),...S.links.map(l=>R.load[l.id]||0)];
return r.map(x=>typeof x==='number'?x.toFixed(6):x).join('|');})()`);
const size = JSON.parse(ev("JSON.stringify({pops:Object.keys(S.pops).length,links:S.links.length,pni:S.pni.length,caches:S.caches.length,customers:S.biz.length,ix:Object.keys(S.ixp).length})"));
return { ev, errors, time, outcome, size };
}
const median = (a) => { const s = [...a].sort((x, y) => x - y); return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2; };
const ms = (x) => x == null ? '–' : x >= 100 ? x.toFixed(0) : x >= 10 ? x.toFixed(1) : x.toFixed(2);
(async () => {
const head = open(HEAD), base = BASE ? open(BASE) : null;
const sameOutcome = base ? base.outcome() === head.outcome() : null;
const res = {};
for (const [k, , body, o] of METRICS) {
if (o && o.play) { res[k] = { head: null, base: null, samples: null }; continue; }
const h = [], b = [];
for (const v of [head, base].filter(Boolean)) { v.time(body); v.time(body); } // warm up
for (let i = 0; i < RUNS; i++) {
// Alternate who goes first, so drift over the run lands on both sides.
if (base && i % 2) { b.push(base.time(body)); h.push(head.time(body)); } else { h.push(head.time(body)); if (base) b.push(base.time(body)); }
}
res[k] = { head: median(h), base: base ? median(b) : null, samples: { head: h, base: base ? b : null } };
}
const errs = [...head.errors, ...(base ? base.errors : [])];
const browser = args.includes('--browser') ? await require('./perf-browser').runBrowser({ head: HEAD, base: BASE, save: SAVE, metrics: METRICS, runs: RUNS, exe: opt('--chrome', process.env.PERF_CHROME) }) : null;
const { mannWhitneyP } = require('./perf-stats');
const pOf = (r) => (r.samples && r.samples.base ? mannWhitneyP(r.samples.head, r.samples.base) : 1);
const verdict = (r, noise = 2) => {
if (r.base == null || r.head == null) return '';
const ratio = r.head / (r.base || 1e-9);
if (Math.abs(r.head - r.base) < noise || pOf(r) >= 0.01) return '≈';
if (ratio >= 1.5) return '🔴 slower';
if (ratio >= 1.15) return '⚠️ slower';
if (ratio <= 0.85) return '🟢 faster';
return '≈';
};
const pct = (r) => r.base == null || r.head == null ? '' : `${r.head >= r.base ? '+' : ''}${(((r.head - r.base) / (r.base || 1e-9)) * 100).toFixed(0)}%`;
const pTxt = (r) => { if (r.base == null || r.head == null) return ''; const p = pOf(r); return p < 0.001 ? '<0.001' : p.toFixed(p < 0.1 ? 3 : 2); };
// One table per environment, all the same shape. `noise` is the absolute floor below which nothing counts.
const table = (res, noise) => (base ? '| What | Base | This PR | Change | p | |\n|---|--:|--:|--:|--:|---|\n' : '| What | Time |\n|---|--:|\n') +
METRICS.map(([k, label]) => { const r = res[k]; return base ? `| ${label} | ${ms(r.base)} | ${ms(r.head)} | ${pct(r)} | ${pTxt(r)} | ${verdict(r, noise)} |` : `| ${label} | ${ms(r.head)} |`; }).join('\n') + '\n';
const slowIn = (res, noise) => METRICS.filter(([k]) => /slower/.test(verdict(res[k], noise))).map(([, l]) => l);
const s = head.size;
let md = `## Performance on a big network\n\n${s.pops} POPs · ${s.links} links · ${s.pni} PNIs · ${s.caches} cache boxes · ${s.ix} IX ports · ${s.customers} customers. Median of ${RUNS} runs, in milliseconds.\n\n`;
md += `### Headless (jsdom)\n\nOur JavaScript only: jsdom has no layout and its DOM is far slower than a browser's, so trust the routing rows most here. It has no Worker either: a day in play is timed in Chromium only.\n\n` + table(res, 2);
const slow = base ? slowIn(res, 2) : [];
const { PROFILES } = browser ? require('./perf-browser') : { PROFILES: [] };
for (const p of PROFILES) {
// The map row is the whole frame, up to a pixel read back from the surface that drew it; say which one that was.
const mp = browser.profiles[p.key].maps, mapName = (m) => (!m || !m.length ? 'no map' : m.map((x) => (x === 'gl' ? 'WebGL' : '2D canvas')).join(' then '));
const drew = mp ? ` The map was drawn with ${base ? `${mapName(mp.base)} (base) and ${mapName(mp.head)} (this PR)` : mapName(mp.head)}; its row waits for that surface to finish.` : '';
md += `\n### Chromium ${browser.version}: ${p.key === 'phone' ? 'phone' : 'desktop'}\n\n${p.key === 'phone' ? 'A 390×844 screen at 3× pixel density, with the CPU slowed down 4× like a mid-range Android.' : 'A 1280×800 window at full speed.'} Real DOM, layout and canvas.${drew}\n\n` + table(browser.profiles[p.key], 2 * p.rate);
if (base) slow.push(...slowIn(browser.profiles[p.key], 2 * p.rate).map((l) => `${l} (Chromium ${p.key})`));
}
if (base) {
md += `\n${sameOutcome ? '✅ Routing results are identical to the base.' : '⚠️ Routing results differ from the base: traffic is carried differently. Expected if this PR changes gameplay; a bug if it only promises to be faster.'}\n`;
md += slow.length ? `\n**Slower:** ${slow.join(', ')}. Please explain or fix before merging.\n` : '\nNo slowdowns beyond noise.\n';
}
for (const [where, list] of [['', errs], [' in Chromium', browser ? browser.errors : []]]) {
if (list.length) md += `\n⚠️ Page errors${where} while benchmarking:\n\n${list.slice(0, 5).map((e) => '- `' + String(e).slice(0, 200).replace(/`/g, "'") + '`').join('\n')}\n`;
}
md += `\n<sub>scripts/perf-bench.js · A row only counts as slower or faster when it moved by 15% or more and p &lt; 0.01 (Mann–Whitney U), and by more than 2 ms (8 ms on the phone). Headless Chromium draws the canvas in software; phones usually use the GPU.</sub>\n`;
console.log(md);
const out = opt('--md', null); if (out) fs.writeFileSync(out, md);
const sum = opt('--summary', null); if (sum) fs.appendFileSync(sum, md + '\n');
const js = opt('--json', null); if (js) fs.writeFileSync(js, JSON.stringify({ size: s, runs: RUNS, results: res, sameOutcome, errors: errs, browser }, null, 2));
})().catch((e) => { console.error(e); process.exit(1); });

View file

@ -1,99 +0,0 @@
// The perf-bench workloads in real Chromium, for what jsdom cannot show: real DOM speed (jsdom is about 30×
// slower at it), layout (jsdom has none, so it cannot see a forced reflow) and canvas drawing. Two profiles: a
// desktop at full speed, and a phone (390×844, 3× pixel density, CPU slowed 4× like a mid-range Android).
// Used by scripts/perf-bench.js --browser. Needs Chromium: a local `playwright` with its browser, or
// `playwright-core` (a dev dependency) plus a Chrome binary in PERF_CHROME or --chrome (CI uses the runner's Chrome).
const { pathToFileURL } = require('node:url');
const PROFILES = [
{ key: 'desktop', label: 'Desktop', rate: 1, ctx: { viewport: { width: 1280, height: 800 }, deviceScaleFactor: 1 } },
{ key: 'phone', label: 'Phone (4× slower CPU)', rate: 4, ctx: { viewport: { width: 390, height: 844 }, deviceScaleFactor: 3, isMobile: true, hasTouch: true } },
];
function chromium(exe) {
// With a Chrome binary given, playwright-core is enough; without one, a full playwright brings its own browser.
for (const m of exe ? ['playwright-core', 'playwright'] : ['playwright', 'playwright-core']) {
try { return require(m).chromium; } catch (e) { /* try the next one */ }
}
throw new Error('--browser needs playwright-core (npm ci) and a Chrome binary in PERF_CHROME, or a local playwright');
}
const median = (a) => { const s = [...a].sort((x, y) => x - y); return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2; };
async function openPage(browser, profile, file, save, errors) {
const ctx = await browser.newContext(profile.ctx);
const page = await ctx.newPage();
// Nothing from the network (fonts, stats): both versions see exactly the same page, and no request adds noise.
await page.route('**/*', (r) => (r.request().url().startsWith('file:') ? r.continue() : r.abort()));
// Same as the tests: no animation loop or update checks running between measurements, and seeded randomness.
await page.addInitScript(() => { window.__TUBES_TEST__ = true; let r = 777; Math.random = () => { r = (r * 16807) % 2147483647; return r / 2147483647; }; });
page.on('pageerror', (e) => errors.push(String(e.message || e)));
await page.goto(pathToFileURL(file).href, { waitUntil: 'load' });
await page.evaluate((s) => { S = migrate(JSON.parse(s)); UI.started = true; UI.pitched = true; UI.speed = 0; closeModal(); compute(); renderAll(); }, save);
const cdp = await ctx.newCDPSession(page);
if (profile.rate > 1) await cdp.send('Emulation.setCPUThrottlingRate', { rate: profile.rate });
await cdp.send('HeapProfiler.enable');
// One run of a workload, timed inside the page so the round trip to Node does not count. Garbage is collected
// first, so a run never pays for the one before it (its own garbage still costs it, as in the game).
// The browser leaves layout and canvas drawing for the next frame, so code that changes the DOM or draws the map
// would look free: each run ends by forcing both (reading a size, and one pixel back from the surface the map was
// last drawn on: the WebGL canvas when the card drew it, which waits for the card to finish, else the 2D canvas).
// A run also says which map drew (gl, 2d, or none when it drew nothing).
const time = async (k, body) => { await cdp.send('HeapProfiler.collectGarbage'); return page.evaluate(([k, body]) => {
const F = window.__fx || (window.__fx = {}); const f = F[k] || (F[k] = new Function(body)); const map = document.getElementById('map').getContext('2d');
const G = typeof GLX === 'object' ? GLX : null, px = window.__px || (window.__px = new Uint8Array(4));
const t = performance.now(); f(); void document.documentElement.offsetHeight;
const gl = G && G.shown && G.gl; if (gl) gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px); else map.getImageData(0, 0, 1, 1);
return { ms: performance.now() - t, map: G && G.shown ? 'gl' : '2d' }; }, [k, body]); };
// One game day as it is played: its steps on the page, its routing in the route worker (built from the page itself,
// see 28-route-worker.js). Only the time it holds the page counts: starting the day, each answer from the worker and
// each step that waited for a frame. Waiting for the worker does not count; the page is free meanwhile.
// null when this page has no worker to play with.
const play = async () => { await cdp.send('HeapProfiler.collectGarbage'); return page.evaluate(async () => {
window.__TUBES_TEST__ = false;
try {
const w = typeof rwOn === 'function' && rwOn() && rwStart(); if (!w) return null;
let busy = 0; const wrap = (f) => function (...a) { const t = performance.now(); try { return f.apply(this, a); } finally { busy += performance.now() - t; } };
const om = w.onmessage, later = RW.later; w.onmessage = wrap(om); if (later) RW.later = (f) => later(wrap(f));
S.nextFail = S.nextEvent = S.day + 99;
try { const t = performance.now(); rwDay(); busy += performance.now() - t; while (RW.job) await new Promise((r) => setTimeout(r, 1)); }
finally { w.onmessage = om; if (later) RW.later = later; }
return RW.dead ? null : busy;
} finally { window.__TUBES_TEST__ = true; }
}); };
return { ctx, time, play };
}
// Returns {version, profiles: {desktop: {compute: {head, base}, ...}, phone: {...}}, errors}.
async function runBrowser({ head, base, save, metrics, runs, exe }) {
// One browser per version: pages of one browser can share a renderer process and its heap, and then one
// version's garbage is collected while the other one is being timed.
const launch = () => chromium(exe).launch(exe ? { executablePath: exe } : {});
const hb = await launch(), bb = base ? await launch() : null;
const errors = [], out = { version: hb.version(), profiles: {}, errors };
try {
for (const p of PROFILES) {
const h = await openPage(hb, p, head, save, errors), b = base ? await openPage(bb, p, base, save, errors) : null;
const res = out.profiles[p.key] = {};
// Which map each version drew with, over all the runs that drew one (a version falling back mid-run shows both).
const maps = res.maps = { head: new Set(), base: new Set() };
for (const [k, , body, o] of metrics) {
const H = [], B = [], run = (v) => (o && o.play ? v.play() : v.time(k, body));
const go = async (v, into, m) => { const r = await run(v); if (o && o.play) into.push(r); else { into.push(r.ms); if (k === 'map') m.add(r.map); } };
for (const v of [h, b].filter(Boolean)) { await run(v); await run(v); } // warm up (and the worker starts)
for (let i = 0; i < runs; i++) {
// Alternate who goes first, like the jsdom runs.
if (b && i % 2) { await go(b, B, maps.base); await go(h, H, maps.head); } else { await go(h, H, maps.head); if (b) await go(b, B, maps.base); }
}
// A version without a worker gives nothing to compare.
const ok = (a) => a.every((x) => x != null);
res[k] = { head: ok(H) ? median(H) : null, base: b && ok(B) ? median(B) : null, samples: { head: ok(H) ? H.map((x) => +x.toFixed(1)) : null, base: b && ok(B) ? B.map((x) => +x.toFixed(1)) : null } };
}
res.maps = { head: [...maps.head], base: b ? [...maps.base] : null };
await h.ctx.close(); if (b) await b.ctx.close();
}
} finally { await hb.close(); if (bb) await bb.close(); }
return out;
}
module.exports = { runBrowser, PROFILES };

View file

@ -1,39 +0,0 @@
#!/usr/bin/env node
// Builds tests/fixtures/big-network.json: a deterministic, very large late-game network that the performance
// benchmark (scripts/perf-bench.js) loads into the base and the head of every pull request. Big on purpose: about
// a hundred POPs, a few hundred links and customers, and close to a thousand PNIs and cache boxes, like the saves
// that made the game lag (#89). Regenerate only when the save format changes in a way old saves cannot load:
// node scripts/perf-fixture.js
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('../tests/harness');
const { ev, errors } = load({ seed: 4242 });
ev(`(()=>{UI.pitched=true;ACT.start({});S.cash=1e13;S.lvl=LEVELS.length;S.won=true;for(const g of GOALS)S.done[g.id]=0;S.tut=null;
const top=RG.findIndex(r=>r.lvl===LEVELS.length&&r.maxP===PORT.length-1);
const cs=ALLC.filter(c=>!CITY[c].ixOnly&&!CITY[c].cn);
for(const c of cs){if(!S.pops[c])ACT.buildPop({city:c});const p=S.pops[c];if(!p)continue;p.rgen=top>=0?top:RG.length-1;p.routers=RMAX;if(!p.bb)ACT.launchBB({city:c});if(p.bb)p.bb.d=CITY[c].P*0.65;if(Math.random()<0.3)ACT.addSite({city:c});}
const pops=Object.keys(S.pops);
// A backbone: every POP to its two nearest neighbours, plus long-haul shortcuts.
const L=(a,b,t)=>{if(a===b)return;UI.pending=null;UI.via=null;UI.lmode='wave';UI.route='diverse';try{openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();}catch(e){closeModal();}};
for(const a of pops){const near=pops.filter(b=>b!==a).sort((x,y)=>kmBetween(a,x)-kmBetween(a,y)).slice(0,2);for(const b of near)if(!pairLinks(a,b).length)L(a,b,3);}
for(let i=0;i<60;i++){const a=pops[Math.floor(Math.random()*pops.length)],b=pops[Math.floor(Math.random()*pops.length)];L(a,b,4);}
// Transit in some cities, IX ports with route servers everywhere.
for(const c of pops.slice(0,30)){const ts=NETS.filter(n=>n.price&&n.pops.includes(c)&&(n.type==='t1'||n.type==='t2')).slice(0,2);for(const t of ts)ACT.buyTransit({city:c,net:t.id,tier:3});}
for(const c of pops)for(const x of ixIdsIn(c)){try{ACT.buyIx({city:x,tier:3});}catch(e){}if(S.dk&&S.dk.q){S.dk.q=null;}closeModal();if(S.ixp[x]!==undefined&&!S.rs[x])ACT.rs({city:x});}
compute();
// PNIs wherever a network is present, and cache boxes from every CDN.
for(const n of NETS)for(const c of pops)if(S.pni.length<950&&n.pops.includes(c)&&!n.tail)S.pni.push({id:'p'+n.id+'_'+c,net:n.id,city:c,tier:3,n:1,site:'a'});
for(const n of NETS.filter(n=>n.cache))for(const c of pops)for(const k of [1,2])if(S.caches.length<850)S.caches.push({id:'c'+k+n.id+'_'+c,city:c,net:n.id,site:'a'});
// Real customers: accept offers until there are a few hundred.
for(let i=0;i<6000&&S.biz.length<420;i++){S.offers=[];spawnOffer();const o=S.offers[0];if(o&&bHas(o))ACT.accept({id:o.id});}
S.offers=[];S.nextFail=S.day+30;S.nextEvent=S.day+30;S.inc=[];
for(let d=0;d<20;d++)dayTick();
})()`);
if (errors.length) { console.error(errors); process.exit(1); }
const save = ev('JSON.stringify(S)');
const n = JSON.parse(ev("JSON.stringify({pops:Object.keys(S.pops).length,links:S.links.length,pni:S.pni.length,caches:S.caches.length,biz:S.biz.length,transit:S.transit.length,ix:Object.keys(S.ixp).length,served:Math.round(R.served)})"));
const out = path.join(__dirname, '..', 'tests', 'fixtures', 'big-network.json');
fs.mkdirSync(path.dirname(out), { recursive: true });
fs.writeFileSync(out, save + '\n');
console.log(`wrote ${path.relative(process.cwd(), out)} (${Math.round(save.length / 1024)} KB):`, n);

View file

@ -1,19 +0,0 @@
// Statistics for scripts/perf-bench.js.
// Is the head really slower or faster, or is it the machine? Shared CI runners swing a single run by ±30% on
// identical code, so a difference only counts when it is big (15%) AND the samples say it is real: a two-sided
// Mann–Whitney U test (no assumption about how the timings are spread), p below 0.01.
function mannWhitneyP(a, b) {
const all = [...a.map((v) => [v, 0]), ...b.map((v) => [v, 1])].sort((x, y) => x[0] - y[0]);
const n1 = a.length, n2 = b.length, N = n1 + n2, rank = new Array(N);
let ties = 0;
for (let i = 0; i < N;) { let j = i; while (j + 1 < N && all[j + 1][0] === all[i][0]) j++; const r = (i + j) / 2 + 1, t = j - i + 1; for (let k = i; k <= j; k++) rank[k] = r; ties += t * t * t - t; i = j + 1; }
const r1 = all.reduce((sum, [, g], i) => sum + (g === 0 ? rank[i] : 0), 0), U = r1 - n1 * (n1 + 1) / 2;
const sd = Math.sqrt(n1 * n2 / 12 * ((N + 1) - ties / (N * (N - 1))));
if (!sd) return 1;
const z = (Math.abs(U - n1 * n2 / 2) - 0.5) / sd;
// Two-sided p from the normal approximation (fine from about 8 samples a side).
const t = 1 / (1 + 0.2316419 * z), d = 0.3989423 * Math.exp(-z * z / 2);
return Math.min(1, 2 * d * t * (0.3193815 + t * (-0.3565638 + t * (1.781478 + t * (-1.821256 + t * 1.330274)))));
}
module.exports = { mannWhitneyP };

View file

@ -1,12 +1,10 @@
#!/usr/bin/env node #!/usr/bin/env node
// Prints the CHANGELOG.md bullets for one version as a JSON array of strings. // Prints the CHANGELOG.md bullets for one version as a JSON array of strings.
// Usage: node scripts/release-notes.js 1.2.0 // Usage: node scripts/release-notes.js 1.2.0
// node scripts/release-notes.js 2.0.0 --story the release's story instead: the paragraphs of prose between
// its heading and its first bullet or ### heading (often none)
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const version = process.argv[2], story = process.argv.includes('--story'); const version = process.argv[2];
const text = fs.readFileSync(path.join(__dirname, '..', 'CHANGELOG.md'), 'utf8'); const text = fs.readFileSync(path.join(__dirname, '..', 'CHANGELOG.md'), 'utf8');
const lines = text.split('\n'); const lines = text.split('\n');
const start = lines.findIndex((l) => l.startsWith(`## [${version}]`)); const start = lines.findIndex((l) => l.startsWith(`## [${version}]`));
@ -18,15 +16,4 @@ if (start >= 0) {
else if (/^\s{2,}\S/.test(l) && notes.length) notes[notes.length - 1] += ' ' + l.trim(); else if (/^\s{2,}\S/.test(l) && notes.length) notes[notes.length - 1] += ' ' + l.trim();
} }
} }
if (story) { process.stdout.write(JSON.stringify(notes));
const paras = [];
if (start >= 0) {
let cur = [];
for (let i = start + 1; i < lines.length && !lines[i].startsWith('## [') && !/^\s*-\s+/.test(lines[i]) && !lines[i].startsWith('###'); i++) {
const l = lines[i].trim();
if (l) cur.push(l); else if (cur.length) { paras.push(cur.join(' ')); cur = []; }
}
if (cur.length) paras.push(cur.join(' '));
}
process.stdout.write(JSON.stringify(paras));
} else process.stdout.write(JSON.stringify(notes));

View file

@ -1,84 +0,0 @@
#!/usr/bin/env node
// Many random games, played move for move on main's page and on this checkout's, compared after every move and day
// (scripts/lib/route-fuzz.js). For refactors that promise identical routing.
//
// node scripts/route-fuzz.js 300 games against origin/main
// node scripts/route-fuzz.js --games 50 --from 1000 games with seeds 1000..1049
// node scripts/route-fuzz.js --seed 1234 -v one game, every move printed (to replay a divergence)
// node scripts/route-fuzz.js --save tests/fixtures/big-network.json --games 10 --moves 30 from a big network
// node scripts/route-fuzz.js --jobs 2 --base OLD.html --out fuzz.json
// Exit code 1 when any game diverged; each divergence is printed with its seed and its last moves.
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { fork } = require('node:child_process');
const args = process.argv.slice(2);
const opt = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };
const has = (k) => args.includes(k);
function child() {
const { openPage, playGame } = require('./lib/route-fuzz');
const base = openPage(opt('--base'), 'base'), head = openPage(opt('--head'), 'head');
process.on('message', (m) => {
if (m.stop) process.exit(0);
const t = Date.now();
let res;
try { res = playGame({ base, head }, m.seed, { moves: m.moves, save: m.save }); } catch (e) { res = { seed: m.seed, div: { where: 'driver crashed', error: String(e.stack || e) }, log: [] }; }
process.send({ seed: m.seed, ms: Date.now() - t, start: res.start, moves: res.moves, days: res.days, div: res.div, acts: res.acts, log: m.verbose || res.div ? res.log : null, errors: res.errors });
});
process.send({ ready: true });
}
function parent() {
const page = require('./lib/page');
const tmp = (n) => path.join(os.tmpdir(), `tubes-fuzz-${process.pid}-${n}.html`);
const BASE = opt('--base', null) || (() => { const f = tmp('base'); fs.writeFileSync(f, page.assembleRef(opt('--base-ref', 'origin/main'))); return f; })();
const HEAD = opt('--head', null) || (() => { const f = tmp('head'); fs.writeFileSync(f, page.assemble().html); return f; })();
const one = opt('--seed', null);
const from = +opt('--from', 1), games = one ? 1 : +opt('--games', 300);
const seeds = one ? [+one] : Array.from({ length: games }, (_, i) => from + i);
const jobs = Math.max(1, Math.min(+opt('--jobs', Math.max(1, os.cpus().length)), seeds.length));
const verbose = has('-v');
const moves = opt('--moves', null) ? +opt('--moves') : undefined;
// --save FILE: every game starts from this save (a plain one, or an export from the menu) instead of a new network.
const RAW = opt('--save', null) ? JSON.parse(fs.readFileSync(opt('--save'), 'utf8')) : null;
const save = RAW ? JSON.stringify(RAW.app === 'series-of-tubes' && RAW.S ? RAW.S : RAW) : undefined;
const results = [];
let next = 0, live = 0;
const t0 = Date.now();
const done = () => {
const div = results.filter((r) => r.div), tot = (k) => results.reduce((a, r) => a + (r[k] || 0), 0);
const kinds = {};
for (const r of results) if (r.start) { const k = r.start.kind + (r.start.kind === 'normal' || r.start.kind === 'sandbox' ? ':' + r.start.preset : ''); kinds[k] = (kinds[k] || 0) + 1; }
console.log(`\n${results.length} games, ${tot('moves')} moves, ${tot('days')} days in ${((Date.now() - t0) / 1000).toFixed(0)} s. Starts: ${JSON.stringify(kinds)}`);
const acts = {};for (const r of results) for (const k in r.acts || {}) acts[k] = (acts[k] || 0) + r.acts[k];
if (has('--acts')) console.log('Actions pressed: ' + Object.entries(acts).sort((a, b) => b[1] - a[1]).map(([k, n]) => k + ' ' + n).join(', '));
const errs = [...new Set(results.flatMap((r) => r.errors || []))];
if (errs.length) console.log('Page errors:\n' + errs.slice(0, 10).map((e) => ' ' + e.slice(0, 200)).join('\n'));
if (div.length) {
console.log(`\n${div.length} games diverged:`);
for (const r of div) console.log(JSON.stringify({ seed: r.seed, start: r.start, ...r.div }, null, 1).slice(0, 4000));
} else console.log('No divergence: identical routing and game state in every game, cached and uncached.');
const out = opt('--out', null);
if (out) fs.writeFileSync(out, JSON.stringify(results, null, 1));
process.exit(div.length ? 1 : 0);
};
for (let j = 0; j < jobs; j++) {
const c = fork(__filename, ['--child', '--base', BASE, '--head', HEAD], { stdio: ['ignore', 'inherit', 'inherit', 'ipc'] });
live++;
const feed = () => { if (next < seeds.length) c.send({ seed: seeds[next++], moves, verbose, save }); else c.send({ stop: true }); };
c.on('message', (m) => {
if (!m.ready) {
results.push(m);
const tag = m.div ? 'DIVERGED at ' + m.div.where : 'ok';
console.log(`seed ${m.seed} ${m.start ? m.start.kind + ' ' + (m.start.id || m.start.preset) + ' ' + m.start.city : ''}: ${m.moves} moves, ${m.days} days, ${(m.ms / 1000).toFixed(1)} s, ${tag}`);
if (verbose && m.log) console.log(m.log.map((l) => ' ' + l).join('\n'));
}
feed();
});
c.on('exit', () => { if (--live === 0) done(); });
}
}
if (has('--child')) child(); else parent();

View file

@ -1,58 +0,0 @@
#!/usr/bin/env node
// Times each tests/*.test.js on its own and writes tests/durations.json (seconds per file), which
// `npm test -- --shard i/n` uses to split the files into parts of about equal time.
// Run it after adding or growing slow tests; it takes a few minutes. Files run as many at once as the
// machine has cores, so absolute numbers vary, but their sizes relative to each other are what count.
//
// npm run test:timings
// node scripts/test-timings.js --merge DIR (CI) fold the parts' --timings files into it
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawn } = require('node:child_process');
const root = path.join(__dirname, '..');
const dir = path.join(root, 'tests');
// --merge DIR: fold the timings CI's parts wrote (scripts/test.js --timings) into tests/durations.json. Files that are
// gone drop out; files no part ran keep their old time.
const mi = process.argv.indexOf('--merge');
if (mi >= 0) {
const from = process.argv[mi + 1], dur = path.join(dir, 'durations.json');
let out = {};
try { out = JSON.parse(fs.readFileSync(dur, 'utf8')); } catch (e) { /* none yet */ }
let n = 0;
for (const f of fs.readdirSync(from, { recursive: true }).filter((f) => String(f).endsWith('.json'))) {
for (const [k, v] of Object.entries(JSON.parse(fs.readFileSync(path.join(from, String(f)), 'utf8')))) if (v > 0) { out[k] = v; n++; }
}
const have = new Set(fs.readdirSync(dir).filter((f) => f.endsWith('.test.js')).map((f) => 'tests/' + f));
const sorted = Object.fromEntries(Object.keys(out).filter((k) => have.has(k)).sort().map((k) => [k, out[k]]));
fs.writeFileSync(dur, JSON.stringify(sorted, null, 1) + '\n');
console.log(`merged ${n} timings; tests/durations.json has ${Object.keys(sorted).length} of ${have.size} files`);
process.exit(0);
}
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.test.js')).sort().map((f) => 'tests/' + f);
const jobs = Math.max(1, parseInt(process.env.TEST_JOBS, 10) || os.availableParallelism());
const out = {};
let next = 0, failed = 0;
function run() {
if (next >= files.length) return Promise.resolve();
const f = files[next++], t = performance.now();
return new Promise((res) => {
const p = spawn(process.execPath, ['--test', f], { cwd: root, stdio: 'ignore' });
p.on('close', (code) => {
out[f] = Math.round((performance.now() - t) / 100) / 10;
if (code) { failed++; console.log(`✗ ${f} failed (timed anyway)`); }
console.log(`${String(out[f]).padStart(6)}s ${f}`);
res();
});
}).then(run);
}
Promise.all(Array.from({ length: jobs }, run)).then(() => {
const sorted = Object.fromEntries(Object.keys(out).sort().map((k) => [k, out[k]]));
fs.writeFileSync(path.join(dir, 'durations.json'), JSON.stringify(sorted, null, 1) + '\n');
const sum = Object.values(out).reduce((a, b) => a + b, 0);
console.log(`${files.length} files, ${Math.round(sum)} s in all; wrote tests/durations.json${failed ? ` (${failed} failed)` : ''}`);
});

View file

@ -1,104 +0,0 @@
#!/usr/bin/env node
// Runs every tests/*.test.js, each file in its own process, as many at once as the machine has cores. New test
// files are picked up on their own, so adding one never touches package.json (and never conflicts with someone
// else adding theirs).
//
// npm test everything
// npm test -- tests/peering.test.js just these files (other arguments go to node --test)
// npm test -- --shard 2/4 one of four parts of about equal time
// npm test -- --shard 2/4 --list which files that part holds, without running them
// node scripts/test.js --plan 6 the split into 6 parts as JSON (CI's plan job: one list per runner)
// npm test -- --timings out.json also write each file's seconds to out.json (CI merges these into
// the durations the next run splits by)
// TEST_JOBS=1 npm test one file at a time, as it used to be
// npm test -- --stress 8 tests/x.test.js hunt a flaky test: 8 copies of these files at once, on a machine kept
// busier than CI ever is, and how many runs failed (and why)
//
// Parts are balanced by tests/durations.json, each file's typical seconds. CI keeps it fresh in its cache from every
// run on main (.github/workflows/ci.yml); npm run test:timings rewrites the committed copy. A file missing from it
// counts as a typical one, so a stale list only makes the parts a little uneven.
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawn, spawnSync } = require('node:child_process');
const root = path.join(__dirname, '..');
const dir = path.join(root, 'tests');
const args = process.argv.slice(2);
const list = args.includes('--list');
if (list) args.splice(args.indexOf('--list'), 1);
let stress = 0;
const ti = args.indexOf('--stress');
if (ti >= 0) {
stress = parseInt(args[ti + 1], 10);
if (!(stress >= 1)) { console.error('--stress wants a count, like --stress 8'); process.exit(2); }
args.splice(ti, 2);
}
let timings = null;
const tmi = args.indexOf('--timings');
if (tmi >= 0) { timings = args[tmi + 1]; args.splice(tmi, 2); if (!timings) { console.error('--timings wants a file'); process.exit(2); } }
let plan = 0;
const pi = args.indexOf('--plan');
if (pi >= 0) { plan = parseInt(args[pi + 1], 10); args.splice(pi, 2); if (!(plan >= 1)) { console.error('--plan wants a count, like --plan 6'); process.exit(2); } }
let shard = null;
const si = args.indexOf('--shard');
if (si >= 0) {
const m = /^(\d+)\/(\d+)$/.exec(args[si + 1] || '');
if (!m || +m[1] < 1 || +m[1] > +m[2]) { console.error('--shard wants i/n, like 2/4'); process.exit(2); }
shard = [+m[1], +m[2]];
args.splice(si, 2);
}
let files = args.some((a) => a.endsWith('.test.js')) ? [] :
fs.readdirSync(dir).filter((f) => f.endsWith('.test.js')).sort().map((f) => path.join('tests', f));
// Longest first, each onto the part with the least so far: parts within a file's length of each other.
function part(list, i, n) {
let dur = {};
try { dur = JSON.parse(fs.readFileSync(path.join(dir, 'durations.json'), 'utf8')); } catch (e) { /* none yet: by count */ }
const known = list.map((f) => dur[f.replace(/\\/g, '/')]).filter((s) => s > 0).sort((a, b) => a - b);
const typical = known.length ? known[known.length >> 1] : 1;
const w = (f) => dur[f.replace(/\\/g, '/')] > 0 ? dur[f.replace(/\\/g, '/')] : typical;
const load = Array(n).fill(0), out = Array.from({ length: n }, () => []);
for (const f of list.slice().sort((a, b) => w(b) - w(a) || a.localeCompare(b))) {
let k = 0;
for (let j = 1; j < n; j++) if (load[j] < load[k]) k = j;
load[k] += w(f); out[k].push(f);
}
return out[i - 1].sort();
}
if (plan) {
console.log(JSON.stringify(Array.from({ length: plan }, (_, i) => part(files, i + 1, plan).join(' '))));
process.exit(0);
}
if (shard && files.length) {
files = part(files, shard[0], shard[1]);
console.log(`# part ${shard[0]}/${shard[1]}: ${files.length} files`);
if (list) { for (const f of files) console.log(f); process.exit(0); }
// node --test with no files would run every test it can find: an empty part has nothing to do.
if (!files.length) process.exit(0);
}
const jobs = Math.max(1, parseInt(process.env.TEST_JOBS, 10) || os.availableParallelism());
// Stress: N runs of the same files at once, each its own node --test, so they fight for the CPU the way the four
// CI parts and their own parallel files do (and worse). A test that only passes on a quiet machine fails here.
if (stress) {
if (!args.some((a) => a.endsWith('.test.js'))) { console.error('--stress wants the test files to run, like tests/agent-relay.test.js'); process.exit(2); }
const runs = Array.from({ length: stress }, (_, i) => new Promise((res) => {
const c = spawn(process.execPath, ['--test', '--test-reporter=dot', ...args], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
let out = ''; c.stdout.on('data', (d) => { out += d; }); c.stderr.on('data', (d) => { out += d; });
c.on('close', (code) => res({ i: i + 1, code, out }));
}));
Promise.all(runs).then((rs) => {
const bad = rs.filter((r) => r.code !== 0);
for (const r of bad) console.log(`\n--- run ${r.i} failed ---\n${r.out.slice(-4000)}`);
console.log(`\n# stress: ${rs.length - bad.length} of ${rs.length} runs passed, ${stress} at once on ${os.availableParallelism()} cores`);
process.exit(bad.length ? 1 : 0);
});
return;
}
const rep = timings ? ['--test-reporter=spec', '--test-reporter-destination=stdout',
`--test-reporter=${path.join(__dirname, 'lib', 'timings-reporter.js')}`, `--test-reporter-destination=${timings}`] : [];
const r = spawnSync(process.execPath, ['--test', `--test-concurrency=${jobs}`, ...rep, ...args, ...files], { stdio: 'inherit', cwd: root });
process.exit(r.status ?? 1);

View file

@ -1,242 +0,0 @@
#!/usr/bin/env node
// The weekly Architect run generator, the twin of scripts/weekly-puzzle.js. Every Sunday .github/workflows/weekly-puzzle.yml
// runs it to publish site/architect/weekly/<key>.json, which the game fetches when Puzzles opens
// (src/game/60-features/98-architect-weekly.js). It plays the real game headless, so the briefs are judged by the game's
// own checklist and chaos monkey review.
//
// node scripts/weekly-architect.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing
// node scripts/weekly-architect.js --key 2026-W45 that week (--force replaces an existing file)
// node scripts/weekly-architect.js --next 3 this week and the next two
// node scripts/weekly-architect.js --check re-play every week not over yet; one whose reference no longer
// earns three stars is regenerated with rev + 1; then validate every file
// --page FILE / --dir DIR another build of the game / where the files live
//
// How a run is made: an HQ in a region the last weeks did not have, and its nearest cities as the sites to come. Then a
// reference architect plays it brief by brief, and each brief is designed against the network it has built so far, so
// every brief asks for something new: a site to connect, a site that one cut would strand made mission-critical, a ring
// it does not have yet, a latency cap its paths miss, a site that closes. The reference builds the cheapest fix it finds
// (connect to the nearest POP; for a site a cut strands, the cheapest tube from the stranded side to the rest on another
// trench or cable) until the game's review passes. Its tube count is the brief's plan, its spend plus a little the
// budget, and the whole run is then replayed from the file and must earn three stars.
const fs = require('node:fs');
const path = require('node:path');
const { game, world } = require('./weekly-puzzle');
const { lit } = require('./lib/js-literal');
const ROOT = path.join(__dirname, '..');
const SCHEMA = 1, HISTORY = 4, ATTEMPTS = 40, DEM_MAX = 380;
const NAMES = ['architect_weekly.name_all_roads_lead_to_hq', 'architect_weekly.name_the_hq_job', 'architect_weekly.name_hq_and_friends'];
const JOKES = ['architect_weekly.joke_hq_signed_the_lease', 'architect_weekly.joke_one_network_a_handful'];
const hash = (s) => { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; };
function rng(seed) { let a = seed >>> 0 || 1; return () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
const pick = (r, a) => a[Math.floor(r() * a.length)];
const shuffle = (r, a) => { a = a.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; };
const ceil10k = (x) => Math.ceil(x / 10000) * 10000;
const list = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^\d{4}-W\d{2}\.json$/.test(f)).map((f) => f.slice(0, -5)).sort() : []);
const J = (ev, code) => JSON.parse(ev(`JSON.stringify(${code})`));
// ---------- playing the game ----------
// Load a run definition into the page as this week's, with the briefs known so far.
function stage(ev, key, hq, briefs) {
ev(`UI.arWk={key:'${key}',def:{id:arWkId('${key}'),key:'${key}',wk:true,n:'',j:'',hq:'${hq}',via:[],budget:2e7,briefs:${lit(briefs)},rev:1},at:Date.now()}`);
}
// Lay one tube the way a player does: a diverse trench when the pair already has one overland. The size is what all
// the traffic needs (100G, or 400G once there is more than 100G), smaller where a long cable cannot take it.
const tierFor = (ev) => (ev('S.pz.cities.reduce((a,c)=>a+(c===S.ar.hq?0:arDem(c)),0)') > 100 ? 2 : 1);
function lay(ev, a, b, via, tier) {
if (!ev(`!!S.pops['${a}']`)) [a, b] = [b, a];
const n = ev('S.links.length');
for (let t = tier == null ? tierFor(ev) : tier; t >= 0; t--) {
ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:${t}});closeModal()`);
if (ev('S.links.length') === n + 1) return [a, b, via, t];
if (tier != null) break;
}
throw new Error(`could not lay ${a}-${b} ${via}`);
}
// One step of a reference, as the file keeps it: a tube [a, b, route, size], ['@rm', city] closing a POP, or
// ['@tier', n, size] resizing the n-th tube.
function step(ev, s) {
if (s[0] === '@rm') { ev(`ACT.pzRmPop({city:'${s[1]}'})`); return; }
if (s[0] === '@tier') { const n = ev(`(()=>{const l=S.links[${s[1]}];ACT.pzTier({id:l.id,tier:${s[2]}});return S.links[${s[1]}].tier;})()`); if (n !== s[2]) throw new Error(`could not resize tube ${s[1]}`); return; }
lay(ev, s[0], s[1], s[2], s[3]);
}
// Room for the traffic: upsize the busiest tube that is not cut (or, when it cannot grow, lay a second one beside it).
function makeRoom(ev, W, steps, cut) {
const ls = J(ev, `(()=>{${cut ? `for(const l of S.links)if(pzUnit(l)===${lit(cut)})l.cut=1;` : ''}compute();const o=S.links.map((l,i)=>({i,a:l.a,b:l.b,cut:!!l.cut,tier:l.tier,u:(R.load[l.id]||0)/capOf(l)})).filter(x=>!x.cut).sort((x,y)=>y.u-x.u);for(const l of S.links)l.cut=0;compute();return o;})()`);
for (const l of ls.slice(0, 3)) {
if (l.tier < 2) { const t = ev(`(()=>{const l=S.links[${l.i}];ACT.pzTier({id:l.id,tier:${l.tier + 1}});return S.links[${l.i}].tier;})()`); if (t === l.tier + 1) { steps.push(['@tier', l.i, t]); return; } }
const o = W.opts(l.a, l.b).filter((x) => !x.second).sort((x, y) => x.cost - y.cost)[0];
if (o) { try { steps.push(lay(ev, o.a, o.b, o.via)); return; } catch (e) { /* try the next tube */ } }
}
throw new Error('no room to be made');
}
// What the review would say: the first cut that strands a mission-critical site or leaves a site short.
const reviewFail = (ev) => J(ev, `(()=>{let f=null;for(const u of [...new Set(S.links.map(pzUnit))]){const x=arCut(u);for(const l of x.ls)l.cut=0;if(x.gold.length||x.short.length){f={u,gold:x.gold,short:x.short,dark:x.dark};break;}}compute();return f;})()`);
const passes = (ev) => ev('arShowStart();arShowSkip();S.ar.passed===pzSig()');
// The reference architect: fix what the checklist and the review find, cheapest first, until the brief passes.
function solveBrief(ev, W, steps) {
for (let guard = 0; guard < 24; guard++) {
for (const c of J(ev, 'S.pz.avoid.filter(c=>S.pops[c])')) { ev(`ACT.pzRmPop({city:'${c}'})`); steps.push(['@rm', c]); }
const e = J(ev, '(()=>{const e=arEval(),r=[...arReach(S.ar.hq,arAdj())];return {conn:e.conn,lat:e.lat,rings:e.rings,ready:e.ready,why:e.why,r,miss:e.sites.filter(s=>!s.ok).map(s=>s.c)};})()');
const best = (from, to, skip) => { let o = null; for (const a of from) for (const b of to) if (a !== b) for (const x of W.opts(a, b)) if (!x.second && x.unit !== skip && (!o || x.cost < o.cost)) o = x; return o; };
if (!e.conn) { const c = e.miss[0], o = best([c], e.r); if (!o) throw new Error(`no way to ${c}`); steps.push(lay(ev, o.a, o.b, o.via)); continue; }
if (e.lat && !e.lat.ok) { const os = W.opts(e.lat.a, e.lat.b).filter((x) => !x.second && x.ms <= e.lat.cap).sort((x, y) => x.cost - y.cost); if (!os.length) throw new Error('latency cap out of reach'); steps.push(lay(ev, os[0].a, os[0].b, os[0].via)); continue; }
const rg = e.rings.find((x) => !x.ok);
if (rg) { const cs = rg.cs, has = J(ev, 'S.links.map(l=>edgeKey(l))'); let done = false;
for (let i = 0; i < cs.length && !done; i++) { const a = cs[i], b = cs[(i + 1) % cs.length]; if (has.includes(ev(`edgeKey({a:'${a}',b:'${b}'})`))) continue; const o = best([a], [b]); if (o) { steps.push(lay(ev, o.a, o.b, o.via)); done = true; } }
if (!done) throw new Error('ring out of reach'); continue; }
if (!e.ready) { if (/thin/i.test(e.why) || J(ev, 'arEval().sites.some(s=>!s.full)')) { makeRoom(ev, W, steps, null); continue; } throw new Error(`not ready: ${e.why}`); }
const f = reviewFail(ev); if (!f) return;
if (f.short.length && !f.gold.length) { makeRoom(ev, W, steps, f.u); continue; }
// A cut strands a mission-critical site: join the stranded side to the rest another way.
const rest = J(ev, `Object.keys(S.pops).filter(c=>!${lit(f.dark)}.includes(c))`), o = best(f.dark, rest, f.u);
if (!o) throw new Error('no second way'); steps.push(lay(ev, o.a, o.b, o.via));
}
throw new Error('the brief would not pass');
}
// ---------- designing a run ----------
// The brief kinds after the first two. Each is designed against the reference network as it stands, or refused (null).
function design(kind, ev, W, r, s) {
const pops = J(ev, 'S.pz.cities'), gold = J(ev, 'S.ar.gold'), hq = s.hq, next = () => s.todo.shift(), dem = (c) => { const g = Math.min(s.room, pick(r, [10, 20, 20, 30])); s.room -= g; return { [c]: g }; };
const weak = J(ev, `S.pz.cities.filter(c=>c!==S.ar.hq&&!S.ar.gold.includes(c)&&[...new Set(S.links.map(pzUnit))].some(u=>arDark(u).includes(c)))`);
if (kind === 'gold') { if (!weak.length) return null; const c = weak.sort((a, b) => W.km(hq, b) - W.km(hq, a))[0]; return { gold: [c] }; }
if (kind === 'addgold') { if (!s.todo.length || s.room < 10) return null; const c = next(); return { add: [c], dem: dem(c), gold: [c] }; }
if (kind === 'move') { const c = pops.filter((x) => x !== hq && !gold.includes(x) && !(s.lat || []).includes(x)).sort((a, b) => W.km(hq, b) - W.km(hq, a))[0];
if (!c || !s.todo.length || s.room < 10) return null; const n = next(); return { drop: [c], add: [n], dem: dem(n), gold: [n] }; }
if (kind === 'lat') { let bestP = null;
for (const a of pops) for (const b of pops) { if (a >= b) continue; const cur = J(ev, `arLat('${a}','${b}')`), os = W.opts(a, b).filter((x) => !x.second); if (cur == null || !os.length) continue;
const ms = Math.min(...os.map((x) => x.ms)), cap = Math.ceil(ms * 1.12 * 10) / 10; if (cap < 2 || cap >= cur * 0.85) continue;
if (!bestP || cur / cap > bestP.k) bestP = { a, b, cap, k: cur / cap }; }
if (!bestP) return null; s.lat = [bestP.a, bestP.b]; return { lat: [bestP.a, bestP.b, bestP.cap] }; }
if (kind === 'grow') { const cs = pops.filter((c) => c !== hq).map((c) => [c, ev(`arDem('${c}')`)]).sort((x, y) => y[1] - x[1]); if (!cs.length || s.room < 60) return null;
const [c, d] = cs[0], g = d + Math.min(s.room, pick(r, [60, 90, 120])); s.room -= g - d; return { dem: { [c]: g } }; }
if (kind === 'ring') { const cs = pops.filter((c) => c !== hq).sort((a, b) => W.km(hq, a) - W.km(hq, b)).slice(0, 2); if (cs.length < 2) return null;
const ring = [hq, ...cs]; if (ev(`arRingOk(${lit(ring)})`)) return null; return { ring }; }
return null;
}
// Play a run from scratch: stage, start, then brief by brief design (when designing) or follow the file, solve, review, next.
function play(g, W, key, hq, plan, r, sites) {
const { ev } = g, briefs = [], steps = [], s = { hq, todo: sites.slice(), room: DEM_MAX, lat: null };
const first = () => { const c = s.todo.shift(), g0 = Math.min(s.room, pick(r, [20, 30, 40])); s.room -= g0; return { add: [c], dem: { [c]: g0 } }; };
for (let i = 0; i < plan.length; i++) {
let b = null;
if (plan[i] === 'add1') b = first();
else if (plan[i] === 'add2') { if (s.todo.length < 2) throw new Error('not enough sites'); const a = s.todo.shift(), c = s.todo.shift(), ga = Math.min(s.room, 20); s.room -= ga; const gc = Math.min(s.room, pick(r, [10, 20])); s.room -= gc; b = { add: [a, c], dem: { [a]: ga, [c]: gc } }; }
// A kind that cannot be made here gives way to one the run has not had yet, then to a new mission-critical site.
else for (const k of [plan[i], ...['lat', 'ring', 'move', 'grow', 'gold'].filter((x) => !plan.slice(0, i).includes(x) && x !== plan[i]), 'addgold']) { b = design(k, ev, W, r, s); if (b) { plan[i] = k; break; } }
if (!b) throw new Error(`brief ${i + 1}: nothing left to ask`);
b.tubes = 9; briefs.push(b); stage(ev, key, hq, briefs.map((x) => Object.assign({ t: '' }, x)));
if (i === 0) ev(`ACT.pzArStart({id:arWkId('${key}')})`); else ev('ACT.pzArNext()');
if (ev('S.ar.bi') !== i) throw new Error(`brief ${i + 1} did not start`);
const st = []; solveBrief(ev, W, st); steps.push(st);
b.tubes = ev('S.links.filter(l=>(l.br|0)===S.ar.bi).length');
if (!st.length) throw new Error(`brief ${i + 1} asks for nothing new`);
ev(`UI.arWk.def.briefs[${i}].tubes=${b.tubes}`);
if (!passes(ev)) throw new Error(`brief ${i + 1}: the review does not pass`);
}
return { briefs, steps, spend: ev('arSpend()') };
}
// Replay a file the way a player would, from its own reference: it must pass every brief and earn three stars.
function verify(g, j, key) {
const { ev } = g, def = J(ev, `arWkValid(${lit(j)},'${key}')`);
if (!def) return { ok: false, why: 'the game rejects it' };
if (!j.ref || !Array.isArray(j.ref.steps) || j.ref.steps.length !== def.briefs.length) return { ok: false, why: 'no reference' };
try {
ev(`UI.arWk={key:'${key}',def:arWkValid(${lit(j)},'${key}'),at:Date.now()}`);
ev(`ACT.pzArStart({id:arWkId('${key}')})`);
for (let i = 0; i < def.briefs.length; i++) {
for (const st of j.ref.steps[i]) step(ev, st);
if (!passes(ev)) return { ok: false, why: `brief ${i + 1} does not pass` };
if (i < def.briefs.length - 1) ev('ACT.pzArNext()');
}
const sp = ev('arSpend()'), stars = ev(`arStars(${sp})`);
ev('arStop(true)');
return stars === 3 ? { ok: true, spend: sp } : { ok: false, why: `the reference earns ${stars} stars (spend ${sp}, budget ${j.budget})` };
} catch (e) { return { ok: false, why: e.message }; }
}
function generate(g, key, dir) {
const { ev } = g, W = world(ev);
// The regions of the last weeks, so the HQ moves around the world.
const past = list(dir).filter((k) => k < key).map((k) => { try { return JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')).hq; } catch (e) { return null; } });
const recent = past.slice(-HISTORY).map((c) => W.C[c] && W.C[c].reg), used = past.slice(-12);
for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
const r = rng(hash(`architect|${key}|${attempt}`));
const hqs = W.cities.filter((c) => !used.includes(c.id) && (!recent.includes(c.reg) || attempt >= ATTEMPTS / 2));
const hq = pick(r, hqs).id;
const near = W.cities.filter((c) => c.id !== hq && c.reg === W.C[hq].reg && W.km(hq, c.id) < 2500).sort((a, b) => W.km(hq, a.id) - W.km(hq, b.id)).slice(0, 8).map((c) => c.id);
if (near.length < 6) continue;
const mid = shuffle(r, ['lat', 'ring', 'move', 'addgold', 'grow']).slice(0, r() < 0.5 ? 2 : 3);
const plan = ['add1', 'add2', 'gold', ...mid, 'gold'];
const sites = [...near.slice(0, 3), ...shuffle(r, near.slice(3))];
try {
const run = play(g, W, key, hq, plan, r, sites);
const jk = pick(r, JOKES), j = { v: SCHEMA, key, hq, budget: ceil10k(run.spend * 1.06), name: { l: pick(r, NAMES), p: { hq } }, joke: { l: jk, p: jk === JOKES[0] ? { hq } : {} }, briefs: run.briefs, ref: { spend: run.spend, steps: run.steps } };
const v = verify(g, j, key);
if (!v.ok) { if (process.env.DEBUG) console.warn(`${key} #${attempt}: ${v.why}`); continue; }
return j;
} catch (e) { if (process.env.DEBUG) console.warn(`${key} #${attempt} (${hq}): ${e.message}`); }
}
throw new Error(`${key}: no run survived verification`);
}
// --check: every file is what the game accepts, under its own name, and the weeks still to come earn three stars.
function check(g, dir, now = Date.now()) {
const { ev } = g, bad = [], keys = list(dir);
for (const k of keys) {
let j; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { bad.push(`${k}: not JSON`); continue; }
if (!ev(`!!arWkValid(${lit(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; }
if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, j, k); if (!v.ok) bad.push(`${k}: ${v.why}`); }
}
if (keys.length) {
let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* reported below */ }
if (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(keys)) bad.push('index.json does not list exactly the weekly files');
}
return bad;
}
// A release can change prices under weeks already out: a week not over yet whose reference no longer earns three stars
// is regenerated with its rev up, so players' stars for that week (only that week) start again. Past weeks stay.
function refresh(g, dir, now = Date.now()) {
const { ev } = g, fixed = [], bad = [];
for (const k of list(dir)) {
let j = null; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { /* regenerated below */ }
const valid = !!j && ev(`!!arWkValid(${lit(j)},'${k}')`), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now;
if (valid && (!live || verify(g, j, k).ok)) continue;
const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1;
try { writeWeek(dir, Object.assign(generate(g, k, dir), { rev })); fixed.push(`${k}: regenerated as rev ${rev}`); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); }
}
let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* rewritten */ }
if (list(dir).length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(list(dir)))) { writeIndex(dir); fixed.push('index.json rewritten'); }
return { fixed, bad };
}
const writeIndex = (dir) => fs.writeFileSync(path.join(dir, 'index.json'), JSON.stringify({ v: SCHEMA, weeks: list(dir) }) + '\n');
const writeWeek = (dir, j) => { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify(j) + '\n'); writeIndex(dir); };
const say = (j) => `${j.key}: HQ ${j.hq}, ${j.briefs.length} briefs (${j.briefs.map((b) => Object.keys(b).filter((k) => k !== 'tubes' && (k !== 'dem' || !b.add)).map((k) => (k === 'dem' ? 'grow' : k)).join('+')).join(', ')}), budget ${j.budget}, reference ${j.ref.spend}`;
module.exports = { generate, verify, check, refresh, writeWeek, writeIndex, list, say, step };
if (require.main === module) {
const args = process.argv.slice(2), opt = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; };
const dir = path.resolve(ROOT, opt('--dir', 'site/architect/weekly')), g = game(opt('--page') && path.resolve(opt('--page')));
if (!g.ev("typeof arWkValid==='function'")) { console.log('This game has no weekly Architect runs yet.'); process.exit(0); }
if (args.includes('--check')) {
const r = refresh(g, dir);
for (const x of r.fixed) console.log(`fixed: ${x}`);
const bad = [...r.bad, ...check(g, dir)];
for (const b of bad) console.error(`error: ${b}`);
console.log(bad.length ? `${bad.length} problem(s)` : `${list(dir).length} weekly Architect run(s) OK`);
process.exit(bad.length ? 1 : 0);
}
const first = opt('--key') || g.ev(`pzWeekKey(Date.now()+12*3600e3)`), n = +opt('--next', 1);
for (let i = 0; i < n; i++) {
const key = g.ev(`pzKeyAdd('${first}',${i})`);
if (!key) { console.error(`error: ${first} is not a week`); process.exit(1); }
if (fs.existsSync(path.join(dir, key + '.json')) && !args.includes('--force')) { console.log(`${key}: already there`); continue; }
const j = generate(g, key, dir); writeWeek(dir, j); console.log(say(j));
}
}

View file

@ -1,413 +0,0 @@
#!/usr/bin/env node
// The weekly puzzle generator. Every Sunday .github/workflows/weekly-puzzle.yml runs it to publish that week's
// puzzle as a static file, site/puzzles/weekly/<key>.json, which the game fetches when Puzzles opens
// (src/game/60-features/93-puzzles-weekly.js). It loads the real game headless (tests/harness.js), so it uses the
// game's own cities, cables, prices, week keys, file validator and star code.
//
// node scripts/weekly-puzzle.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing
// node scripts/weekly-puzzle.js --key 2026-W45 that week (--force replaces an existing file)
// node scripts/weekly-puzzle.js --next 3 this week and the next two
// node scripts/weekly-puzzle.js --check regenerate weeks not over yet whose budget this game no longer verifies
// (see refresh()), then validate every file; fails only if that fails
// --page FILE play another build of the game (the live release), see the workflow
// --dir DIR where the files live (default site/puzzles/weekly)
//
// How a puzzle is made: pick a theme the last weeks did not have, choose 4-6 cities for it (avoiding last weeks'
// cities) and the traffic they carry (content in the first city, eyeballs in the others; a latency sprint adds a
// circuit with a latency cap). Search for the cheapest topology that connects them and the cheapest one that survives
// any single cut (a whole cable or a trench), then size each with the game's own routing (scripts/lib/puzzle-solver.js):
// links and routers big enough for every flow, after any single cut too, then as small as they can be. The budget is
// that N-1 build plus a little. Both reference builds are judged by the game's own star code and must earn their
// stars, or the candidate is thrown away and another one tried.
const fs = require('node:fs');
const path = require('node:path');
const ROOT = path.join(__dirname, '..');
const SV = require('./lib/puzzle-solver');
const { lit } = require('./lib/js-literal');
const SCHEMA = 2, HISTORY = 4, THEME_GAP = 3, REG_GAP = 2, ATTEMPTS = 40, KEEP = 6;
const THEMES = ['tour', 'ring', 'detour', 'ocean', 'islands', 'sprint'];
// ---------- the game, headless ----------
function game(file) {
const { load } = require('../tests/harness');
let g = load(file ? { file } : {});
if (file && !g.ev("typeof pzWkValid==='function'")) {
console.warn(`warning: ${file} has no published weekly puzzles yet; using src/ instead`);
g = load();
}
SV.install(g.ev);
// N-1 counts a whole cable as one failure (every segment of a cable shares its risk), as the solver does.
if (g.ev("pzUnit({cable:'x',a:'a',b:'b'})") !== 'cab:x') throw new Error('this game counts cable segments separately; the solver would not match its N-1 check');
return g;
}
// ---------- small helpers ----------
const hash = (s) => { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; };
function rng(seed) { let a = seed >>> 0 || 1; return () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
const pick = (r, a) => a[Math.floor(r() * a.length)];
const shuffle = (r, a) => { a = a.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; };
const ceil10k = (x) => Math.ceil(x / 10000) * 10000;
function perms(a) { if (a.length <= 1) return [a]; const out = []; a.forEach((x, i) => { for (const p of perms([...a.slice(0, i), ...a.slice(i + 1)])) out.push([x, ...p]); }); return out; }
function subsets(a) { const out = []; for (let m = 0; m < 1 << a.length; m++) out.push(a.filter((_, i) => m >> i & 1)); return out; }
// ---------- the world, as the game prices it ----------
function world(ev) {
const cities = JSON.parse(ev("JSON.stringify(Object.values(CITY).filter(c=>!c.off&&!c.cn).map(c=>({id:c.id,name:c.name,lands:lands(c),reg:c.reg,P:c.P,lon:c.lon,lat:c.lat,pop:pzPopCost(c.id)})))"));
const C = Object.fromEntries(cities.map((c) => [c.id, c]));
const cablePairs = JSON.parse(ev('JSON.stringify(CABLE_PAIRS.map(p=>[p.cid,p.a,p.b]))')).filter(([, a, b]) => C[a] && C[b]);
const cabs = {}; for (const [cid, a, b] of cablePairs) { (cabs[a] = cabs[a] || new Set()).add(cid); (cabs[b] = cabs[b] || new Set()).add(cid); }
const memo = new Map();
// Every way to join a and b: overland (first wave, and a second one on a diverse route) and each cable.
const opts = (a, b) => {
const k = a < b ? a + '|' + b : b + '|' + a; if (memo.has(k)) return memo.get(k);
const rs = JSON.parse(ev(`JSON.stringify(pzRoutes('${a}','${b}').filter(r=>!subWaveWhy(0,r.km,r.sub)).map(r=>({via:r.via,cab:r.cab,sub:r.sub,ms:r.ms,c:pzLinkCost(r,0,false),c2:r.sub?0:pzLinkCost(r,0,true)})))`));
const out = [];
for (const r of rs) {
if (r.cab) out.push({ a, b, via: r.via, sub: true, ms: r.ms, cost: r.c, unit: 'cab:' + r.cab });
else { out.push({ a, b, via: 'land', sub: false, ms: r.ms, cost: r.c, unit: `land:${k}:1` }); out.push({ a, b, via: 'land', sub: false, ms: r.ms, cost: r.c2, unit: `land:${k}:2`, second: true }); }
}
out.sort((x, y) => x.cost - y.cost || (x.unit < y.unit ? -1 : 1));
memo.set(k, out); return out;
};
const km = (a, b) => { const A = C[a], B = C[b], r = Math.PI / 180, h = Math.sin((B.lat - A.lat) * r / 2) ** 2 + Math.cos(A.lat * r) * Math.cos(B.lat * r) * Math.sin((B.lon - A.lon) * r / 2) ** 2; return 12742 * Math.asin(Math.sqrt(h)); };
return { cities, C, cablePairs, cabs, opts, km };
}
// ---------- judging a build (the game has the last word; this steers the search) ----------
function judge(W, P, links) {
const nodes = new Set(); for (const l of links) { nodes.add(l.a); nodes.add(l.b); }
// A second overland wave on a pair needs the first one.
for (const l of links) if (l.second && !links.some((x) => x !== l && !x.second && x.via === 'land' && x.unit === l.unit.replace(/2$/, '1'))) return null;
if (new Set(links.map((l) => l.unit)).size !== links.length) return null;
const cost = [...nodes].reduce((s, c) => s + W.C[c].pop, 0) + links.reduce((s, l) => s + l.cost, 0);
const comp = (skip) => { const adj = {}; for (const l of links) if (l.unit !== skip) { (adj[l.a] = adj[l.a] || []).push(l.b); (adj[l.b] = adj[l.b] || []).push(l.a); }
const seen = new Set([P.cities[0]]), q = [P.cities[0]]; while (q.length) { const u = q.pop(); for (const v of adj[u] || []) if (!seen.has(v)) { seen.add(v); q.push(v); } } return seen; };
const all = comp(null);
if (!P.cities.every((c) => all.has(c))) return { ok: false, cost };
if (P.avoid.some((c) => nodes.has(c))) return { ok: false, cost };
if (P.noSub && links.some((l) => l.sub)) return { ok: false, cost };
if (P.ring) { const nb = {}; for (const l of links) { (nb[l.a] = nb[l.a] || new Set()).add(l.b); (nb[l.b] = nb[l.b] || new Set()).add(l.a); }
if (links.length !== nodes.size || ![...nodes].every((c) => nb[c].size === 2)) return { ok: false, cost }; }
if (P.lat) { const [a, b, ms] = P.lat, d = { [a]: 0 }, done = new Set();
for (;;) { let u = null; for (const k in d) if (!done.has(k) && (u === null || d[k] < d[u])) u = k; if (u === null || u === b) break; done.add(u);
for (const l of links) { const v = l.a === u ? l.b : l.b === u ? l.a : null; if (v && !(d[v] <= d[u] + l.ms)) d[v] = d[u] + l.ms; } }
if (!(d[b] <= ms)) return { ok: false, cost }; }
const weak = [...new Set(links.map((l) => l.unit))].filter((u) => { const g = comp(u); return !P.cities.every((c) => g.has(c)); });
return { ok: true, cost, n1: weak.length === 0, weak };
}
// ---------- the solver ----------
// Cheapest tree over a node set (Kruskal on each pair's cheapest way), with some links forced in.
function tree(W, nodes, forced = []) {
const par = Object.fromEntries(nodes.map((n) => [n, n])), f = (x) => (par[x] === x ? x : (par[x] = f(par[x])));
const out = [];
for (const l of forced) { par[f(l.a)] = f(l.b); out.push(l); }
const es = [];
for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) { const o = W.opts(nodes[i], nodes[j]).filter((x) => !x.second); if (o.length) es.push(o[0]); }
es.sort((x, y) => x.cost - y.cost);
for (const e of es) if (f(e.a) !== f(e.b)) { par[f(e.a)] = f(e.b); out.push(e); }
return out.length - forced.length === nodes.length - 1 - forced.length ? out : null;
}
// Add the link that removes the most single points of failure per dollar, until none are left.
function harden(W, P, nodes, links) {
links = links.slice();
for (let guard = 0; guard < 12; guard++) {
const j = judge(W, P, links); if (!j || !j.ok) return null; if (j.n1) return links;
let best = null;
for (let i = 0; i < nodes.length; i++) for (let k = i + 1; k < nodes.length; k++) for (const o of W.opts(nodes[i], nodes[k])) {
if (links.some((l) => l.unit === o.unit)) continue;
const jj = judge(W, P, [...links, o]); if (!jj || !jj.ok) continue;
const gain = j.weak.length - jj.weak.length; if (gain <= 0) continue;
const score = gain / o.cost; if (!best || score > best.score) best = { score, o };
}
if (!best) return null; links.push(best.o);
}
return null;
}
// Every simple cycle through the node set, each hop by one of its three cheapest ways, cheapest first.
function cycles(W, P, nodes, bound) {
let best = null; const [h, ...rest] = nodes;
if (nodes.length < 3) return null;
for (const p of perms(rest)) {
if (p[0] > p[p.length - 1]) continue; // each cycle once
const ring = [h, ...p], hops = ring.map((x, i) => W.opts(x, ring[(i + 1) % ring.length]).filter((o) => !o.second).slice(0, 3));
if (hops.some((o) => !o.length)) continue;
const pop = ring.reduce((s, c) => s + W.C[c].pop, 0);
const go = (i, acc, cost) => {
if (cost >= Math.min(bound, best ? best.cost : Infinity)) return;
if (i === hops.length) { const j = judge(W, P, acc); if (j && j.ok && j.n1) best = { cost: j.cost, links: acc.slice() }; return; }
for (const o of hops[i]) { if (acc.some((l) => l.unit === o.unit)) continue; acc.push(o); go(i + 1, acc, cost + o.cost); acc.pop(); }
};
go(0, [], pop);
}
return best;
}
function solve(W, P) {
const vias = P.via.filter((c) => !P.avoid.includes(c));
let one = null, three = null, naive = null;
const keep = (cur, links) => { if (!links) return cur; const j = judge(W, P, links); if (!j || !j.ok) return cur; return !cur || j.cost < cur.cost ? { cost: j.cost, links, n1: j.n1 } : cur; };
for (const sub of subsets(vias)) {
const nodes = [...P.cities, ...sub];
const forced = P.lat ? [W.opts(P.lat[0], P.lat[1]).filter((o) => !o.second).sort((x, y) => x.ms - y.ms)[0]].filter(Boolean) : [];
const ts = [tree(W, nodes), forced.length ? tree(W, nodes, forced) : null].filter(Boolean)
// A via city left as a leaf is money for nothing.
.filter((t) => sub.every((v) => t.filter((l) => l.a === v || l.b === v).length >= 2));
if (!P.ring) for (const t of ts) {
one = keep(one, t);
// The obvious way to survive a cut: a second, different way along every hop of the tree.
const dbl = t.slice(); let okd = true;
for (const l of t) { const alt = W.opts(l.a, l.b).find((o) => o.unit !== l.unit && !dbl.some((x) => x.unit === o.unit)); if (!alt) { okd = false; break; } dbl.push(alt); }
if (okd) { const j = judge(W, P, dbl); if (j && j.ok && j.n1 && (!naive || j.cost < naive.cost)) naive = { cost: j.cost, links: dbl }; if (j && j.ok && j.n1) three = keep(three, dbl); }
const hd = harden(W, P, nodes, t); if (hd) three = keep(three, hd);
}
if (nodes.length <= 7) { const c = cycles(W, P, nodes, three ? three.cost : Infinity); if (c) { three = keep(three, c.links); if (P.ring) one = keep(one, c.links); } }
}
return { one, three, naive };
}
// ---------- themes: which cities, which twist ----------
function pools(W) {
const byLand = {};
for (const c of W.cities) { const k = c.lands[0] + '/' + c.reg; (byLand[k] = byLand[k] || []).push(c.id); }
const big = Object.values(byLand).map((g) => g.filter((c) => W.C[c].P >= 100)).filter((g) => g.length >= 6);
const isl = W.cities.filter((c) => byLand[c.lands[0] + '/' + c.reg].length === 1 && c.lands.length === 1 && (W.cabs[c.id] || new Set()).size >= 2).map((c) => c.id);
return { big, isl };
}
const near = (W, c, from, n) => from.filter((x) => x !== c).sort((a, b) => W.km(c, a) - W.km(c, b)).slice(0, n);
function draft(W, theme, r, banned) {
const { big, isl } = pools(W), free = (c) => !banned.has(c);
const P = { theme, cities: [], via: [], avoid: [], noSub: false, ring: false, lat: null };
if (theme === 'tour' || theme === 'ring' || theme === 'detour') {
const g = pick(r, big).filter(free);
if (g.length < 6) return null;
if (theme === 'detour') {
const hub = pick(r, g.slice().sort((a, b) => W.C[b].P - W.C[a].P).slice(0, 4)), around = near(W, hub, g, 8);
if (around.length < 6) return null;
const sh = shuffle(r, around); P.cities = sh.slice(0, 4); P.via = sh.slice(4, 6); P.avoid = [hub];
} else {
const seed = pick(r, g), n = theme === 'ring' ? 4 + Math.floor(r() * 2) : 4 + Math.floor(r() * 3);
P.cities = [seed, ...shuffle(r, near(W, seed, g, n + 2)).slice(0, n - 1)];
if (theme === 'tour') P.via = near(W, seed, g, n + 4).filter((c) => !P.cities.includes(c)).slice(0, 1);
P.ring = theme === 'ring';
}
} else if (theme === 'ocean') {
const land = (c) => W.C[c].lands[0], ok = W.cablePairs.filter(([, a, b]) => land(a) !== land(b) && free(a) && free(b) && big.some((g) => g.includes(a)) && big.some((g) => g.includes(b)));
if (!ok.length) return null;
const [, a, b] = pick(r, ok), ga = big.find((g) => g.includes(a)).filter(free), gb = big.find((g) => g.includes(b)).filter(free);
const a2 = pick(r, near(W, a, ga, 3)), b2 = pick(r, near(W, b, gb, 3));
if (!a2 || !b2) return null;
P.cities = [a, a2, b, b2];
// Other landing points on either shore that cross the same ocean: the stepping stones to a second crossing.
const shores = W.cablePairs.filter(([, x, y]) => (land(x) === land(a) && land(y) === land(b)) || (land(x) === land(b) && land(y) === land(a))).flatMap(([, x, y]) => [x, y]);
P.via = shuffle(r, [...new Set(shores)].filter((c) => free(c) && !P.cities.includes(c))).slice(0, 2);
} else if (theme === 'islands') {
const i0 = pick(r, isl.filter(free)); if (!i0) return null;
const hops = W.cablePairs.filter(([, x, y]) => x === i0 || y === i0).map(([, x, y]) => (x === i0 ? y : x));
const islN = near(W, i0, isl.filter((c) => free(c) && W.km(i0, c) < 4500), 3), main = near(W, i0, [...new Set(hops)].filter((c) => free(c) && !isl.includes(c)), 2);
if (!islN.length || !main.length) return null;
P.cities = [i0, ...shuffle(r, islN).slice(0, 1 + Math.floor(r() * 2)), main[0]];
P.via = [...new Set([...islN, ...main, ...hops])].filter((c) => !P.cities.includes(c) && free(c)).sort((x, y) => W.km(i0, x) - W.km(i0, y)).slice(0, 3);
} else if (theme === 'sprint') {
const ok = [];
for (const [, a, b] of W.cablePairs) { if (!free(a) || !free(b) || W.C[a].P < 100 || W.C[b].P < 100) continue;
const o = W.opts(a, b).filter((x) => !x.second); if (o.length < 2) continue;
const fast = o.slice().sort((x, y) => x.ms - y.ms)[0], cheap = o[0];
if (fast.unit !== cheap.unit && fast.ms < cheap.ms * 0.94 && fast.ms >= 5) ok.push([a, b, fast.ms, cheap.ms]); }
if (!ok.length) return null;
const [a, b, fms, cms] = pick(r, ok.sort((x, y) => (x[0] + x[1] < y[0] + y[1] ? -1 : 1)));
const ms = Math.ceil(fms * 1.04 + 0.5); if (ms >= cms) return null;
const ga = big.find((g) => g.includes(a)) || [], gb = big.find((g) => g.includes(b)) || [];
const extra = [...near(W, a, ga.filter(free), 2), ...near(W, b, gb.filter(free), 2)];
P.cities = [a, b, ...shuffle(r, extra).slice(0, 1 + Math.floor(r() * 2))];
P.via = W.cablePairs.filter(([, x, y]) => [x, y].includes(a) || [x, y].includes(b)).flatMap(([, x, y]) => [x, y]).filter((c, i, s) => s.indexOf(c) === i && free(c) && !P.cities.includes(c)).sort((x, y) => W.km(a, x) - W.km(a, y)).slice(0, 2);
P.lat = [a, b, ms];
}
if (new Set([...P.cities, ...P.via, ...P.avoid]).size !== P.cities.length + P.via.length + P.avoid.length) return null;
if (P.cities.length < 3 || P.cities.length > 6) return null;
// The traffic: content in the first city, eyeballs in the others (less across an ocean, where waves are dear), and
// for a sprint a circuit between its two cities under the latency cap.
const far = theme === 'ocean' || theme === 'islands', sizes = far ? [5, 8, 10, 15] : [10, 20, 30, 40, 60];
P.src = [P.cities[0]];
P.dem = P.cities.slice(1).map((c) => ({ t: 'eye', a: c, g: pick(r, sizes) }));
if (P.lat) P.dem.unshift({ t: 'l2', a: P.lat[0], b: P.lat[1], g: 10, ms: P.lat[2] });
return P;
}
// ---------- names and jokes: labels and their fill-ins ----------
function words(ev, W, P, r) {
const T = JSON.parse(ev(`JSON.stringify(PZ_WK_THEMES['${P.theme}'])`)), c = P.cities, last = c[c.length - 1];
const fill = (l) => { const need = [...new Set([...ev(`EN['${l}']`).matchAll(/\{(\w+)\}/g)].map((m) => m[1]))], p = {};
for (const k of need) p[k] = k === 'hub' ? P.avoid[0] : k === 'reg' ? W.C[c[0]].reg : k === 'ms' ? P.lat[2] : k === 'n' ? c.length : k === 'a' ? (P.lat ? P.lat[0] : P.theme === 'tour' ? last : c[0]) : k === 'b' ? (P.lat ? P.lat[1] : c[2] || last) : null;
return { l, p }; };
return { name: fill(pick(r, T.names)), joke: fill(pick(r, T.jokes)) };
}
// ---------- one week ----------
function history(dir, key) {
const keys = list(dir).filter((k) => k < key).slice(-HISTORY);
const files = keys.map((k) => JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')));
return { cities: new Set(files.flatMap((f) => [...(f.cities || []), ...(f.via || []), ...(f.avoid || [])])), themes: files.slice(-THEME_GAP).map((f) => f.theme),
regs: files.slice(-REG_GAP).map((f) => f.cities && f.cities[0]).filter(Boolean) };
}
const list = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^\d{4}-W\d{2}\.json$/.test(f)).map((f) => f.slice(0, -5)).sort() : []);
// A topology's links, sized for the traffic: every wave at the smallest size that carries it all (after any single cut
// too, for the N-1 build), as the game routes it, with the cheapest routers that fit.
const TIER_G = [10, 100, 400];
function size(ev, def, links, n1) {
ev(`pzBegin(${lit(def)})`);
const tot = def.dem.reduce((a, f) => a + f.g, 0), t0 = Math.max(0, TIER_G.findIndex((g) => g >= tot));
for (let t = t0; t < TIER_G.length; t++) {
const L = [...links.map((l) => [l.a, l.b, l.via, t, 0]), ...def.dem.map((f, i) => f.ms ? ['@route', i, 'fast'] : null).filter(Boolean)], j = SV.judge(ev, L);
if (n1 ? j.three : j.one) { const r = n1 ? SV.improve(ev, L) : { links: L, ...j }; return r; }
}
return null;
}
// Plays a sized build (links and routers) in the game and returns the stars it earns.
function play(ev, def, b) {
ev(`localStorage.removeItem('sot-puzzles');pzBegin(${lit(def)})`);
SV.judge(ev, b.links); ev(`pzsApplyRt(${lit(b.rt)})`);
return JSON.parse(ev('JSON.stringify((({stars,spend,goal,n1,cheap})=>({stars,spend,goal,n1,cheap}))(pzEval()))'));
}
const fileOf = (key, P, budget, w, sol) => ({ v: SCHEMA, key, theme: P.theme, cities: P.cities, src: P.src, dem: P.dem, via: P.via, avoid: P.avoid, budget,
twist: Object.assign({}, P.ring ? { ring: true } : {}, P.noSub ? { noSub: true } : {}),
name: w.name, joke: w.joke, ref: { one: sol.one.cost, three: sol.three.cost } });
// The topology search reads a sprint's latency cap from its circuit.
const shape = (def) => { const l2 = def.dem.find((f) => f.t === 'l2' && f.ms); return { theme: def.theme, cities: def.cities, via: def.via, avoid: def.avoid, noSub: def.noSub, ring: def.ring, lat: l2 ? [l2.a, l2.b, l2.ms] : null }; };
// Topology, then sizes: the 1-star and 3-star references with their prices.
function sized(g, W, P, def) {
const sol = solve(W, P); if (!sol.one || !sol.three) return null;
const one = size(g.ev, def, sol.one.links, false), three = size(g.ev, def, sol.three.links, true);
if (!one || !three) return null;
// The three-star build delivers too: when it is the cheaper one (a ring, sized down), it is the one-star reference.
const o = one.spend <= three.spend ? one : three;
return { one: { cost: Math.round(o.spend), b: o }, three: { cost: Math.round(three.spend), b: three } };
}
// The game's own validator decides what a puzzle is; then both references must earn their stars.
function verify(g, W, j, key, known) {
const { ev } = g, def = JSON.parse(ev(`JSON.stringify(pzWkValid(${lit(j)},'${key}'))`));
if (!def) return { ok: false, why: 'the game rejects the file' };
const P = shape(def), sol = known || sized(g, W, P, def);
if (!sol) return { ok: false, why: 'no build delivers the traffic and survives a cut' };
if (sol.three.cost > def.budget) return { ok: false, why: `the cheapest N-1 build found costs ${sol.three.cost}, over the budget ${def.budget}` };
const s1 = play(ev, def, sol.one.b), s3 = play(ev, def, sol.three.b);
if (s1.stars < 1) return { ok: false, why: `the one-star reference earns ${s1.stars} stars` };
if (s3.stars !== 3) return { ok: false, why: `the three-star reference earns ${s3.stars} stars (${JSON.stringify(s3)})` };
return { ok: true, sol, s1, s3 };
}
// Three stars need the smart design: the budget sits just above the cheapest N-1 build found, sized for its traffic.
const budgetOf = (sol) => Math.max(50000, ceil10k(sol.three.cost * 1.05));
function generate(g, key, dir) {
const { ev } = g, W = world(ev);
if (ev(`pzWeekStart('${key}')`) == null) throw new Error(`${key} is not a week`);
// Themes take turns (none of the last weeks' again); the week's own theme first, the others only if it finds nothing.
const hist = history(dir, key), free = THEMES.filter((t) => !hist.themes.includes(t)), h = hash(key);
const order = free.map((_, i) => free[(h + i) % free.length]);
for (const theme of order) {
const cands = [];
for (let at = 0; at < ATTEMPTS && cands.length < KEEP; at++) {
const r = rng(hash(`${key}|${theme}|${at}`)), P = draft(W, theme, r, hist.cities);
// Not the same part of the world as the last two weeks.
if (!P || hist.regs.some((c) => W.C[c] && W.C[c].reg === W.C[P.cities[0]].reg && W.C[c].lands[0] === W.C[P.cities[0]].lands[0])) continue;
const sol = solve(W, P);
if (!sol.one || !sol.three) continue;
// Prefer puzzles where surviving a cut takes real thought: the obvious "double everything" costs a lot more.
const smart = sol.naive ? sol.naive.cost / sol.three.cost : 1.05, slack = sol.three.cost / sol.one.cost;
const score = Math.min(smart, 1.6) + Math.min(slack, 2) * 0.2 + r() * 0.05;
cands.push({ P, score, w: words(ev, W, P, r) });
}
cands.sort((a, b) => b.score - a.score);
for (const c of cands) {
// Sized with the traffic: the budget sits just above the cheapest N-1 build found.
const def = JSON.parse(ev(`JSON.stringify(pzWkValid(${lit(fileOf(key, c.P, 1e6, c.w, { one: { cost: 0 }, three: { cost: 0 } }))},'${key}'))`));
const sol = def && sized(g, W, c.P, def);
if (!sol) { console.warn(`${key}: rejected a ${theme} puzzle: no build carries its traffic`); continue; }
const j = fileOf(key, c.P, budgetOf(sol), c.w, sol), v = verify(g, W, j, key, sol);
if (v.ok) return j;
console.warn(`${key}: rejected a ${theme} puzzle: ${v.why}`);
}
}
throw new Error(`${key}: no puzzle survived verification`);
}
// --check: every file is what the game accepts, under its own name, and the weeks still to come are solvable.
function check(g, dir, now = Date.now()) {
const { ev } = g, W = world(ev), bad = [], keys = list(dir);
for (const k of keys) {
let j; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { bad.push(`${k}: not JSON`); continue; }
if (!ev(`!!pzWkValid(${lit(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; }
if (!j.ref || !Number.isInteger(j.ref.one) || !Number.isInteger(j.ref.three) || j.ref.one > j.ref.three || j.ref.three > j.budget) { bad.push(`${k}: bad ref`); continue; }
if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, W, j, k); if (!v.ok) bad.push(`${k}: ${v.why}`); }
}
const ip = path.join(dir, 'index.json');
if (keys.length) {
let idx = null; try { idx = JSON.parse(fs.readFileSync(ip, 'utf8')); } catch (e) { /* reported below */ }
if (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(keys)) bad.push('index.json does not list exactly the weekly files');
}
return bad;
}
/* --check, first part: a release can change prices, cables or cities under weeks that are already published. Every
week not over yet is re-solved with this game; when its budget no longer verifies it is regenerated, deterministically:
the same puzzle (theme, cities, twist, name) with a new budget when that still works, else a fresh puzzle for the
same key. Its rev goes up, so players' stars for that week (and only that week) start again; new references alone
keep the rev. Past weeks can no longer be played, so they keep their stars and are only replaced when the game
rejects them outright. Returns what changed and what could not be fixed. */
function refresh(g, dir, now = Date.now()) {
const { ev } = g, W = world(ev), fixed = [], bad = [];
for (const k of list(dir)) {
const f = path.join(dir, k + '.json');
let j = null; try { j = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { /* regenerated below */ }
const valid = !!j && ev(`!!pzWkValid(${lit(j)},'${k}')`), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now;
if (valid && !live) continue;
const v = valid ? verify(g, W, j, k) : null;
if (v && v.ok) {
if (j.ref && j.ref.one === v.sol.one.cost && j.ref.three === v.sol.three.cost) continue;
j.ref = { one: v.sol.one.cost, three: v.sol.three.cost }; writeWeek(dir, j); fixed.push(`${k}: new references`); continue;
}
const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1;
let n = null;
if (valid) {
const def = JSON.parse(ev(`JSON.stringify(pzWkValid(${lit(j)},'${k}'))`));
const sol = sized(g, W, shape(def), def);
if (sol) {
const c = Object.assign({}, j, { budget: budgetOf(sol), ref: { one: sol.one.cost, three: sol.three.cost }, rev });
if (verify(g, W, c, k, sol).ok) n = c;
}
}
if (!n) { try { n = Object.assign(generate(g, k, dir), { rev }); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); continue; } }
writeWeek(dir, n); fixed.push(`${k}: regenerated as rev ${rev}${n.theme === (j && j.theme) && JSON.stringify(n.cities) === JSON.stringify(j.cities) ? ', same puzzle, new budget ' + n.budget : ', a new ' + n.theme + ' puzzle'}`);
}
let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* rewritten */ }
if (list(dir).length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(list(dir)))) { writeIndex(dir); fixed.push('index.json rewritten'); }
return { fixed, bad };
}
const writeIndex = (dir) => fs.writeFileSync(path.join(dir, 'index.json'), JSON.stringify({ v: SCHEMA, weeks: list(dir) }) + '\n');
const writeWeek = (dir, j) => { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify(j) + '\n'); writeIndex(dir); };
module.exports = { game, generate, check, refresh, solve, sized, shape, world, writeWeek, writeIndex, list };
if (require.main === module) {
const args = process.argv.slice(2), opt = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; };
const dir = path.resolve(ROOT, opt('--dir', 'site/puzzles/weekly')), g = game(opt('--page') && path.resolve(opt('--page')));
if (args.includes('--check')) {
// Fix what a release's new prices broke, then check everything; only what could not be fixed fails.
const r = refresh(g, dir);
for (const x of r.fixed) console.log(`fixed: ${x}`);
const bad = [...r.bad, ...check(g, dir)];
for (const b of bad) console.error(`error: ${b}`);
console.log(bad.length ? `${bad.length} problem(s)` : `${list(dir).length} weekly puzzle(s) OK`);
process.exit(bad.length ? 1 : 0);
}
// By default the week that holds "12 hours from now": run early on Sunday, that is the week starting that morning.
const first = opt('--key') || g.ev(`pzWeekKey(Date.now()+12*3600e3)`), n = +opt('--next', 1);
for (let i = 0; i < n; i++) {
const key = g.ev(`pzKeyAdd('${first}',${i})`);
if (!key) { console.error(`error: ${first} is not a week`); process.exit(1); }
if (fs.existsSync(path.join(dir, key + '.json')) && !args.includes('--force')) { console.log(`${key}: already there`); continue; }
const j = generate(g, key, dir); writeWeek(dir, j);
console.log(`${key}: ${j.theme}, ${j.cities.join(' ')}${j.via.length ? ' via ' + j.via.join(' ') : ''}${j.avoid.length ? ' avoid ' + j.avoid.join(' ') : ''}, budget ${j.budget} (1★ ${j.ref.one}, 3★ ${j.ref.three})`);
}
}

View file

@ -1,298 +0,0 @@
#!/usr/bin/env node
// The weekly scenario generator, the twin of scripts/weekly-puzzle.js. Every Sunday .github/workflows/weekly-puzzle.yml
// runs both; this one publishes site/scenarios/weekly/<key>.json, which the game fetches when the Scenarios list opens
// (src/game/60-features/94-scenarios-weekly.js). It loads the real game headless, so it uses the game's own cities,
// cables, prices, week keys, file validator and goal code.
//
// node scripts/weekly-scenario.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing
// node scripts/weekly-scenario.js --key 2026-W45 that week (--force replaces an existing file)
// node scripts/weekly-scenario.js --next 3 this week and the next two
// node scripts/weekly-scenario.js --check re-play every week not over yet with this game; a week its reference
// no longer wins is regenerated with rev + 1 (see refresh()); then
// validate every file. Fails only if that fails.
// --page FILE / --dir DIR another build of the game / where the files live
//
// How a scenario is made: pick a theme the last weeks did not have (TEMPLATES, plain data), a home city from another part
// of the world than the last weeks', its rules and the reference plan (which links to build, in order). Then the
// reference player (scripts/lib/scenario-bot.js) plays it through the game's own actions with the scenario's seed. The
// goal's number is calibrated from that run (what the reference reached about three quarters of the way in), and the
// scenario is verified: not won on day 0, won by the reference with time to spare. Its finishing day is the par.
const fs = require('node:fs');
const path = require('node:path');
const BOT = require('./lib/scenario-bot');
const { lit } = require('./lib/js-literal');
const ROOT = path.join(__dirname, '..');
const SCHEMA = 1, HISTORY = 4, THEME_GAP = 4, REG_GAP = 3, ATTEMPTS = 12, AT = 0.8, MARGIN = 0.9;
// ---------- the templates: data only. `home` names a city pool, `goal` a goal type of the game, `plan` a planner ----------
const TEMPLATES = {
budget: { goal: 'served', home: 'big', days: [240, 300], cash: [150000, 250000], lvl: 2, mods: ['pricey'], plan: 'spread', hops: 4 },
spat: { goal: 'reach', home: 'big', days: [240, 300], cash: [500000, 800000], lvl: 2, rules: { spat: true }, plan: 'spread', hops: 3, tr2: true, avoid: ['cog'] },
region: { goal: 'ix', home: 'ixrich', days: [270, 365], cash: [200000, 350000], lvl: 2, plan: 'exchanges', hops: 14 },
event: { goal: 'event', home: 'big', days: [180, 240], cash: [500000, 900000], lvl: 2, plan: 'spread', hops: 2, sizes: [1600, 800, 400, 200] },
flood: { goal: 'floods', home: 'big', days: [240, 300], cash: [1500000, 2500000], lvl: 4, rules: { ddos: true }, plan: 'spread', hops: 2, scrub: 2 },
island: { goal: 'pops', home: 'island', days: [240, 365], cash: [250000, 500000], lvl: 3, plan: 'islands', hops: 3 },
cable: { goal: 'path', home: 'landing', days: [270, 365], cash: [200000, 400000], lvl: 3, plan: 'detour', g: [400, 800], n: 45 },
latency: { goal: 'lat', home: 'fast', days: [180, 270], cash: [300000, 600000], lvl: 3, plan: 'fast', n: 60 },
};
// ---------- the game, headless ----------
function game(file) {
const { load } = require('../tests/harness');
let g = load(file ? { file } : {});
if (file && !g.ev("typeof wsValid==='function'")) { console.warn(`warning: ${file} has no weekly scenarios yet; using src/ instead`); g = load(); }
return g;
}
const J = (ev, s) => JSON.parse(ev(`JSON.stringify(${s})`));
// ---------- small helpers ----------
const hash = (s) => { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; };
function rng(seed) { let a = seed >>> 0 || 1; return () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
const pick = (r, a) => a[Math.floor(r() * a.length)];
const between = (r, [lo, hi], step) => lo + Math.floor(r() * ((hi - lo) / step + 1)) * step;
// A goal number players can read: two significant digits, rounded down.
const nice = (x) => { if (x < 10) return Math.max(1, Math.floor(x)); const p = 10 ** (Math.floor(Math.log10(x)) - 1); return Math.floor(x / p) * p; };
// ---------- the world, as the game sees it ----------
function world(ev) {
const cities = J(ev, `Object.values(CITY).filter(c=>pzCityOk(c.id)).map(c=>({id:c.id,reg:c.reg,P:c.P,land:lands(c)[0],nl:lands(c).length,ix:ixIdsIn(c.id).length,lon:c.lon,lat:c.lat}))`);
const C = Object.fromEntries(cities.map((c) => [c.id, c]));
const pairs = J(ev, 'CABLE_PAIRS.map(p=>[p.cid,p.a,p.b])').filter(([, a, b]) => C[a] && C[b]);
const byLand = {}; for (const c of cities) (byLand[c.land] = byLand[c.land] || []).push(c.id);
const km = (a, b) => { const A = C[a], B = C[b], r = Math.PI / 180, h = Math.sin((B.lat - A.lat) * r / 2) ** 2 + Math.cos(A.lat * r) * Math.cos(B.lat * r) * Math.sin((B.lon - A.lon) * r / 2) ** 2; return 12742 * Math.asin(Math.sqrt(h)); };
const cabs = (c) => pairs.filter(([, a, b]) => a === c || b === c);
const pools = {
big: cities.filter((c) => c.P >= 150 && byLand[c.land].length >= 5).map((c) => c.id),
ixrich: cities.filter((c) => c.ix && cities.filter((x) => x.reg === c.reg && x.land === c.land && x.ix && km(c.id, x.id) < 2500).length >= 9).map((c) => c.id),
island: cities.filter((c) => byLand[c.land].length <= 2 && c.nl === 1 && cabs(c.id).length >= 2).map((c) => c.id),
landing: cities.filter((c) => c.P >= 100 && cabs(c.id).length >= 3).map((c) => c.id),
fast: cities.filter((c) => c.P >= 100 && cabs(c.id).length >= 2).map((c) => c.id),
};
return { cities, C, pairs, byLand, km, cabs, pools };
}
const near = (W, c, from, n) => from.filter((x) => x !== c).sort((a, b) => W.km(c, a) - W.km(c, b)).slice(0, n);
// ---------- drafts: a template, a home, rules, the goal's fixed parameters and the reference plan ----------
// Plans are lists of steps for the reference player: {k:'hop',v:[a,b,tier,via]} lights a wave a-b (a new POP at b).
function draft(g, W, theme, r, hist) {
const T = TEMPLATES[theme], free = (c) => !hist.cities.has(c) && !hist.regs.includes(W.C[c].reg);
const homes = W.pools[T.home].filter(free); if (!homes.length) return null;
const home = pick(r, homes), H = W.C[home];
const f = { theme, city: home, cash: between(r, T.cash, 50000), days: between(r, T.days, 10), lvl: T.lvl, rules: { ...(T.rules || {}) }, mods: (T.mods || []).slice() };
const plan = { home, bb: true, ix: true, steps: [], avoid: T.avoid || [], tr2: !!T.tr2, scrub: T.scrub || 0 };
const hop = (a, b, t = 1, via = null) => plan.steps.push({ k: 'hop', v: [a, b, t, via] });
const land = W.byLand[H.land].filter((c) => c !== home && W.km(home, c) < 1500);
let goal = null, words = {};
if (T.plan === 'spread') {
// Overland to the nearest big cities, each from the closest POP already built.
const to = near(W, home, land.filter((c) => W.C[c].P >= 60), T.hops); if (to.length < Math.min(2, T.hops)) return null;
const built = [home]; for (const c of to) { hop(near(W, c, built, 1)[0], c); built.push(c); }
if (theme === 'budget') goal = { t: 'served', p: { g: 0 } };
if (theme === 'spat') goal = { t: 'reach', p: { r: 99, g: 0 } };
if (theme === 'flood') goal = { t: 'floods', p: { n: 0, big: 0 } };
if (theme === 'event') { const day = Math.round(f.days * (0.6 + r() * 0.15)); goal = { t: 'event', p: { city: home, g: 0, day, dur: 3 + Math.floor(r() * 3) } }; plan.event = { city: home, day }; words = { day }; }
} else if (T.plan === 'exchanges') {
const to = near(W, home, W.cities.filter((c) => c.reg === H.reg && c.land === H.land && c.ix).map((c) => c.id), T.hops); if (to.length < T.hops) return null;
const built = [home]; for (const c of to) { hop(near(W, c, built, 1)[0], c); built.push(c); }
plan.allIx = true; goal = { t: 'ix', p: { reg: H.reg, n: 0 } }; words = { reg: H.reg };
} else {
// Cable work: plan inside the game, which knows each pair's cables under this scenario's rules.
let a = home, b = null, cs = null;
if (theme === 'cable') {
// Cut one cable everywhere it lands; the goal is its far end, the long way round.
const mine = W.cabs(home).filter(([, x, y]) => W.C[x].land !== W.C[y].land && W.C[x === home ? y : x].P >= 60);
if (!mine.length) return null;
const [cid, x, y] = pick(r, mine); b = x === home ? y : x;
// The whole cable, and every other cable straight from home to its far end: the corridor is closed.
const cut = new Set([cid, ...W.pairs.filter(([, p, q]) => (p === home && q === b) || (p === b && q === home)).map(([c]) => c)]);
f.rules.banPairs = W.pairs.filter(([c, p, q]) => c === cid || (cut.has(c) && [p, q].includes(home) && [p, q].includes(b))).map(([c, p, q]) => `${c}:${p}-${q}`);
if (f.rules.banPairs.length > 40) return null;
const gb = pick(r, T.g); plan.tier = J(g.ev, `LT.findIndex(x=>x.g>=${gb})`);
goal = { t: 'path', p: { a, b, g: gb, n: T.n } }; words = { cab: cid, a, b };
} else if (theme === 'island') {
const hops = W.cabs(home).map(([, x, y]) => (x === home ? y : x)).filter((c, i, s) => s.indexOf(c) === i && W.km(home, c) < 6000);
if (hops.length < 2) return null;
// The nearest islands a cable away, and one more island further out.
const isl = W.pools.island.filter((c) => c !== home && W.km(home, c) < 9000 && !hops.includes(c));
cs = [...near(W, home, hops, 2), ...near(W, home, isl, 1 + Math.floor(r() * 2))];
if (cs.length < 3) return null;
goal = { t: 'pops', p: { cs } };
} else if (theme === 'latency') {
// Far enough that the fast way takes more than one cable.
const ok = W.cities.filter((c) => c.P >= 100 && c.land !== H.land && W.km(home, c.id) > 5000 && W.km(home, c.id) < 11000 && W.cabs(c.id).length >= 2).map((c) => c.id);
if (!ok.length) return null; b = pick(r, ok); goal = { t: 'lat', p: { a, b, ms: 0, n: T.n } }; words = { a, b };
}
plan.targets = cs || [b]; plan.fast = theme === 'latency';
f.goal = goal;
return { f, plan, words, T };
}
f.goal = goal;
return { f, plan, words, T };
}
// ---------- names and descriptions: labels and their fill-ins ----------
function texts(ev, d, r) {
const T = J(ev, `WS_THEMES['${d.f.theme}']`), p = d.f.goal.p;
const fill = (l) => { const need = [...new Set([...ev(`EN['${l}']`).matchAll(/\{(\w+)\}/g)].map((m) => m[1]))], o = {};
for (const k of need) o[k] = k === 'city' ? d.f.city : k === 'ms' ? p.ms : k === 'g' ? p.g : k === 'n' ? p.n : d.words[k];
return { l, p: o }; };
return { name: fill(pick(r, T.names)), desc: fill(pick(r, T.descs)) };
}
// ---------- playing a draft ----------
const fileOf = (key, d, seed, extra) => ({ v: SCHEMA, key, theme: d.f.theme, city: d.f.city, cash: d.f.cash, days: d.f.days, lvl: d.f.lvl, rules: d.f.rules, mods: d.f.mods, goal: d.f.goal, ...extra, seed, ref: d.plan });
// Cable plans are made in the game, once the scenario's rules are in force: the shortest chain of POPs to each target.
function cablePlan(ev, plan) {
if (!plan.targets) return plan;
const steps = J(ev, `(()=>{const home=S.scn.home,T=${lit(plan.targets)},fast=${!!plan.fast},out=[],have=new Set([home]);
const ok=c=>pzCityOk(c)&&cityOn(c)&&!cnCity(c);
const edges=u=>{const o=[];for(const p of CABLE_PAIRS){const v=p.a===u?p.b:p.b===u?p.a:null;if(!v||!ok(v))continue;const cs=cablesOk(u,v);if(!cs.length)continue;
const c=cs.slice().sort((x,y)=>x.km*(CAB[x.cid].lat||1)-y.km*(CAB[y.cid].lat||1))[0];o.push([v,c.km*(CAB[c.cid].lat||1)/200,c.cid]);}
for(const c of CITIES)if(c.id!==u&&ok(c.id)&&!isSub(u,c.id)&&kmBetween(u,c.id)<(fast?4000:1800))o.push([c.id,kmBetween(u,c.id)*1.3/200,null]);return o;};
for(const t of T){if(have.has(t))continue;const d={},pv={},done=new Set();for(const h of have)d[h]=0;
for(;;){let u=null;for(const k in d)if(!done.has(k)&&(u===null||d[k]<d[u]))u=k;if(u===null||u===t)break;done.add(u);for(const [v,w,cid] of edges(u)){const nd=d[u]+(fast?w:1+w/1000);if(!(d[v]<=nd)){d[v]=nd;pv[v]=[u,cid];}}}
if(d[t]===undefined)return null;const chain=[];for(let v=t;!have.has(v);v=pv[v][0])chain.unshift([pv[v][0],v,${plan.tier || 1},pv[v][1]]);for(const h of chain){out.push({k:'hop',v:h});have.add(h[1]);}}
return out;})()`);
return steps ? { ...plan, steps } : null;
}
// Starts the draft in the game (so its rules apply), finishes the plan, and plays it with the reference player.
function run(g, file, plan, days) {
const { ev } = g;
ev(`localStorage.removeItem('sot-wkscn');wsBegin(${lit(file)},'Ref');if(UI.pendGame)ACT.pitchSkip()`);
const p = cablePlan(ev, plan); if (!p || (plan.targets && p.steps.length < 2)) return null;
return { plan: p, res: BOT.play(ev, { ...file, ref: p }, p, { days, stop: false }) };
}
// The goal's number, from the reference run: what it held about three quarters of the way in.
function calibrate(g, d, key, seed) {
const { f } = d, p = f.goal.p, t = f.goal.t, at = Math.round(f.days * AT);
// The validator wants a complete goal: start from placeholders the game accepts.
const probe = JSON.parse(JSON.stringify(f.goal));
if (t === 'served') probe.p.g = 50000; if (t === 'reach') probe.p.g = 50000; if (t === 'ix') probe.p.n = 60; if (t === 'floods') probe.p.n = 60;
if (t === 'event') probe.p.g = 10; if (t === 'lat') probe.p.ms = 400;
// Probed with placeholder numbers; the real name and text are filled in once the numbers are known.
const tmp = { ...d, f: { ...f, goal: probe } }, file = fileOf(key, tmp, seed, { ...texts(g.ev, tmp, rng(1)), par: 1 });
if (t === 'event') {
// The biggest event the reference delivers in full.
for (const size of d.T.sizes) { probe.p.g = size; file.goal = probe; const o = run(g, { ...file }, { ...d.plan, event: { ...d.plan.event, g: size } }, p.day + p.dur + 1); if (o && g.ev('(S.stats.evFull||0)>=1')) { p.g = size; return { plan: o.plan }; } }
return null;
}
if (t === 'lat') {
const o = run(g, file, d.plan, at); if (!o) return null;
const best = g.ev(`bestLat('${p.a}','${p.b}')`); if (!isFinite(best)) return null;
p.ms = Math.ceil(best * 1.03 + 0.5); return { plan: o.plan };
}
const o = run(g, file, d.plan, at); if (!o) return null;
const m = o.res.m, v = m[m.length - 1];
if (t === 'served') p.g = nice(Math.min(...m.slice(-14)));
if (t === 'reach') { if (g.ev('R.reach') < 0.99) return null; p.g = nice(Math.min(...m.slice(-14))); }
if (t === 'ix') p.n = Math.floor(v);
if (t === 'floods') { p.n = Math.floor(v); p.big = Math.min(5, g.ev('S.stats.ddosOkBig||0')); }
if ((p.g !== undefined && p.g < 5) || (p.n !== undefined && p.n < 2)) return null;
return { plan: o.plan };
}
// The game's validator decides what a scenario is; then it must need play, and the reference must win with time to spare.
function verify(g, j) {
const { ev } = g;
if (!ev(`!!wsValid(${lit(j)},'${j.key}')`)) return { ok: false, why: 'the game rejects the file' };
// Played with the longest clock the game allows, so a late win still shows its day (the days change nothing else).
const res = BOT.play(ev, { ...j, days: 400 }, j.ref, { stop: true });
if (res.won0) return { ok: false, why: 'won on day 0' };
if (!res.won) return { ok: false, why: `the reference does not win in ${j.days} days` };
if (res.won > j.days * MARGIN) return { ok: false, late: res.won, why: `the reference wins only on day ${res.won} of ${j.days}` };
if (res.won < 40) return { ok: false, why: `the reference wins already on day ${res.won} of ${j.days}` };
return { ok: true, par: res.won };
}
// ---------- one week ----------
const list = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^\d{4}-W\d{2}\.json$/.test(f)).map((f) => f.slice(0, -5)).sort() : []);
function history(W, dir, key) {
const files = list(dir).filter((k) => k < key).slice(-HISTORY).map((k) => JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')));
return { themes: files.slice(-THEME_GAP).map((f) => f.theme), regs: files.slice(-REG_GAP).map((f) => W.C[f.city] && W.C[f.city].reg).filter(Boolean), cities: new Set(files.map((f) => f.city)) };
}
function generate(g, key, dir) {
const { ev } = g, W = world(ev);
if (ev(`pzWeekStart('${key}')`) == null) throw new Error(`${key} is not a week`);
const hist = history(W, dir, key), free = Object.keys(TEMPLATES).sort().filter((t) => !hist.themes.includes(t)), h = hash('scn|' + key);
const order = free.map((_, i) => free[(h + i) % free.length]);
for (const theme of order) {
for (let at = 0; at < ATTEMPTS; at++) {
const r = rng(hash(`${key}|${theme}|${at}`)), d = draft(g, W, theme, r, hist);
if (!d) continue;
const seed = 1 + (hash(`${key}|seed|${at}`) % 2147483646), c = calibrate(g, d, key, seed);
if (!c) { console.warn(`${key}: rejected a ${theme} scenario in ${d.f.city}: no goal to calibrate`); continue; }
d.plan = c.plan;
const w = texts(ev, d, r), j = fileOf(key, d, seed, { name: w.name, desc: w.desc, par: 1 });
let v = verify(g, j);
// A goal with a fixed bar (a path, a set of POPs, a latency) gets the days the reference needed, and a third more.
const day = v.ok ? v.par : v.late;
if (day && ['path', 'pops', 'lat'].includes(j.goal.t)) { j.days = Math.min(365, Math.max(180, Math.ceil(day / 0.7 / 10) * 10)); v = verify(g, j); }
if (v.ok) { j.par = v.par; return order0(j); }
console.warn(`${key}: rejected a ${theme} scenario in ${d.f.city}: ${v.why}`);
}
}
throw new Error(`${key}: no scenario survived verification`);
}
// Fields in a fixed order, so files diff well.
const order0 = (j) => { const o = {}; for (const k of ['v', 'key', 'rev', 'theme', 'city', 'cash', 'days', 'lvl', 'rules', 'mods', 'goal', 'name', 'desc', 'seed', 'par', 'ref']) if (j[k] !== undefined) o[k] = j[k]; return o; };
// --check: every file is what the game accepts, under its own name, listed in the index; weeks not over yet still verify.
function check(g, dir, now = Date.now()) {
const { ev } = g, bad = [], keys = list(dir);
for (const k of keys) {
let j; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { bad.push(`${k}: not JSON`); continue; }
if (!ev(`!!wsValid(${lit(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; }
if (!j.ref || !Array.isArray(j.ref.steps)) { bad.push(`${k}: no reference plan`); continue; }
if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, j); if (!v.ok) bad.push(`${k}: ${v.why}`); else if (v.par !== j.par) bad.push(`${k}: par is ${j.par}, the reference wins on day ${v.par}`); }
}
let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* reported below */ }
if (keys.length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(keys))) bad.push('index.json does not list exactly the weekly files');
return bad;
}
/* --check, first part: a release can change prices, cables or the simulation under weeks already published. Every week
not over yet is re-played with this game. Still won with time to spare: only its par follows. Not any more: it is
regenerated for the same key, deterministically, with rev + 1, so last week's wins for it no longer show. Past weeks
are only replaced when the game rejects them outright. */
function refresh(g, dir, now = Date.now()) {
const { ev } = g, fixed = [], bad = [];
for (const k of list(dir)) {
let j = null; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { /* regenerated */ }
const valid = !!j && ev(`!!wsValid(${lit(j)},'${k}')`) && j.ref && Array.isArray(j.ref.steps), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now;
if (valid && !live) continue;
const v = valid ? verify(g, j) : null;
if (v && v.ok) { if (v.par !== j.par) { j.par = v.par; writeWeek(dir, j); fixed.push(`${k}: new par ${v.par}`); } continue; }
const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1;
let n; try { n = order0({ ...generate(g, k, dir), rev }); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); continue; }
writeWeek(dir, n); fixed.push(`${k}: regenerated as rev ${rev}, a ${n.theme} scenario in ${n.city}`);
}
let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* rewritten */ }
if (list(dir).length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(list(dir)))) { writeIndex(dir); fixed.push('index.json rewritten'); }
return { fixed, bad };
}
const writeIndex = (dir) => fs.writeFileSync(path.join(dir, 'index.json'), JSON.stringify({ v: SCHEMA, weeks: list(dir) }) + '\n');
const writeWeek = (dir, j) => { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify(j) + '\n'); writeIndex(dir); };
module.exports = { game, generate, verify, check, refresh, list, writeWeek, TEMPLATES };
if (require.main === module) {
const args = process.argv.slice(2), opt = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; };
const dir = path.resolve(ROOT, opt('--dir', 'site/scenarios/weekly')), g = game(opt('--page') && path.resolve(opt('--page')));
if (args.includes('--check')) {
const r = refresh(g, dir);
for (const x of r.fixed) console.log(`fixed: ${x}`);
const bad = [...r.bad, ...check(g, dir)];
for (const b of bad) console.error(`error: ${b}`);
console.log(bad.length ? `${bad.length} problem(s)` : `${list(dir).length} weekly scenario(s) OK`);
process.exit(bad.length ? 1 : 0);
}
const first = opt('--key') || g.ev(`pzWeekKey(Date.now()+12*3600e3)`), n = +opt('--next', 1);
for (let i = 0; i < n; i++) {
const key = g.ev(`pzKeyAdd('${first}',${i})`);
if (!key) { console.error(`error: ${first} is not a week`); process.exit(1); }
if (fs.existsSync(path.join(dir, key + '.json')) && !args.includes('--force')) { console.log(`${key}: already there`); continue; }
const j = generate(g, key, dir); writeWeek(dir, j);
console.log(`${key}: ${j.theme} in ${j.city}, ${j.days} days, goal ${j.goal.t} ${JSON.stringify(j.goal.p)}, par ${j.par}`);
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.9 KiB

After

Width:  |  Height:  |  Size: 8.2 KiB

Before After
Before After

View file

@ -1 +0,0 @@
{"v":1,"key":"2026-W44","hq":"cor","budget":1580000,"name":{"l":"architect_weekly.name_all_roads_lead_to_hq","p":{"hq":"cor"}},"joke":{"l":"architect_weekly.joke_hq_signed_the_lease","p":{"hq":"cor"}},"briefs":[{"add":["bue"],"dem":{"bue":40},"tubes":1},{"add":["scl","mvd"],"dem":{"scl":20,"mvd":20},"tubes":2},{"gold":["mvd"],"tubes":2},{"drop":["scl"],"add":["ldb"],"dem":{"ldb":10},"gold":["ldb"],"tubes":2},{"lat":["ldb","mvd",10.1],"tubes":1},{"dem":{"bue":100},"tubes":0},{"add":["cgr"],"dem":{"cgr":10},"gold":["cgr"],"tubes":2}],"ref":{"spend":1489176,"steps":[[["cor","bue","land",1]],[["cor","scl","land",1],["bue","mvd","land",1]],[["bue","cor","land",1],["mvd","bue","land",1]],[["@rm","scl"],["cor","ldb","land",1],["ldb","cor","land",1]],[["ldb","mvd","land",1]],[["@tier",2,2],["@tier",0,2]],[["ldb","cgr","land",2],["cgr","ldb","land",2]]]}}

View file

@ -1 +0,0 @@
{"v":1,"key":"2026-W45","hq":"maa","budget":930000,"name":{"l":"architect_weekly.name_hq_and_friends","p":{"hq":"maa"}},"joke":{"l":"architect_weekly.joke_one_network_a_handful","p":{}},"briefs":[{"add":["blr"],"dem":{"blr":30},"tubes":1},{"add":["hyd","cbo"],"dem":{"hyd":20,"cbo":20},"tubes":2},{"gold":["cbo"],"tubes":1},{"ring":["maa","blr","hyd"],"tubes":1},{"drop":["hyd"],"add":["dac"],"dem":{"dac":20},"gold":["dac"],"tubes":2},{"gold":["blr"],"tubes":1}],"ref":{"spend":869628,"steps":[[["maa","blr","land",1]],[["blr","hyd","land",1],["maa","cbo","smw6",1]],[["cbo","maa","smw4",1]],[["hyd","maa","land",1]],[["@rm","hyd"],["maa","dac","land",1],["dac","maa","land",1]],[["blr","maa","land",1]]]}}

View file

@ -1 +0,0 @@
{"v":1,"key":"2026-W46","hq":"svg","budget":610000,"name":{"l":"architect_weekly.name_the_hq_job","p":{"hq":"svg"}},"joke":{"l":"architect_weekly.joke_one_network_a_handful","p":{}},"briefs":[{"add":["krs"],"dem":{"krs":30},"tubes":1},{"add":["osl","ebj"],"dem":{"osl":20,"ebj":20},"tubes":2},{"gold":["ebj"],"tubes":2},{"lat":["osl","svg",2.2],"tubes":1},{"drop":["krs"],"add":["cph"],"dem":{"cph":20},"gold":["cph"],"tubes":3},{"dem":{"osl":140},"tubes":0}],"ref":{"spend":567292,"steps":[[["svg","krs","land",1]],[["krs","osl","land",1],["krs","ebj","land",1]],[["krs","svg","land",1],["ebj","krs","land",1]],[["osl","svg","land",1]],[["@rm","krs"],["ebj","svg","land",1],["ebj","cph","land",1],["cph","osl","land",1]],[["@tier",0,2],["@tier",1,2],["@tier",2,2],["@tier",3,2]]]}}

View file

@ -1 +0,0 @@
{"v":1,"weeks":["2026-W44","2026-W45","2026-W46"]}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

Some files were not shown because too many files have changed in this diff Show more