Compare commits

...

939 commits
v1.3.0 ... main

Author SHA1 Message Date
jvanvik
41e6fd78ef Review fixes for Starblink, Island Wi-Fi and late joiners
Some checks failed
CI / plan (push) Has been cancelled
CI / build (push) Has been cancelled
CI / translations (push) Has been cancelled
Container image / gate (push) Has been cancelled
CI / part (push) Has been cancelled
CI / test (push) Has been cancelled
CI / timings (push) Has been cancelled
Container image / test (push) Has been cancelled
Container image / publish (push) Has been cancelled
- Until a zone's first circuit or spur is up, its row and panel say when the islands come online instead of homes out of 0 and a red 0% served (wisp-commissioning-homes-of-zero).
- Once your own constellation flies, a zone's Starblink row points to GEO, MEO or a spur (wisp.leo_no_rivals), never to a pie dish (zone-leo-pie-dish-advice).
- The late joiner's welcome and bank note say the match is on home broadband, not island Wi-Fi, in all six languages (late-match-island-homes).
- A gateway's section shows its city's transit ports (Transit out of the city) and warns when they fill; the fiber row only where there is fiber (leo-backhaul-transit-only).
- Spurs are subsea cable, no longer unrepeatered, in every language and the catalog comment (spur-unrepeatered-1400km).
- French calls a spur a câble de dérivation, not a câble d'antenne (fr-spur-cable-antenna).
2026-11-12 03:36:31 +01:00
jvanvik
5ca8270db9 Island Wi-Fi: no new routing fields until you run a zone
emptyR() carried cityWisp, wisp and wispL in every game, so a game with no island zones no longer routed to the same R
as main and tests/route-fuzz.test.js failed on its first move. compute() now adds them only while a zone runs (as
satU), wispMoney() returns without them, and the agent's results docs say so. tests/wisp-zones.test.js checks that a
game without zones, and one below level 2, has none of them. The mp-sim fixtures were written again with
tests/lib/mp-sim-fixtures.js (only the three empty fields left them; a second run changes nothing).
2026-11-12 02:40:09 +01:00
jvanvik
66ac7d0af1 Island Wi-Fi, Starblink and late joiners work together
Checked after merging the three, and pinned with a test (tests/late-joiners.test.js): a late network with a Starblink
zone and a lit spur pays its islanders' income in full but has only its homes matched; investors on a revenue share
take their cut of homes, islands and an IPv4 lease, never of the match; a spur cut and a solar storm need a lit spur or
a LEO circuit, not a number of days, and come on the network's own outage schedule (S.nextFail, counted from S.day0),
so no grace needed moving; a reload keeps the game.

- CHANGELOG: Island Wi-Fi names zones as the game does (Abaco and Eleuthera) and says a spur has upkeep but no rent.
- Agent: a stray "., " in the pops doc where the Starblink and Island Wi-Fi lines met.
- Plans: open question 6 (WISP zones and a rented LEO tier) marked answered and built.
2026-11-12 02:25:24 +01:00
jvanvik
dcdb501f16 Late joiners: a network that joins a server session late starts on its date, with a head start
One calendar for a server session (the user's answer to Q1): a network that joins begins on the session's date, and
one that joins after day 180, when the shared market starts to move, gets a head start (answered 2026-11-11).
Dormant until the host (T3) passes a start day: in the plain build and in single-device play S.day0 is 0 and the
game is as before.

- S.day0, the calendar day a network began: 0 in newGame(), repaired in sanitize() (at most S.day), so old saves load.
  netAge() is the network's age; the first-days rules count it: the charter window (and specSanitize), the tutorial's
  five days, the DDoS grace and early size cap, route leaks, RPKI, the world's bad news, shortages and control-plane
  events, sold-out routes, the scrubbing customers, loan offers, the broker's first calls, the Speedrun and Blitz
  badges and the day counts in the win, lose and Glass Baron windows. The market, the calendar and world events stay
  on the session's date.
- beginState() takes o.day for a session network in Normal mode (lateStart()): the day, the first outage and event,
  the home POP and the first IPv4 block are stamped with it, so the block cannot be sold on day one at the session's
  price.
- The head start (60-features/81-late-joiners.js): starting cash topped up by the rise in hardware prices (START_CASH
  x (hwTrend - 1), to $1,000, at most $60k, with the market rule only) and the first 365 days of home broadband
  matched (R.rev.late: what homes pay after the Australian wholesale cut or levy; outside investors' share, inside
  revMo). A second welcome with a button to the bank, a Goals card, a bank section, a line in a city's broadband pitch
  and a toast when the year is over; every label in all six dictionaries.
- The "since you started" lines (supply chain, bandwidth market, wave prices) measure from the network's own start.
- Server-run engine: srvBegin takes begin.day (an integer from 0, else the begin fails), the fake engine begins there
  and keeps day0 in its saves, CLOCK.off leaves the shape checker and the contract test, and the fixtures' network
  begins on day 473 (written again with tests/lib/mp-sim-fixtures.js; a second run changes nothing).
- Gameplay rule F11, the agent's day0 doc and status age, ARCHITECTURE and the plans (Q1's game side built, open
  question 1 answered).
- tests/late-joiners.test.js; F11 in tests/gameplay-rules.test.js; a late begin in tests/mp-sim-engine.test.js; one
  calendar in tests/mp-sim-contract.test.js.

Merged onto Starblink and Island Wi-Fi: revMo counts both the islands (V.wisp) and the match (V.late), the revenue
share base keeps V.wisp and leaves V.late out; F11 sits before F12 in the gameplay rules and their test; the mp-sim
fixtures were written again with tests/lib/mp-sim-fixtures.js (a second run changes nothing).
2026-11-12 02:16:44 +01:00
jvanvik
9067bae1ce CHANGELOG: shorter first sentences for the Unreleased bullets 2026-11-12 02:15:22 +01:00
jvanvik
efe4405ea4 Investors on a revenue share take their cut of IPv4 lease income (#150)
Merged onto Island Wi-Fi: the revenue share base keeps the islands (V.wisp) and adds IPv4 leases (V.ip4); the CHANGELOG bullet goes above the Island Wi-Fi and Starblink ones.
2026-11-12 02:15:22 +01:00
jvanvik
6f0c080875 Island Wi-Fi for 18 groups of outer islands, by satellite and spur cable (#83)
Each zone (Vanua Levu & Taveuni off Suva, the Out Islands off Nassau, and
16 more) is a pool of island homes at your POP in its city: no node and no
link on the map, its Gbps join the city's demand. Rent backhaul at the
city's teleport (about 35% sign up over GEO, 75% over MEO, 90% over
Starblink from a gateway there) or, from level 3, lay a spur cable and
everyone may sign up. The first order brings the island kit. Islanders pay
island prices, their homes are IPv6-only in the NAT64 pool, and investors
on a revenue share take their cut. A spur can be cut for weeks (failure
'wspur', chaos only): a satellite kept beside it carries the islands. Zones
are off in puzzles, the Architect, scenarios and below level 2.

The satellite geometry works on points now (satSeesAt, satPairAt, satKmAt;
the city functions wrap them, with the same answers). Starblink serves a
zone only from a gateway in its own city (16 of 18; a gateway anywhere in
reach would serve the same 16), with its storm and rival rule; Nunavut and
Southeast Alaska stay on GEO. Rules W6 and F12.
2026-11-12 02:12:21 +01:00
jvanvik
7967a29083 Rent low-orbit satellite capacity from Starblink (#83)
A Starblink gateway on a teleport at a POP on your fiber (level 5, within
56 degrees of the equator) rents LEO circuits of 5 to 50 Gbps to small
islands and remote towns within 1,200 km: a bent pipe 550 km up, about
30 ms round trip, 3% of the service counted as bad, and no selective
network refuses it. LEO puts GEO and MEO circuits on the same pair on
standby and waits beside a cable. The gateway's Infra section shows its
POP's forwarding load and the fiber out of the city, the islands'
bottleneck. A rare solar storm (and Pie's own) puts LEO in safe mode for
a day or two. Once your own crust carries traffic Starblink sells nothing
new. Rule O8. Hooks for island Wi-Fi: leoReachLL, leoKmLL, leoMsLL.
2026-11-12 01:34:46 +01:00
jvanvik
08eb349d87 Merge upstream: POP standards, latency contracts, device transfer, typed links and NOC downgrades (3.4.0, 3.5.0)
Some checks are pending
CI / plan (push) Waiting to run
CI / part (push) Blocked by required conditions
CI / build (push) Waiting to run
CI / translations (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / timings (push) Blocked by required conditions
Container image / gate (push) Waiting to run
Container image / test (push) Blocked by required conditions
Container image / publish (push) Blocked by required conditions
Conflicts, file by file:
- CHANGELOG.md: the fork's Unreleased bullets on top; 3.5.0 and 3.4.0 exactly as upstream has them.
- src/i18n/en.js, site/i18n/{de,es,fr,it,pt}.js: merged label by label, sorted; the labels each side dropped stay dropped.
- src/agent/10-domains.js, 30-docs.js, 40-read.js: both sides' enums, state docs and tables (popStd as the build standard, popTiers, ip4, mp).
- src/agent/20-commands.js: the fork's wording on accept and upRouter, upstream's acceptFix, utilityKitAll/New and pt*; theme, session and transfer acts in the local table.
- src/game/60-features/80-new-game.js: ip4, rgen and mp next to popTiers.
- src/game/80-simulation/29-route-core.js, 30-compute.js: the route core takes both SATN and the spill tiers (TT).
- src/game/80-simulation/40-billing.js: upstream's gulfPair and borderShut; linkCut() is built on borderShut, linkDown() keeps express and satellite.
- src/game/80-simulation/50-sanitize.js: PNI bundles up to PNI_LAG_MAX next to the fork's link kinds; popStdSanitize then ptSanitize; mpSanitize then lcSanitize.
- src/game/80-simulation/75-customer-lifecycle.js: clGrow() stops at a type's most (#137) and at an IPv4 block that is not free (#150).
- src/game/90-actions/60-links.js: rmLink keeps the express guard and moves on to the next parallel link (#119).
- src/game/90-actions/85-routing-and-routers.js: rmRouter checks the PNIs on its routers (#323), upRouter keeps own().
- src/game/90-actions/89-game-and-settings.js: the menu keeps the build standard and session tiles and gains Send to another device.
- src/game/93-ui/40-hud-and-panels.js, 70-link-panels.js: offers show both the IPv4 note and Buy and sign; link headers name their cities, the closed-border section reads in dark mode; the express count stays.
- src/game/93-ui/50-city-panel.js: the teleport section and Link to a city.
- src/game/94-dashboard/40-connections.js: upstream's per-table next port size replaces the fork's own 400G guard.
- src/game/94-dashboard/90-noc-window.js, 96-map/95-clicks.js, 99-loop.js: both sides' acts and boot steps.
- src/styles/40-modal.css: the dark-mode tag tokens and the transfer textarea.
- tests/mcp-commands.test.js: both sides' sample args.

Interaction fixes:
- POP standards and the build standard: a POP marked as a kind keeps its kind's routers (ptKind). The build
  standard's router jobs and the intern's model swaps leave it alone; every other target still applies. Both sheets say so.
- Spill tiers: pathMs() fills a path's ground latency and satellite edges too, so a tier's detour costs users its
  latency (it went uncharged before).
- Send to another device: a session network goes by the session's own #mp= link; its save file is called a copy.
- Buy and sign (#241) does not buy for an offer whose IPv4 block does not fit.
- Dark mode: the closed-border title and the renewal ticks use the dark-aware red (upstream's #292 test follows).
- Server-run tables: the new acts classified (pt*, acceptFix and utilityKitAll quote their cost); mp-sim fixtures
  written again with tests/lib/mp-sim-fixtures.js.

Review fixes:
- POP standards: ptSave, ptApply, ptPlan, ptAll and popStdSet find a POP with own(), so 'toString' is no POP (also
  decomToggle, decomGo, dkStay).
- Server-run envelope: an arg value that names anything on Object.prototype is refused, in args, drafts and
  ctx.win.ui.
- Decommissioning a POP drops its POP-standard mark, so live state stays what a reload makes of it (the T2 gate
  refused later pt* acts).
- acceptFix, ptApply, ptAll and utilityKitAll take a quote within 1% (quoteNear), like utilityKit and bstdApply:
  router prices drift daily.
- The transfer paste box reads in dark mode (--text, as input.t).
- A session's #mp= link pasted under From another device opens it (saved, then loaded again with it), in MP builds.
- The express and satellite circuit panels name their cities as links (#196); a circuit shows the closed-border
  section (#329).
- CHANGELOG: the fork's 400G connections bullet goes (3.5.0 ships it); bullets for POP kinds, the session link and Buy
  and sign's IPv4 check.
2026-11-12 00:52:42 +01:00
Frederic Jung
9c26d03952
Conferences stop notifying once you are Tier 1 (#101)
After the Tier 1 goal, the 30-day reminders, the report (and its coin sound)
on the day and the sales engineer's booking notes are no longer shown or
logged. Registering, sponsoring, the glow, raffles and capacity deals work as
before, and the Deals tab still lists conferences.

Fixes #101
2026-11-11 18:37:18 +01:00
Frederic Jung
99b16f6184
Type a city to start a link, downgrade from the NOC dashboard, and fixes (3.5.0) 2026-11-11 15:59:04 +01:00
Frederic Jung
727c8f8500
Connections list: look up the next port size in each port's own table
nx() now takes the size table it should look in, so fabric ports ask NNI
(up to 400G) instead of special-casing the 400G port. Adds the PR number
to the #342 CHANGELOG bullet.
2026-11-11 15:54:37 +01:00
Frederic Jung
2b8bd1c402
Start a link by typing the city it goes to (#343)
A POP's Infra tab gets Link to a city: it opens the city finder in link
mode, which offers only cities a link from there could end in, and picking
one (or Enter) opens the same link window as dragging between the two on the
map. Much easier than finding a far-away city on a crowded phone screen.

Fixes #343
2026-11-11 15:44:38 +01:00
Frederic Jung
c52e7c7747
Downgrade and chase connections from the NOC dashboard (#336)
The Connections tab now has the POP panel's shrink buttons next to the
upgrades: a downgrade to the next smaller port for transit, PNIs and IX
ports, one LAG member less (also for NNIs), and Chase it for a PNI that is on
order or waiting for a bigger port. Same actions and conditions as the panel;
the NOC pop-out window runs them in the game.

Fixes #336
2026-11-11 15:44:28 +01:00
Germain Carré
e2b3615a19
Keep the Connections list working with 400G fabric ports (#342) 2026-11-11 15:35:50 +01:00
Frederic Jung
e27e9e3066
Keep hand-listed alien waves on the market (#340)
With the capacity market selling alien waves (or pairs), its daily pass set
every fiber's listing to what the thresholds allowed: 128 waves listed by hand
came back as 96 (after the 25% kept back), or were taken off entirely when
the route's demand was below the minimum or the price below the floor.

A listing now remembers how much was listed by hand (l.list.hw / hp). The
broker lists its own share on top, capped at what the fiber has free; sales
use up the broker's share first; switching a product or route off keeps the
hand-listed part. cmClean() checks the new fields, so old saves load as before.

Fixes #340
2026-11-11 12:06:23 +01:00
Frederic Jung
c137d3552d
Send networks to another device, latency routes, POP standards and more (3.4.0) 2026-11-10 14:50:26 +01:00
Frederic Jung
1ccdda171b
Send a network to another device through the share sheet instead of QR codes (#263)
QR codes do not scale: a played network takes several, a big one dozens. The
save file now goes through the device's own share sheet (AirDrop, Quick Share,
a chat with yourself, email), whatever its size, and opens on the other device
with Import a save. Chromium refuses to share .json files, so there the same
file goes as .txt, which Import a save now takes too. The whole-network link
stays for copy and paste. The file is prepared before the tap, because a share
sheet only opens straight from a user's gesture.
2026-11-10 13:19:00 +01:00
Frederic Jung
79426f7a00
Move a network to another device with QR codes or a link (#263)
No server and no account: the network travels gzipped in the fragment of a
link, which browsers never send anywhere. One link carries all of it, to copy
or share; QR codes carry it in parts that a phone's own camera app opens one
after another, and the receiving page collects them in any order, then imports
the network like a save file. To keep the codes few they leave out the charts'
history and the news log (a year-old network: 4 codes instead of 10); the link
carries everything. The QR encoder is a small built-in one, checked against the
reference implementation for every mask.
2026-11-10 12:31:40 +01:00
Frederic Jung
b892dcd923
Merge pull request #335 from fjaeckel/claude/endgame-scale
Late game grows sideways: eyeball traffic where the eyeballs are, AI campuses in 34 metros, PNIs by router, spill tiers
2026-11-10 11:09:32 +01:00
Frederic Jung
dc696c72f2
Merge remote-tracking branch 'origin/main' into claude/endgame-scale 2026-11-10 09:40:05 +00:00
Frederic Jung
102298a9ed
Merge pull request #334 from fjaeckel/claude/latency-contracts
Strict latency contracts: big late-game customers who pay for a latency SLA
2026-11-10 10:39:52 +01:00
Frederic Jung
e8cbb9b440
Merge branch 'claude/latency-contracts' into trial
# Conflicts:
#	.claude/skills/gameplay-rules/SKILL.md
#	CHANGELOG.md
#	tests/day-steps.test.js
#	tests/route-fuzz.test.js
2026-11-10 09:36:11 +00:00
Frederic Jung
12ce66b33a
Merge remote-tracking branch 'origin/main' into claude/latency-contracts
# Conflicts:
#	CHANGELOG.md
2026-11-10 09:33:49 +00:00
Frederic Jung
d42fc5b68e
Merge pull request #333 from fjaeckel/claude/bulk-actions
Fewer clicks in the late game: POP standards, kit everywhere, buy on signing, network search
2026-11-10 10:33:33 +01:00
Frederic Jung
d2e642adb9
Merge remote-tracking branch 'origin/main' into claude/bulk-actions 2026-11-10 09:23:29 +00:00
Frederic Jung
1cf8d547bf
Merge pull request #332 from fjaeckel/claude/visibility
Show what is at stake in a renewal, and open a link's cities from its panel
2026-11-10 10:23:21 +01:00
Frederic Jung
a98e34711b
Keep puzzles and scenarios on plain shares; per-city share sums; tests follow the new traffic split
Puzzles, Architect runs and scenarios keep the table's split (their references and
pars were made with it). Week 2026-W44's reference now wins on day 185 (offers draw
from the wider campus list). The cache planner sums each city's own split.
2026-11-10 08:37:31 +00:00
Frederic Jung
870227100d
Route fuzz: leave the link panel's header city links out of the buttons both pages offer
They only change the view, and main's page has plain text there, so offering them would
make the two pages diverge on a screen that routes the same.
2026-11-10 07:56:26 +00:00
Frederic Jung
69cdb3e372
Grow sideways in the late game: localised eyeball traffic, spread AI campuses, PNIs by router, spill tiers
Traffic to networks that sell to homes now starts where their users live (#48),
giant AI circuits come from campuses in 34 metros and less often from crowded
ones (#61), a PNI bundles eight members per router up to 32 (#323), and
RouteScript spill tiers move overflow onto detours within a latency budget (#136).
2026-11-10 07:25:21 +00:00
Frederic Jung
d8223bad04
Tests: route fuzz compares the customer catalog, day steps waits longer for its trial
A new customer type changes which offers a seeded late-game draws, so the
fuzz games cannot play move for move like main (as with a world change), and
the sales-trial race in day-steps comes on day 46 instead of before day 20.
2026-11-10 07:14:36 +00:00
Frederic Jung
32b0b282f8
Bulk actions for the late game: POP standards, kit everywhere, buy on signing, network search
- POP standards by kind (micro, medium, regional hub), one button per POP and one per kind in Utilities (#315)
- Redundancy kit at every POP from Utilities, and in the intern's template (#317)
- Offers that need a generator, second router or second site can buy it and sign (#241)
- The intern's Light more fiber order can leave new fiber dark (#316)
- Search and connected-only filter for a POP's transit, exchange, PNI and cache lists (#199)
- The link panel moves on to the next parallel link after a decommission (#119)
2026-11-10 07:03:57 +00:00
Frederic Jung
e51510a115
Strict latency contracts: big late-game customers who pay for a latency SLA (#137)
From customer level 7, low-latency wholesale routes ask for 1.6 or 3.2 Tbps
between two cities with the latency limit trading links already have
(REQS.lat on the circuit latency compute() measures). They pay about three
times a hyperscaler DCI per Gbps on the same route, never grow past 3.2 Tbps,
and every day over the limit after the provisioning grace credits a day's fee
and costs extra patience. New rule F9 in gameplay-rules.
2026-11-10 06:56:02 +00:00
Frederic Jung
d086fcbd92
Show traffic, price per Gbps and path terms on renewal haggles; link panel city names open the city
Renewal haggles in Deals now show booked and served Gbps (sites for SD-WAN), the
price per Gbps now and asked, and the latency limit and path terms the customer
signed for, each ticked as the network stands today (#292).

The two city names in the header of wave, dark fiber and virtual circuit panels
are buttons that open that city (#196).
2026-11-10 06:51:34 +00:00
Frederic Jung
80baa970e7
Merge pull request #331 from fjaeckel/claude/fix-329
Say why a link is down when a closed border took it (#329)
2026-11-10 07:40:27 +01:00
Frederic Jung
36629195cc
Say why a link is down when a closed border took it (#329)
The Gulf spat and Russia's sovereign internet drill take links down in
linkDown(), and the map draws them broken, but the link panels only
explained cuts and incidents, so a Doha–Abu Dhabi wave looked healthy
in its panel with no way to fix it. The panels now show a 'Border
closed' section with the days left, and the wave and dark fiber modals
warn before leasing across the closed Qatar border.
2026-11-10 02:02:10 +00:00
jvanvik
9601345201 Review fixes for the small-fix batch
Some checks failed
CI / plan (push) Has been cancelled
CI / build (push) Has been cancelled
CI / translations (push) Has been cancelled
CI / part (push) Has been cancelled
CI / test (push) Has been cancelled
CI / timings (push) Has been cancelled
What an IPv6-only swap still owes is set aside for every job after it,
not only for the next swap. The intern's shift reads it once (X.ow in
opsShift(), refreshed when the build standard order starts a swap) and
every standing order's can() keeps it above the cash floor, whoever
started the swap; the sheet's button checks it for every job of the
click. Before, the same click or the next shift could spend it (a
generator, a line system swap), and the swap then paid its routers
under the floor or waited for weeks. ip6Owed() is 0 while IPv4 is
plentiful, when the swaps wait anyway.

satOnly() counts a fiber or cable to the island only once it has optics
of its own: dark glass carries none of the island's traffic, so the
selective peers keep refusing and an exchange session there stays
paused. ixSessions() looks up the city's satellite circuit once per
exchange instead of once per member.

The standing-order descriptions of the build standard and the optical
upgrade say a customer's wave holds a fiber, not any customer (new
labels, every language). The batch's CHANGELOG bullets get first
sentences that fit the in-app notes; the satellite bullet says PNIs and
your own exchange keep peering, the hint bullet that it shows up to
four teleports. German and Italian express.dim use the dictionaries'
own words, and the German and Spanish IPv6-only note reads naturally.
2026-11-09 23:43:53 +01:00
jvanvik
9496c26a25 Plans: what the batch of 2026-11-09 built, and what it decided not to
next-session.md listed the batch as in progress. It now lists the nine
commits with what each built and what its builder left out on purpose,
folds in the IPv6-only row's notes (item 4 is built; the NAT64 ratio is
not in the standard; a swap starts only with all of it to spare) and the
wave rule (dfWaveCust()), and keeps one small follow-up: two standing-order
descriptions still say no customer may ride a swapped fiber. ARCHITECTURE's
IPv6-only row names the build standard's v6 row.
2026-11-09 23:08:08 +01:00
jvanvik
417160f383 Build standard: a Broadband: IPv6-only row, rolled out by the button and the intern (#150)
The owed follow-up to IPv6-only broadband (next-session item 4). A new POP
target, v6, shown and planned only while IPv4 is scarce (rule ip4): bstdPlan()
makes a job per broadband city still on dual stack (ip6Todo()), the most
dual-stack homes first (the most behind CGNAT, the most addresses freed), each
calling ACT.ip6Go(). Its price is the whole swap (ip6Cost(), the city panel's
own figure); its mo is the IPv4 bill's change, counted one city after another
on a copy so the sum is all of them done.

ip6Go() pays nothing at the start (the routers are paid day by day), so these
jobs are marked later: the button and the std order start one only with the
whole swap in hand on top of what the swaps under way still owe (ip6Owed(),
X.can's new owed argument for the floor), and the order counts the whole swap
against its month's budget (not in what the shift paid up front). The button's
toast counts started swaps whole, as the quote did.

The sheet shows the row and a note only while ip4On(); bstdLine() counts it;
the MCP docs (bstdSet, bstdApply, popStd) name it. Strings in all six
dictionaries. Tests: tests/bstd-ipv6-only.test.js (order and price, the
button, budget and floor, rule off, saves, the sheet at 360 px portrait and
landscape in every language).
2026-11-09 23:02:19 +01:00
jvanvik
02b6c24d7b Intern: write the shift log as a reload keeps it, and drop opsTidy()
The day's log named every order that ran out of budget, and the week's tally
got an empty list for a job with no place (a rushed repair, a route server);
a reload keeps three places a kind and no empty lists, so opsTidy() trimmed
live state after every shift. The shift now writes it that way itself: the
broken orders are cut to three ([...X.broke].slice(0,3)), and W.wh[k] is made
only for a job that names a place. tests/canonical-state.test.js passes
without opsTidy() (a year of the big network with everything on, checked
every day), so it is gone.
2026-11-09 23:02:05 +01:00
jvanvik
286ae48207 Build standard: never take a fiber dark under a customer's wave; the intern no longer skips leased pairs and IRUs
The build standard's Apply could swap the line system on a fiber that carries a
sold alien wave or a Lambda Bazaar managed wave, taking those customers dark for
a day with no warning. The intern refused any fiber with any customer on it,
leased pairs and IRUs included, though a line-system swap cannot touch them.

One helper next to fiberOk(), dfWaveCust(), says whether a customer rides the
fiber's line system (every fiber type but glass: dfpair, pairs, capfib), and both
bstdDarkOk() and opsDarkPre() use it. bstdPlan() holds such a fiber (J.held) and
lists it in J.wv; the sheet and the MCP quote give that reason. The link
panel's own upgrade button (ACT.upSys) still swaps with a warning toast.
2026-11-09 23:02:02 +01:00
jvanvik
1f76639b8f Selective peers will not meet you where a satellite is your only way out (#83)
An island or remote town that only satellite circuits join to the rest of
your network (satOnly: no built wave, fiber, cable or pie dish there, its
fastest circuit otherwise) is a place many selective networks will not
peer: they would hand you traffic for your whole network to haul through
orbit. Like remote peering, the verdict is stable per network (a hash):
60 in 100 selective networks refuse a GEO hop, 15 in 100 a MEO one, and
every network that minds MEO minds GEO too. It is judged on what is built,
never on today's cuts, so the single-spur trap does not also pause your
peering mid-outage.

peerOk refuses new IX sessions and PNIs there with one line naming the
orbit and the circuit's round trip; ixSessions leaves an existing session
out while the island is satellite-only, without deleting it from S.peers,
so it carries again once a wave or cable is lit. Existing PNIs stay. No new
state, nothing for saves.
2026-11-09 23:01:51 +01:00
jvanvik
ae78e82ddb Express lightpaths: regen cards for their channels, and dirty connectors dim them (#58)
A regen site added to a fiber that already carries expresses now charges a
regen card for every express channel in that glass, as it does for the
fiber's own channels. One helper, regenAddCost(), prices it for the action,
the fiber panel's button and the MCP dry-run quote, so the three agree.
Lighting an express over existing regen sites already paid its cards
(xpCost); only adding a site later was free for them.

A dirty connector on a fiber is in the glass, so it now dims the expresses
riding that fiber by the same factor (capOf multiplies xpG by xpGlassF over
the express's fibers), and the express's panel names the fiber. The other
link-degrading incidents (MTU mismatch, microbursts, a marginal optic's CRC
errors) belong to the fiber's own routers and optics, which an express
bypasses, as the optic-failure incident already treats them, so they leave
expresses alone. The incident marks the connector with loss.glass=true;
sanitize keeps the flag only when it is true, so an old save's loss loads
as router-side, as it behaved before. A fiber that only carries expresses
can now get the dirty connector too (never the router-side variants), like
the backhoe and amp-hut incidents already find it.
2026-11-09 23:01:46 +01:00
jvanvik
2dc8274f34 The no-cable hint in the link window names the satellite (#83)
Upstream 3.3's hint for a coast where no subsea cable lands (#321) said only a
cable of your own could get to Iqaluit or Adamstown, and left satellites out at
Pevek, though a teleport reaches all three. Once teleports are on sale (level
2) and a bird you may rent from sees the city, the 'own' case says a satellite
circuit or a cable of your own can get there (a new string), and every case
adds the satellite line: the city panel's 'Your teleports can reach' with a
button per teleport to its order sheet (satOpen), or where to build one. Not
in puzzles, and not before level 2, like the rest of the satellites.
2026-11-09 23:01:43 +01:00
jvanvik
7930d332f1 IPv4 notices in the notifications open the address space (#150)
The IPv4 toasts (CGNAT, out of IPv4, a renewal that could not grow, an
IPv6-only city done) carry an Address space button, but openOf() did not know
ip4Open, so their line in the NOC's notifications had no Open. It now maps to
a log target of its own, 'ip4', like 'ops' for opsOpen: Open runs ip4Open, the
bank scrolled to its Address space (just the bank if IPv4 is off since).
sanitize() keeps the new target. ip4Open is also on the NOC window's list of
actions it may run in the game, should a dashboard tab ever draw it.
2026-11-09 23:01:43 +01:00
jvanvik
27ffa33d7c Dark mode: red text and the market's heat tags read on the dark panels (#80)
Red warning text used var(--bad), 3.8 to 4.8:1 on the dark cards and tints.
Every text use now takes var(--tx-red,var(--bad)): light mode keeps --bad,
dark gets #FF8E9B (5.65:1 or better on paper, soft and every tint). --bad
stays the fill under white letters (buttons, counters, bars).

Lambda Bazaar's Hot and Cool tags kept their light pastel chips at night.
They now use the dark tints (--tint-o, --tint-b) with --tx-amber and a new
--tx-blue, keeping the same colours by day.

The dark-mode test checks the tags, the text tokens on every dark card, that
no tag keeps a bare pastel fill, and that no red text in --bad is left in the
styles or the game's markup.
2026-11-09 23:01:43 +01:00
jvanvik
8068a45abd Plans: the server-run design in the repo, what is left now, and the fork's files
- docs/plans/server-run.md: the server-run design, which lived only outside
  the repo, with a status at the top (T1 and T2 merged, T3, T4 and the
  integration waiting for the go; the four answers; the questions still
  open) and a section on what building T2 changed: a checkpoint needs more
  than route memory (rt carries pt, sl, ord and rk), who a worker exit
  counts against, the budgets now over, the contract additions, the open
  path-window question and what the shared calendar changes. The answers
  are marked where sections 0, 1 and 14 ask; probes are named, not pathed.
- docs/plans/next-session.md: rewritten to match main at 3e30621: what is
  built, the answers, the holds, the nine open questions, what is in
  progress and next, and only the limitations that still hold.
- docs/ARCHITECTURE.md: a table of the fork's own files (build standard,
  dark mode, IPv4, IPv6-only, express fiber, satellites, multiplayer,
  server-run play, the session server and the engine), kept apart from
  upstream's tables so merges stay clean.
- docs/MULTIPLAYER.md: server-run play is being built and not switched on.
2026-11-09 23:01:43 +01:00
jvanvik
3e30621684 Test timings of the server-run engine's tests and the built-ins test
Some checks failed
CI / plan (push) Waiting to run
CI / part (push) Blocked by required conditions
CI / build (push) Waiting to run
CI / translations (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / timings (push) Blocked by required conditions
Container image / gate (push) Has been cancelled
Container image / test (push) Has been cancelled
Container image / publish (push) Has been cancelled
Seconds per file from a full npm test --timings run on this machine
(every file at once), for the shard split.
2026-11-09 22:22:40 +01:00
jvanvik
77f4035853 Six actions look up their city among the network's own POPs only
launchBB, addSite, addRouter, upRouter, addGen and myIxUp read S.pops[city]
(S.myIx[city]) without checking the key, so a city named '__proto__' found
Object.prototype and wrote to it (launchBB left Object.prototype.bb behind,
and every for…in after it saw that), and 'constructor' spent cash on
statics of Object. Only an MCP agent or a request to a server-run network
can send such a city; the page's own buttons never do. Each now takes the
POP only when it is an own key (own(), as sanitize() does).

tests/act-args-builtins.test.js sends every action an agent may send with
'__proto__', 'constructor' and 'prototype' in each usual arg and checks
that the page's built-ins stay as they were; without this change it finds
exactly these six. No state, strings or saves change.

Performance on the big network against 61e31c5 (npm run perf, headless,
median of 15 runs, ms):

| What | Base | This | Change | p |
|---|--:|--:|--:|--:|
| Routing: compute() | 25.4 | 28.1 | +11% | 0.90 |
| One game day: dayTick() | 27.8 | 28.7 | +3% | 0.77 |
| An action: after() | 1.82 | 1.77 | -3% | 0.77 |
| Side panel and left list | 58.8 | 57.1 | -3% | 0.013 |
| NOC dashboard tabs | 95.9 | 95.9 | +0% | 1.00 |
| Map at three zoom levels | 3.49 | 3.30 | -6% | 0.53 |
| The NOC intern's shift: opsDay() | 3.45 | 3.52 | +2% | 0.80 |

Routing results are identical to the base; no slowdowns beyond noise.
2026-11-09 22:18:56 +01:00
jvanvik
9597d89079 Server-run engine: review fixes
The review of track T2 found these; each has a test in tests/mp-sim-*.

- Built-ins: an arg, array entry or draft that is '__proto__', 'constructor'
  or 'prototype' is refused by the envelope check and again by the realm
  (free text may still say them). After every realm call the trampoline
  checks the realm's built-ins against what they were at load; a realm
  whose built-ins changed answers {srvErr, polluted} and is replaced from
  the worker's mark like one that timed out. S as one JSON per key is a
  null-prototype object, so the epilogue's for…in never reads a prototype.
- A realm that cannot be built again is never used again: rebuild() tries
  once more without the packed R, and when that fails too the network is
  dropped (NO_REALM), and the engine tells the host (opts.onLost).
- A mark that fails or runs out of time changes nothing: it clears the old
  mark first, the realm is built again from its own save, never from an
  older mark, and the reply names the mark. A day rebuilds only from its
  own attempt's mark.
- A day whose alone or nets is not a list is refused whole (ERR); a throw
  in a load or day step answers that call, never ends the worker.
- An exit counts against the session the worker was running (the worker
  says so before each job and step), else as before. Workers of their own
  are capped (opts.maxOwn, 4): past that a session is given up.
- A worker that exits before it is ready is started again after a pause
  that doubles; after 5 in a row every call answers SIM_DOWN.
- The game text is read and compiled once, in createEngine: a src/ that
  does not compile throws there, and every worker, also one started after
  an exit, runs the game engine.simId names.
- A damaged route memory never breaks a save that loads (routed from
  nothing, logged), and only a server network loads (S.mp.sim, Normal).
- Routing memory (UI.rk, UI.rkR) is kept by the in-place restore and
  carried in rt (rk), so a reloaded or rolled-back network skips the same
  routings as the one that kept going.
- A fresh realm takes over the fx of the one it replaces (the mark's after
  a failed call, all of them after a read): badges, windows and toasts
  waiting for a page are not lost to a timeout.
- Windows: the stand-in elements answer querySelector from what was
  written (a [data-x] marker) and have a working classList, never the
  inert proxy that said every window is open. A request's ctx may name the
  open window, ctx.win = {k, ui} (mp-sim-acts.js WINDOWS: bstd, routing,
  charter, ops, pie), with the view state only the page holds (the
  intern's POP, the pie window's tab and POP), checked in the realm. This
  is an addition to the contract of design 5.8 that the page (T4) sends.
  The stand-in is hidden again after an act.
- xpBuild's via is a TEXT arg (256): a six-span express fits.
- actDone, askDone and pulled carry ms, the worker time of the call;
  engine.mem() and engine.has(code, nid) are public; prefs() passes a
  realm's err through; after close() every call rejects CLOSED.
- The fake engine fails as the engine does (NO_REALM, ERR, a load without
  a save, a day of an unknown session or naming an unloaded network,
  GAVE_UP, SIM_DOWN, CLOSED, onLost), its greet says its one-shots once and
  never 'told'; a test runs the same edge calls on both.
- SIM_DRAFT is built from DRAFT_TYPES.
2026-11-09 22:16:52 +01:00
jvanvik
3b8c331556 Auto-TE and the chaos monkey's leaving are written as a reload makes them
Two places left a key in a shape that sanitize() repairs on the next load, so
the live game was not its own save (the server-run engine refuses such an
action at its gate, and its strict day check would refuse such a day):

- buyTE wrote S.te as {on, day}; a reload adds script:''. It now writes the
  script slot itself (src/game/90-actions/30-route-script-and-tools.js).
- mkLeave turned the monkey off but kept start, until, snip, n, hurt and c;
  sanitize() keeps only next and on for a monkey that is away. It now leaves
  S.monkey as {next, on:0}, after the toasts that still read the visit's count
  (src/game/85-incidents/40-chaos-monkey.js). This covers the visit running
  out, the banana and the rules sending it home.

No new state field, nothing for old saves: both keys load as before. Nothing a
player sees changes, so no CHANGELOG bullet.

Tests: tests/backbone-core.test.js (S.te after buyTE equals what a reload makes
of it) and tests/chaos-monkey.test.js (S.monkey after each way home: outlasted,
hurt, sent home by calmer rules, bribed). Both fail without this change. The
server-run tests take their workarounds out: buyTE and the banana pass the gate
and leave the network the page leaves (tests/mp-sim-acts.test.js, the former
todo), the 60-day realm-vs-page plan clicks buyTE on day 21 instead of setting
S.te, and the gate audit no longer excuses either act.

The Pie in the Sky line the review also named (60-pie.js:66, S.monkey.n++ on a
monkey that is away) is not reachable: its only caller fires a laser incident
behind mkOn(), so it is left as it is.

Performance (npm run perf -- --base-ref 61e31c5, headless, big network, median
of 15 runs, ms):

| What | Base | This | Change | p |
|---|--:|--:|--:|--:|
| Routing: compute() | 27.3 | 26.1 | -4% | 0.51 |
| One game day: dayTick() | 29.7 | 30.1 | +1% | 0.71 |
| An action: after() | 1.96 | 1.86 | -5% | 0.48 |
| Side panel and left list | 62.0 | 59.2 | -5% | 0.023 |
| NOC dashboard tabs | 110 | 110 | +0% | 0.93 |
| Map at three zoom levels | 3.69 | 3.90 | +6% | 0.43 |
| The NOC intern's shift: opsDay() | 4.06 | 3.95 | -3% | 0.11 |

Routing results identical to the base; no change beyond noise.
2026-11-09 20:47:42 +01:00
jvanvik
72f31e809b Server-run engine: every call answers, and a crashing load gets its own worker
A load whose networks did not all check out could hang its session for good, a
worker could spin on a job it could never run, a session whose load crashed its
worker never got a worker of its own, and an unload followed at once by a load
(a language change) lost the session's place or never answered. Fixed:

- Worker: a load call is checked whole before it touches anything. One that
  names no network, or one twice, is refused (ERR) and every realm stays as it
  was. A network without a save now answers err (broken) like one whose save
  does not load, and the others load. A network marked loading with no load
  under way answers NO_REALM instead of waiting for ever.
- Worker: it goes on only while something ran. If a job were ever still
  waiting when nothing could run, it is answered (ERR, logged) rather than left
  pending, and the worker no longer busy-loops on it.
- Engine: a session is on its worker from the moment its load is sent. A worker
  exit counts against the sessions whose load was under way (else against every
  session it held), so a save that crashes its worker gets a worker of its own
  after two exits and is given up (GAVE_UP) after a third, while the sessions
  that only shared the worker lose their realms but not their place in the pool.
  Loads under way count for placement.
- Engine: an unload no longer drops the placement of a session whose next load
  is under way, so an unload and a load sent back to back stay on one worker; a
  worker of its own is retired only when no call is pending on it (a pending
  call there used to never settle).
- Engine: a message that cannot be sent rejects (ERR) and leaves nothing pending.
- Realm: a what-if puts UI.hotMap back too (teSlop's trial left its own).
- Realm: a network in a language this server has no dictionary for plays in
  English, as the page does, instead of loading broken.

Tests (tests/mp-sim-engine.test.js): a malformed load changes nothing and every
call of the session answers within 3 s, with the workers idle after; an unload
and a load back to back keep the session on its worker; a session whose load
takes its worker down twice gets a worker of its own, then GAVE_UP, while the
bystander is never blamed; an ask leaves UI.hotMap as it was; a network in an
unknown language loads in English. Each fails on the engine before this change
(the worker's alone: the hang; the engine's alone: the placement and the exits;
the realm's alone: teSlop's hotMap and the language).

The two drafts no test played are played now (tests/mp-sim-acts.test.js): a
premium border crossing into Hong Kong (buildLink with cnPrem) and the AI's own
script deployed as it wrote it while it drops most of the traffic (teDeploy with
slop, on a small network with one capped transit port), each compared byte for
byte with the page's clicks, and both read in the DRAFTS check (nothing is left
unplayed).

Runs, each file alone under an 8G cap: mp-sim-engine 16/16 (11.6 s),
mp-sim-contract 8/8, mp-sim-acts 5 + 1 todo (10.9 s), mp-sim-determinism 6/6
(53.4 s).
2026-11-09 20:47:31 +01:00
jvanvik
c5c7ea9508 Server-run engine: a restored network plays on exactly as before
A network loaded from its checkpoint drifted from the one that never stopped:
after a checkpoint on day 1, 2 or 5 its R differed at once (bizDem at Ashburn
6426 against 26, then cityDem, citySrv, tNet), and from the next day S too
(cash, eyeball growth). Three causes, each shown by a probe:

- R after a day is the R of the day's last routing, made before the day's end
  changed S (customers who left or signed, moods, bills, transit history) and
  routed from the memory of the R before it. srvLoad routed the saved S again
  from R's own memory: another R, which the next day reads (sfOf for eyeball
  growth, the peering share). Every compute() in the realm now 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 routing point (pt: the memory,
  the keys that changed since, the keys S did not have then), and srvLoad
  routes that S again from it: the same R, byte for byte. The old restore test
  checkpointed after day 10, where a failure or event routed again at the end
  of the day and nothing changed after it: it passed by luck.
- The sales desk's tried offers (UI.slTried, an offer that did not fit waits a
  week) live outside S. A fresh realm forgot them and the desk tried other
  offers. rt carries them (sl); a day mark keeps them and the in-place restore
  after a throw puts them back (before, a parsed S dropped them).
- A save and a reload give some keys back in another key order (a customer's
  defaults go last, the intern's week tally in its own order), and the week's
  report lists the tally in that order. At a checkpoint rt carries the live
  text of each such key (ord, srvGate's round trip, about 8 ms), taken on load
  only where it holds what sanitize() made of the save. A fresh realm after a
  timeout takes the mark's own text the same way (live).

The plain game drifts across a save and a reload too (jsdom: from the first
day after it; the page routes a reloaded S with an empty R and keeps no desk
memory): a game property, so the engine carries what is missing.

The envelope keeps its shape {s, uidN, rt, last, day}; rt keeps R's own route
memory, so an older checkpoint loads as before (close, not exact). Big network:
the checkpoint grows from about 42-49 KB gzip to 54-79 KB (rt 7-29 KB; the
whole R would be 375 KB), srvSave from 2-2.5 ms to 7-8 ms, a load by one
routing. A day with its mark costs the same (big 39.8 -> 37.8 ms, busy
90.0 -> 88.8 ms, within noise: the day mark joins per-key JSON now, which pays
for the routing point).

Tests: the restore test checkpoints after days 1, 2, 5 and 10 of the scenic big
network and of the same network busy (intern on every order, the desk signing
on its own, failures, events, an attack), those after days 2 and 10 right after
an action and a what-if (sent to the copies too), each compared byte for byte
at once and 10 days later (SIM_LONG: after every day to 30, 60 checkpoints). It
fails on the old engine, and without any one of the three parts. The retry test
plays busy networks (fails without the desk memory in srvRestore). The market
checkpoint compares bytes too; canon() is gone.
2026-11-09 20:16:38 +01:00
jvanvik
065c922287 Server-run play, part 2: the engine
The engine that runs every network of a server session (server-sim design,
section 4): each network in its own vm realm, realms in a small pool of
worker threads, a promise API for the session host. Nothing uses it yet;
the plain build and the game are unchanged (no file under src/).

- scripts/lib/mp-sim-realm.js: one network in a DONT_CONTEXTIFY realm
  running the plain page's game (never the MP page's client folder), with
  recording DOM stand-ins, no-op timers that count, and the srv... calls:
  load from a checkpoint (route memory seeded, then routed), begin a new
  network, marks and restores, the day as a page runs it, the action
  pipeline with drafts, arming, the sanitize gate and rollback, what-ifs
  that put S, R, the dice and uidN back, pulls with top-level key diffs,
  slim R and flow records on demand, fx captured and bounded, saves, cards.
- scripts/lib/mp-sim-worker.js: realms per session in one worker, days one
  network at a time with other messages between them, loads and unloads
  waiting for a session's day, time limits; a throw goes back to the mark
  in place, a timeout gets a fresh realm (new epoch) carrying the old R, a
  day is retried once and the network broken after a second failure.
- scripts/lib/mp-sim-engine.js: createEngine() with the fake engine's API,
  placement by realm count, every pending call rejected when its worker
  exits, a worker of its own after two exits in an hour; snapWith() joins
  the host's clock, roster and since to a realm's snapshot.
- Contract: a pulled snapshot is the realm's half (the host adds clock,
  roster, since); haptic fx carry milliseconds; the fake engine follows,
  with close() and snapWith(). The button crawl moved to tests/lib.
- Tests: realm vs jsdom byte for byte over 60 scenic big-network days with
  actions; restore; retry after a throw or a timeout; realm order; a timer
  audit and the gate over a sweep of sent buttons (SIM_LONG=1: a year and
  every button); captures, rollbacks, asks, selection reports, ordering,
  bounds, pollution, worker exits; the act tables against the game.

The gate found two keys the game writes in a shape a reload repairs (buyTE's
S.te, mkLeave's S.monkey): game fixes for the integrator, kept visible as a
todo test and a list in the audit.

Rebased onto the 3.3.0 merge (61e31c5): the engine itself needed no change. A
realm still routes in the game's own code (no route worker, no saves), the
route cache that now keeps list orders from day to day leaves a checkpoint and a
retry the same, and the capacity market and moved customers play in a realm as
on a page, under the strict gate. The tests needed three things: an old save's
first days earn the new traffic badges, which the unwatched network's snapshot
keeps; the restore test compares JSON text with sorted keys instead of a
deep-equal of two networks (a diff of gigabytes when they differ); and the crawl
opens the windows that move a customer, with a new test playing the market's and
the path moves' acts, 40 days of sales and a checkpoint against the page.
2026-11-09 19:30:38 +01:00
jvanvik
61e31c53d3 Merge upstream: Lambda Bazaar, traffic badges, moving customers and faster routing (3.3.0)
Some checks are pending
CI / plan (push) Waiting to run
CI / part (push) Blocked by required conditions
CI / build (push) Waiting to run
CI / translations (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / timings (push) Blocked by required conditions
Container image / gate (push) Waiting to run
Container image / test (push) Blocked by required conditions
Container image / publish (push) Blocked by required conditions
CHANGELOG.md: upstream's released sections as they are; main's 11 Unreleased bullets kept under Unreleased.
scripts/lib/route-fuzz.js: upstream's skip of dashboard tabs the base lacks, plus main's trimming of args the base's buttons lack.
src/game/10-catalog/40-ports.js: upstream's one-pass portsAt(); an express still takes ports per channel at its ends.
src/game/10-catalog/60-reach-and-subsea.js: upstream's dfLit/dfCap0/dfOn (managed waves carved out); capOf() keeps xp and sat.
src/game/60-features/80-new-game.js: upstream's vol and cm in a new game, with main's ip4, rgen, mp and saved-shape fields.
src/game/60-features/95-standing-orders.js: upstream's portsAt, cachePlan and promiseCheck, inside main's build-standard routers order, optup marks, opsDarkPre and decom gone list; opsPairs still leaves satellites out.
src/game/80-simulation/30-compute.js: upstream's routing core; main's satellite edges (SATN) pass into it, express risks and sat/ip4 money stay.
src/game/80-simulation/29-route-core.js: main's satellite latency note moved into the core, where upstream moved the flow loop.
src/game/80-simulation/40-billing.js: main's linkCut() and xp/sat in linkDown(), with upstream's dfOn().
src/game/80-simulation/50-sanitize.js: upstream's cmClean listings and cmFix/volFix; main keeps the xp/sat kinds, mpSanitize, ip4Fix and satSanitize.
src/game/80-simulation/60-requirements.js: upstream's shared diversity graph; an express link carries the list of trenches it rides.
src/game/91-save.js: upstream's saves in the worker, except a multiplayer session network, whose text is made on the page (mpSave) so the server gets the very save the slot holds; bootNotes() kept.
src/game/91-slots.js: upstream's slot text and day, with main's mp badge on a slot.
src/game/93-ui/70-link-panels.js: a fiber says both its managed waves and the expresses it carries.
src/game/94-dashboard/60-dashboard.js: upstream's carried tile, main's themed demand line.
src/game/95-modals/70-link-modal.js: main's Express tab, then upstream's hint for a coast no cable lands on (#321).

After the merge:
- Moving a circuit: a path over an express shares the trenches of the fibers it rides, so it is never called fully diverse from a path along them (test in express-fiber).
- The capacity market and moving customers leave the slots expresses hold (test in express-fiber; no code change needed).
- The NOC log keeps only the kinds a reload keeps: the market's info/warn news is a plain line, live as after a reload.
- New acts classified for server-run play: market and path moves sent, marketOpen and pathOpen local; pathPin's path may be longer than 64 characters.
- Server-play fixtures written again (new cm and vol fields); the dark-mode test reads mapStill()'s three states.
- A big multiplayer network that moved on still pushes its save to the server (test in multiplayer).
- The full suite ran on jsdom 31.0.0 and playwright-core 1.65.0, the versions the merged lockfile pins.
2026-11-09 19:04:21 +01:00
Frederic Jung
e0671c02be
Move customers between paths, and big networks route in half the time (3.3.0) 2026-11-09 13:37:12 +00:00
Frederic Jung
1579f3743b
Merge pull request #311 from thesysadmindev/move-customer-path 2026-11-09 13:15:55 +00:00
Frederic Jung
b087d4b4e5
Merge pull request #327 from fjaeckel/dependabot/npm_and_yarn/jsdom-31.0.0
Tools: Bump jsdom from 30.1.3 to 31.0.0
2026-11-09 13:39:07 +01:00
Frederic Jung
4630ba99af
Clear the open code scanning alerts
- auto-release.yml: the by-hand test run passes github.sha (what it got anyway) instead of an
  output that also reads workflow_run.head_sha, so CI never checks out a ref a workflow_run
  handed over in a job that uses caches (cache poisoning, 7 alerts in ci.yml).
- tests/harness.js: the script splitter also matches end tags like </SCRIPT > (bad HTML
  filtering regexp).
- Tests paste the fixture saves into the page with lit(), which escapes what could end a
  script or a string, instead of plain JSON.stringify (improper code sanitization).
2026-11-09 12:36:08 +00:00
dependabot[bot]
6a44da4017
Tools: Bump jsdom from 30.1.3 to 31.0.0
Bumps [jsdom](https://github.com/jsdom/jsdom) from 30.1.3 to 31.0.0.
- [Release notes](https://github.com/jsdom/jsdom/releases)
- [Commits](https://github.com/jsdom/jsdom/compare/v30.1.3...v31.0.0)

---
updated-dependencies:
- dependency-name: jsdom
  dependency-version: 31.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-09 12:35:14 +00:00
Frederic Jung
f00bc733d0
Two CSS checks read jsdom 31 as well as 30
jsdom 31 (#327) serializes calc() with its terms sorted and expands the
overflow shorthand into overflow-y; the diagnostic readout and puzzle
dock tests now accept both.
2026-11-09 13:30:28 +01:00
Frederic Jung
d6b08dded3
Kept exit orders also check each exit's kind
An exit that turned from an exchange into a PNI at the same place in the list, city and
preference kept the order made for the exchange, which sorts behind a PNI at the same
distance, so the cached routing could differ from routing without the cache (#320 review).
The exit signature now includes the kind. Also drops the unused e.vis.
2026-11-09 10:40:39 +00:00
Frederic Jung
249ad4d478
Merge pull request #320 from antt0n/perf/routing-core 2026-11-09 10:21:20 +00:00
thesysadmindev
d98b11a1f7
Merge branch 'fjaeckel:main' into move-customer-path 2026-11-09 20:32:27 +11:00
Frederic Jung
36b9b170c5
Merge pull request #326 from fjaeckel/dependabot/npm_and_yarn/tools-e5c9720653
Tools: Bump playwright-core from 1.64.1 to 1.65.0 in the tools group
2026-11-09 09:27:02 +01:00
Frederic Jung
3dbeaeeeb7
Merge pull request #328 from fjaeckel/dependabot/github_actions/actions-aa5920e445
CI: Bump anthropics/claude-code-action from 1.0.268 to 1.0.269 in the actions group
2026-11-09 09:26:47 +01:00
Christopher Hawker
3554e9f700 Moving waves checks the room the broker would sell: bandwidth for managed waves, and what is kept back
Managed waves need a channel as big as the wave and their bandwidth spare after your own traffic and
the share kept back, on leased fiber too. A move bumps CM_V so their capacity follows them, merging
needs the same size, and alien waves leave the kept-back channels alone. Pinned customers' badges
share one path graph per routing result.
2026-11-09 16:45:08 +11:00
Christopher Hawker
93d7c87dc7 Move a customer to another path between the same two POPs
Alien waves and leased fiber pairs sit on one fiber (b.link), so they move to
another working fiber between the same cities, under the rules for selling
capacity on it. Circuits have no link of their own, so moving one pins it to a
list of cities (b.pin), which routing follows while every link on it is up. When
one is down the circuit follows routing, and it comes back by itself.

The window lists the most diverse options first, compared by trench. Moves are
free and instant, and contracts keep their price.
2026-11-09 16:23:59 +11:00
dependabot[bot]
5d76d3afc8
CI: Bump anthropics/claude-code-action
Bumps the actions group with 1 update: [anthropics/claude-code-action](https://github.com/anthropics/claude-code-action).


Updates `anthropics/claude-code-action` from 1.0.268 to 1.0.269
- [Release notes](https://github.com/anthropics/claude-code-action/releases)
- [Commits](c0949c50a7...61a9c274fa)

---
updated-dependencies:
- dependency-name: anthropics/claude-code-action
  dependency-version: 1.0.269
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-09 00:57:31 +00:00
dependabot[bot]
afd71a0899
Tools: Bump playwright-core from 1.64.1 to 1.65.0 in the tools group
Bumps the tools group with 1 update: [playwright-core](https://github.com/microsoft/playwright).


Updates `playwright-core` from 1.64.1 to 1.65.0
- [Release notes](https://github.com/microsoft/playwright/releases)
- [Commits](https://github.com/microsoft/playwright/compare/v1.64.1...v1.65.0)

---
updated-dependencies:
- dependency-name: playwright-core
  dependency-version: 1.65.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: tools
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-09 00:57:10 +00:00
Frederic Jung
ef6bd750ea
Merge pull request #324 from fjaeckel/claude/fix-321
Say how to reach a coast where no subsea cable lands yet (#321)
2026-11-08 19:25:06 +01:00
Frederic Jung
1e15c61e3d
Merge remote-tracking branch 'origin/main' into claude/fix-321
# Conflicts:
#	CHANGELOG.md
2026-11-08 18:20:34 +00:00
Frederic Jung
9cdab7235b
Merge pull request #325 from fjaeckel/claude/fix-322 2026-11-08 19:19:06 +01:00
Frederic Jung
71e7dcec59
Say how to reach a coast where no subsea cable lands yet (#321)
Iqaluit, Adamstown, Murmansk and the Russian Arctic towns have a beach but
no cable, so the link modal listed nobody to hop through ("Cables from
Iqaluit reach . Hop through one of those."), and from the other side it
suggested hops that could never get there. Now it says to go overland when
a road leads in, or that only your own cable reaches it, with the own-cable
button (or its level hint) underneath.
2026-11-08 17:57:32 +00:00
Frederic Jung
d971ded259
Hold the lay ship through a construction delay instead of restarting the lay (#322)
A delay that hit your own subsea cable while it was being laid moved the
whole laying stretch later: the ship vanished, the laid km went back to
zero and the survey and factory could be hurried and paid for again. The
delay now holds the ship where it is (l.lay: start, share laid, resume
day), so laying picks up after the delay. Old saves without the field lay
as before; sanitize() repairs or drops it.
2026-11-08 17:57:27 +00:00
Frederic Jung
4292cd4c74
Merge pull request #319 from antt0n/perf/intern-and-promises 2026-11-08 11:00:54 +00:00
Frederic Jung
a1c0afbbbf
Merge pull request #318 from antt0n/perf/page-stays-free
Big networks hold the page less: ambient map at 30 fps, saves and transfers handled by the worker
2026-11-08 11:50:15 +01:00
Antoine
44116103be
The intern and customers' promises counted once per network: ports, caches and PNIs in one pass, shared searches
The game plays exactly as before.

* The NOC intern plans every POP in one pass: portsAt() counts router ports for all cities at once (routers, ports
  and cache orders; the ports job keeps ports in use and reserved by city between two jobs), cachePlan() sorts the
  boxes by POP once and cityShSum() sums a city's shares once per table, pniFlows() reads every POP's flows from
  routing's columns (R.flc) in one pass and pniWant() gives the weekly PNI round its sort key from typed columns.
  pniBatchRun() lets a frame through every few networks; pniQuote() looks existing PNIs and ports up from the batch.
* A dark fiber's capacity asks optG() once per run of identical optics (dfLit()); linkDown() and ownGlass() ask
  dfOn(), whether it carries anything for you, without the sum unless an optic is out or managed waves are sold on
  it. terrIslands() tests !l.sub first.
* Latency: latGraph() lists each city's links once in S.links order (typed arrays), latRun() is the same search with
  the same sums, latPairs() searches once per city for a boutique's finance routes and the latency offers.
* Diverse paths: divGraph()/divOn() number the cities and risks once; promiseCheck() shares a diversity graph, the
  land islands and one latency search per origin across every customer when the intern weighs taking a fiber out,
  and spots0() shares the graph for sovereign offers.

Tests: day-steps (cache planner, ports at every POP and flows from columns equal the old ways; the PNI round through
pniBatchRun), fiber-lit-and-latency (with failed optics and managed waves), shared-promise-checks, intern-personas.
2026-11-07 23:55:37 +01:00
Antoine
1edf0abb54
Routing core made once, list orders kept, and Auto-TE's detour searches cut: same routing, much less work
The game plays exactly as before.

* The core of compute() (rankPass, directPass, sendGroup, send, push, carry, altPath) is ROUTE in 29-route-core.js,
  built once by routeCore(): made inside compute() they were new functions every call and V8 threw away their code.
  Exits are read by number from typed columns (USED, CAPX, CIX, HPX, VISX), each list is an object of one shape.
* The route cache keeps, for each list and source city, the order routing tries it (xOrder()); a list whose exits,
  cities and preferences are unchanged on the same graph keeps its orders when other exits change (rcExitKeep()).
* Auto-TE: pairs with no detour are marked (TEF), exits that cannot help are skipped (dud()), one failed search
  answers the next ones, dijkstraTo() searches in arrays kept between calls, teSearch() runs on the graph as flat
  arrays and picks up where the last search from the same POP stopped.
* The PNI/IX tie-break (#298) reaches the core.

Tests: route-cache, routing-reference, speed (the fast core against the plain path, Auto-TE on crowded meshes with
POPs outside the core, picked-up searches counted).
2026-11-07 23:51:35 +01:00
Antoine
b9d6319302
The page stays free while big networks play: ambient map at 30 fps, saves in the worker, less to carry back
The game plays exactly as before; only what holds the page changes.

* mapStill() tells three cases apart: still (drawn once a second), ambient (only the animation clock moved: drawn at
  most every 29 ms, so 30 fps on 60 and 120 Hz screens) and moving (camera, pointer, selection, network: every frame).
  The animations follow the clock, so they keep their speed.
* save() skips the storage write when the text is the one the slot already holds (SLOT.txt) and no write is on its
  way; leaving the page still writes. A big autosave that moved on is packed, turned into text, stamped and
  compressed in the route worker (rwSave(), rwGzip()); the page only writes what comes back. A lost worker hands its
  pending saves back to the page (rwSaveBack(), rwGzBack()).
* Less crosses back from the worker: R.efg stays there while R is its own last answer (RW.wR, efg 0), R.egDesc comes
  as 0 or as the entries that changed (rwDescOut()/rwDescIn()), what crossed each link travels as typed arrays decoded
  on demand (rwLOut()/rwLIn()), and the full ports (hotMap) come along with R. Every message is read in order
  (rwMsg()), so both sides always hold the same last answer.
* Idle frames build the diverse-paths map and the latency floors a millisecond at a time (diversityWarm(),
  latWarm()), before the first offer asks.
* Diagnostic info shows how fast days really come: speed asked, speed held, how long a day takes (15-day-pace.js).
* perf-bench: "The NOC intern's shift: opsDay()" and, in Chromium, "One game day in play: page time only", a day
  played with the real route worker counting only the time it holds the page.

Tests: frame-pacing, day-pace, save-size, persist, route-worker (efg as typed arrays, hotMap from the worker),
day-steps (a second page plays the worker: answers without R.egDesc, with only its changes, posts without R.efg,
renewal haggles answered through the worker), intern-dark-fiber-worker, webgl-zoom-sprites, speed.
2026-11-07 22:22:51 +01:00
Frederic Jung
d03dde6fcd
Release deploys again when its tests were skipped on purpose
A skipped job skips every job that needs it, even through one that runs
anyway: since auto-release passes tested=true, the tests job is skipped,
build ran with always(), and deploy (no condition of its own) was skipped.
v3.2.0 built and never went live. Deploy and IndexNow now run whenever
the job before them succeeded.
2026-11-07 14:38:19 +01:00
Frederic Jung
91b2afe706
Lambda Bazaar capacity market and traffic badges (3.2.0) 2026-11-07 14:11:01 +01:00
Frederic Jung
2f738dceda
Lambda Bazaar: a capacity market for your dark fiber
A new NOC tab sells spectrum, managed 100G, 400G, 800G and 1.6T waves, and dark pair IRUs on every route you hold
fiber on. Demand per route moves every day (its own cycle, noise, and news: fiber cuts, hyperscalers, AI clusters,
rivals lighting glass, mergers) and grows about 15% a year, with buyers moving to bigger waves over the years and
carriers on your glass asking to move up a size. You choose what to keep back for your own traffic, from what demand
the broker lists, and the price it never sells below. Managed waves come out of capacity you lit; prices follow the
fiber's cost, how hot and how full the route is, and its latency (400G at 2.7x 100G on land, 3.8x subsea). A Cable
broker pays 3% instead of 10% and sees each route's forecast and routes worth building.

Rule F5 now bounds sales by the moving market; new rule F8 covers managed waves. The route fuzz skips dashboard tabs
main does not have yet.
2026-11-07 13:34:41 +01:00
Frederic Jung
e6b5464352
Traffic badges: legendary only at the top of each ladder
1 Tbps is common, 10 Tbps rare, 100 Tbps epic (was legendary) and 1 Pbps
stays legendary, the same steps as the petabyte-to-zettabyte ladder.
2026-11-07 13:12:01 +01:00
Frederic Jung
fcb7264570
Traffic badges: a Tbps ladder and an odometer up to a zettabyte
Serving 1 Tbps (rare) and 10 Tbps (epic) now earn badges below the old
100 Tbps and 1 Pbps ones. S.vol counts the petabytes a game has carried
(a day of 1 Gbps is 10.8 TB), with badges at 1 PB, 100 PB, 1 EB and
1 ZB, and a Carried tile on the dashboard. Old saves start the count
from the 180 days of history they keep. The route fuzz takes badges
only this checkout has off its page, since an unlock's log line shifts
every id after it.
2026-11-07 13:08:11 +01:00
jvanvik
e8808f605d The connections list no longer breaks on a 400G fabric port
Some checks failed
CI / plan (push) Has been cancelled
CI / build (push) Has been cancelled
CI / translations (push) Has been cancelled
CI / part (push) Has been cancelled
CI / test (push) Has been cancelled
CI / timings (push) Has been cancelled
connUp offered the next PORT tier for a fabric (NNI) port, but fabric ports
stop at 400G: NNI[3] was undefined and renderDash threw. Upstream code
(85701db); the city panel already maps over NNI and is fine.

Perf (jsdom, big network, vs 4b922ab): no slowdowns beyond noise, routing
identical.
2026-11-07 10:33:22 +01:00
jvanvik
4b922aba02 Merge upstream: sharded test runs, auto-release follows CI (3.1.0)
Some checks failed
CI / plan (push) Waiting to run
CI / part (push) Blocked by required conditions
CI / build (push) Waiting to run
CI / translations (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / timings (push) Blocked by required conditions
Container image / test (push) Has been cancelled
Container image / publish (push) Has been cancelled
The fork's Unreleased bullets stay above upstream's 3.1.0 section. The dark
mode test reads the theme script from the page's HTML, since the harness
now runs script bodies outside the DOM.
2026-11-07 10:29:33 +01:00
Frederic Jung
4e6f780c81
No double runs in a release: container test and weekly tests once
A version bump's push started docker.yml's test, then auto-release
started docker.yml again for the tag, which tests the same code before
it publishes: the push skips its test while the version is not tagged.
The deploy re-ran the weekly-puzzle tests even when main's weekly files
are the tag's own, which CI had just tested: it now runs them only for
files that differ (a newer or refitted week) or an untested tag.
2026-11-07 10:28:57 +01:00
jvanvik
d1e127da67 Server-run play, part 1: game prerequisites and shared contracts
Groundwork for running multiplayer games on the session server; nothing
of it is switched on yet, and the plain build is unchanged.

- A new network in two halves (beginState/beginShow), the coach split into
  tutAdvance/coachDom, toastPop split out of toast, bootNotes() for the
  once-per-load toasts, the five text actions take their text as an
  argument, and srvOn() with its two checks in the loop.
- Live state is what a reload makes of it (migrate() is a no-op on it):
  new POPs, ports, PNIs, customers, attacks, dark fiber and the intern's
  notes are written in their saved shape; a 365-day test proves it.
- pniAll and bstdApply check the quote the sheet showed (bstdApply by its
  plan, within 1% for the daily hardware drift; utilityKit too).
- assemble({mp}) leaves src/game/98-server-play/ and its CSS out of every
  page but a multiplayer build's, which also gets a SIM_ID build id.
- Contracts for the server, protocol and browser parts: the action tables
  and envelope check (scripts/lib/mp-sim-acts.js), event fixtures, a shape
  checker, a fake engine, and load({mp:true}) in the test harness.
- route-fuzz judges both pages with one migrate(), so reload repairs of
  the base no longer count as divergences.
2026-11-07 10:26:06 +01:00
Frederic Jung
03523cb16b
Auto-release follows CI instead of testing the release again
A version bump on main ran the whole suite twice: once in CI for the
push, once more in auto-release. Auto-release now starts when CI
finishes on main and releases only if that run was green, tagging the
exact commit CI tested. Started by hand, it still tests first, since
there is no CI result to go by.
2026-11-07 10:00:15 +01:00
Frederic Jung
0342d90657
Faster tests, split everywhere: one sharded CI for pushes and releases
- The harness builds the DOM without the page's 2 MB of script text and
  runs the scripts straight in the window: a page load in tests takes
  about half the time (jsdom's parser was slow on the script text).
- That also took the game's source out of the DOM, which showed three
  tests that matched a phrase in the page source rather than the screen;
  they now check the panel, the routing window and the dictionary.
- CI plans its split once and runs the tests on 6 runners; every run on
  main records each file's time and caches it, so the parts stay even
  without anyone refreshing tests/durations.json.
- auto-release.yml and release.yml call the same sharded tests instead
  of running all 170 files on one runner each (11 and 15 min); a release
  is tested once, before it is tagged.
- Audit: five tests that duplicated a gameplay rule or checked nothing
  are gone; the two slowest checks sample a third of the cities, and a
  year of play to reach one due date became a moved due date.
2026-11-07 07:24:09 +01:00
jvanvik
e25f843526 Plans: IPv6-only broadband follow-up, and what it left out
Some checks are pending
CI / test 1/4 (push) Waiting to run
CI / test 2/4 (push) Waiting to run
CI / test 3/4 (push) Waiting to run
CI / test 4/4 (push) Waiting to run
CI / build (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / translations (push) Waiting to run
2026-11-07 07:06:37 +01:00
jvanvik
69328ce257 IPv6-only broadband: 464XLAT city by city, a NAT64 pool next to CGNAT
A broadband city can swap its home routers for ones with a CLAT (ip6Go /
ip6Stop, from the city panel's Home broadband). Over 30 to 180 days an even
share of the homes moves each day, paid as the routers go in ($4 a home),
waiting while cash is short; starting needs only the first day's share. New
homes in a swapping or finished city get the new router at the same price.
The panel says how many addresses it frees and what it does to the monthly
IPv4 bill.

ip4Use splits homes into public, behind CGNAT and IPv6-only: the NAT64 pool
(ceil(IPv6-only homes / NAT64 ratio), 64/128/256, default 128) comes right
after business blocks, before dual-stack homes. NAT64 gateways cost the same
per Gbps of IPv4 as CGNAT boxes; NAT64 refunds sit under CGNAT's at the same
ratio and never reach zero. The IPv4 share of home traffic is now a curve:
0.55 on day 0, two points less a year, floor 0.2. Out-of-space advice names
the sharing left to stretch. Everything is under rule ip4; old saves load
unchanged (no field means dual stack).
2026-11-07 07:01:34 +01:00
jvanvik
3bc1641a46 Plans: the server runs every multiplayer game, at 1x with a speed vote
Some checks are pending
CI / test 1/4 (push) Waiting to run
CI / test 2/4 (push) Waiting to run
CI / test 3/4 (push) Waiting to run
CI / test 4/4 (push) Waiting to run
CI / build (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / translations (push) Waiting to run
2026-11-07 06:55:24 +01:00
jvanvik
fbae6fc3ed The build standard owns the router model and the line system; one owner per fiber
The routers order reads its model from the build standard (bstd().g, 'keep'
is the old next-model-up rule) and the optical upgrade order its line system
(bstd().sys). The Ops sheet shows "From the build standard: X" with a button
to the sheet. Old saves move a model or line system from an order that was
running into the standard when it has none of its own; a paused order's or
an unhired intern's setting is dropped. opsParam refuses model/sys and points
at bstdSet.

The build standard's order is a generator now: every first job that takes a
fiber dark goes through the optical order's routing test (opsDark, in the
route worker in play), under one shared budget of dark swaps a night (two for
Kevin) and the week-long memory for a failed fiber. A fiber one order worked
on is the other's no more that shift, and decom keeps waves the standard just
upgraded. The plan is checked at every job, since the shift rests between
them: a POP gone or changed by hand meanwhile is skipped. The button still
runs the whole plan at once on the page.
2026-11-07 06:55:01 +01:00
Frederic Jung
7a6eb29013
Interns with specialities, optical upgrades, renewal haggles, seven French cities and smoother big networks (3.1.0) 2026-11-07 06:36:19 +01:00
jvanvik
032470f486 Merge upstream: route worker for every routing, intern specialisations, sales renewals, French cities
Some checks are pending
CI / test 1/4 (push) Waiting to run
CI / test 2/4 (push) Waiting to run
CI / test 3/4 (push) Waiting to run
CI / test 4/4 (push) Waiting to run
CI / build (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / translations (push) Waiting to run
# Conflicts:
#	CHANGELOG.md
#	src/game/60-features/39-sales-auto.js
#	src/game/60-features/95-standing-orders.js
#	src/game/85-incidents/40-chaos-monkey.js
#	src/game/88-days/10-day-tick.js
#	tests/gameplay-rules.test.js
#	tests/i18n.test.js
2026-11-07 05:26:28 +01:00
jvanvik
040e25faab Plans: propose a shared session clock for multiplayer
Some checks are pending
CI / test 1/4 (push) Waiting to run
CI / test 2/4 (push) Waiting to run
CI / test 3/4 (push) Waiting to run
CI / test 4/4 (push) Waiting to run
CI / build (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / translations (push) Waiting to run
2026-11-07 05:06:17 +01:00
jvanvik
b533f3baa8 Plans: multiplayer phase 2 design, and what is left after this round
Some checks failed
CI / test 1/4 (push) Waiting to run
CI / test 2/4 (push) Waiting to run
CI / test 3/4 (push) Waiting to run
CI / test 4/4 (push) Waiting to run
CI / build (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / translations (push) Waiting to run
Container image / test (push) Waiting to run
Container image / publish (push) Blocked by required conditions
Auto-release / release (push) Has been cancelled
2026-11-07 01:12:23 +01:00
jvanvik
e1ae8e0164 Satellite teleports: GEO and MEO circuits for islands and remote towns (#83)
The early and mid-game satellite option, before Pie in the Sky. Build a
teleport at a POP that a satellite sees, then rent capacity from it to
a remote POP: GEO (Intelsplat, Kacophony) needs no capex but costs a lot
a month per Gbps, 1-10 Gbps at about 600 ms; MEO (O3bservant) needs
tracking antennas at the teleport and gives multi-Gbps at about 130 ms
where both ends are under its ring, at least 5 degrees up. Coverage
follows each bird's footprint by ocean region. Latency feeds the latency
model: users who ride a satellite notice, in proportion to the share.

A circuit beside a cable goes on standby, whichever came first, and
carries only what the cable cannot: the classic single-cable island
backup. Satellites are not subsea links for covenants, scenario goals or
subsidies (Pitcairn's UK grant needs a cable). Express fiber and the
build standard leave satellite circuits alone.
2026-11-07 01:12:23 +01:00
jvanvik
8e1f2d66a5 Express fiber: light a wave through a city without its router (#58)
An express lightpath runs from A to C over your own or IRU dark fibers
A-B, B-C (up to six) and passes B through its ROADM as light: ports only
at its two ends, no hop in B, the fibers' latency added up. It takes one
channel slot on every fiber it rides, needs a ROADM line system on each,
and an optic that makes the whole run between regen sites. Routing, the
route worker, traceroute, diverse paths and saves see it as a link A-C.

A cut, a build, an amp or ROADM failure or a line system swap on any
fiber under it darkens it; backhoes and the chaos monkey still find
fibers that only carry expresses. "Express to..." on a fiber and an
Express tab in the link window plan one, with reach, slots per fiber and
the price. The intern's optics order leaves fibers that only carry
expresses bare, decom never hands one back, and the build standard keeps
a fiber's line system while an express on it carries traffic.
2026-11-07 01:06:30 +01:00
jvanvik
eac0604300 IPv4 address space: scarce, bought, leased, leased out; IPv6 is free (#150)
A rule (ip4), on in On-call and BGP at 3 a.m., off in the gentler
presets, sandbox and puzzles; scenarios only when they opt in. You start
with a /21 from the registry, sized so the early game never notices
(a gameplay-rules F1 test plays six start cities for 50 days). Business
customers need a block by kind and size; broadband homes take what is
left and the rest go behind CGNAT, which costs a box per home and
annoys some customers. An offer that does not fit cannot be signed and
says why, and a customer that cannot grow at renewal stays its size.

The bank's Address space section buys and sells blocks on a transfer
market with a gentle trend, leases blocks in, and leases spare blocks
out for monthly income, in real CIDR sizes (/24 to /16), at most 256
blocks (what a save keeps). Old saves get what they already use, plus
room, so nothing changes on load. The dashboard's AS box now lists the
blocks you announce.
2026-11-07 01:04:00 +01:00
jvanvik
2cd6b71198 Dark mode: Light, Dark or Auto under Settings › Theme (#80)
A device preference (localStorage sot-theme, never in the save), applied
by a small script in <head> before the first paint, so there is no flash;
Auto follows prefers-color-scheme live, and a choice reaches other tabs
and the NOC window. Panels, HUD, drawers, toasts, modals, the phone tab
bar, charts, puzzles, the architect and Pie Control take their colours
from custom properties with night values (AA text contrast); light tints
keep their old colour as the fallback, so the light look is unchanged.

Both map renderers read a light and a dark palette (96-map/15-palette.js):
sea, land, clouds, coastlines, labels and the tube outline. A theme
switch repaints the cached layers once (the WebGL land buffers are
rebuilt once); nothing changes per frame. The multiplayer leaderboard's
own row and the menu rank badge follow the theme too.
2026-11-07 01:01:50 +01:00
jvanvik
95aa9b6532 Multiplayer for self-hosted copies: sessions, server-side saves, a leaderboard
Off unless the page is built with MP_API set (MP_API=/api/mp npm run
build): a plain build has no door, no chip and makes no requests. The
session server is scripts/mp-server.js (npm run mp), plain node:http,
which can also serve the built site so one process sits behind the
reverse proxy; docs/MULTIPLAYER.md has the nginx and Caddy setups.

A session has a six-character code, one seed and one rules preset, so
every player starts in the same world, and up to twelve players with
their own AS numbers. Saves go to the server on a new game day at most
every 15 s and when the page hides, ordered by a sequence number (409 on
a stale push, and the player picks which one to keep). Tokens live in
localStorage, never in the save; the server keeps only their hash. A
#mp= link moves a network to another device. The session panel shows
the leaderboard, the feed and a short chat; each player's public card
(tier, POPs, links, exchanges, transit, peak, customers, score) carries
what in-game peering between players will need next.

Server limits: body sizes, one upload per player, uploads per address
and in total, sessions per hour, wrong-code lockout; addresses counted
per IPv6 /64, X-Forwarded-For only with --trust-proxy.
2026-11-07 00:42:39 +01:00
jvanvik
2b48a6ad65 A build standard for the whole network, kept by the intern
One sheet sets the target state for every POP, port and fiber: router
model and count, a second building, a generator, LAG members (split over
both buildings), an exchange port wherever there is one, PNIs spread
over the cities that pay, the line system, the fastest optics that reach
and wave sizes. S.popStd keeps its name; an old {g,rt} standard loads
with the same meaning.

One read-only plan prices every job with the game's own cost helpers,
POPs busiest first, then ports, then fiber hottest first. The sheet's
summary, the MCP quote, "Bring everything up now" and the new "Keep to
the build standard" order all use it, so the quote is what the click
spends. The order works a few jobs a shift through the budget and the
cash floor: a second router before a swap on a busy POP, no generator
under a nogen covenant, no De-Kicks, a line system swap only where the
fiber is quiet or a parallel link carries it, one a shift. New POPs get
the POP part of the standard, and the template's kit no longer pays for
it twice. opsMoNow counts generators and second buildings.
2026-11-07 00:41:42 +01:00
Frederic Jung
52e740cdae
A slow phone gives a day longer slices between frames
A device that cannot hold 50 frames a second waited a whole slow frame at almost every rest of a big day, so the
game played up to a third slower at 8x. There a day gets half of its own frame, up to 32 ms; screens that keep up
keep 3 to 8 ms.
2026-11-06 22:48:52 +01:00
Frederic Jung
410eb81544
Merge pull request #313: every routing a day needs runs in the route worker, and a long day lets frames through
Conflicts with main resolved: the intern's chosen router model, optical upgrades and personas are generators like the
other orders, with a rest after each job. The optical upgrade's fiber test is a step the day answers, in the route
worker in play (opsDark(), {dark}), like the sales desk's trial; the renewal desk's reroute is a step too (slRenRun()).
2026-11-06 22:47:54 +01:00
Frederic Jung
ed0cac9974
Interns: the same orders, each best at one part of the job
The three interns run every order the same way at the same salary;
each is now better at one thing, and says so when hired:
- Anycast Annie peers: the IX order runs every day, not only weekly, and
  the PNI order twice a week.
- Kevin from the night shift does maintenance: two line system swaps a
  night instead of one, and never a fat finger. He rolls the same dice
  (catching it before Enter), so a seeded game plays the same whoever is
  hired.
- Tracy Route plans ahead: the transit, ports, routers, optics and
  optical transport orders act as if traffic were already 10% higher
  (OPS_AHEAD).
2026-11-06 20:23:25 +00:00
Frederic Jung
c96f9e7644
Sales renewal labels go through N_() so the translation check sees them 2026-11-06 21:03:19 +01:00
Frederic Jung
74e8611f8e
The sales desk answers renewal haggles, each salesperson their way
With the new switch at the sales desk, whoever runs sales answers a
renewal haggle three days after it opens, unless the player did first.
The engineer gives business customers their discount and keeps nerdy
ones at the market price (nobody leaves); the shark holds the old price,
often with a fresh promise, bills a month of the saving, and loses some
(nerds most); the CEO gives 10% more off for a double term, says yes, or
picks a fight. Every answer is a hash of the contract. The switch is
stored only when on, so existing saves are unchanged.
2026-11-06 20:56:50 +01:00
Frederic Jung
d7aad7d965
France follow-up: pun names only, real Lille calibration, Lyon appended
Toulouse's data center is the Pink City Colo. SFR, Bouygues, OVH, Scaleway and Free join the
real-name blocklist, and the CHANGELOG bullet names only the puns. Lille calibration is what
PeeringDB lists within reach (4 facilities, 24 networks, Tourcoing and Roubaix included).
Lyon goes at the end of the big and mid city lists like every other addition. The Tier 1
island guardrail stays at 70: on current main the French networks leave the count at 64.
2026-11-06 20:49:31 +01:00
Frederic Jung
f317b25bc5
Merge pull request #288 from Lambro-codes: seven French cities, four French networks, and the Atlantic cables on the Atlantic coast 2026-11-06 20:26:25 +01:00
Frederic Jung
647e302f1c
The intern upgrades optical transport
A new standing order, Upgrade optical transport. On fiber that is full
and runs above a level, it moves the line system up one size (the
Upgrade click), or trades the smallest lit channels for the biggest
optic that fits, one at a time (setChCount; the old optics go to
spares). With a line system chosen, every fiber below it is moved up,
both steps in one night if need be, cold or not.

A line system swap is a day without the fiber, so only where another
live path joins its cities, no customer rides it, and routing the
network without it serves as much as today (one compute, measured
against today's routing). One fiber is tested and swapped a night,
and a fiber that failed is left alone for a week (not saved), so the
order costs at most one routing more, and only on a night with a
fiber to try.
2026-11-06 18:26:24 +00:00
Frederic Jung
1e7638c4b9
The intern standardizes routers on a chosen model; Ops settings are lists
Some checks are pending
CI / test 1/4 (push) Waiting to run
CI / test 2/4 (push) Waiting to run
CI / test 3/4 (push) Waiting to run
CI / test 4/4 (push) Waiting to run
CI / build (push) Waiting to run
CI / test (push) Blocked by required conditions
CI / translations (push) Waiting to run
Keep routers ahead gets a Model setting: the next generation when busy
(as before), or a model to standardize on. With a model, every POP on a
smaller one is swapped to it, the busiest first, within the monthly budget,
through the same upRouter click: never a step down, only unlocked models
that fit, and only where a second router carries the traffic or nothing
runs yet. Busy POPs on it only get more routers.

Every setting in the Standing orders sheet (each order's dials, budgets,
the cash floor) is a dropdown instead of a button that steps through the
values. The change handler passes a select's data-args, the actions take
the picked position (v) and still step without one for the MCP tools,
which now declare v as optional.
2026-11-06 17:19:17 +00:00
Antoine
f3df5e5d23
Steps resumed after the worker routes read the game as it is: a sales trial, the intern's PNI round and a failure's incident
While a step of the day waits for the route worker, the player can act. Three steps then resumed on what they had
noted before:
- a sales trial overtaken by an action ran again with the happy customers as indices into S.biz: a customer dropped
  meanwhile made one point past the end and the day stopped on an exception. dayAgain() makes the trial's checks,
  the customer and who is happy again on the game as it is; an offer signed or declined by hand meanwhile is not
  the desk's;
- the intern's PNI round placed the batch's quotes as they were: a PNI ordered by hand while it waited was ordered
  a second time. pniRequote() quotes each order again just before it is placed;
- a failure and the monkey's snip took the last incident after their routing: repaired meanwhile, it was gone or
  another one. They keep their own incident before the routing, and offer a repair only while it stands.
2026-11-06 14:24:18 +01:00
Antoine
3c45d7dca1
A day that reroutes no longer stops the page at x8: every routing it needs goes to the route worker
The day split of #312 on its own, from 3.0.0, without its routing core, save or map changes. On a big network at
x8 the game stopped whenever a day rerouted: after a failure, an event, the NOC intern's shift or the sales desk's
signing, dayPost() routed on the page.

* The day is a generator (dayRun(), dayPreRun(), dayPost()): each yield is a compute() it needs. dayTick() answers
  them on the spot (tests, fallback); in play rwGo() posts each one to the route worker. A failure (failureRun()), a
  DDoS and Auto-RTBH (ddosNewsRun()), the chaos monkey's snip (mkSnipRun()), an event's cut (eventRun()), the
  intern's shift (opsRun()) and the sales desk (slAutoRun(), its trials answered by the worker with offerTrial())
  are steps of the day. fireFailure(), opsDay() and slAutoDay() still play them in one go.
* yield DAY_REST lets a long day draw a frame between two steps (half a frame, 3 to 8 ms, RW.budget). One day in
  flight at a time, resting or routing: the clock waits for the day, and a half day is never saved.
* UI.tick is set around every step (dayStep()), so quiet notifications hold in play, not only in dayTick().
* The daily mood check works out the land islands once per pass over the customers (TERR), instead of walking
  every land link for each customer afraid of sharks. This fix is thesysadmindev's, from #310; here the islands are
  worked out again if something routed meanwhile (RW.gen), since the mood loop can now rest between customers.

Same game either way: tests/day-steps.test.js plays a second page as the worker and compares each day with
dayTick(), the intern on every order, failures, events, DDoS and the monkey forced.

Thanks to thesysadmindev for the profiling in #310 that pointed at the reroutes, and for the sharks fix.
2026-11-06 14:24:18 +01:00
Frederic Jung
9d64aa0144
Pie in the Sky, three charters and Sales runs the deals (3.0.0) 2026-11-06 10:02:28 +01:00
Frederic Jung
9a5522bbb1
Deals belong to Sales: the intern sticks to the network, the sales desk signs deals for you, orbit ones too
The NOC intern loses the sales order. Saves that had it load cleanly: sanitize drops the order, its log lines and its
weekly tally, and an intern who was running it hands its switch and minimum to the sales desk (S.slAuto).

With someone at the sales desk, the player can let them sign offers once a game day and decline the ones under a
minimum (39-sales-auto.js), each in their own style: the engineer and the CEO sign after the #185 routing trial (one a
day, a misfit waits a week), the shark signs every offer whose POPs are up, promises and commission included, and the
CEO's declines are a handshake away. Orbit offers need room on their landing dish instead of a trial. Nobody at the
desk (the default; the CEO is a choice, not a given): every deal is signed by hand. The sales desk runs before the
intern's shift, so a deal signed today is in the loads the intern works from. The sheet shows the switch, the minimum
and this week's and last week's tally; the NOC gets one notice a week.

Orbit offers go through the desk too (99-pie-sales.js): they carry o.by, so commission, renewal haggles and each
one's mark at renewal apply. The engineer only offers where the landing dish has 1.5x room on a well-served POP, and
those customers renew like the nerds (0.5x leave). The shark rings airlines, cruise lines and the Mars mission first,
at the biggest size that fits and 25% more, and half of them get a full-sky promise (REQS.skyfull: a crust at 90%)
before there is one; they grumble down to 40 happiness and never cancel over the promise alone. The CEO plays every
other golf game with the Founder: the biggest orbit deal that fits, Mars first, at 30% off; jitters cut his orbit
prices by 0.4x the jitters and from 0.6 the Founder skips golf. Without a salesperson orbit offers are drawn exactly
as before (the O7 balance save has nobody at the desk: payback unchanged, 7.0 years on seed 7, 7.5 on seed 11).

Also: the scenario reference plays 'sales' as the CEO signing for you; the route fuzz leaves out the state and
buttons of a standing order only main still has; the intern's on/off dials (paid peering, keep a spare) show their
translated value in the shipped page instead of the raw label.
2026-11-06 09:58:01 +01:00
Frederic Jung
2243280aff
Pie in the Sky: the Founder's antics make markets jumpy, then it wears off
- Every 60 to 120 days while a rocket company exists (the first 90 days after the plan starts), the
  Founder does something daft: a post, a gasp toast and a temporary effect (99-pie-jitters.js).
  A once-a-game antic takes orbit billing down for 3 to 5 days (no orbit income, then a restore post);
  a 3 a.m. spree (orbit offers x0.6 and a 4-point orbit mood dip for 14 days); a fight with a regulator
  (a landing-rights spat via pieSpatStart in a country with a dish or rights, within the spat limit);
  a leaked launch date (insurance 8% -> 14% for 30 days); Mars next year (offers x1.5 for 14 days, a
  promise like the others whose slip cancels the unhappiest 2% of orbit customers).
- Market jitters (S.pie.founder.jit, 0..1): each antic bumps it, it fades by 1/30 a day, and while
  high it lowers orbit offer odds (up to -30%) and holds orbit happiness under 100-25*jit (never low
  enough to cancel at renewal). The Company tab shows one line and a small meter next to the feed.
- Rule O5: harm only with pieChaos(); with chaos off he only posts. Dice only with a company.
- Saves: new founder fields in pieBlank, repaired in pieSanitize (pieAnticFix); old saves load calm.
- Insurance button shows the current premium (pie.ins_on_p replaces pie.ins_on). Agent docs updated.
- pie-balance: compute() also reruns when orbit billing goes down or comes back.
- tests/pie-founder.test.js: each antic, decay, once-only billing outage, chaos off, saves, 360 px.
2026-11-06 09:58:00 +01:00
Frederic Jung
9d74873edb
NOC tab and Pie Control tidied for phones: Pie Control in the NOC top row, traceroute in Routing & DDoS, government money in the bank
- NOC tab: Pie Control is a button in the top row next to "Open NOC dashboard" (only once the rocket
  company is unlocked) and replaces the Pie in the Sky card; a spat waiting for an answer keeps its card.
  The Connections button is gone (it lives in the NOC dashboard), and the traceroute moved into the
  Routing & DDoS modal as an entry that opens the unchanged traceroute modal.
- Government money (Rural Digital Pie Fund, Pitcairn grant, Ex-Im Pie Bank) is a section of the bank,
  shown with a rocket company or anything of the fund's to show. pieGovOpen, the action the toasts use,
  opens the bank there; pieTab({t:'gov'}) does too.
- Pie Control has four tabs (Traffic, Company, Launch, Dishes) in one segmented control that fits 360 px,
  styled like the HUD's speed buttons. The Founder's posts and the orbit books moved into the Company tab,
  newest three posts shown and the rest folded. A stale UI.pieTab of 'gov', 'book' or 'founder' falls back.
- Agent docs for pieGovOpen, pieTab, routingOpen and connOpen; the route fuzzer drops connOpen from the
  NOC tab on both pages to stay in lockstep with main.
- Tests: tests/noc-panel-layout.test.js, and the pie tests follow the moves.
2026-11-06 09:58:00 +01:00
Frederic Jung
176a6995b1
Pie globe: continents clip cleanly at the rim instead of fluttering
Hidden coast was pushed onto the rim, so coasts on the edge shivered while the globe turned, and from some angles Eurasia's
fill ran the long way round and painted the whole globe green for a step (up to 47% of the picture flipping between two
half-degree steps). Each ring is now clipped at the horizon as map libraries do: the fill follows the rim in the ring's own
turning direction to the next point where coast comes back, and only real coast is outlined.
2026-11-06 09:58:00 +01:00
Frederic Jung
95f3851557
Pie in the Sky: a grand opening when a crust starts carrying traffic, so regular customers sign as the patchy ones fade 2026-11-06 09:58:00 +01:00
Frederic Jung
7001174d79
Pie in the Sky, the early game: a pace forecast on the Launch tab, patchy-sky customers before 40%, a hint to wait on dishes
- Launch tab: each crust being filled says when it is full at today's pace (piePace: the pads that reach it, one launch per
  leadDays(gap) each with the rocket last queued or the fastest available, capped by the factory with the shelf and the
  queue as a buffer). Past two years and pad-bound, one nudge for another pad at the coastal POP nearest the equator,
  with a build button (piePadTip).
- Patchy-sky customers (60-features/99-pie-patchy.js): a revenue line in pieMoney, no flows, so routing is unchanged and
  games without a rocket company never see it. Up to $30M/mo for Shortcrust (scaled by crust size), ramping from 10% to
  40% coverage with one working dish under the crust, then times (1 - pieCarry) so it hands over to regular orbit
  customers by 60%. Shown on the Traffic tab; booked in S.pie.book like all orbit income.
- Dishes tab: under 30% coverage, a gentle note that dishes earn nothing yet and cost money every month.
- Payback on the O7 run is unchanged at one decimal (seed 7: 7.2 years, seed 11: 8.2).
2026-11-06 09:58:00 +01:00
Frederic Jung
267f9efc72
Pie in the Sky for agents: every Pie action classified and typed, its state and results documented 2026-11-06 09:57:59 +01:00
Frederic Jung
b3153c020f
Pie in the Sky: no government line in the books without a rocket company, so other games route exactly as on main 2026-11-06 09:57:51 +01:00
Frederic Jung
b4a7576251
Pie in the Sky: closing a panel stops the globe again, after the rebase onto 2.10.0
The merge that mounted the globe in Pie Control did not survive the rebase: closeModal() stops the globe once more, and its tests are back.
2026-11-06 09:57:51 +01:00
Frederic Jung
8b92adcaa8
Pie in the Sky: government money for rocket companies
A Gov tab in Pie Control with three state programmes:

- Rural Digital Pie Fund: reverse auctions for towns only orbit reaches
  (a cut-off POP on backhaul, or a small town of your terminals). Ask
  90%, 70% or 50% of the reserve against a rival; the lower ask is paid
  monthly for five years while the town stays 70% served (monthly
  average) from a 90-day deadline. One bad month warns, two revoke the
  award and claw back half of the last year's support.
- Ex-Im Pie Bank: a BANKS loan of half the value of the pies flying and
  booked (at most 20% of a full Shortcrust, counted by O7), 1.5-2.5%
  over 60 months, never offered by the usual banks. Space covenants:
  launch n pies in a year, keep a pie dish in the lending country. A
  breach brings the bank's penalty, +3 points, a new launch deadline
  and, with chaos on, a "data stays home" or landing-rights spat there.
- Pitcairn: served from orbit (backhaul or home terminals) at 90% of its
  demand, latency forgiven, the UK pays a $120k/mo satellite grant.

Subsidies count in the orbit's books. tests/pie-gov.test.js covers the
features; pie-balance.test.js gains a run with government money, which
must pay back sooner by at most two years.
2026-11-06 09:57:51 +01:00
Frederic Jung
1de0723c35
Pie in the Sky: a full constellation pays back in about seven years
Rule O7's payback half is now played through the game loop
(tests/pie-balance.test.js): the big-network save runs a full lasered
Shortcrust by a sensible policy until its books balance, in 5 to 10 years
(6.3 on seed 7; 7.4 and 6.9 on seeds 11 and 3). The static formula is gone.

Retune: pies $0.5M (+$0.25M lasers), from $1M (+$0.5M); landing rights
$12,000 per eyeball up to $100M a year, from $28,000 up to $200M; orbit
rates x1.25 (pizza 25k, flywifi 36k, boat 27.5k, marsorb 44k); PIE_SELL
0.25 -> 0.4; PIE_OFFER_RATE 1/6 -> 1/3.
2026-11-06 09:57:51 +01:00
Frederic Jung
46ba4e04d2
Pie in the Sky: a terminal lands where all of it fits
pieLand() prefers the nearest dish with room for the whole terminal and
only then the nearest with any room left, so a nearly full dish no longer
serves a sliver of a customer who then cancels while other dishes sit idle.
2026-11-06 09:57:51 +01:00
Frederic Jung
d7d5d21372
Pie in the Sky: dips in orbit hurt instead of emptying the sky
A crust carries a share of its traffic from 40% coverage, growing to all
of it at 60% (pieCarry/pieCap), instead of nothing until 60%. Pies wear out
over the last 30% of their life (pieAlive), deterministic, so a launch month
no longer deorbits on one day. Storms take 2-10% and food fights 5-10% of a
crust (PIE_HIT), down from up to 40% and 20%. Orbit customers lose at most
PIE_PATIENCE happiness a day without service, about a month to cancel.
2026-11-06 09:57:51 +01:00
Frederic Jung
48d2cedbee
Pie Control globe: replay recent launches, with payload release or a fireball
The last six flights (UI only, never saved) replay on the globe every six seconds: a good one
spills its pies at the top and a reusable booster flies home; a failed one blows up partway
with a flash, smoke and debris. About 0.4 ms per frame while Pie Control is open.
2026-11-06 09:57:50 +01:00
Frederic Jung
ff0276f325
Pie Control: backhaul rows, globe arcs and orbit traceroute for cut-off POPs
The Traffic tab gets a Backhaul group (how full, where it lands, the ms
it adds, or why it is missing), the empty-sky checklist a backhaul item,
dish rows count backhaul; the globe draws backhaul as a sky arc,
highlighted on tap; the traceroute to and from a cut-off POP shows its
hops through space. Strings in every language; tests in
tests/pie-backhaul.test.js.
2026-11-06 09:57:50 +01:00
Frederic Jung
940ce0df10
Pie in the Sky: backhaul for POPs cut off from the backbone
A pie dish at a POP the backbone does not reach now lifts all of that
POP's own traffic to a landing dish on the backbone (bent pipe within
1,000 km, lasers past that): one virtual edge, capacity min(dish, landing
dish, crust) after terminals, latency the orbit path. Its IGP weight is
Infinity; only the cut-off POP's paths are rerun with it (pieRelink), so
POPs on the backbone never route through orbit and saves without a
cut-off dish route exactly as before. Spats, safe mode, a down crust,
landing rights and backhoes cut it.

A cut-off dish now reports 'backhaul' or 'isl' (it said 'ok' when it
had local terminals). Rule O3 now reads: a cut-off pie dish carries only
its own POP's traffic and local terminals, never transit between other
cities.
2026-11-06 09:57:40 +01:00
Frederic Jung
4ad080cb91
Pie Control: Traffic tab, empty-sky checklist, orbit traceroute
A new first tab shows what rides the sky: a headline, load per crust,
who is riding (tap to highlight on the globe), per-dish load and why a
dish is idle, and a checklist when nothing flows. The traceroute lists
circuits through orbit with their uplink, laser and downlink hops.
Strings in all languages, tests in tests/pie-traffic.test.js.
2026-11-06 09:57:40 +01:00
Frederic Jung
df6e0e0964
Pie in the Sky: traffic on the globe, load rings on dishes
The globe draws sky circuits as glowing arcs through the crust and
terminals as hops to their dish, width by Gbps, with packets moving
along; the highlighted flow goes on top. Dishes on the globe and the
map badge get a green/amber/red load ring.
2026-11-06 09:57:39 +01:00
Frederic Jung
ad8d036913
Pie in the Sky: traffic data for orbit (flows, crust and dish load)
R.pie now lists each terminal customer and sky circuit with its Gbps,
revenue, dishes and hops, plus load and an idle reason per crust and
dish. The fiber-only latency is worked out lazily, once per compute.
Routing is unchanged; saves without S.pie pay nothing.
2026-11-06 09:57:39 +01:00
Frederic Jung
52c31d94b5
Pie routing test: simpler sky check 2026-11-06 09:57:39 +01:00
Frederic Jung
6812638a5b
Pie in the Sky: orbit prices, rules O2-O4 and both bounds of O7
Terminal customers are priced so that a full lasered Shortcrust on the
big-network save pays back in about 9.6 years, and no crust pays back in under
5 even with the whole sellable sky sold at the dearest prices (Shortcrust 5.3,
Flaky 7.4, Upper 9.2, Frozen 40). O2, O3 and O4 get rules and tests.
2026-11-06 09:57:39 +01:00
Frederic Jung
80bddc8694
Pie in the Sky: customers in orbit
Homes and boats, airlines, cruise ships and the Mars mission (only in saves of
this version) call once a baked crust and a dish with room can serve them,
remote towns like Pitcairn and the Arctic first. What is signed never outgrows
a quarter of the sky's capacity. Orbit has its own sales desk, so the ground's
offers keep their odds.
2026-11-06 09:57:39 +01:00
Frederic Jung
8035fc03cc
Pie in the Sky: routing through orbit
Baked crusts become sky nodes in the routing graph: each dish on the backbone
gets an uplink, and with lasers dishes 3,000 km or more apart are joined through
space at c in vacuum, priced along the great circle at the shell's height. Only
latency-routed circuits fly (O4); IP traffic never sees orbit. Half-baked
crusts carry nothing, dishes carry at most their antennas (O2), dishes off the
backbone carry no transit (O3). Terminal customer types and their strings come
with it. Saves without S.pie add no work to compute().
2026-11-06 09:57:39 +01:00
Frederic Jung
727541a9d8
Pie in the Sky: incidents in orbit and geopolitical spats
Solar storms (safe mode saves most pies), food fights (debris, launches dearer for a year,
Space Roomba fix), rain fade on tropical dishes, backhoes at the dish, astronomers
(VisorSat or science customers sulk), the Founder's 3 a.m. posts and the chaos monkey
snipping laser links. Nine spats with two answers each on a bottom sheet: landing rights
refused, data stays home, spectrum squabble, kill switch, orbital land grab, jamming,
launch diplomacy, not over my airspace. All gated by chaos and 90 quiet days (O5),
seeded, repaired by sanitize, translated in every language.
2026-11-06 09:57:38 +01:00
Frederic Jung
112450d158
Pie globe: launches by pad city, crust sizes from CRUSTS when present 2026-11-06 09:57:38 +01:00
Frederic Jung
d3174600e7
Pie in the Sky: animated 3D globe for Pie Control, with a night view
An orthographic Earth on a 2D canvas (sticker look, plus a night view with stars,
city lights and terminator) showing a capped sample of each crust's pies, laser
links, pie-dish beams and launches. One rAF loop only while open (30 fps cap,
DPR <= 2, idle while hidden), nothing left behind once closed. Land comes from
LANDS_LL. The world map only gets a pink pie-dish badge at cities with a dish,
behind one null check per visible city when there are none.
2026-11-06 09:57:38 +01:00
Frederic Jung
c860a128e4
CHANGELOG: Pie in the Sky 2026-11-06 09:57:37 +01:00
Frederic Jung
2729779501
Tests for Pie in the Sky, and rules O1, O5 and O7 2026-11-06 09:57:37 +01:00
Frederic Jung
7fb7be305d
Pie in the Sky: rocket company foundation
Catalog (rockets, crusts, prices), state with newGame default and a full
sanitize repair, the one-time unlock on the Tier 1 win (sandbox from day 0),
company, factory, pads, R&D, launches, dishes, landing rights, the daily tick,
the Founder feed, three badges, a plain Pie Control modal from the NOC tab,
and hooks for routing, spats and the globe. Translated in every language.
2026-11-06 09:57:37 +01:00
Frederic Jung
d2c7294ed3
Plan: Pie in the Sky constellation spec 2026-11-06 09:57:23 +01:00
Frederic Jung
50e0119497
Charters: tests follow the popup, the tutorial waits only for a picker on screen
The tutorial waited for a charter whenever one was due, also where the
picker is not shown (seeded tests); it now waits only while the picker is
open. Two tests still read the old wording for own subsea cables (level 9
or Tier 1 now), and the route fuzz signs the classic charter on both pages
when a normal game starts, so neither shows charter buttons the other
has not.
2026-11-06 08:45:42 +01:00
Frederic Jung
934a83588a
Charters: a popup at the start, and a third one, the Cable broker (#300)
A new Normal game now asks what it is building before anything else, in
a popup that holds the clock and cannot be closed without an answer;
the tutorial waits for it. A save still in its first month that never
picked is asked on load. Sandbox, puzzles and scenarios never ask.

The Cable broker builds and lights glass from day one at the prices
everyone pays at the top level: dark fiber, every line system and optic,
digging without the pioneer markup, own subsea cables and their
upgrades, eight pairs, and every router those optics need. Everything
else unlocks by level as before. Its offers lean to carriers buying
waves and pairs, capacity conferences are open to it at any level, and
carriers call about three times a year with a capacity deal. It runs its
own ten-goal ladder and wins Glass Baron (own cables on five continents,
$1M a month of capacity sales), with a badge; Tier 1 stays its own win.

Classic and boutique networks may lay their own subsea cable from
customer level 9 as well as after Tier 1.

Rule M6 (gameplay-rules): a charter changes what you set out to do,
never what things cost. Closes #300.
2026-11-06 08:41:44 +01:00
Frederic Jung
f303f29f22
PNIs and IX ports are both peering: traffic leaves at the nearest one (#298)
Routing tried every PNI (rank 1) before any IX port (rank 2), like a
local-pref above peering, so a PNI in London pulled New York's traffic
across the Atlantic even with the same network at the New York IX. PNIs
now route at rank 2 with the IX ports, nearest first. At the same distance
the PNI goes first: an IX port counts as PNI_TIE (0.001) further away,
far below any link weight (at least 1). Distances compare as
(Da-Db)+(dta-dtb) so exits at one distance stay exactly equal, and the
POP-local shortcut skips lists that mix PNIs and IX ports. Backup only and
RouteScript's prefer pni keep their say. The traceroute, the reference
allocation in the tests and the RouteScript help follow.
2026-11-06 06:31:21 +00:00
Frederic Jung
7c65b9e7ed
Space plays again at the speed you paused (#299)
Space set the clock to 0 or 1×, so a game at 4× came back at 1× after a
pause. Space and the phone's play button now share playPause(), which keeps
the last speed; autoPause() records it too, so a game loaded at a speed, or
paused by a window, resumes where it was.
2026-11-06 05:57:28 +00:00
Frederic Jung
85701dbb82
Fabric ports at 10G, 100G or 400G, in LAGs; fabric customers only when they fit
A fabric (NNI) port comes in 10G, 100G or 400G, as fast as the router
takes and no faster than 400G, and bundles into a LAG of up to eight
members like transit, IX and PNIs. Each member takes a router port (10G
on a breakout, a quarter of one) and pays the monthly price; upgrading
moves and pays for every member. 10G and 100G keep their prices, 400G is
$3,000/mo. A model change that would strand a 400G fabric port is refused,
and saves drop fabric ports that make no sense.

The NNI requirement counted what the port already carried but not the
offer's own bandwidth, so an offer passed as long as the port was not
already over and auto-accept took customers that did not fit. It now
counts the offer too.

Closes #140, closes #307.
2026-11-06 06:52:48 +01:00
Frederic Jung
4ec3fb4a1a
Merge pull request #304 from antt0n/fix/map-stale-floaters
fix(map): drop the last network's floaters when another one starts
2026-11-06 06:37:25 +01:00
Frederic Jung
efd7a42edd
Merge pull request #309 from fjaeckel/claude/fix-305 2026-11-06 06:17:16 +01:00
Frederic Jung
7f3b742451
Own subsea cables land on the city's dot, nudged cities too (#305)
An own cable's map line came straight from its surveyed lon/lat path, so it
ended at the city's exact coordinates, while the city itself is drawn with its
display nudge (CITY_NUDGE). Fujairah's [1,2] left every own cable there 2 px
above the dot; Dubai, Karachi, Barcelona and Osaka are off by more. The ends of
the map line now sit on the drawn city, as commercial cables already do; the
saved path and its length are unchanged.
2026-11-06 01:50:40 +00:00
Antoine
fca11b39d2
fix(map): drop the last network's floaters when another one starts
Floaters ("New POP!", payday money) live in FLOATS and fade on the map's
animation clock, which only runs while the game does. A new network
whose clock stands still (the agent's clock on the development page)
kept the previous network's floaters frozen over its map until a reload:
hundreds of them after a payday on a big network at 8x.

Each floater now records the network that raised it, and the map drops
any that belong to another one (new game, another slot, import, puzzle,
title screen). Same code for the 2D and WebGL maps.
2026-11-05 21:40:13 +01:00
Frederic Jung
dd6e4f4f8a
Fix CodeQL code-scanning alerts
- Values pasted into eval'd or inline-script code go through lit() (scripts/lib/js-literal.js), which escapes <, >, /, U+2028 and U+2029 after JSON.stringify
- build test and i18n-check read script tags with a DOM parser or a plain search, not HTML regexes
- mcp.js parses the Authorization header without a backtracking regex
2026-11-05 21:24:26 +01:00
Frederic Jung
e7729d0a1e
Harden workflows and dev scripts against code-scanning findings
- auto-release: pass step outputs to run scripts through env, not ${{ }} interpolation
- perf-comment: download the PR's perf artifact to RUNNER_TEMP, outside the workspace
- dev server: log errors to the terminal instead of sending stack traces in the response
- i18n-add/i18n-check: escape every regex metacharacter when building patterns from labels
2026-11-05 21:04:21 +01:00
Frederic Jung
1a6c63e920
Tools: playwright-core 1.64.1, ws 8.22.1 (#301)
Dependabot's group update, applied on top of the jsdom update (#302),
whose lockfile it conflicted with.
2026-11-05 20:35:55 +01:00
Frederic Jung
b5fba00e0b
Merge pull request #302 from fjaeckel/dependabot/npm_and_yarn/jsdom-30.1.3
Tools: Bump jsdom from 24.1.3 to 30.1.3
2026-11-05 20:30:54 +01:00
Frederic Jung
bf6090f413
Merge branch 'main' into dependabot/npm_and_yarn/jsdom-30.1.3 2026-11-05 20:26:08 +01:00
Frederic Jung
478e767c83
Latency test: no padding is zero however the DOM spells it
jsdom 30 reports an unset padding as '0', not '0px', which failed the
check for the yellow bars in the jsdom update (#302).
2026-11-05 20:25:23 +01:00
Frederic Jung
7c0f1b3b05
Merge pull request #303 from fjaeckel/dependabot/github_actions/actions-b2576794da 2026-11-05 20:22:56 +01:00
Frederic Jung
131e2f7b9c
Container smoke test: container names Docker accepts
A name must be at least two characters; the build itself passed.
2026-11-05 20:15:44 +01:00
dependabot[bot]
8d3db207be
CI: Bump the actions group with 2 updates
Bumps the actions group with 2 updates: [actions/download-artifact](https://github.com/actions/download-artifact) and [actions/upload-artifact](https://github.com/actions/upload-artifact).


Updates `actions/download-artifact` from 4.3.0 to 8.0.2
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](d3f86a106a...9000827ccb)

Updates `actions/upload-artifact` from 4.6.2 to 7.0.2
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](ea165f8d65...cf430e030d)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: 8.0.2
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/upload-artifact
  dependency-version: 7.0.2
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-05 19:15:08 +00:00
dependabot[bot]
8ebd1fd425
Tools: Bump jsdom from 24.1.3 to 30.1.3
Bumps [jsdom](https://github.com/jsdom/jsdom) from 24.1.3 to 30.1.3.
- [Release notes](https://github.com/jsdom/jsdom/releases)
- [Commits](https://github.com/jsdom/jsdom/compare/v24.1.3...v30.1.3)

---
updated-dependencies:
- dependency-name: jsdom
  dependency-version: 30.1.3
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-05 19:15:05 +00:00
Frederic Jung
aa444c2d94
Merge #297: the MCP server as a container image
Its change landed as 9c8cda4, with the follow-up in 98735eb; this records
the pull request's own commit as merged. No files change.
2026-11-05 20:14:36 +01:00
Frederic Jung
98735eb769
Container image: releases only, a token by default, lean layers; every action pinned
The image is published to GHCR as the release's version when a release
dispatches docker.yml, and never as latest or per commit. Pushes and pull
requests that touch it build it and try headless (with and without a
token) and browser mode, without publishing.

The image: node:24-slim pinned by digest (the major CI tests on), npm ci
from the lockfile in its own layer, only src, site, scripts and the
harness copied in (an allow-list .dockerignore), root-owned and run as
node, /saves ready for --save-dir. The entrypoint runs the servers with
node directly and, with no SOT_MCP_TOKEN, makes a token for the run and
prints it (MCP_NO_TOKEN=1 to opt out); the docs publish ports to
127.0.0.1 and explain --allow-host. Labels, SBOM and provenance on push.

Every GitHub Action in every workflow is pinned to a commit SHA with its
version, and Dependabot keeps the actions, the image's base and the npm
tools current. tests/docker.test.js guards all of it. The ADR and the
github-pages skill say the image is a tool: GHCR only, never Pages.
2026-11-05 20:14:04 +01:00
Wolfgang Nagele
9c8cda44c1
Build container images for easy MCP use 2026-11-05 20:14:04 +01:00
Frederic Jung
908f2e0de9
Puzzles on phones that never scroll, a fairer meet-halfway, Fujairah on its coast (2.10.1) 2026-11-05 17:33:36 +01:00
Frederic Jung
107b0b825a
Puzzles on phones: fixed overlays that never scroll
A bar pinned at the top holds the puzzle's state (name, stars, money,
undo, menu), the goal being worked on with Show me, and a chip per flow
that opens its city. A city or a link opens a short card at the bottom,
split into tabs (links, router, traffic; size, traffic, routing) that
each fit on a 360 px phone, portrait or landscape. Architect runs get
the same bar. Reset moves to the menu on phones. Desktop is unchanged.
The old swipe-up sheet and its peek state are gone.
2026-11-05 17:18:50 +01:00
Frederic Jung
d7fb2a9617
Fujairah one step west, onto the coast it lands on
The nudge to [2,2] put the city just off the UAE coastline, so the
landmass test failed; [1,2] is on land, still on the east coast where
its cables land and well away from Muscat.
2026-11-05 17:18:37 +01:00
Frederic Jung
8c96fa5bc1
Meet halfway between the bill and the ask; Fujairah back on its coast (#293, #295)
Meeting halfway split the difference between the ask and today's market
price, which after a fall in prices sat right next to the ask. It now
splits the two prices the Deals row shows, and the button names it.
Fujairah's display nudge moved it a degree south onto Muscat; it now
sits on the UAE's east coast where its cables land.
2026-11-05 17:10:22 +01:00
Wolfgang Nagele
f19b337d7b Build container images for easy MCP use 2026-11-05 10:17:05 -05:00
Frederic Jung
eb294e9b14
WebGL map, customer contracts and a sales desk (2.10.0) 2026-11-05 11:39:40 +01:00
Frederic Jung
151b7786ed
Tests wait for state instead of sleeping, on free ports
The relay, parity and benchmark server tests slept fixed times before
asserting, which a busy CI runner overran. They now wait for what they
need (the relay reports what it holds), take a port from the OS, and
use fresh HTTP connections. npm test -- --stress N hunts flakes.
2026-11-05 11:38:26 +01:00
Frederic Jung
02d3709944
GPU benchmark server test: listen on 127.0.0.1, where it connects
On the CI runners localhost resolves to ::1 first, so the server listened
there while the test connected to 127.0.0.1.
2026-11-05 11:22:53 +01:00
Frederic Jung
aef744af50
Show a cable's name and a repair button from a save as text
The city panel put the name of your own subsea cable and an incident's
repair label into its HTML as they came from the save. Both are escaped
now, and sanitize() keeps a cable's name to a string of 60 characters.
2026-11-05 11:15:05 +01:00
Frederic Jung
7f4fdf6043
WebGL map: join each line's segments, and draw a link being dragged out under the cities
A see-through line on the card was one round-ended quad per segment, so
where two met it was blended twice: the selected tube's halo showed a
darker blob at every point, and the cables a notch at every corner. Each
segment now knows its neighbours' directions and keeps only its side of
the corner's bisector, as the 2D canvas strokes a path once.

The link being dragged out was painted on the overlay, above the cities
and their labels; it now goes to the card, under them, as in 2D, and its
price label is a picture like the others.

Auto after Always 2D, when the browser will not give the context back,
gives the card up instead of waiting for it all session. Firefox reads
the card's name from RENDERER, without the extension it warns about.
2026-11-05 11:15:05 +01:00
Frederic Jung
f9c85ab0c3
GPU benchmark: answer only its own page, and print what it sends as plain text
Any site open in the same browser could POST results (printed to the
terminal, escape sequences included, and written to --out), and DNS
rebinding could read the save. The server now checks the Host header and
the origin of a POST, caps the body at 2 MB, drops control characters,
and no longer sends stack traces. The panel no longer shows <sub> tags.
2026-11-05 11:15:05 +01:00
Frederic Jung
57c0594a90
Merge pull request #291 from thesysadmindev/unbuilt-pops
A dashboard tab listing the cities with no POP yet
2026-11-05 11:12:07 +01:00
Frederic Jung
c1d726c105
Relay test waits for the late page instead of a fixed 2.5 s
On a busy CI runner the page took longer than that to load and answer,
and the test failed although the server did proceed.
2026-11-05 11:04:47 +01:00
thesysadmindev
e62e4c7c98
Merge branch 'main' into unbuilt-pops 2026-11-05 21:01:24 +11:00
Frederic Jung
13768c61cb
Merge #281: draw the map with WebGL2 by default, 2D as fallback 2026-11-05 10:13:28 +01:00
Frederic Jung
939aaeea59
Sales and contract rolls hash what a deal is, not its clock-made id
Offer and customer ids come from Date.now(), so the shark's oversell, the CEO's veto, his promises
and every contract roll differed each time the same game was played, and the shark test could fail
on CI (67% oversold against 54%, short of its 15-point margin). They now hash the deal or the
customer (type, cities, name, size), and a test checks two ids give the same roll.
2026-11-05 09:45:19 +01:00
Frederic Jung
27c4977412
A sales desk: the engineer turned salesdroid, the shark, or the CEO
From customer level 2, one person runs sales at a time, next to the NOC intern:
- The engineer turned salesdroid ($9k/mo) books you into every network operators' meeting 30 days
  ahead at the usual ticket price, brings 40% more offers (half as many again while a meeting's glow
  lasts) but never the huge deals, and their customers leave less often at renewal (half as often
  for the nerdy ones: HFT, ISPs, universities, L2). Haggles badly.
- The shark ($15k/mo) brings bigger sizes at 25% more, takes a month of each deal as commission,
  oversells half of them with a requirement the network does not meet yet, never brings technical
  customers, makes selective peering desks want 25% more traffic, wins most haggles, and their
  customers leave 50% more often.
- The CEO (free) signs the biggest internet customer the network can take on the golf course every
  50-80 days at 30% off, often with a promise nobody checked, signs about a third of the offers you
  decline anyway, and has opinions. He cannot be fired: a board meeting brings a VP of Sales a month
  later.
Customers remember who signed them (by), which the renewals read. Every roll is a hash of the day
or the deal, so games without a salesperson keep their random stream.

The differential fuzz also leaves out buttons for actions main does not have yet.
2026-11-05 09:32:24 +01:00
Frederic Jung
b9860edc77
Dark fiber leases cost half as much again (#203)
A leased pair was $400 + $1/km a month, so a single 400G wave on the
same route cost two to three times the whole fiber. It is now $600 +
$1.50/km (amplifiers as before): a lease pays off at a couple of 400G
waves, as dark fiber does. Leases already signed keep their price (l.mo).
Alien-wave rent follows, since it is priced against the fiber.

The differential route fuzz now also compares link prices, so a
deliberate price change compares this checkout with itself, as a change
to the world already does.
2026-11-05 08:19:05 +00:00
Christopher Hawker
5259e93034 Merge remote-tracking branch 'upstream/main' into unbuilt-pops
# Conflicts:
#	CHANGELOG.md
2026-11-05 18:27:21 +11:00
Christopher Hawker
0cdbef97fe A dashboard tab listing the cities with no POP yet
The dashboard shows what you have built, not what you haven't. The new tab lists every city you could still open, with its eyeballs, exchange and price, and sorts, filters by region and pages like the other long lists. Open selects the city on the map, so a build still goes through the city panel and its warnings. The tab also works in the NOC window.
2026-11-05 18:26:44 +11:00
Frederic Jung
8841fdacb9
Customers come and go: contracts, renewals at the market price, growth, haggles and leaving (#178)
Every customer now signs for a term (enterprise and hosting 1-3 years, wholesale and circuits 2-5,
fiber pairs 10-20). When it ends most renew at today's bandwidth price, happy ones often grow to
the next size, a few with competitors around ask for a discount 30 days ahead (match, meet halfway
or let go in Deals; no answer matches), and some leave: unhappy ones because of the service, others
acquired, bust, insourced, moved (they stay if you have a POP there), multihomed, project ended,
a cheaper bid, or now and then one of the odder reasons (never more than one every 60 days).

The bandwidth market is flat for six months, then about 10% cheaper a year, slowed by dearer
hardware, moving in a slow three-year cycle and pushed up during a shortage. New offers and
renewals are priced in it; one renewal moves a price at most 25% down or 10% up.

Nothing happens in a first term. Rolls are hashes of the customer and its term, never Math.random,
so seeded games keep their stream. Old saves get renewals spread over the next year. Happy
customers of a year or more send a referral about every six weeks. The dashboard's Customers tab
shows customers won and lost each month and why, renewals due and the market; customer rows show
the contract end.

The differential fuzz now leaves out state fields only this checkout has, so a new feature's state
does not fail the comparison with main while everything both games share must still match.
2026-11-05 08:15:53 +01:00
Frederic Jung
b8d313b029
Alien waves priced against their fiber; crews halve a build at most (#203)
An alien wave rented for about as much as leasing the whole fiber, so a
route sold out to its market earned 11 to 35 times its lease and the
gear paid back in one to three months. A wave now rents for 30% of the
fiber's monthly cost (lease plus amplifiers), and each one sold between
the same two cities goes cheaper, down to 40% of the first: a full
route earns 2 to 6 times its lease. Signed contracts keep their price.
Gameplay rule F6.

Extra crews could bring any land build to the next day. They now cut it
to half its planned time at most, and the button says when it would be
done. Gameplay rule F7.

A typed order (the agent API) could end a wave, dark fiber or cable in a
city the map does not show, and opened a POP there.
2026-11-05 06:50:25 +00:00
Frederic Jung
45ffdba8ae
Sweden beyond Stockholm: Gothenburg, Malmö and Haparanda (closes #206)
Gothenburg between Oslo and Copenhagen on Netnod's exchange, Malmö across the Øresund on SONIX, and Haparanda where GlobalConnect's fibre crosses the land border to Finland. A Nordic fibre carrier sells transit along that route; Tele2, Telenor and Arelion reach the new cities.
2026-11-05 07:31:17 +01:00
Frederic Jung
28e732448e
Merge pull request #290 from fjaeckel/claude/fix-289
Scrubbed clean traffic no longer shows as DDoS junk on links (#289)
2026-11-05 07:05:29 +01:00
Frederic Jung
72f4bb54f3
Scrubbed clean traffic no longer shows as DDoS junk on links (#289)
What a scrubbing center sends back to its target is the target's own
traffic, but compute() carried it under the junk bucket, so a small
flood at a big customer showed up as hundreds of gigabits of DDoS junk
on the backbone. It now has its own bucket, shown as scrubbed clean
traffic in the link panel.
2026-11-05 02:09:52 +00:00
Antoine
c3e1dd9348
WebGL map: keep each picture in a clear border in the atlas
The card blends the texels around the point it reads, so a picture drawn
off whole pixels, or stretched while a zoom moves, read half a texel past
its edge: its neighbour in the atlas, or a picture left from before the
last reset. The map showed thin coloured lines along the edges of cities
and labels. Each picture now goes in with a clear one-texel border, and
painting on the pad is clipped to the picture so the border stays clear.
2026-11-05 00:59:38 +01:00
Antoine
8c2000f6b1
CHANGELOG: one bullet per change players will see
The WebGL work had eight bullets, so with upstream's three the app's What's new (five bullets) showed only two of
ours, and four described fixes to the WebGL map itself, which no release has had: a zoom that lost the context, the
cities repainted at every step of a zoom, the coastlines' points, the garbage per frame. What a player gets from them
goes into the first bullet (smooth zooms, the coastlines, Always 2D freeing the card, a lost card coming back), which
leaves four, each with the pull request's number.
2026-11-05 00:21:38 +01:00
Antoine
32f330b1c3
WebGL map: check the pictures sent to the card at most once a second
A frame that sent pictures read getError() to know whether the card took them. In every browser WebGL runs in another
process, and each read waits for it to finish everything sent so far, uploads included: a wait on the main thread on
exactly the frames that already cost the most (a pan or a zoom sends pictures on most frames, up to 321 in one).

The card keeps an error until it is read, so one read a second still finds a refusal: the pictures are now checked at
most every GL_MEM_EVERY (1 000) ms, and a picture refused in between shows at worst as a dark box until then, after
which the map goes to 2D as before. The first pictures sent into a new atlas are still checked at once, where a card
that allocates it lazily refuses. The cost could not be timed here (no Vulkan driver on this machine for Chromium to
reach the graphics card); the change bounds it whatever it is.

Tests: webgl-out-of-memory reads at most twice in two seconds of panning, and a refusal after the first check gives
the map to 2D within a second.
2026-11-05 00:21:37 +01:00
Antoine
c652bce7d2
Diagnostic info: say how often the map was drawn, and drop a key no release had
The loop runs at the screen's rate even when a still map is not drawn again, so the readout's "fps" said 60 or 240 on
a map that was not being drawn at all, which a bug report would take for the map's speed. It now also says how often
the map was drawn ("map drawn N/s"). The sot-fps setting it carried over only ever existed on this branch, never in a
release, so it is no longer read or removed; ?fps and ?nofps still open and close the readout.
2026-11-05 00:21:36 +01:00
Antoine
b7a9ec3e3c
Settings: say whether the card can draw the map without setting it up
Settings › Map drawing said "This browser cannot" by calling glInit(), so opening Settings on the title screen or in a
puzzle, where the map is drawn in 2D, made the WebGL context and its 64 MB atlas. It now says what is known without
asking the card (glCan()): a card given up or a browser without WebGL2 cannot; a card not tried yet counts as able.
A card that turns out to be the processor's is still named once the game draws its first frame, in Diagnostic info
and in Settings. Test in webgl-context-restore.
2026-11-05 00:21:35 +01:00
Antoine
351b3aa522
WebGL map: take a lost context back, and let it go for Always 2D
The first loss of the WebGL context gave the card up for the session. A context can come back (a driver reset; on a
phone, sometimes just leaving the app), so a phone that went to another app came back to the slower 2D map until the
page was reloaded. Always 2D, chosen in Settings, kept the context and its 64 MB atlas for a map drawn in 2D.

A loss now leaves the 2D map drawing while the context is away (glLost(): the event is cancelled so the browser may
give it back), and everything on the card is built again on the same context when it comes back (glRestored(),
glForget(): glInit() runs as for the first frame). A card lost more than GL_LOSSES (2) times is given up for the
session, so a card that keeps failing does not keep the map switching. Always 2D lets the context go through
WEBGL_lose_context and Auto asks for it back, the same path, never counted as a loss; a context the browser gives back
after the player chose Always 2D is let go again. Without the extension, and for the GPU benchmark's switches
(mapGl(on,false)), the context is kept as before. The listeners and the overlay's wrappers are set once.

Diagnostic info says when the map waits for a lost context. Tests: webgl-context-restore (7), and the loss test of
webgl-out-of-memory now waits for the context instead of giving it up.
2026-11-05 00:21:35 +01:00
Antoine
57546ea18e
2D map: hold its pictures to 48 MB, letting go of those unused the longest
The 2D map keeps a canvas per picture, and the list was capped only by its length (1 400). A long zoom on a big
network paints every city again at each step of its scale, so a pinch from 0.6 to 3.2 and back held 181 MB of
pictures (the TTL save: 179 MB) where one frame uses 2 to 23 MB.

At the end of a frame over 48 MB, the pictures it did not use go, those unused the longest first, down to 36 MB, and
each canvas let go is emptied (0×0) so its pixels are freed without waiting for the collector. The frame's own
pictures are never let go, so a screen that needs more keeps what it needs. Finding a picture now marks it as used.

Measured in jsdom on the same pinch (1280×800 at 2×): 43 MB at most (TTL: 40 MB); 4 781 pictures painted against
4 083 (TTL: 5 549 against 6 030); at most 321 painted in one frame, the same as before (the zoom's own steps).
The card's atlas is unchanged: it has its own fixed size.
2026-11-05 00:21:34 +01:00
Antoine
d57b3ae10f
WebGL map: say how the land's stencil counts, and what the land costs the card 2026-11-05 00:21:33 +01:00
Antoine
10ef838e87
WebGL map: free what the card holds when it is given up for good
Given up while its context still lived (memory refused, a setup failing half-way), the card kept the atlas (64 MB at
4096 px), the tubes' points and the rest while the 2D map began painting its own pictures. glKill() now deletes the
biggest and lets the context go (WEBGL_lose_context, where the browser has it), unless the browser already lost it;
glInit() keeps the context from the start so a failed setup is let go too, and the loss event of a context let go on
purpose does not give the card up a second time. Always 2D still keeps the card for later.
2026-11-04 23:07:25 +01:00
Antoine
123b3d00ea
WebGL map: give the card up for 2D when it refuses a picture without saying so
The atlas, the land, the tubes and the cables read getError() after they are sent, but a picture sent into the atlas
(texSubImage2D) was marked as sent at once: a card short of memory that only set OUT_OF_MEMORY left it kept and
drawn from an atlas that never got it. A frame that sent new pictures now asks once, at its end and before drawing
them; a refusal gives the map to 2D in the same frame and forgets the card's pictures. A frame that only reuses the
atlas still asks nothing.
2026-11-04 23:06:11 +01:00
Antoine
fe109cff84
WebGL map: fill overlapping coastlines as land, as the 2D map does
The card filled the land by an odd/even count over all the coastlines at once, so two coasts that overlap cancelled
out into sea: Timor, drawn by two coastlines, lost most of its inside and its shadow when zoomed in. The 2D map fills
each coast on its own. The fan now turns every coast the same way and the stencil counts windings (+1 and -1 by the
triangles' facing, filled where not zero), which is the 2D canvas's nonzero rule: an overlap counts 2 and stays land.
Same number of draws.
2026-11-04 23:04:48 +01:00
Antoine
b03bec267c
2D map: keep the land picture on the graphics card in Firefox on a computer
The 2D map paints its land into an offscreen picture. In Firefox that picture was a software canvas
(willReadFrequently), because Firefox on Android garbled big paths on its graphics card (#43). Firefox on a computer
had it too, and a software canvas is sent to the card again on every frame, at a cost that grows with the picture:
the whole world at mid zoom, four screens of it zoomed in.

Only Firefox on Android keeps it now (softCanvas()). Measured in Firefox 159 on Windows (RTX 4090, full screen
2560x1440), 2D map, frames per second at zoom 0.6 / 1.1 / 1.6 / 3.2:
- big-network fixture, main: 56 / 37 / 34 / 26; with this change: 64 / 49 / 51 / 78;
- the 183-POP save, main: 32 / 25 / 25 / 22; with this change: 36 / 26 / 33 / 55.
(Measured with the change injected into main's page; the land picture is the same code on this branch.)

tests/world-layer-firefox.test.js: which browsers get the software canvas, and that the land is an ordinary one
elsewhere.
2026-11-04 22:37:15 +01:00
Antoine
cdc7c6d1eb
Settings: one Diagnostic info readout for the screen, the map's drawing and its speed
Settings › Viewport info is now Diagnostic info, and the frame meter of the WebGL work joins it: one readout in a
corner instead of two, for bug reports. It shows:
- what the screen tells the game, as before (sizes, visual viewport, safe areas, standalone, the tab bar);
- what draws the map: WebGL2 and the graphics card's name, or 2D and why (Always 2D, a puzzle, no WebGL2, a
  processor pretending to be a card, a lost context, a card out of memory: glKill() keeps the reason);
- how fast: frames per second, the 95th percentile and slowest frame, draw()'s mean time, the speed and zoom, and on
  the card its segments and packets.
?vp and ?fps open it, ?novp and ?nofps close it, five taps on the date toggle it, and a device that had the frame
meter on keeps it. Its text stays technical and in English: it is pasted into reports. On a 360 px phone it wraps
inside the screen and never takes a tap. The setting's name and description are translated.

tests/diagnostic-info.test.js: the setting, the readout's parts, each reason for 2D, the frame figures, the address
flags and the old setting, the taps, and the phone layout.
2026-11-04 22:37:15 +01:00
Antoine
52c8aaffd6
WebGL map: give the card up for 2D when it runs out of memory without saying so
A card short of memory may refuse a texture or a buffer without throwing: the call only leaves OUT_OF_MEMORY for
getError(), which nothing read. Refused, the 64 MB atlas drew every city, label and marker as a black box while the
map stayed on the card (seen in Chromium by refusing it).

The big uploads now read it (glMem()): the atlas, the land for each zoom level, the tubes once a day, the cables.
The atlas tries 2048 px (16 MB) before giving up; any other refusal is the card's error, so draw() gives WebGL up
for the session and draws the same frame again in 2D. getError() is never read on an ordinary frame: each read waits
for the card.

tests/webgl-out-of-memory.test.js: a 4096 px atlas refused gives a 2048 px one; both refused, or the land or the
tubes refused, leave the map in 2D in that frame with no glitch for the player; panning reads no error.
2026-11-04 22:37:15 +01:00
Antoine
fb76a1e6fd
2D map: draw the pictures with the map's own pen, as main did
Cities, markers and labels are now pictures painted once on a canvas of their own. Drawn straight on the map,
main's dashed rings (the selected city, the cities feeding a selected tube, a flood), the cones' tips, a sleeping
POP's "zzz" and a working cable ship's spark took the state the tubes and labels left on the map's canvas: round
line ends and corners, text centred on its middle. A new canvas starts with square ends and text on its baseline, so
the rings came out with square dashes and the "zzz" sat higher. Every picture now starts with that pen (sprPen()),
on the card's shared canvas too.

tests/map-2d.test.js holds the 2D map to main, for players who keep it:
- for the same state, a frame drawn from the kept pictures is, call for call, the frame painted with no cache at
  all: over every state a POP can be in, a city without a POP, random views of the big network with days passing,
  and seeded random games after every move and day (the route-fuzz driver, two pages in lockstep);
- every tube's width, colour, dash and packets follow main's formulas;
- the 2D map never asks for WebGL, never draws a picture without a canvas, keeps one canvas per picture, draws as
  a 2D map after the card is switched off or lost, and paints again at a new pixel density;
- money pop-ups fade as before; every picture starts with the right pen.
Planted bugs (incomplete keys, a stale key memo, the tubes' looks kept without the routing, one shared 2D canvas,
no pen) each fail it. A pixel comparison with main in Chromium (desktop and phone, the fixture, a late-game save and
states from random games) found the pen and nothing else beyond sub-pixel edges.
2026-11-04 22:37:14 +01:00
Antoine
87b153db6f
WebGL map: keep the pictures' keys, the waves and the clouds out of the garbage
A frame joined a key for every city, label, quiet dot and stamp it drew, built a closure
to paint each even when the picture was already there, concatenated a prefix onto every
key, made an array per city per copy of the map for its place on screen, and rebuilt
the waves' and the clouds' arrays. Keys are now kept per city (packed into one number for
the yes/no parts), per label text and look, per stamp and scale, and joined again only
when the picture changes; pictures already painted are found before any closure is
made; the card's and the 2D map's pictures are two maps, so keys need no prefix; the
cities' places and the POP lights are computed in place; the waves and the clouds are
written into arrays kept from frame to frame.

Sampled heap profile, TTL save, RTX 4060 Ti: allocations under drawFrame 68 -> 37 MB/s
at x1 and 62 -> 43 MB/s during a pan/zoom sweep; under glBegin 5.4 -> 0.5 MB/s.
2026-11-04 22:37:14 +01:00
Antoine
3482142ae5
WebGL map: simplify the coastlines for the zoom
On the card the land was most of a frame's work (the stencil fills twice, the sand, the
edge), and it scales with vertices, not pixels. The land is now built per zoom level
(powers of 2) with each coastline simplified (Douglas-Peucker) so that no point moves
more than 0.25 px at the level's zoom; zooming in takes the finer level at once, zooming
out keeps it until the zoom is 10 % under it. COAST, onLand() and the 2D map are
unchanged.
2026-11-04 22:37:14 +01:00
Antoine
eeeccc60d4
WebGL map: keep the cities' pictures while the zoom moves, paint them sharp once it rests
The scale of a city's picture is in steps of 1/24, so a pinch repainted every city every
~4 % of zoom: hundreds of pictures a frame, and the atlas full and reset over and over.
On the card, while the zoom moves, pictures that grow with it (cities, ships, badges) keep
the step of the scale held when it began, stretched by up to 1.25x either way by the
card's filtering, and take a new one beyond that; 250 ms after the zoom stops they are
painted at their own step again, and a still map is drawn once more for it. The 2D map
paints every step as before.
2026-11-04 22:37:13 +01:00
Antoine
2ff634a0ed
WebGL map: paint the card's pictures on one canvas, so a long zoom keeps the context
Every sprite kept its own <canvas> once it was in the atlas: a long pan and zoom made
~20,000 of them, then a frame of one to two seconds, then CONTEXT_LOST and a silent
fallback to 2D (4 sweeps out of 5). The card's pictures are now painted on one reused
canvas and sent to the atlas at once (texSubImage2D with a sub-rectangle); a full atlas
restarts and takes the picture at once. The 2D map, and a picture too big for the atlas,
keep a canvas each. The card's and the 2D map's pictures are kept apart, and giving the
card up drops its pictures.
2026-11-04 22:37:13 +01:00
Antoine
39941c257e
WebGL map: keep the 2D map where WebGL is drawn by the processor
With the perf benchmark now waiting for the surface the map was drawn on,
headless Chromium showed what WebGL costs without a graphics card: its
SwiftShader renderer spends about 8 µs per instance, so the coastlines alone
(29k segments, twice) took about 480 ms and a big map 1.4 s a frame, where the
2D canvas takes 46 ms. Players get the same with a blocked driver, a virtual
machine or Mesa's llvmpipe. glInit() now reads the renderer first and keeps
the 2D map on SwiftShader, llvmpipe, softpipe, lavapipe, WARP or any
"software" renderer; GLX.soft lets the GPU benchmark measure them anyway.
2026-11-04 22:37:13 +01:00
Antoine
1e9b1d458b
GPU benchmark: isolate trials, time the card, say which map drew
- A trial now ends before the next starts: the clock stops, the frame
  callback is cancelled (and a queued one turned away), a day still in the
  route worker is waited for (or dropped), the clock's leftovers are cleared,
  and every trial starts from the same random numbers.
- The renderers take turns going first, scenario by scenario; ?reps=N runs
  each N times and reports medians.
- draw() is labelled as CPU submission time; the card's own time comes from
  EXT_disjoint_timer_query_webgl2 where available (read frames later, never
  waited for, disjoint results dropped); a run drawn by the other map is
  flagged.
- npm run perf --browser reads its sync pixel back from the surface the map
  was drawn on (the WebGL canvas waits for the card) and says which map each
  version drew with.
2026-11-04 22:37:13 +01:00
Antoine
8491b1a8f6
WebGL map: keep every sprite, the attack ring, an empty title map and a 2D fallback
- A sprite or disc drawn as the queue grows was written into the old array and
  lost: the record is now taken before the array is read.
- A city's picture without an attack shared its cache key with step 0 of a
  DDoS ring (always, with animations off): no attack is now phase -1, and
  cityStatic() reads only what the key holds.
- Back at the title (or on a damaged save), drawFrame() returned before hiding
  the card's layers, so the last network stayed behind the title: the layers
  are now shown or hidden on entry.
- An error from the card (frame start, tube upload, atlas, sprite flush) now
  gives WebGL up and draws the same frame in 2D, once; the 2D context, the
  sprite queue and GLS.frame are reset whatever fails. Other errors still
  reach tickErr() and leave WebGL on.
- Selecting a tube no longer rebuilds and uploads every tube, packet and
  point (about 230 KB on the big-network fixture): its halo is its own small
  buffer.
2026-11-04 22:37:12 +01:00
Antoine
cf9ab5e774
Draw the map with WebGL2 by default, with the 2D canvas as fallback
- Sea, land, waves, clouds, cables, tubes and packets are drawn by the
  graphics card; the land is geometry built once, so panning and zooming
  repaint nothing.
- Cities, labels and markers are painted once into a sprite atlas and drawn
  in one call (with drawImage in 2D, which speeds up the 2D map too).
- Settings > Map drawing: Auto or Always 2D, per device. Browsers without
  WebGL2, a lost context and puzzles keep the 2D map.
- npm run bench:gpu compares 2D and WebGL in a real browser on a real GPU;
  ?fps shows a frame meter.
2026-11-04 22:37:12 +01:00
Frederic Jung
7aa6506e70
Drop the puzzle label the goal list no longer uses 2026-11-04 22:00:32 +01:00
Frederic Jung
29af343739
Puzzles on phones: three goals in plain words with Show me, the problem marked on the map, a sheet that starts small, and a quieter map
The stars become three goals; the current one says what is wrong and what to do. A red ring marks a city still short, a pulsing ✂ the link whose cut hurts. Cities far from the puzzle are left off the map, and idle stepping stones are nameless dots until tapped, used or zoomed in on.
2026-11-04 21:48:21 +01:00
Frederic Jung
b2dddf8f06
Follow-up to #285: Columbus III-and-a-half comes ashore near Cádiz
It never landed on the Biscay coast: its Spanish landing was Conil, on the Gulf of Cádiz,
between Lisbon and the Mediterranean. Its Miami pair keeps ending at Madrid, as on main,
so saves with a Columbus link keep it.
2026-11-04 21:40:51 +01:00
Frederic Jung
96062ed114
Merge pull request #285 from Lambro-codes/feat/bilbao-landing
feat(world): add Bilbao and land the Biscay cables there
2026-11-04 21:40:51 +01:00
Frederic Jung
253927f10c
Merge pull request #286 from Lambro-codes/feat/graph-tooltips
feat(noc): tooltips and clickable legends on the dashboard charts
2026-11-04 21:36:28 +01:00
Lambro-codes
bac645ed5b feat(noc): tooltips and clickable legends on the dashboard charts
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-04 18:58:45 +01:00
Lambro-codes
6906a333b3 feat(world): seven French cities, four French networks, and the Atlantic cables on the Atlantic coast
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-04 17:40:35 +01:00
Lambro-codes
e23a0e2c90 feat(world): add Bilbao and land the Biscay cables there
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-04 17:40:34 +01:00
Frederic Jung
5b24282224
Kinder jokes, meetings where they meet, a quiet North Korea (2.9.1) 2026-11-04 16:40:38 +01:00
Frederic Jung
6da0449ae9
Jokes target networks, never people; meetings meet where they really do; North Korea is a trickle
Every joke now follows the code of conduct: networks, cables and routers are fair game, people, countries
and beliefs are not. Renamed eight networks, three own-cable names and one AI site, and rewrote about forty
descriptions (state censorship and surveillance jabs, national stereotypes, a parody religion, innuendo, a
real person) in every language.

Event customers named after a network operators' meeting only come to a city where it meets: NANOG in the
US, APRICOT in Asia Pacific and Oceania (not mainland China, Hong Kong, the Middle East or Central Asia),
DENOG in Germany, UKNOF in the UK, RIPE in Europe, the Middle East and Africa, DKNOG in Copenhagen.

Pyongyang's broadband tops out around 0.7 Gbps, and no customer of any kind spawns in North Korea.
2026-11-04 16:36:05 +01:00
Frederic Jung
cfbe1afdcd
Atlas Shrugged Telecom is now Atlas Hold-the-Line Telecom 2026-11-04 15:51:46 +01:00
Frederic Jung
39fb61fd31
NOC in its own window, calling the bank, overland fiber where there is no road, deeper zoom, and the Euro Run fix (2.9.0) 2026-11-04 15:37:37 +01:00
Frederic Jung
7295064167
Architect: a diverse tube takes the cheapest other route, and the detour message names every site (closes #282)
The diverse button picked the first other cable listed, which on Amsterdam–London is the dearest, so the Euro Run's plain plan ended at $416k against a $410k budget.
2026-11-04 14:46:47 +01:00
Frederic Jung
0d72311911
Call the bank from AA up, and weird conditions always apply (#251)
A rating no longer gets the buttons. On top of the usual conditions every
called loan carries this week's quirk from CALL_ODD (a yacht, an odd number
of POPs, no links on a Friday, a job for the nephew...): one at AAA, two at
AA. It turns over every 7 days, so a call still rolls no dice and calling
again the same week gets the same offer.
2026-11-04 13:36:46 +00:00
Frederic Jung
8d709d7fb9
Merge pull request #283 from thesysadmindev/call-the-bank
Call the bank: ask for a loan from the Bank window
2026-11-04 13:34:30 +00:00
Frederic Jung
ea59443748
NOC window: wait as long as a window may go quiet before saying the pop-up was blocked
A slow machine loading the whole page on a big network can take more than 4 s
to say hello; the warning now waits NOC_LOST (10 s).
2026-11-04 13:32:16 +00:00
Frederic Jung
97e7cb17bd
Merge pull request #279 from thesysadmindev/noc-window
A NOC screen in its own window, for a second display
2026-11-04 13:31:24 +00:00
Frederic Jung
eae0b3d127
Merge pull request #284 from yeled/df-pop-checks
Typed orders get the map's limits: a link starts at a POP, and Build POP and Found IX say why they can't
2026-11-04 14:26:54 +01:00
Frederic Jung
0d8d5df472
Nothing leaves South Korea over land
Its only land border is the DMZ, so a South Korean city and any city of
another country are across the sea (isSub()), whatever landmass they share:
Seoul reaches China, Russia and Japan by subsea cable only.
2026-11-04 13:25:34 +00:00
Charlie Allom
82f3833d8f
Founding your own IX says why it can't
foundIx returned without a word in mainland China, where an exchange
already runs (incumbent or your own), and without a POP, while its dry
run quoted $80k with nothing blocked. foundIxWhy() gives the reason, most
lasting first (China reuses the panel's own text), for the toast and the
quote alike.

The route fuzz's direct moves called foundIx at every POP city. They now
offer it only where the city panel shows the button, as their comment
says, so a refusal that now logs a toast does not count as diverging
from main.
2026-11-04 23:07:57 +10:00
Charlie Allom
034a5de66e
Merge remote-tracking branch 'origin/main' into df-pop-checks
# Conflicts:
#	src/game/90-actions/60-links.js
#	src/game/90-actions/87-fiber-and-hardware.js
#	src/game/90-actions/90-action-helpers.js
2026-11-04 22:49:53 +10:00
Frederic Jung
08bf22cfec
Fiber over land inside one country; no circuits between the Koreas
Towns with no road in (Russia's Arctic and Kamchatka, Juneau and Alaska's
Arctic coast, Greenland's towns) keep their own landmass, which now says
which land it is really part of. isSub() lets two cities of one country on
that land build over land; other countries still need the sea. Inside one
country, Europe to Asia (Moscow-Vladivostok, Istanbul-Ankara) is no longer
a crossing between continents.

North and South Korea join Kyiv-Moscow in a table of pairs nobody sells a
circuit between: the link window says so, the actions refuse, and neither
the diversity map nor the latency floor counts a link there.
2026-11-04 12:46:37 +00:00
Charlie Allom
4b554f2ecb
A POP in a retired city says why it can't open
buildPop returned without a word for a city that is off the map (the small
Brazilian towns retired in 3d469d9), so the agent API reported no_effect
with no toast. It now toasts that the city is off the map and names the
nearest open city in its country to build in instead, and its dry run
reports that as blocked. An old save that kept a POP there is unchanged.
2026-11-04 22:46:10 +10:00
Charlie Allom
3fd44908af
A link starts at one of your POPs, for typed orders too
The map only drags a link from a POP, but buildLink, orderDf and orderCable
read both ends from UI.pending, which the agent API fills from its
arguments. An agent could sign a dark fiber IRU from a city with no POP
(Aracaju got three of them). The three orders now refuse that with a toast,
and their dry-run quotes report it as blocked.

Three tests ordered from a city with no POP (ACT.start ignores city, so the
only POP was Frankfurt); they now open the POP they assumed.
2026-11-04 22:45:52 +10:00
Christopher Hawker
ae70e8e750 Call the bank: ask for a loan from the Bank window
With a rating of A or better, five amount buttons in the Bank window make an
immediate offer. The terms follow from the rating alone (bank, APR, conditions
and limit in CALL_TERMS), so calling again gets nothing better and rolls no
dice. The limit is a multiple of monthly revenue less current debt. An offer
goes through the existing card and takeLoan, and a new call replaces an earlier
called offer.

Fixes #251
2026-11-04 23:40:46 +11:00
thesysadmindev
6c0342ad1f
Merge branch 'main' into noc-window 2026-11-04 23:08:54 +11:00
Frederic Jung
ac5ce7fa05
Zoom in twice as far; ships at anchor keep clear of their port
ZMAX goes from 16 to 32. A club ship near its home city is drawn at least
46 px (times the icon scale) out from the city's marker, along the line from
the city, and a tap on a city's own marker picks the city before any ship.
2026-11-04 11:54:31 +00:00
Frederic Jung
0ad36c2178
Release skill: CI tests and benchmarks a release, so don't run them locally 2026-11-04 09:31:25 +00:00
thesysadmindev
b6d89847bb
Merge branch 'main' into noc-window 2026-11-04 20:31:14 +11:00
Frederic Jung
b405bf78fc
Every capital of the world, peering headroom for the intern, smaller ports (2.8.0) 2026-11-04 09:30:49 +00:00
Christopher Hawker
f9d24699c1 Merge remote-tracking branch 'upstream/main' into noc-window
# Conflicts:
#	CHANGELOG.md
#	src/game/99-loop.js
#	tests/harness.js
2026-11-04 20:01:57 +11:00
Christopher Hawker
80f671953a A NOC screen in its own window, for a second display
A button next to the speed controls opens this page at ?noc=<slot> in a
noopener pop-up, so it runs on its own thread. The window never claims the
slot, saves or runs a day. The game sends it a copy of S and R over a
BroadcastChannel, at most once a second and only while a window is connected,
and runs its clicks through an allowlist of the same ACT.* a click uses.

The window opens on a dark wallboard: a live world map of links and POPs,
traffic and money graphs, alarms, and the hottest ports with the dashboard's
own upgrade buttons (connUp). Clicking a POP filters the ports. Details shows
the full dashboard. Phones do not show the button.
2026-11-04 20:01:37 +11:00
Frederic Jung
47799d7e47
Merge remote-tracking branch 'origin/main' 2026-11-04 08:32:00 +00:00
Frederic Jung
95fd50b0bb
Relay comment points at where agent mode now holds the clock 2026-11-04 09:09:53 +01:00
Frederic Jung
ad9aabb265
Follow-ups to #271
- IX ports are measured at their nominal capacity: a LACP fault or one
  building down no longer buys a bigger port for a day or two.
- The order stops before working anything out when its budget is spent
  (31 ms a day to 0.05 ms on the big network at 3x), and a port that takes
  a LAG no longer prices every upgrade first.
- The log names the exchange, not its city.
- Tests for the LACP case and a remote IX port; a test comment's numbers;
  a shorter CHANGELOG bullet that no longer promises a per-POP switch for
  remote ports.
2026-11-04 08:03:10 +00:00
Frederic Jung
8b0e198c03
Merge pull request #271 from thesysadmindev/intern-port-headroom
The intern can keep PNI and IX ports ahead of their traffic (closes #234)
2026-11-04 07:55:14 +00:00
Frederic Jung
c7fd54b067
Latency offers only ask for a ceiling a build can meet (#273)
The ceiling came from the straight-line distance, and nothing checked that a
path could reach it: Pevek-Anadyr asked for 4.3 ms over a 7.7 ms sea route.
latFloor() is the fastest a build could get, over own fiber on land and the
routes of cables that land at both ends; an offer whose ceiling is below that
and below what you already have is not made, as diverse offers are not.
2026-11-04 07:54:55 +00:00
Frederic Jung
b74fe1bda6
Merge pull request #266 from wnagele
# Conflicts:
#	CHANGELOG.md
2026-11-04 08:44:34 +01:00
Frederic Jung
24d865aa57
Follow-ups to #276, #277 and #278
Saves clamp a runaway DE-Kicks price and its remembered quote to the ceiling, and a clipped rise announces only what the bill shows.
A PNI steps down only to the smallest size its network sells, so Tier 1 and closed-CDN PNIs stop at 100G.
A trace off the metrics says it shows a customer circuit's path, not where the internet traffic goes.
2026-11-04 08:11:03 +01:00
Frederic Jung
c358b715c7
Merge pull request #278 from Lambro-codes
# Conflicts:
#	CHANGELOG.md
2026-11-04 07:46:20 +01:00
Frederic Jung
2d9d4177be
Merge pull request #277 from Lambro-codes
# Conflicts:
#	CHANGELOG.md
2026-11-04 07:46:20 +01:00
Frederic Jung
4ce7331c6a
Merge pull request #276 from Lambro-codes
# Conflicts:
#	CHANGELOG.md
2026-11-04 07:46:19 +01:00
Frederic Jung
3250d95d38
Merge pull request #275 from Lambro-codes 2026-11-04 07:46:12 +01:00
Frederic Jung
c04fbe88b8
Merge pull request #274 from fjaeckel/claude/fix-272 2026-11-04 06:39:35 +01:00
Lambro-codes
35854ee253 feat(peering): step exchange ports, transit ports and PNIs down one size
Shrinking a port meant leaving and rejoining. The exchange, transit and PNI panels now have a button that steps the port down one size (downIx, downT, downP). A PNI cannot step down while an augment is on order. The actions are classified in the MCP command table.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-04 05:36:04 +01:00
Lambro-codes
b57c022860 feat(traceroute): choose how the trace is routed
The traceroute can follow the metrics, the lowest latency or the quietest links, like a customer circuit. traceMode is classified in the MCP tables.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-04 04:32:17 +01:00
Lambro-codes
81e4fbd215 fix(peering): cap the DE-Kicks personal price multiplier
DE-Kicks ports stop getting dearer once they cost four times the list price. The yearly harmonisation kept compounding, so a long game paid $100k a month for one port.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-04 04:32:16 +01:00
Lambro-codes
2d88a04584 feat(ui): show billions of dollars and petabits per second
Money shows $1.20B and bandwidth 1.00 Pbps instead of running on in millions and terabits, including the NOC graph and the fibre labels on the map.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-04 04:32:16 +01:00
Frederic Jung
ba835c0604
Your own subsea cable round Cape Horn earns The Long Way Round (#272)
The badge only counted a wave on the old ring between Buenos Aires and
Santiago. Your own cable between them (laid since #67) has no cable id, so
it never counted. It now counts any of your own subsea cables whose
surveyed path passes south of Tierra del Fuego.
2026-11-04 01:56:19 +00:00
Wolfgang Nagele
7438fd1065 Agent mode: an AI agent plays in the player's own tab, with the agent's clock or a running one
The MCP server gains a second session, --browser: the game in the player's tab, reached through the
agent relay npm run dev hosts at /agent (loopback unless --host; Host and Origin checked, no token).
The player turns it on in Settings → Agent API, a section only the development page has, and picks the
clock: a pace of 30 s to 5 min a day that nobody can pause, or the agent's own. Headless gets the
running clock too (--clock realtime --pace MS) and both get a wait tool.

All of it lives in src/agent/ (development page only). The game offers HOOKS, UI.clockLocked,
setSpeed() and runClock(dt), the frame's day block moved out unchanged, and nothing more: the page
players get grows by under 1 KB gzipped and runs exactly as before.
2026-11-03 16:18:43 -05:00
Wolfgang Nagele
2526dd458d MCP server on the official SDK, over stdio or HTTP
scripts/mcp.js registers the same tools on @modelcontextprotocol/server (2.4.0, with
@modelcontextprotocol/node 2.1.2 for node:http; dev dependencies, pinned) instead of its own JSON-RPC
loop. stdio works as before; --http [HOST:]PORT serves Streamable HTTP at /mcp, on loopback unless
told otherwise.

Over HTTP every request's Host must be an address of this machine (or --allow-host), an Origin other
than localhost is refused, and a bearer token (SOT_MCP_TOKEN or --token-file) is optional; bound
beyond loopback without one, the server warns. load_save and export_save take JSON only there, or files
under --save-dir and nowhere else. Calls from every client run one at a time, in order.
2026-11-03 16:18:38 -05:00
Wolfgang Nagele
5b76685e5c MCP: the agent facade moves into src/agent/, assembled into the development page only
The command tables and the page-side reads, screens and dispatch (scripts/lib/mcp-commands.js and
mcp-page.js) become src/agent/, the facade window.TUBES.call(tool, args) in the page's own scope.
A new <!-- @include-dev agent --> line in src/index.html pastes it in after the game, but only in the
development page (npm run dev, the MCP server, i18n-check, tests that ask with load({agent:true})).
The build drops the line whole: _site/ is byte for byte what main builds.

Tests load the page players get by default, the build test fails if anything outside src/agent/ names
the facade's api/API_ names, and the pages test checks the built page carries none of it and still
plays. ADR 0004 records the rule.
2026-11-03 16:18:38 -05:00
Frederic Jung
b2366ed260
Every capital in Africa, which completes every capital of the world
Brazzaville and Congo Telecom join, Abuja gets Nigeria's wholesale backbone, the Gulf of Guinea and Comoros islands sit on their cables, and the capitals test now checks all 193 UN members.
2026-11-03 22:11:43 +01:00
Frederic Jung
b4cfa2b320
Every capital in South, East and Southeast Asia and the Pacific 2026-11-03 21:17:45 +01:00
Frederic Jung
894307a35c
Every capital in the Middle East, the Caucasus and Central Asia, with Bahrain on the Gulf's cables
The MCP server reads a dropdown as its selected option, so a long network list no longer crowds the traceroute out of a report.
2026-11-03 20:48:15 +01:00
Frederic Jung
296392fb96
Every capital in Europe: Tirana to Ljubljana, Malta and Cyprus on their cables, and Bern
Sixteen capitals and Bern. National telcos with their real ASNs (One Albania,
Andorra Telecom, Beltelecom, BH Telecom, Hrvatski Telekom, Cyta, Cablenet, FL1,
Hoi, Telia Lietuva, Bite, GO, Melita, Moldtelecom, Monaco Telecom, Crnogorski
Telekom, Slovak Telekom, Telekom Slovenije, Telenet San Marino), and the groups
already in the game take the countries they really run (A1, Orange, Vodafone,
Telekom Srbija, Magyar Telekom, TIM). Andorra and Monaco have one operator each
(W2), San Marino buys its transit in Italy (W3).

Malta and Cyprus are islands on PEACE, MedNautilus, Blue and Malta's own lines
to Sicily; Malta's coastline from Natural Earth. Exchanges only where PeeringDB
has one with members. The capitals test covers Europe's 44.
2026-11-03 19:40:23 +01:00
Frederic Jung
c5c0d853ae
Every capital in the Americas: the eastern Caribbean, Central America, the Guianas, Haiti, Sucre
Saint John's, Basseterre, Roseau, Castries, Kingstown and Saint George's land
ECFS and Southern Caribbean Fiber in their real order (the old pairs stay for
saves), with Flow and Digicel on every island. San Salvador, Tegucigalpa and
Managua get Claro and Tigo; Belize, Guyana, Suriname and Haiti their national
telcos (BTL, GTT, Telesur, Natcom, real ASNs). Sucre, Bolivia's constitutional
capital, has no facility, so it is a W3 exception.

Guyana and Suriname land SG-SCS, Deep Blue One and X-Link; Haiti Fibralink to
Jamaica and the Bahamas' BDSNi, and shares Hispaniola with the Dominican
Republic. The six islands' coastlines come from Natural Earth 1:50m, like
Cebu's. Exchanges only where PeeringDB lists one with members.

tests/capitals.test.js checks the Americas' 35 capitals.
2026-11-03 19:11:56 +01:00
Frederic Jung
017eba4ca2
Every US state capital, Washington DC, Canada's capitals and Greenland
44 US cities (every missing state capital and DC) and 12 Canadian ones (every
provincial and territorial capital), sized by metro population, with exchanges
only where PeeringDB lists a real one. Level Tree is in every state capital;
Cogentle, AT&Tease and Drizzle Electric in the bigger ones, and Drizzle on the
Edmonton, Winnipeg, Saskatoon and Quebec City exchanges as Hurricane is.

Greenland: Nuuk, Qaqortoq, Sisimiut and Aasiaat, each its own landmass (no road
or fiber over the ice), on Greenland Connect's real landings (Iceland-Qaqortoq-
Nuuk-Newfoundland) and Connect-the-Dots North up the coast. Too Sassy (Tusass,
AS8818) is the one operator. Iqaluit has only satellites: a beach, no seller.

New regional carriers: Bell Alien (Bell Aliant, AS855), SaskTell-Tale (SaskTel,
AS803), Northwest Passage Tel (Northwestel, AS22573). Victoria and Iqaluit are
documented W3 exceptions, Greenland a W2 one; the real names go on the blocklist.
2026-11-03 17:57:27 +01:00
Christopher Hawker
44c587221a Merge remote-tracking branch 'upstream/main' into intern-port-headroom
# Conflicts:
#	CHANGELOG.md
2026-11-03 22:56:58 +11:00
Christopher Hawker
62c242c9a7 The intern can keep PNI and IX ports ahead of their traffic (closes #234)
A new standing order, Keep peering headroom, works like the transit one: it
keeps each PNI and IX port above a multiple of today's traffic (1.25x to 3x).
A single port at a POP with several routers gets a second port in a LAG; any
other port moves up to the smallest port size that fits, or the biggest the
router takes. If the preferred move cannot be done it tries the other one.

It pays through the same actions as a click (ACT.pni, ACT.lagP, ACT.buyIx,
ACT.lagIx), is off by default, has the Headroom and Budget dials and the
per-POP switch, and keeps to the cash floor. A PNI augment on order is waited
for, router ports an augment will take are not promised twice, and nothing
is bought while a DDoS flood is live, since the flood counts as port usage.

The intern's monthly bill figure (opsMoNow) now counts IX ports too.
2026-11-03 22:54:54 +11:00
Frederic Jung
41d5bc8b21
Northern Australia, keyboard shortcuts, faster subsea cables (2.7.0) 2026-11-03 12:47:12 +01:00
Frederic Jung
d1a2504104
Merge branch 'pr270b'
# Conflicts:
#	CHANGELOG.md
#	src/game/93-ui/82-keys.js
2026-11-03 12:10:19 +01:00
Frederic Jung
48ba0048da
Keyboard shortcuts: the Help button works on the title screen; MCP knows the new actions
Before a game starts the click handler only runs allowlisted actions, so Help's
Keyboard shortcuts button did nothing on the title screen. Allow it, and close
the list with helpClose, so ? returns to the title instead of leaving an empty
map. popStep, zoomStep and keys are views for the MCP server.
2026-11-03 11:50:48 +01:00
Frederic Jung
9cf90d0ad0
Merge branch 'pr270' 2026-11-03 11:50:47 +01:00
Charlie Allom
c5c5aac970
Merge remote-tracking branch 'origin/main' into keyboard-shortcuts 2026-11-03 10:48:01 +00:00
Charlie Allom
3192f42b5a
$ steps through the open offers, soonest to expire first
$ moves the map to the next offer's city, in the Deals list's order,
opens the Customers tab on a POP and marks the offer under Offers here
(UI.offerAt, the existing .row.on style). Two offers in one city each
get a press; any other selection clears the mark. With nothing on the
table it says so with the Deals tab's own "No open offers" text.
2026-11-03 10:47:51 +00:00
Frederic Jung
b7e5f193b4
pages test: look for raw labels one text node at a time
The check joined whole panels' textContent, so a NOC log line ending in a
full stop ran into its timestamp ('facendo.' + 'proprio ora') and read as a
label. The new cities moved the seeded game onto such a line in Italian.
2026-11-03 10:43:45 +00:00
Charlie Allom
daec638bfc
MCP: classify popStep, zoomStep and keys, the keyboard shortcuts' actions, as views 2026-11-03 10:39:00 +00:00
Charlie Allom
a0acb27c7a
Merge remote-tracking branch 'origin/main' into keyboard-shortcuts
# Conflicts:
#	CHANGELOG.md
2026-11-03 10:39:00 +00:00
Frederic Jung
823e4188be
Pay to hurry the permits and factory of your own subsea cable (closes #258)
Before laying starts, seaRush buys 30 days a step (or all of them at once)
at $500k plus $60 a km, with the market's build prices. The floor is the
factory: 60 days plus a day per ~80 km from the order (prepMin, through
leadDays), then the lay ships still need their time at sea, which a second
ship still halves. 6,000 km: from 600 days of prep to 132 for about $13M.
2026-11-03 10:35:16 +00:00
Charlie Allom
2680f3d82b
The arrow keys and W A S D move the map while held
The map moves at 700 px a second on screen at any zoom. The keys run
their own frame loop only while one is down, so the game loop does no
extra work. Letting go, a window opening or leaving the browser window
stops it, and a slow frame moves at most 50 ms worth. Arrows still
scroll the NOC dashboard when it is open, and Alt or Cmd with an arrow
stays the browser's.
2026-11-03 10:31:42 +00:00
Frederic Jung
4d609d996f
Port Hedland, Townsville and Alice Springs; the wet season up north (closes #255)
Three cities in the gaps of northern Australia, Telstraya everywhere, Hocus
Pocus in Port Hedland and Townsville, Aussie Boyband in Townsville. Port
Hedland lands the No Worries Cable System up to Darwin (the real NWCS) and a
Port Hedland-Singapore pair on the Darwin Award Cable (the DJSC interconnect
onto the ASC). Alice Springs has no cable and its only facility is an old
telegraph station.

Cities in the tropical north (Darwin, Port Hedland, Townsville) are wet: from
November to April a cut on land there takes twice as long to reach, with its
own message. The real DigiCo, iseek, NEXTDC, NWCS and DJSC names go on the
blocklist.
2026-11-03 10:28:03 +00:00
Frederic Jung
2a503b223e
MCP: fix the quote that broke the rules reference 2026-11-03 10:23:12 +00:00
Frederic Jung
83740911e8
MCP: new_game takes the Best Effort preset (soft); docs and the rules reference say so 2026-11-03 10:22:30 +00:00
Charlie Allom
d88684d86e
n opens the NOC dashboard, and a letter right after it opens a tab
n then o, u, c, t, r or l, within a second, opens Overview, Customers,
Connections, Traffic, Links & routers or Leased lines. n never closes
the dashboard, so n c switches tabs without it flashing shut; Escape
closes it. Shift on the way does not cancel the wait, any other key
does. The ? list shows the letters.
2026-11-03 10:20:15 +00:00
Frederic Jung
a031b81d4d
Merge branch 'pr269' into HEAD
# Conflicts:
#	CHANGELOG.md
2026-11-03 10:19:15 +00:00
Frederic Jung
186e4c65d1
MCP: classify routingOpen, the new Routing & DDoS window, as a view 2026-11-03 10:18:52 +00:00
Charlie Allom
23eeddf44f
Keyboard shortcuts: [ ] step through your POPs, - = zoom, ? lists every key
[ and ] select the previous or next of your POPs, in the order Find a
city lists them, and move the map there. - and = (also _ and +) zoom
around the middle of the map. ? opens a list of every shortcut, and Help
links to it on a computer. Keys are ignored while typing, with Ctrl or
Cmd held, or behind an open window.
2026-11-03 10:08:29 +00:00
Frederic Jung
1c498734b4
Merge branch 'pr264' into HEAD 2026-11-03 09:56:14 +00:00
Frederic Jung
366c9a2542
Best Effort mode, Routing & DDoS settings, full POP prices (2.6.0) 2026-11-03 10:30:49 +01:00
Frederic Jung
3048c18b14
Fit the left tabs on small screens; move routing settings into a modal
The left panel's four tabs overflowed its 272px width on tablets and small
laptops: Goals wrapped its count, Networks ran off the edge. Counts now sit
on the tab's corner, labels stay on one line and shrink last.

Backbone, Auto-TE and DDoS settings sat below every notification in the NOC
tab. A Routing & DDoS button at the top opens them in a modal that redraws
in place after each action, with a red dot when Auto-TE is paused.
2026-11-03 10:20:57 +01:00
Charlie Allom
a47fc0735f
Show the cache hop in traceroute only when a cache is the exit
The hop for an embedded cache sat in a bare else, so every trace that
left over transit, an exchange or a PNI without a peer's cone printed
an "embedded cache in your rack" hop, even with no cache box at all.
2026-11-03 08:32:00 +00:00
Frederic Jung
4a66bbf998
Best Effort: PNIs are up at once, no attack warnings without attacks
A pnis rule (wait or instant): in Best Effort pniLead() is 0, new PNIs are
on the moment they are ordered and augments and LAG members are applied at
once (pniUpDone(), split out of pniDay()). Gaming customers' attack warning
shows only where DDoS can happen.
2026-11-03 08:19:10 +00:00
Frederic Jung
09f205e458
Add Best Effort, a soft mode, and quiet notifications
A fourth Normal preset, gentler than Change Freeze: calm chaos (so no DDoS
and no chaos monkey), quick builds and no market, plus four new rules that
only it softens: sea cuts mend on their own clock without cable ships, no
conference season, a five-year Ministry of Tubes rescue loan instead of
game over, and customers who sour half as fast. The new rules are written
into S.rules only when they differ from the classic game, so older networks'
rules stay byte for byte what they were.

Quiet notifications is a new setting for every mode, on by default in Best
Effort: toasts the day itself raises pop up only for trouble and milestones,
the rest goes to the NOC log; what a click says still shows. Best Effort
badges count as Freeze-dried. The preset picker is four wide, two by two on
a phone in portrait.
2026-11-03 08:12:09 +00:00
Frederic Jung
de4a750cdd Let the intern light new fiber with the biggest optic (#262)
The optics order gets an Optics setting: most Gbps per dollar (the old
behaviour, still the default) or the biggest optic on new fiber, the most
Gbps per channel that fits the budget. It is still an intern: once a fiber
is lit it keeps adding what is in there and never swaps optics or line
systems. X.can() takes a quiet flag so asking about an unaffordable optic
is not logged as the budget running out.
2026-11-03 09:11:08 +01:00
Frederic Jung
3e57b41e13 Keep route-server networks on the route server (#265)
With an Open policy and the route server on, the peering desk still picked
networks the route server already reached and stored them as bilateral
sessions. It now skips a request from a network ixSessions() already has,
after drawing its random numbers, so the desk's draws stay as they were.

The changed peer list still moves seeded games a little: the Mid-Atlantic
scenario's floor goes from day 40 to 30 (main wins on days 34-58 across
seeds), and the past week 2026-W44 is regenerated as rev 3.
2026-11-03 09:03:33 +01:00
Wolfgang Nagele
a72cb7d760 MCP server: typed, checked actions with outcomes and dry-run prices; schema, catalog, state, results and ui tools 2026-11-02 21:10:35 -05:00
Frederic Jung
da1a4e2f3c
Give POPs built by links, fiber, cables and seats the standard routers (#261)
Only Build POP applied the standard. A wave, dark fiber, own subsea cable
or consortium seat to a new city now applies it too, and their offers
quote newPopCost() (the site plus the standard's routers).
2026-11-02 21:45:30 +01:00
Frederic Jung
1a4a62d0f2
Show the standard POP's routers in the price of a new POP (#261)
The Build POP button quoted only the site, though popStdApply then paid
for the standard routers on top. popStdQuote() prices the standard the
way it is paid; the button, a note under it and the intern's one-tap
template now include it, and the toast says what the routers cost.
2026-11-02 21:40:14 +01:00
Frederic Jung
15dc5741d4
Mostly a performance release: half the routing CPU, no freezes, instant clicks; real calendar, right-sized caches (2.5.0) 2026-11-02 07:39:18 +01:00
Frederic Jung
295908f859
Cache boxes sized by the city's own traffic split: Russia, China and Korea use their network lists, no box without local traffic (closes #260) 2026-11-02 07:36:17 +01:00
Frederic Jung
add3d67e48
Merge perf/6-routing-design: routing keeps its structural tables and runs as small functions, about half the CPU, identical results (347 fuzzed games)
# Conflicts:
#	CHANGELOG.md
2026-11-01 21:57:08 +01:00
Frederic Jung
640b65ce9a
Differential random games: main's page and this checkout's play the same seeded game move for move
scripts/route-fuzz.js plays many random games (every mode: presets, sandbox, scenarios,
the weekly, puzzles, architect runs, or a save) on two pages in one process and compares
all of R, R.fl, R.ef, the PNI lists and S after every move and every day, and routing with
the kept tables against routing without them. tests/route-fuzz.test.js plays four.
2026-11-01 21:44:30 +01:00
Frederic Jung
8b0c624b21
Merge remote-tracking branch 'origin/main' into perf/6-routing-design 2026-11-01 19:42:12 +01:00
Frederic Jung
204af83bff
Merge origin/main 2026-11-01 19:27:10 +01:00
Frederic Jung
0dad03727f
Merge #254: a plug-in optic too short for a subsea cable is no longer sent to upgrades that cannot stretch it (closes #253)
# Conflicts:
#	CHANGELOG.md
2026-11-01 19:27:10 +01:00
Frederic Jung
d93d598d01
Tests count calendar months, not 30 days (#257) 2026-11-01 19:27:01 +01:00
Frederic Jung
37def9dd6b
The game as a local MCP server: play, inspect and debug it from an AI client
scripts/mcp.js speaks MCP over stdio and loads the game from src/ in jsdom,
seeded, like the tests. Tools: new_game, load_save, export_save, status,
advance (with per-day timings), network, city, find, traceroute,
peering_check, hot_spots, actions, act, screen, panel, click, open_link.
Actions go through ACT as buttons do; files, slots, settings and the clock
stay out of reach, and nothing evaluates code in the page. Nothing is
hosted and the page is unchanged. See docs/MCP.md.
2026-11-01 18:04:22 +00:00
Frederic Jung
2122db8cc4
Architecture notes on the kept routing tables and compute()'s small functions; CHANGELOG 2026-11-01 19:04:18 +01:00
Frederic Jung
85e62f6392
Routing adds up per-kind traffic in typed arrays and keeps its group array's storage: half the allocation per compute
R.egT and R.netEg were summed by key in push(), which boxes every new value; they are now Float64Array sums written
back after routing, in the same order and key order. The first group G was emptied with length=0 for every flow,
which gives back its storage so the next push allocates it again; it is now G[0..GN). 27.5 MB -> 13.5 MB per compute.
2026-11-01 19:04:17 +01:00
Frederic Jung
a428ed817f
Routing keeps its structural tables between calls and runs its hot loops as small functions, identical results
compute() was one 33 KB function that V8 never kept optimised: it ran in baseline code, boxing every number,
and was recompiled in the background (about a second of compile each time on a loaded machine) only to deopt.
Its stages now run as closures of their own (compute's own bytecode: 7.7 KB) and the money is computeMoney().
The shortest paths and the exit lists (okBy, reach, BRJ/LIST, DSEL) are kept between calls under keys built
from everything they depend on (29-route-cache.js). Exits and paths have one object shape each.
The equivalence tests compare cached against uncached routing; tests/route-cache.test.js checks the keys.
2026-11-01 19:04:17 +01:00
Frederic Jung
3501a642a2
A real calendar: months of 28 to 31 days and leap years; monthly prices, loans, the intern budget and conferences follow it (#257) 2026-11-01 19:02:06 +01:00
Frederic Jung
25a43e22df
A 1.6T transponder takes two ports on 800G routers, one per 800G client (#256) 2026-11-01 19:02:06 +01:00
Frederic Jung
935c08839f
Clicks that change nothing routing reads keep their routing (loans do reroute); CHANGELOG corrected 2026-11-01 18:36:52 +01:00
Frederic Jung
de9b56befe
Puzzle speed test: time the fastest of 7 evaluations, so a busy CI runner cannot fail it 2026-11-01 18:09:52 +01:00
Frederic Jung
167e2a715b
Merge perf/3-worker: each day's routing runs in a Web Worker built from the page's own script, identical results 2026-11-01 16:52:07 +01:00
Frederic Jung
fde4279633
M3: the day's rule checks now live in its two halves, dayPre() and dayPost() 2026-11-01 16:39:35 +01:00
Frederic Jung
18db953818
Merge remote-tracking branch 'origin/main' into perf/3-worker
# Conflicts:
#	src/game/80-simulation/30-compute.js
2026-11-01 16:14:07 +01:00
Frederic Jung
bc5539c632
Merge perf/2-typed-arrays: routing loop on typed arrays, identical results 2026-11-01 15:43:25 +01:00
Frederic Jung
b6c2fe677b
Speed test: switch off the routing shortcuts in their new spelling (flows are columns now) 2026-11-01 15:34:42 +01:00
Frederic Jung
9bdc2b70e1
Prototype: route each game day in a Web Worker built from the page's own script
The day is split around its routing (dayPre, compute, dayPost). In play, S goes to a
worker started from a Blob URL of the page's inline game script (nothing fetched), the
day waits for R and finishes when it arrives. Actions, failures, events and the intern
still route synchronously; an action mid-day wins over the worker's stale answer.
R crosses as plain data: R.ef as its raw arrays (transferred), flows as columns.
Tests and any worker failure keep the synchronous path.
2026-11-01 15:04:45 +01:00
Frederic Jung
88c37d1b48
Routing loop: gather flows in reused scratch columns, and walk paths and exit lists with index loops
Fewer short-lived objects per compute: no array growth while gathering flows
(copied into each result's own columns), no iterator results in push or in
the exits-by-network setup, and R.efg reads the edge sums in place. Results
are identical to main.
2026-11-01 14:52:36 +01:00
Frederic Jung
0eba165bed
Cable ships, two new Tier 1s, shared cache ports, standard POPs and a faster big network (2.4.0) 2026-11-01 13:32:07 +00:00
Frederic Jung
89fc8b8d03
Routing loop: keep flows in typed-array columns instead of objects, and add up link and transit totals without boxing numbers
Flows are packed into Float64Array/Int32Array columns; R.fl builds the old
objects only when read. Edge egress sums keep a slot per egress in a plain
array, and R.tNet is added up in a typed array and written out at the end,
in the same key order. Results are identical to main.
2026-11-01 14:27:45 +01:00
Frederic Jung
0355eb4e38
Routing loop: set up a flow's city tables only once it has exits at the rank; drop the per-rank flow rebuild that cost more than it saved 2026-11-01 14:09:17 +01:00
Frederic Jung
dd10a6c19c
Faster routing and map: finished flows leave the rank loop, flows keep their exit table, lazy exit labels, off-screen links culled by box 2026-11-01 13:51:25 +01:00
Frederic Jung
fda5607238
Doitsche Telekomm and Tangerine Telecom are Tier 1s (#194)
Both are typed t1 and count for the Tier 1 goal in new games only (t1v 4);
older saves keep the Tier 1s they were playing for. Doitsche sells transit
at 12/Gbps, the dearest in Europe outside the China crossing, and keeps its
paid peering and 1G PNIs. Tangerine keeps its selective policy, sells at 6,
and gains a Frankfurt PoP like every other Tier 1.

W2 now counts Tier 1 incumbents with home markets; the N3 exceptions for
both are gone, since Tier 1s are not checked there.
2026-11-01 12:23:33 +00:00
thesysadmindev
54f40221d5
Merge branch 'main' into sea-optic-hint 2026-11-01 23:11:36 +11:00
Frederic Jung
19b546f5ab
Damaged saves are retried by the next version and have a Try again button; imports up to 64 MB 2026-11-01 13:08:43 +01:00
Frederic Jung
597cc40aef
Faster Networks tab and map labels: count connections without building them, cache exchange lists, grid label check 2026-11-01 13:08:43 +01:00
Frederic Jung
5e27f9e787
Cable ships a tad smaller on the map 2026-11-01 12:07:24 +00:00
Christopher Hawker
0bf27a66c7 A plug-in optic too short for a subsea cable is no longer sent to upgrades that cannot stretch it (closes #253)
On an own subsea cable, the hint under an optic that cannot reach the route
said "Consider submarine terminals or optical engineering" for every optic.
Those upgrades only lengthen the Sienna WaveMagic 1.6T and 3.2T transponder
modes (optModes()); the 400ZR+ and 800ZR+ plug-ins gain nothing, also with
both upgrades in service. Perth to Cape Town (8,891 km) showed it: 800ZR+
reaches 5,400 km and the advice was to buy $17M of upgrades that change
nothing.

chWhy() now asks whether the optic would reach with both upgrades in service
(withSubUps()). If so, the advice stays. If not, the hint says the upgrades do
not stretch this optic and names the optics that do reach the route. A
consortium seat and a leased line keep their own message.
2026-11-01 23:03:47 +11:00
Frederic Jung
66aaaec5f1
A waiting subsea cut offers a charter only when it beats waiting for the club's first ship home 2026-11-01 11:52:42 +00:00
Frederic Jung
620253b57b
Cable ships a size bigger on the map; a ship at work sits just off the cut marker 2026-11-01 11:48:42 +00:00
Frederic Jung
a77eef8ce7
Own cables are laid by the lay fleet, never by a repair ship: one list of lay ship names, the one in the toast lays the cable 2026-11-01 11:46:37 +00:00
Frederic Jung
96e2c2f537
Cable ships: club repair ships sail out to subsea cuts, private charters jump the queue, lay ships build your cables
A subsea cut sends the nearest free ship of its region's maintenance club from its port, along the cable routes at about 500 km a day; the cut lasts while it sails, waits for permits in slow countries and splices (3-5 days shallow, 6-12 deep). Ships stay busy until home (S.fleet). With the club's ships all out the cut waits; a private charter of the quickest free ship costs $1M + $200/km sailed. Own subsea builds show survey/factory, then a lay ship at 150 km/day; a second lay ship can be booked before laying ($3M + $150k/day saved), and crews no longer speed up cables at sea. Ships are drawn on the map and can be tapped.
2026-11-01 11:24:53 +00:00
Frederic Jung
1fa5566d66
Connections overview prices 400G cache boxes right; tests pin 100G boxes where they mean them 2026-11-01 12:06:20 +01:00
Frederic Jung
7202441716
400G cache boxes behind 400G or faster router ports 2026-11-01 11:37:34 +01:00
Frederic Jung
6b8791c605
Bulk PNI test fills the ports now that caches share them (#252) 2026-11-01 11:32:29 +01:00
Frederic Jung
533532ba32
A standard POP: new POPs get the standard router model and count at once (closes #240) 2026-11-01 11:32:29 +01:00
Frederic Jung
5d7b626519
Clarovision peers only over paid PNIs (closes #213) 2026-11-01 11:32:28 +01:00
Frederic Jung
999aaca0e8
Cache boxes share router ports: as many 100G boxes per port as its speed holds (closes #252) 2026-11-01 11:32:28 +01:00
Frederic Jung
38fdf9b4d8
Subsea hurry costs a cable ship: charters for builds, the repair-ship queue for cuts
Speeding up an own subsea cable charters another cable ship ($3M plus $500/km per 30 days saved), and a rush repair on a subsea cut costs $1M plus $200/km. Land crews and trench repairs keep their prices.
2026-11-01 10:25:32 +00:00
Frederic Jung
bd6ba6bfd7
Merge #205: A carrier's own transit port takes its traffic, with a Carry here switch for other POPs
Thanks to thesysadmindev.
2026-11-01 09:32:28 +00:00
Frederic Jung
31e1951376
CHANGELOG: the link-focus bullet from #250 goes under Unreleased, not 2.3.0 2026-11-01 09:19:24 +00:00
Christopher Hawker
eb78d7104e Prefer keeps the say at its own POP only, and the direct ranks stop slowing the game day
Review of #205:

- Prefer no longer switches the carrier-direct rule off for the whole network.
  A POP with a Prefer-marked transit port keeps what Prefer says; every other
  POP keeps the rule. compute(), traceroute and the reference loop in the tests
  all use the same per-POP rule, and a new test covers it (New York and Chicago,
  Prefer on one POP's Tell-Ya port).
- dayTick() cost. The harness is neutral (the same page on both sides differs by
  1%), but the cost was real: the four extra rank passes inside compute()'s main
  loop made V8 deoptimise compute() 954 times in 30 game days against 46 on main.
  The direct ranks now run in a small function of their own, in the plain way the
  reference loop does (their lists are one carrier's ports), so the main loop is
  the one main has, and the setup moved out of compute(). 61 deopts instead of 954.
- Italian: "Porta qui" read as "port here" next to "Porta più vicina"; it is
  "Instrada qui" now, and "Ogni POP instrada il traffico..." matches.
- Help text: says that real BGP carries the traffic from every POP (the shorter
  AS path beats IGP distance), that Carry here does that here, and that Nearest
  port is the default. All six languages.
2026-11-01 20:07:23 +11:00
thesysadmindev
b8845413d3
Merge branch 'main' into own-carrier-egress 2026-11-01 19:10:37 +11:00
Frederic Jung
061acfe9f1
Merge #250: Inspecting a link moves the map to it
Thanks to ddryden.
2026-11-01 07:57:49 +01:00
Frederic Jung
b9183f1178
City panel fix, caches that scale, Manila, Cebu and Davao (2.3.0) 2026-10-31 16:31:50 +01:00
Frederic Jung
c3b253925d
City panel opens again with the transit order on Already connected (closes #249) 2026-10-31 16:31:33 +01:00
Frederic Jung
f0d0675bad
Free caches scale with demand: more boxes once one per site is not enough (closes #248) 2026-10-31 15:57:46 +01:00
Dennis Dryden
29a5859354 Inspecting a link moves the map to it
Inspect on a congested or busy link (NOC list, dashboard, link toasts and log
entries) now frames the whole drawn line in the part of the map the panel leaves
free: left of the side panel, above a phone's bottom sheet.
2026-10-31 14:53:11 +00:00
Christopher Hawker
a469844f61 Merge remote-tracking branch 'upstream/main' into own-carrier-egress 2026-11-01 01:37:42 +11:00
Frederic Jung
20c70f16e6
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	CHANGELOG.md
2026-10-31 15:00:36 +01:00
Frederic Jung
d2ee430b7d
Philippines: Cebu and Davao get connectivity estimates, RISE & Shine stays off the Pacific route, W44 par 2026-10-31 15:00:26 +01:00
Frederic Jung
2decbdf69c
Merge #247: CI: tests in four parts on four runners, every core in use
CI: tests in four parts on four runners, every core in use
2026-10-31 14:27:07 +01:00
Frederic Jung
2cb22ad3c4
tests/durations.json: seconds per test file, so the four CI parts take about the same time 2026-10-31 14:23:42 +01:00
Frederic Jung
bdbb8b4393
Realistic DDoS, city search and city sizes on the map (2.2.0) 2026-10-31 14:13:42 +01:00
Frederic Jung
a8fa75411c
Merge #214-#217: Manila, Cebu and Davao (fmcglinn)
Adapted to main: Globe is main's Globe-Trotter Telecom (now a Philippine
carrier in Cebu and Davao) instead of a second AS4775, the new Philippine
networks buy transit from NTT and Tata like main's other island networks,
cities and networks carry their country, and Philippine transit sits in the
new pricing. Cable names no longer pile up where short cables crowd.
2026-10-31 14:11:12 +01:00
Frederic Jung
2d1f48f3e6
CI: tests in four parts on four runners, every core in use, older PR runs cancelled
npm test ran every file one after another (--test-concurrency=1, from when there were three files). It now runs as many files at once as there are cores (TEST_JOBS=1 for the old way), and --shard i/n picks one of n parts of about equal time, balanced by tests/durations.json (npm run test:timings). CI runs four parts and the build side by side; a final 'test' job is green only when all are, so the check keeps its name. A newer push to a PR cancels the older run.
2026-10-31 14:11:02 +01:00
Frederic Jung
63a332947b
Merge #246: Transit headroom: an Already connected provider choice (#227)
Transit headroom: an Already connected provider choice (#227)
2026-10-31 14:10:27 +01:00
Frederic Jung
7756d89d41
Find a city: a search box in the HUD and on / that jumps the map there (closes #218) 2026-10-31 13:57:35 +01:00
Christopher Hawker
9dc8aac45a Merge remote-tracking branch 'upstream/main' into own-carrier-egress
# Conflicts:
#	CHANGELOG.md
#	src/game/80-simulation/30-compute.js
#	tests/game.test.js
2026-10-31 23:57:19 +11:00
Frederic Jung
0402cf5845
Merge remote-tracking branch 'origin/main' into claude/fix-227
# Conflicts:
#	CHANGELOG.md
#	tests/standing-orders.test.js
2026-10-31 13:51:12 +01:00
Frederic Jung
d50fc201bb
Merge #245: The intern's PNI order counts the traffic the PNI list shows (#244)
The intern's PNI order counts the traffic the PNI list shows (#244)
2026-10-31 13:48:44 +01:00
Frederic Jung
318db6bed0
Transit headroom: an Already connected provider choice (#227)
With Cheapest the intern signs whoever is cheapest (often Cogentle), and a named provider only ever grows that one port, so a second upstream never grew. Already connected only grows the transit you already buy at each POP, the smallest port first (ties: the cheaper), and never signs a new provider. The default stays Cheapest, so saves behave as before. One new label in all six languages.
2026-10-31 13:34:30 +01:00
Frederic Jung
48356c0179
The intern's PNI order counts the traffic the PNI list shows (#244)
The threshold compared the city's whole eyeball demand times the network's traffic share, so a network whose cache boxes in that POP serve most of it (NetChill) looked far bigger than the PNI list said. It now uses pniVal(net,city).want: what your users there send over transit, an exchange or a PNI elsewhere, from live routing.
2026-10-31 13:29:23 +01:00
Christopher Hawker
d9868a3757 Restore what the merge from main dropped from the carrier's own transit port
The merge kept main's version of compute(), the link actions and panels, the
traceroute exit list and the CHANGELOG, so the city panel called a carryCtl()
that no longer existed and routing never ranked a carrier's own port. Put the
ranking back into compute() on top of the current rank lists and island split,
along with setCarry, carryCtl, the traceroute carry flag, the reference loop in
the routing test and the CHANGELOG bullet. Drop a stale label main had removed
and sort the dictionaries.

The tests follow main too: saves are read from their slot, RouteScript needs
the core to run, Not That Telecom stands in for Cogentle (whose share is now
small), and the flood test uses a smaller sacrificial PNI and IX flood because
a carrier's own traffic now takes its share of the one transit port first.
2026-10-31 23:28:30 +11:00
Frederic Jung
31af9e3ff5
Code of conduct: jokes target networks, cables and routers 2026-10-31 13:24:36 +01:00
Frederic Jung
3e7bbdffad
DDoS rework: tests for the new model, Flood Season and its weekly at level 4, routing reference fix 2026-10-31 12:51:15 +01:00
Frederic Jung
72fb233af7
DDoS rework (#242): world-sized floods on customers, spread over every port, RTBH per target, Flowspec rule budgets, magnet scrubbing, new NOC card
Work in progress: the full test suite is still being brought in line.
2026-10-31 12:20:14 +01:00
thesysadmindev
296de1d946
Merge branch 'main' into own-carrier-egress 2026-10-31 22:16:55 +11:00
Frederic Jung
f5f56d29c0
Merge #243: Map: cities show their size, and crowded small ones step back to a dot
Map: cities show their size, and crowded small ones step back to a dot
2026-10-31 11:56:15 +01:00
Frederic Jung
cb90e735fd
Map: cities show their size, and crowded small ones step back to a dot
Five sizes from a city's eyeballs (P: under 15, 100, 350, 800 and up). Far view: dots grow with size and megacities glow. Near view: the skyline goes from a hut to five towers with an antenna. cityRoom() lets the selected city, your POPs and cities with an offer, outage or puzzle part claim space first, then the biggest; a city with no room is a small dot without a label until you zoom in, still tappable. IX tags for exchanges you haven't joined are smaller, and on outposts and towns only from zoom 1.5. Phones draw city icons at 82% (taps unchanged).
2026-10-31 11:36:48 +01:00
Frederic Jung
e1a6a582fa
Backbone technology, backbone customers, regen sites and capacity broker (2.1.0) 2026-10-31 11:00:53 +01:00
Frederic Jung
64d71adc35
Merge branch 'feat/backbone-tech' 2026-10-31 10:16:00 +01:00
Frederic Jung
251baf5894
Merge feat/backbone-tech: backbone technology levels 2026-10-31 10:16:00 +01:00
Frederic Jung
99c18bdf7a
Backbone rewards: L3VPN, flex-algo and slice customers, fast reroute, interop lab, four badges 2026-10-31 09:20:49 +01:00
Frederic Jung
73f0a4af72
Extremely Networks SLX 9740: the energy drink cartoon 2026-10-31 08:36:51 +01:00
Frederic Jung
662fd98d69
Translations for the broker listings and seat regen sites 2026-10-31 08:32:11 +01:00
Frederic Jung
43938083d4
Consortium seats take regen sites; the broker sells listings as the market wants (#203)
A seat bought at level 2 or 3 could not be lit: early optics do not reach across an
ocean. Seats can now regenerate in the landing stations along their cable.

A capacity broker listing is now standing: list some alien waves or the spare pair
and they sell over time as carriers on that route want capacity. Each route's market
is sized by the eyeballs at both ends (a landing town counts the city it serves), and
rented capacity, from the broker or a random offer, never outgrows it. Gameplay
rule F5.
2026-10-31 08:32:05 +01:00
Frederic Jung
70676d7bfb
Backbone technology: plain IGP, LDP, RSVP-TE, SR-MPLS, SRv6; two new RSVP-TE routers
Each router is classed by the highest backbone it runs and has a vendor. Upgrades
are paid one step at a time and any level paid for can run. Higher levels use
less router CPU, label switching makes pass-through traffic cheaper, Auto-TE and
RouteScript need RSVP-TE or above, and POPs whose routers can't run the backbone
stay outside it. Mixed vendors at the top of what their routers can do get
interop failures. Saves with Auto-TE keep the old rules; puzzles, Architect and
scenarios are unaffected.
2026-10-31 08:27:31 +01:00
Frederic Jung
664dd24bbd
Merge #239: NOC notices that would open the NOC get no Open button (#226 follow-up)
NOC notices that would open the NOC get no Open button (#226 follow-up)
2026-10-31 07:51:57 +01:00
Frederic Jung
2c60af18cc
Merge remote-tracking branch 'origin/main' into claude/noc-open
# Conflicts:
#	CHANGELOG.md
2026-10-31 07:50:21 +01:00
Frederic Jung
e7518507ae
Merge #238: Puzzle list: each section counts its own stars (#231)
Puzzle list: each section counts its own stars (#231)
2026-10-31 07:42:19 +01:00
Frederic Jung
11d6d195e7
Merge remote-tracking branch 'origin/main' into claude/fix-231
# Conflicts:
#	CHANGELOG.md
2026-10-31 07:40:12 +01:00
Frederic Jung
59928d6f8c
Merge #237: The intern's notes name the exchanges it peered at (#228)
The intern's notes name the exchanges it peered at (#228)
2026-10-31 07:38:52 +01:00
Frederic Jung
caa979a671
Merge remote-tracking branch 'origin/main' into claude/fix-228
# Conflicts:
#	CHANGELOG.md
2026-10-31 07:37:43 +01:00
Frederic Jung
3aab9f1d73
Merge #236: A fiber given up keeps its optics: they go on the spares shelf (#229)
A fiber given up keeps its optics: they go on the spares shelf (#229)
2026-10-31 07:36:28 +01:00
Frederic Jung
2b31bd5632
Merge remote-tracking branch 'origin/main' into claude/fix-229
# Conflicts:
#	CHANGELOG.md
2026-10-31 07:34:34 +01:00
Frederic Jung
dc89369c2a
NOC notices that would open the NOC get no Open button (#226)
The notice list is the NOC tab, so a target of tab:noc did nothing. #232 gave the shift report a real target; the chaos monkey's arrival still pointed at the NOC, where its own card already is. logSection() now leaves the button off for that target, whatever posts it.
2026-10-31 07:31:22 +01:00
Frederic Jung
d9f3cede11
Merge #235: Big networks: skip exits behind a full path when routing (#210)
Big networks: skip exits behind a full path when routing, a game day 40% faster (#210)
2026-10-31 07:26:43 +01:00
Frederic Jung
4edd760ff6
Puzzle list: each section counts its own stars (#231)
The 'Your stars' box at the top counted only the puzzle packs, yet sat above the architect runs and the weekly puzzle. It moves right above the packs as 'Stars from the packs' (what unlocks the next pack), and the architect runs header shows its own total like a pack does. Weekly rows already show their stars. One label renamed in all six languages.
2026-10-31 07:25:57 +01:00
Frederic Jung
6021439fe6
The intern's notes name the exchanges it peered at (#228)
opsWhere checked isCity() first, and a city's first exchange has the city's id (lon is LYNX), so 'Apfelwein-IX, London' meant Apfelwein-IX and LYNX. Peering entries are always exchanges: opsLine and opsWeekLine now pass the kind and name them with ixName(). Saved reports read right without migration.
2026-10-31 07:19:18 +01:00
Frederic Jung
2d61c09219
A fiber given up keeps its optics: they go on the spares shelf (#229)
rmLink (a cancelled IRU, your own fiber or a called-off cable) and decommission() dropped links with their channels still plugged in. chBack() puts each optic on the shelf, the same as unplugging it by hand, and a note says how many. One new plural label, in all six languages.
2026-10-31 07:15:35 +01:00
Frederic Jung
928d6f0111
Routing reference skips exits behind a full path too; #210 test checks the answer; CHANGELOG for players
The reference loop now states the rule #225 adds to compute(): without Auto-TE an exit whose shortest path is already full fits nothing, like a full exit. With the same rule both match bit for bit; before, only float rounding differed (at most 3.6e-14 relative), because the ECMP split no longer counts a dead exit's room.
2026-10-31 07:10:27 +01:00
Wesley Marques
8c2dd05d0b
Skip saturated paths during candidate exit scan to prevent routing freezes (#210) 2026-10-31 07:08:31 +01:00
Frederic Jung
59757c2256
Merge #232: The intern's shift report opens the Standing orders sheet (#226)
The intern's shift report opens the Standing orders sheet (#226)
2026-10-31 07:03:23 +01:00
Frederic Jung
198c636442
The intern's shift report opens the Standing orders sheet (#226)
Its NOC notification pointed at the NOC tab, where the notification already
is, so Open did nothing. It now opens the Ops sheet, which holds the report.
2026-10-31 01:44:46 +00:00
Frederic Jung
2d7aff4956
Merge #204: Submarine upgrades that change nothing on a cable can't be bought (#198)
Submarine upgrades that change nothing on a cable can't be bought (#198)
2026-10-30 19:51:19 +01:00
Frederic Jung
816de9b5ec
Merge remote-tracking branch 'origin/main' into claude/fix-198
# Conflicts:
#	CHANGELOG.md
2026-10-30 19:48:22 +01:00
Frederic Jung
7de22c2180
Merge #221: Sold-out wave sizes can't be reached by upgrading a smaller wave (#201)
Sold-out wave sizes can't be reached by upgrading a smaller wave (#201)
2026-10-30 19:48:09 +01:00
Frederic Jung
41e1a62983
Merge remote-tracking branch 'origin/main' into claude/fix-201
# Conflicts:
#	CHANGELOG.md
2026-10-30 19:46:26 +01:00
Frederic Jung
a4aa48c401
Merge #220: Both on a one-member PNI splits the LAG when the augment lands (#219)
Both on a one-member PNI splits the LAG when the augment lands (#219)
2026-10-30 19:45:59 +01:00
Frederic Jung
97c328dce6
Tests: the #219 panel check lives in the #219 test, #69 untouched 2026-10-30 18:35:01 +01:00
Frederic Jung
5f2dd38d2d
Both on a one-member PNI splits the LAG when the augment lands (#219)
A PNI's second member is an augment that arrives months later, so siteSet returned before setting the site and the new member joined the first building. The augment now carries site 'ab' (kept by sanitize), applies it on delivery if the POP still has two sites, and the panel shows Both as chosen while it is on order. Choosing A or B meanwhile drops the intent.
2026-10-30 18:25:12 +01:00
Frederic Jung
51ed64d789
Merge main into claude/fix-198: 2.0's seat check and lead times kept on the upgrade button and action 2026-10-30 18:23:49 +01:00
JMF-Alex
91481b1d6b
Sold-out wave sizes can't be reached by upgrading a smaller wave (#201)
From #202 by JMF-Alex, moved onto 2.0: its test now lives in tests/pnis-and-sold-out.test.js (the peering inbox tests are gone) and also checks the panel button and that nothing is charged.
2026-10-30 18:21:14 +01:00
Frederic Jung
abd55c0846
Release notes: a story for big releases, and the 2.0 story
A CHANGELOG section may open with prose before its first bullet. The build bakes it
into the page and version.json, and "What's new" tells it in full with a link to every
change on GitHub instead of the first sentences of five bullets. The 2.0.0 section gets
its story and every change grouped under headings, Architect runs included.
2026-10-30 16:28:19 +01:00
Frederic Jung
dbd2fa7b55
Routers: the picture in the POP overview's header, left of the city name 2026-10-30 15:48:49 +01:00
Frederic Jung
78d2b7c8c9
Routers: the picture only in the POP overview
The list of other models goes back to its badges; only the model a POP runs shows
its picture.
2026-10-30 15:47:37 +01:00
Frederic Jung
73e11349dc
Routers: a picture for every model
Seventeen cartoons in the map's style, one per router model (the ones picked from the
Router Rogues sketches), drawn as inline SVG from a small kit in its own scope and
built only when a panel shows them. A POP's router section shows its model big; the
list of other models shows each one small.
2026-10-30 14:54:10 +01:00
Frederic Jung
5f478dd318
Weekly Architect runs: sites outgrow their tubes, and a countdown
A grow brief raises a site's traffic past what its tubes carry; the reference makes
room by upsizing the busiest tube, or laying a second one where a long cable cannot
grow. Traffic may now reach 380G. The weekly row says when the next run comes out.
2026-10-30 14:07:45 +01:00
Frederic Jung
4e6e8294d2
Architect runs: a generated run every week
scripts/weekly-architect.js picks an HQ in a region the last weeks did not have and
designs each brief against the network a reference architect has built so far, so
every brief asks for something new; the game's own checklist and chaos monkey review
judge it, and the whole run is replayed from the file for three stars. The game
fetches architect/weekly/<key>.json when Puzzles opens, checks it field by field and
writes the briefs' text itself. The Sunday job and the release deploy carry it like
the weekly puzzles and scenarios. Later briefs' cities no longer show early.
2026-10-30 13:44:04 +01:00
Frederic Jung
601f7028bd
Puzzles: city markers move to the top left, clear of the IX badge
The eyeballs, content and circuit markers sat on the IX badge of cities without a
POP yet (reported by Thomas Kjær). Architect's mission-critical marker is now the
siren like everywhere else.
2026-10-30 13:24:08 +01:00
Frederic Jung
7672db1992
Puzzles: show one trench or separate paths on the map in every puzzle
Two tubes between the same cities read as one line until clicked (reported by
Thomas Kjær). Every puzzle now draws a shared trench as a bundle with a '2× one
trench' tag and separate paths bowed apart with a '2 paths' tag, at any zoom.
2026-10-30 13:15:38 +01:00
Frederic Jung
dbc801169c
Architect runs: use the renamed same-trench and diverse-route labels 2026-10-30 12:35:03 +01:00
Frederic Jung
dc4c0f07d5
Merge v2 into architect: the chaos monkey in every puzzle, and in normal games
Starting a run or a puzzle now sends a monkey left over from an Architect review away.
2026-10-30 12:33:33 +01:00
Frederic Jung
9fc38fa4f4
Puzzles: the chaos monkey acts out the N-1 star in every puzzle
When a build earns a new star the monkey snips each trench and cable in turn on the
map, and cities that lose traffic say how much; then the stars show. It can be let
loose again or skipped. Puzzle texts talk about the chaos monkey instead of a backhoe.
2026-10-30 12:24:53 +01:00
Frederic Jung
cbcb242d90
Architect runs: show whether tubes share a trench or take separate paths
Tubes in one trench are drawn as strands of one bundle with an orange '2× one trench'
pill; separate paths bow well apart with a green '2 paths' pill. Cut tubes no longer
show the backhoe: the monkey does the snipping.
2026-10-30 11:52:54 +01:00
Frederic Jung
5216a66db3
Architect runs: a tube goes red when the monkey snips it, and heals as it runs off
Each review step is now a run (the last cut is whole again) and a snip on arrival,
so the red follows the monkey.
2026-10-30 11:47:22 +01:00
Frederic Jung
cbb7ca8772
Badges: Met the Backhoe becomes Met the Chaos Monkey
Earned on the monkey's first visit instead of any fiber cut; the badge keeps its id,
so ones already earned carry over. Monkey-proof gets a shield. The monkey's cheer
also cancels a spray still pending from its last hop.
2026-10-30 11:44:22 +01:00
Frederic Jung
87364af55d
Architect runs: a skipped review that passes still ends with the monkey's cheer 2026-10-30 11:42:34 +01:00
Frederic Jung
b04e1e22c1
Architect runs: the chaos monkey leaves when you move on to the next brief 2026-10-30 11:36:51 +01:00
Frederic Jung
170914b05e
Architect runs: later briefs stay a surprise
No numbered tags beside cities, no "coming up" plan on a city card and no hint
to build there early: you design for today's brief and find out what comes next.
2026-10-30 11:18:54 +01:00
Frederic Jung
f4486ee955
Chaos monkey: a visitor that snips tubes in On-call and BGP at 3 a.m.
Now and then a chaos monkey moves in for 120 to 240 days and snips a tube every
couple of weeks, weak spots first, instead of the usual random outages. Outlast
it without a customer noticing for a bonus and the Monkey-proof badge, or throw
it a banana. Drawn on the map in shades; gameplay rule F4 with its test.
2026-10-30 10:54:25 +01:00
Frederic Jung
c8113d9043
Map: stop redrawing every frame when no chaos monkey is on it 2026-10-30 10:32:15 +01:00
Frederic Jung
4701cefbfd
Architect runs: draw our own chaos monkey, in shades
A hand-drawn monkey in the map's outline style replaces the emoji: sunglasses,
a spray can, a swaying tail, and poses for running, snipping, dancing and cheering.
2026-10-30 09:33:05 +01:00
Frederic Jung
b3351fb7d9
Architect runs: a chaos monkey runs round the map snipping tubes
The review is now an animated monkey that hops from cut to cut and sprays
chaos where it snips, instead of the backhoe.
2026-10-30 09:25:20 +01:00
Frederic Jung
ab05c80d68
Architect runs: gold sites are now mission-critical (🚨), in all six languages 2026-10-30 09:05:29 +01:00
Frederic Jung
eeac6ebcf4
CHANGELOG: Architect runs preview 2026-10-30 08:08:48 +01:00
Frederic Jung
1d3d8eb2ef
Architect runs: translate into German, Spanish, French, Italian and Portuguese; drop two unused labels 2026-10-30 08:06:14 +01:00
Frederic Jung
235ff2f9b5
Merge v2 into architect 2026-10-30 08:01:42 +01:00
tkjaer
644e6174d9
Architect runs (prototype): one network, built brief by brief
Three runs (Euro Run, Coast to Coast, Pacific Rim) on the puzzle machinery: briefs add sites,
raise demand, make sites gold, ask for rings or latency caps, or close a city; earlier builds
stay paid for, and the backhoe review cuts every trench and cable in turn. By tkjaer, from
seriesoftubes-architect.
2026-10-30 08:01:42 +01:00
fmcglinn
807e981a4d
Philippine eyeballs in line with real populations
Most cities on the map carry about 40G of eyeballs per million people
(São Paulo 41, Recife 39, Seoul 39, Tokyo 37). Manila and Davao sat at
24 and Cebu at 32. At 40G per million: Manila 600 to 1,000 (Demographia
2022 urban area, 24.9 million), Cebu 100 to 125 (Metro Cebu, 2020
census, 3.17 million) and Davao 80 to 135 (Metro Davao, 2020 census,
3.34 million).
2026-10-30 16:26:15 +11:00
fmcglinn
d69ab9f3f9
Waves between Philippine islands cost twice Manila to Hong Kong
Routes with both ends in the Philippines get their own subsea market rate,
PH_WAVE 3.7 instead of Asia's 1.5, so a 10G Manila–Cebu wave costs about
$7,900 a month: twice Manila–Hong Kong and level with Manila–Singapore.
International routes out of the Philippines keep the Asian rate. Leases
already signed keep their price.
2026-10-30 16:26:08 +11:00
fmcglinn
5bc12832e5
In-Vitro-IX ports at double GotchaFIX's price
The incumbent's exchange now charges about twice what GotchaFIX Manila
does: $1,760 a month for 10G and $6,600 for 100G (multiplier 4.4, up
from 2.2).
2026-10-30 16:25:38 +11:00
fmcglinn
cb7d5912d2
GotchaFIX ports at GetaFIX's real prices
GetaFIX charges $700 a month for 10G and $2,800 for 100G. One multiplier
cannot hit both, so GotchaFIX Manila, Cebu and Davao get ixCheap 1.8:
$720 and $2,700, within 4% of each. In-Vitro-IX goes to 2.2 so the
incumbent's exchange stays the dearest in Manila.
2026-10-30 16:25:26 +11:00
fmcglinn
870a2eba95
Philippine pricing: transit 1.9 times the Asian rate, broadband ARPU 0.7
Manila's 100 GigE transit is $2.25 per Mbps against Jakarta's $1.21
(TeleGeography, 2026), so Manila, Cebu and Davao get PH_TRANSIT 4.7, about
1.9 times the 2.5 every other Asian city pays. PLDT Home's full-year 2025
ARPU was PHP 1,447 a month (about US$25), so Philippine homes pay 0.7 of
the base broadband rate.
2026-10-30 16:25:03 +11:00
fmcglinn
55a62d32b2
RISE & Shine at GotchaFIX Cebu and GotchaFIX Davao
RISE.ph (AS63927) peers at GetaFIX Cebu and GetaFIX Davao in PeeringDB,
so RISE & Shine gets PoPs in Cebu and Davao and joins both GotchaFIX
exchanges.
2026-10-30 16:24:24 +11:00
fmcglinn
2b6a28203a
Pan de Sal Cable Network runs straight from Manila to Davao
PDSCN's Luzon–Mindanao segment (lit February 2024) runs from Lucena
through the Visayas to Cagayan de Oro, so the cable gets a Manila–Davao
pair alongside its Cebu landings: overland to Lucena, subsea to Mindanao's
north coast, overland to Davao.
2026-10-30 16:23:56 +11:00
fmcglinn
becbd3de8f
Davao: Mindanao, GotchaFIX Davao, and the trans-Pacific landings moved from Manila
Davao joins the map on Mindanao, with GotchaFIX Davao and Heimdall's Hut.
Mindanao's coastline is now Natural Earth 1:50m (the old simplified ring
left Davao in the sea).

Bi-Frosted's Philippine branch and SEA-US land at Davao, as the real
cables do (Converge's Davao station and Globe's Talomo station), instead
of Manila. sanitize() drops the cable tag from saved links on a pair that
no longer exists, so those links keep working as plain subsea links.

The Pan de Sal Cable Network, the Philippines Long Distance Relationship
and the new Diverge VisMin Express reach Mindanao's north coast from
Cebu and run overland to Davao. PLDTea Time, Snow Globe and Diverge
reach Davao.
2026-10-30 16:23:56 +11:00
fmcglinn
d0d97e068e
Cebu: its own island, GotchaFIX Cebu and two domestic cables from Manila
Cebu joins the map on its own landmass, with its outline taken from
Natural Earth 1:50m (the simplified coastline had dropped it). GotchaFIX
Cebu and Magellan's Last Rack. The Pan de Sal Cable Network (PDSCN,
Luzon to Mactan) and the Philippines Long Distance Relationship (PLDT
DFON, overland to Lucena then subsea to Cebu City) link it to Manila.
PLDTea Time, Snow Globe and Diverge reach Cebu, and typhoons can hit it.
2026-10-30 16:21:12 +11:00
fmcglinn
bb9a474923
RISE & Shine joins Manila as an open-peering Philippine network
AS63927 is a Cebu-based Cable/DSL/ISP with an open peering policy. In
PeeringDB it peers at GetaFIX Manila and PhOpenIX, in Singapore, Hong
Kong and Tokyo (JPNAP), and at DE-CIX Frankfurt, AMS-IX, LINX, Netnod and
Any2West; it is also on VIX, which PeeringDB does not list. So RISE &
Shine is on the game's matching exchanges: GotchaFIX Manila,
Bayanihan-IX, In-Vitro-IX, Lah-IX, Kopi-IX, HK-Kicks, Dim-Sum-IX,
JP-Naptime, DE-KICKS, HAMS-IX, LYNX, NodNod and Any2-Anywhere.
2026-10-30 15:57:24 +11:00
fmcglinn
8501458101
Manila: GotchaFIX, Bayanihan-IX, In-Vitro-IX and four Philippine networks
Manila gets its real exchanges: GotchaFIX Manila (neutral), the free
community Bayanihan-IX and the incumbent-run In-Vitro-IX. Snow Globe,
Diverge, Smarty Pants and Ditto join as Philippine networks. PLDTea Time
and Snow Globe now sell transit, and a PLDTea Time PNI also reaches
Smarty Pants. Old saves with a player-founded Manila exchange keep it.
2026-10-30 14:52:09 +11:00
Frederic Jung
90d4073d17
Merge the peering desk: requests answered by policy; inbox and max-prefix removed 2026-10-29 22:33:09 +01:00
Frederic Jung
039fe743d2
Merge v2 into v2-inbox 2026-10-29 22:12:43 +01:00
Frederic Jung
101ced4482
Tests follow the peering desk: #134 uses an IX loop, Red Sea window, regenerated week 2026-W44 par 2026-10-29 22:12:43 +01:00
Frederic Jung
92536606dd
Tests, CHANGELOG and docs for the peering desk 2026-10-29 21:41:28 +01:00
Frederic Jung
b6213344ce
Test the menu's small GitHub and chat links 2026-10-29 21:40:19 +01:00
Frederic Jung
9ba7f197f1
Merge v2 into v2-inbox 2026-10-29 21:37:17 +01:00
Frederic Jung
4ebe8418a0
Peering desk: incoming requests answered by policy; inbox, max-prefix and the Large Peering Model removed 2026-10-29 21:37:05 +01:00
Frederic Jung
81ad85cb03
The NOC tab shows no numbers: a red dot only while something is broken; drop five unused labels 2026-10-29 21:36:44 +01:00
Frederic Jung
3de3e545e1
Merge the Gangnam Style redesign: sender pays 2026-10-29 21:19:56 +01:00
Frederic Jung
62d6ece5dc
Menu: the NOC chat and bug-report cards become two small links 2026-10-29 21:00:46 +01:00
Frederic Jung
1b5bce7ba5
CHANGELOG: Gangnam Style Peering redesign 2026-10-29 20:59:24 +01:00
Frederic Jung
47c3674e8c
Tests: Gangnam reference hauls from Tokyo; Seoul-only, Tokyo-only and the old plan fail
The reference player learns single PNIs and last-resort transit.
2026-10-29 20:59:17 +01:00
Frederic Jung
b008b3a652
Gangnam Style Peering: sender pays that bites
Under the scenario's new sender rule, Seoul transit carries a sender-pays fee per
Gbps, the Korean incumbents take traffic only over a paid PNI, home broadband pays
less, and Korean users mind any far exit, peering included. The goal asks for
700 Gbps, Seoul 92% served well, 99% reach and a monthly profit. Korea outside
the scenario is unchanged; older Gangnam saves pick up the rule.
2026-10-29 20:59:13 +01:00
Frederic Jung
8c7b7d3c6b
A calmer in-game menu: one main button, six tiles, quiet links underneath 2026-10-29 20:40:13 +01:00
Frederic Jung
79616ead03
Title on phones: a long Continue button wraps instead of making the card scroll sideways 2026-10-29 20:35:18 +01:00
Frederic Jung
c09e293939
Merge the playtest: every scenario and puzzle solvable, tuned and tested 2026-10-29 20:22:46 +01:00
Frederic Jung
271c562205
Tests: Mind the Gap, Order and Progress, Fibre to the Basement and Flood Season checks follow the tuned goals 2026-10-29 20:22:20 +01:00
Frederic Jung
d309b70e0e
CHANGELOG: scenario tuning 2026-10-29 20:00:50 +01:00
Frederic Jung
97223e9d12
Puzzle playtest: Flash Boys' one-star reference is a one-star build; a test that each pack's idea is needed for three stars 2026-10-29 19:59:01 +01:00
Frederic Jung
6ae5cd30dc
Merge branch 'v2' into v2-playtest 2026-10-29 19:57:15 +01:00
Frederic Jung
0ca9ad8a95
Scenario playtest test: a reference strategy and a failing shortcut for every scenario (C1) 2026-10-29 19:57:15 +01:00
Frederic Jung
b79eb73fbf
Merge a clearer PNI list (#175, #172) 2026-10-29 19:56:04 +01:00
Frederic Jung
68bea796f6
Stale PNI button test: open the Tier 2 group, folded when nothing there is worth it (#175) 2026-10-29 19:53:38 +01:00
Frederic Jung
826ccbef46
Scenario playtest: goals that need the theme, tighter days, a real Anchors Away
Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only
when your network joins them up (island POPs won without crossing anything). Fibre to
the Basement also needs 500 Gbps served (it was won on day 2). Anchors Away: nobody sells
transit in Tallinn, ships really do cut the Baltic links about three times a link-year,
and the 99.5% streak no longer counts Great Firewall losses. In the Cogentle Spat, Goggle
peers only once you send it eight times the usual traffic. Flood Season's terabit floods
count when scrubbing or Flowspec took them. Days cut where a reference won in a tenth of
the time; Stepping Stones and Mid-Atlantic Accent start with 5M; Mid-Atlantic Accent's
description no longer claims Lisbon to Lagos is too long for 1.6T.
2026-10-29 19:51:35 +01:00
Frederic Jung
1065630d29
Make the #134 exchange-name test independent of which failure the dice pick 2026-10-29 19:38:23 +01:00
Frederic Jung
1fcfb58751
Merge specialist play: capability offers, demo units, consortium seats, charters (#187, #173) 2026-10-29 19:31:23 +01:00
Frederic Jung
c40e30234a
CHANGELOG: specialist play (#187, #173) 2026-10-29 19:12:44 +01:00
Frederic Jung
d6856591b4
Tests for specialist play, and gameplay rule F3: specialist paths only bring servable customers 2026-10-29 19:12:44 +01:00
Frederic Jung
4e17728a20
Specialist play: capability offers, vendor demo units, pioneer fiber, consortium seats and charters (#187, #173) 2026-10-29 19:12:44 +01:00
Frederic Jung
71f459c4e9
PNI list: tests and changelog (#175, #172) 2026-10-29 19:07:44 +01:00
Frederic Jung
d48fdbf2e5
PNI list: status chips, value line, worth-it tag, filters and groups by type (#175, #172) 2026-10-29 19:07:44 +01:00
Frederic Jung
2699634e0f
PNI list: remember where each flow leaves, and price a PNI per POP from it (#175) 2026-10-29 19:07:44 +01:00
Frederic Jung
8ccf84cf4a
Pick your own AS number next to the name; a round green arrow for another name (#135) 2026-10-29 18:59:07 +01:00
Frederic Jung
a98a0f7154
WIP: own AS number on the title 2026-10-29 18:56:44 +01:00
Frederic Jung
be63e3df67
Title: a hidden label for the language picker; the How the Internet Works card is checked in How to play 2026-10-29 18:01:27 +01:00
Frederic Jung
2604a9c74c
Merge the weekly scenario generator 2026-10-29 18:00:15 +01:00
Frederic Jung
3dbd508b64
Tests for the weekly scenario; C1 covers committed weeks; CHANGELOG 2026-10-29 17:40:51 +01:00
Frederic Jung
0ece48a79d
Ship weekly scenarios with the weekly puzzle run; docs and skills 2026-10-29 17:34:38 +01:00
Frederic Jung
d8df1e37f6
Weekly scenario generator with a reference player, and weeks 2026-W44 to W46 2026-10-29 17:34:38 +01:00
Frederic Jung
da7f4e6927
Weekly scenario in the game: goal types, file validation, Scenarios row, streak and share line 2026-10-29 17:34:38 +01:00
Frederic Jung
f24abe8fc7
Puzzles keep going until three stars: a cheer for each new star, results at three or on Finish 2026-10-29 11:44:39 +01:00
Frederic Jung
2eb22d1df3
Title screen: language first, name on top, compact presets, one home-city drawer 2026-10-29 11:31:46 +01:00
Christopher Hawker
ac5928d41d A carrier's own transit port takes its traffic, with a Carry here switch for other POPs
Transit ports at a POP shared load by free capacity whatever the traffic
was for, so Level Tree's own traffic went out of a Tell-Ya port about
half the time. Traffic bound for a carrier, or for a network that buys
transit from it, now goes out of that carrier's port at the same POP
first (the shorter AS path). Each such port is still an ordinary transit
exit, so POPs without one use it when nothing nearer has room.

A new switch on each transit port, Carry here, pulls that traffic from
every POP across your network to this port. The default, Nearest port,
keeps using the closest transit port from POPs that have no port of the
carrier. The switch only shows when another carrier's port could take
the traffic instead.

Prefer-marked ports, Backup only, RouteScript and Auto-TE keep their say,
and any Prefer-marked transit port switches the rule off. Traceroute
follows the same rule and says why it picked an exit. The setting is
repaired in sanitize(); old saves load with it off.

The routing reference test now has several carriers sharing POPs, ports
that carry, backup ports and RouteScript, and its reference loop knows
the new ranks.
2026-10-29 21:16:21 +11:00
Frederic Jung
e880dc69c1
The Networks list shows 100 networks at a time 2026-10-29 11:13:59 +01:00
Frederic Jung
40019c46ae
Merge Puzzles 2: puzzles with real traffic 2026-10-29 11:09:36 +01:00
Frederic Jung
0ad1ef6435
Changelog and architecture notes: puzzles with traffic 2026-10-29 10:51:00 +01:00
Frederic Jung
b640ab9814
Weekly puzzle: schema 2 with traffic, sized references, regenerated weeks
The generator gives every week content in its first city and eyeballs in the
others (a latency sprint adds a circuit with a cap), sizes both references with
the game's routing, and keeps the per-week rev refresh working with it.
2026-10-29 10:50:04 +01:00
Frederic Jung
12ef18f9e6
Puzzles: eighteen puzzles in five packs with traffic, and their tests
Fat Pipes, Router Rodeo, Traffic Cops, N-1 Club and Grand Tour. Every puzzle has
1-star and 3-star references played through the player's actions; budgets sit
over the cheapest 3-star build the solver found, and the tests check that no
single change keeps three stars for less.
2026-10-29 10:48:24 +01:00
Frederic Jung
69689f18f4
Merge v2 (small fixes, weekly rev) into puzzles with traffic 2026-10-29 10:36:21 +01:00
Frederic Jung
e90f5f675e
Puzzles: real traffic routed by the game, routers, link sizes and paths
Every puzzle now carries demand (eyeballs pulling from a content origin, circuits
with latency caps, best-effort flows) routed by compute(). Stars: delivered,
within budget, N-1 under load. Routers, ports, metrics, standby and the
redundancy check work in puzzles; the whole world is open. Weekly schema 2
carries the demand; scripts/lib/puzzle-solver.js sizes and searches builds.
2026-10-29 10:35:28 +01:00
Frederic Jung
a93eb3e8fd
Merge: Change Freeze stops de-peering, ASN fixes, weekly puzzles regenerate, lighter NOC 2026-10-29 10:33:33 +01:00
Frederic Jung
cc89a266f3
Lighter NOC traffic table: fewer elements and inline styles per network row
The traffic tab lists every network with traffic, now 63 more, each with a
Peer on all POPs button. Rows drop empty traffic-mix segments, the button's
wrapper div and two inline styles (now classes), with the same look. On the
big fixture the tab has 16% fewer elements; NOC dashboard tabs 390 -> 331 ms
against the previous commit (p=0.014).
2026-10-29 10:33:12 +01:00
Frederic Jung
7cbe0ec09b
Regenerate published weekly puzzles when a release's prices break them
--check now re-solves every week not over yet and, when its budget no longer
verifies, regenerates it deterministically: the same puzzle with a new budget
if that works, else a fresh one for the key. A regenerated file carries rev 2,
3...; the game keeps stars per revision, so only that week's stars reset.
Past weeks are left alone unless the game rejects them. release.yml runs it
before the tests on every deploy, weekly-puzzle.yml before making the new
week; either fails only if a week cannot be regenerated.
2026-10-29 10:03:20 +01:00
Frederic Jung
77ec31d1a0
Give Palau's and the Marshall Islands' networks their real ASNs
PNC-See had AS9534 (Maxis, Malaysia) and Never Too Atoll AS21581 (a US
host); the real operators are AS17893 (PNCC) and AS24439 (NTA). Saves key on
network ids, so nothing stored changes. The fudged numbers of the big carriers
and the African/Latin American incumbents are deliberate and stay.
2026-10-29 09:58:01 +01:00
Frederic Jung
e17ddc247b
Change Freeze stops de-peering at exchanges
Snubs (refused and torn-down sessions at exchanges) are part of the market
rule now, so Change Freeze and puzzles have none; On-call is unchanged.
2026-10-29 09:55:35 +01:00
Frederic Jung
9b7b1c150c
Series of Tubes 2.0.0: one game, four doors 2026-10-29 07:57:21 +01:00
Frederic Jung
efb14680cc
Merge save slots: one network per window, consistent saves 2026-10-29 07:57:00 +01:00
Frederic Jung
5dc7bebfb6
Merge gameplay rules: the rulebook skill, its test, and homegrown eyeballs in every country 2026-10-29 07:50:07 +01:00
Frederic Jung
d2f6ac1d5b
Merge review fixes: DDoS (#153 fixes kept, multi-ingress model dropped), locked rules 2026-10-29 07:49:00 +01:00
Frederic Jung
9fe5f124c6
Merge speed round 2: honest transit bills, faster loading 2026-10-29 07:40:40 +01:00
Frederic Jung
08e88d53a8
Save slots: reuse the parsed index between autosaves 2026-10-29 07:40:14 +01:00
Frederic Jung
5f412f72d8
Merge v2 into v2-saves 2026-10-29 07:32:19 +01:00
Frederic Jung
c5142046ed
CHANGELOG: China licence lead time, locked rules and attacker names in saves 2026-10-29 07:17:15 +01:00
Frederic Jung
31e44440e8
Flood Season escalates again, and empty POPs no longer hold floods for free
Every flood was 700G or more from day 1, so the scenario no longer built up. Sizes
are 1.36's again (a third terabit monsters, the rest ordinary floods sized to the
city), growing by the year as #153 had it. Floods go for POPs that serve someone,
and a city with nobody to serve only holds a flood its tools soak up. Seeded runs
over a year: no defence or one 1T center cannot win; one 1T center with full
Flowspec and clean pipe wins around day 100 (main needed two centers, day 164).
2026-10-29 07:17:08 +01:00
Frederic Jung
5f09111a95
Merge v2 into v2-gamerules 2026-10-29 07:15:56 +01:00
Frederic Jung
06da3f7456
Gameplay rules skill, pointer in CLAUDE.md, CHANGELOG for homegrown eyeballs 2026-10-29 07:15:32 +01:00
Frederic Jung
2b8b641216
Tests for the gameplay rules: world, networks, modes, content, fun and fairness, with documented exceptions; drop exchange ports in cities without an exchange 2026-10-29 07:13:56 +01:00
Frederic Jung
7e068fde98
Island eyeballs also buy straight from a Tier 1, like every island network 2026-10-29 07:08:51 +01:00
Frederic Jung
94488bf8f7
Save slots: CHANGELOG and architecture notes 2026-10-29 07:05:48 +01:00
Frederic Jung
871b340910
Homegrown eyeballs: 63 real consumer networks so every country has two of its own, translated 2026-10-29 07:05:32 +01:00
Frederic Jung
df8edddfe6
CHANGELOG: faster loading of big networks 2026-10-29 07:05:31 +01:00
Frederic Jung
732c329844
Requirements: build the possible-diversity map on city indices
The first diversityPossible() call after a save loads (migrate() checks every
customer's requirements) built a graph of every buildable link between all
~28k city pairs, scanning all 475 cable segments for each pair, with string ids
and objects for each of ~19k links: about 0.8 s on a fast machine, ~0.9 s of a
throttled phone's boot. Now the cables come from a table per pair and the graph
holds city indices and one number per risk (each land trench and own cable on
its own; every segment of a cable, or a fabric, sharing one). The answers match
disjointRoutes() over the old link list for all 14,042 sampled pairs, won or not
and with scenario bans.
2026-10-29 07:05:23 +01:00
Frederic Jung
cd46128c09
Save slots: tests for migration, two windows, take-over, stale writes, delete, import/export, puzzles 2026-10-29 07:05:11 +01:00
Frederic Jung
4bb5e07c28
The China licence follows quick lead times: about 5 days instead of 45
Change Freeze and Sandbox deliver everything in a tenth of the time, but the licence
still took 45 days and the button said so. It now waits leadDays(45), and the button
shows that number.
2026-10-29 07:04:45 +01:00
Frederic Jung
1692217549
Flood Season attacker names come only from the game's own list
An imported save could put raw HTML in an attack's attacker name, which reached the
end-of-flood toast unescaped. sanitize() keeps only names from the list, and the
toast escapes the name and city anyway.
2026-10-29 07:03:39 +01:00
Frederic Jung
13376ceb97
Merge the weekly puzzle generator into v2 2026-10-29 07:01:34 +01:00
Frederic Jung
537ec4efd0
Saves get the rules of their mode, whatever their rules say
sanitize() trusted any preset and override in a save, so an edited or imported save
could run a Normal game on puzzle rules (no clock, ever), On-call with infinite money
and open gates, sandbox powers without the sandbox tag, or a scenario off On-call.
Rules now follow the mode: scenarios and the weekly are On-call, a sandbox keeps only
its chaos, a Normal game one of the three Normal presets unchanged.
2026-10-29 07:01:18 +01:00
Frederic Jung
5c2b3a4758
Map: a link's curve only measures the cities that could be in its way
bezGeom() measured every city against every candidate curve, for every link the
first time the map drew it. A curve stays inside the box of its end and control
points, so a city further than the clearance it needs outside that box always
measures as clear; leaving it out gives the same curve. About 4x faster, and
the curves on the big fixture are byte-identical.
2026-10-29 07:01:01 +01:00
Frederic Jung
adc312f27b
Map: test land polygons against their bounding box first
The sea waves, hills and the far view's islet list test points against every
coastline polygon while the page loads: about 0.8 s of a throttled phone's load.
A point outside a ring's box is outside the ring, so nearly every test stops
there. Waves, hills and the far view's islands come out byte-identical.
2026-10-29 07:00:53 +01:00
Frederic Jung
8d72259500
Weekly puzzle generator: v2 counts a whole cable as one failure, so require it instead of patching it in 2026-10-29 07:00:34 +01:00
Frederic Jung
b9b55f1deb
Networks name their home consumer markets (cc): eyeball networks and the Tier 2 incumbents that sell to homes 2026-10-29 06:58:34 +01:00
Frederic Jung
2223a4b044
Merge review fixes: standing orders 2026-10-29 06:58:33 +01:00
Frederic Jung
f4c8400df1
Submarine upgrades that change nothing on a cable can't be bought (#198)
Premium submarine terminals and Optical engineering only extend the
long-haul modes of the coherent optics. On many cable lengths (all of
the Atlantic, and about 17,000-18,500 km like Atlanta to Sydney) neither
changes what any optic carries, yet both could be bought.

subHelps() compares every optic's rate with and without the upgrade,
counting an upgrade that only helps together with the other one. The
link panel disables Install with a note, ACT.subUpgrade refuses, and
the cable order screen disables the toggle and only quotes and charges
picks that still help on the chosen design.
2026-10-29 01:57:32 +00:00
Frederic Jung
023114103d
Weekly puzzle tests: look at the last three weeks only, so they stay fast as weeks pile up 2026-10-28 20:54:34 +01:00
Frederic Jung
d56039695c
Attacks arrive as on 1.36 again: drop the distributed multi-ingress flood model
Frederic's call for 2.0: keep #153's fixes, NOC breakdown, new vectors, gaming risk
and overlapping attacks, but not the per-port model. It split every flood over each
ingress port with traffic (over a thousand on a big network), stored them all in the
save, routed one pinned flow per port, and with it came the build-order and
victim-scoring bugs found in review.

Each attack is again one entry port at the victim (a.entry): upstream clean-pipe,
Flowspec on the victim's router, IX blackholing, a sacrificial PNI and RouteScript
filter it in that order (ddosMitigation), then scrubbing; what leaks is junk at the
victim spread like its traffic, exactly as on main. Saves from 2.0 builds with
a.entries load: sanitize drops the shares and a 'distributed' entry becomes 'edge'.
Removed: R.ingressPorts, ddosEntries/ddosFold/ddosSlices/ddosCities/ddosHasIx, pinned
flows (and the pinned-rank handling in routing and its reference), the mixed-TCAM
line and the 'across N ports' message, and their tests; the scrubbing source-city
test now uses two victims sharing one center. CHANGELOG #153 bullets describe what
ships and credit #153.
2026-10-28 20:53:58 +01:00
Frederic Jung
2011311084
Weekly puzzle 2026-W45 at the merged prices; determinism test compares two fresh runs 2026-10-28 20:52:59 +01:00
Frederic Jung
da8150b7c4
Save slots: several networks per browser, one per window, with a cross-window guard 2026-10-28 20:52:47 +01:00
Frederic Jung
faac3427f3
Merge v2 into v2-weekly 2026-10-28 20:52:08 +01:00
Frederic Jung
587d50decf
Weekly puzzle: tests, CHANGELOG, architecture and deploy notes 2026-10-28 20:50:17 +01:00
Frederic Jung
2ac9143db9
Weekly puzzle workflow: Sunday 03:37 UTC, commit the data to main, redeploy the live release with it through release.yml; releases ship every weekly from main 2026-10-28 20:44:28 +01:00
Frederic Jung
372893ec75
Weekly puzzle generator: themed, solver-budgeted, verified by the game's own stars; first three weeks 2026-10-28 20:42:51 +01:00
Frederic Jung
34b72f6d44
Weekly puzzle: Sunday 06:00 Berlin weeks, published puzzle fetched when Puzzles opens, seeded fallback, countdown and door badge 2026-10-28 20:42:37 +01:00
Frederic Jung
94b27eadf3
Billing: a recompute after the day tick no longer counts today's 95th-percentile sample twice
dayTick() routes the day, then appends today's transit use to t.hist. Every
compute() after that (any click, the intern, the sales trial) took the last 29
entries of t.hist, which now end on today, and added today's use again: today
counted twice and the 30th day back dropped out. So compute() gave a different
transit bill the second time after each day. p95() now leaves today's sample out
once S.hist says the day has been recorded.

This was the only part of compute() that was not a pure function of S. The rest
of the drift round 1 saw (R right after dayTick vs. a fresh compute) is dayTick
itself changing S after its compute (customers churning, events ending), which
is intended: the next day routes the new state. Scenic circuits' hysteresis is
documented, with a test that two calls converge.
2026-10-28 20:42:08 +01:00
Frederic Jung
ec1cf7d3b5
CHANGELOG: standing orders as they ship (sales and repair orders credit #185, PNI batches in the Ops sheet, weekly report) 2026-10-28 20:40:25 +01:00
Frederic Jung
9a0fb48aa3
Standing orders: the hiring pitch promises the weekly shift report 2026-10-28 20:40:14 +01:00
Frederic Jung
94e71beb16
Standing orders: the Ops sheet opens with the intern's mood and a weekly shift report 2026-10-28 20:39:33 +01:00
Frederic Jung
0788b98729
Standing orders: the intern's NOC notice is one shift report a week; the daily lines stay in the Ops sheet 2026-10-28 20:38:27 +01:00
Frederic Jung
e56659f949
Standing orders: caches get a running-cost budget and respect the cash floor; budgets and the shift log show monthly costs 2026-10-28 20:28:50 +01:00
Frederic Jung
b485b54d20
Merge review fixes: puzzles 2026-10-28 20:25:02 +01:00
Frederic Jung
b5cba3e591
BGP at 3 a.m. brings twice On-call's DDoS, as it says, not twenty times
Spicy chaos moved attacks onto the gamers' daily schedule without scaling it, so the
preset had about 20x the attacks of On-call. Without gaming customers, attacks stay
on the failure schedule (which spicy already runs 1.8x as often, with a slightly
heavier DDoS weight to make it 2x); gaming customers still bring their busier one.
2026-10-28 20:23:44 +01:00
Frederic Jung
ef700a3480
Standing orders: one failing order is paused instead of breaking the day; the LAG slip follows the transit order's switches 2026-10-28 20:22:09 +01:00
Frederic Jung
f13b0d40af
Merge review fixes: Tier 1 cone, badges, merged-PR polish 2026-10-28 20:21:11 +01:00
Frederic Jung
23634241c0
Standing orders: per-POP exceptions are dropped with their POP 2026-10-28 20:19:48 +01:00
Frederic Jung
e80fd0e453
Spicy chaos stretches exactly what an incident holds down
stretchInc() stretched anything ending on the same day: always the primary attack
(even when the incident was about another one, never the overlapping ones) and any
unrelated outage that happened to end then. It now finds the attack by i.atk and
everything else by the incident's ref, as clearInc() does, and saves allow the
longest stretched attack (11 days).
2026-10-28 20:19:41 +01:00
Frederic Jung
4c0d535369
Keep the cone carrier lookup out of compute() 2026-10-28 20:18:06 +01:00
Frederic Jung
e7554f66ea
Standing orders: no recompute on a shift that changed nothing in the network 2026-10-28 20:17:59 +01:00
Frederic Jung
9dbbfbe1b8
Standing orders: decommission routes with this shift's new customers before handing back waves 2026-10-28 20:16:35 +01:00
Frederic Jung
40e4c79139
Attacks keep their 12 biggest ingress ports and fold the rest, so saves stay small
Every attack stored every ingress port with traffic (over a thousand on a big
network), which grew the save from 272 KB to 1.8 MB with 14 attacks. The rest is now
one share at the victim, routed like the classic flood over its usual exits; old
saves are folded on load.
2026-10-28 20:16:20 +01:00
Frederic Jung
7b7d3ea1b3
Standing orders: the spare wave kept by decommission sits in another trench than the big link 2026-10-28 20:12:54 +01:00
Frederic Jung
25e3e6db33
DDoS attacks are scored and SLA-charged at their victim only
ddosSf() took the worst service of every city with an ingress port, so on a big
network every attack counted as lost and charged SLA payouts to protected customers
anywhere. Held/lost, the SLA check and the far-scrubbing warning now look at the
attacked city.
2026-10-28 20:11:06 +01:00
Frederic Jung
675c63d561
Floods cross the backbone to their victim again, whatever order the POPs were built in
Each ingress slice gave its junk the ingress city as source, so a flood only filled
the port it came in on: it never loaded the backbone or the victim's router, as it
did before distributed ingress. Junk is now created at the victim, pinned to its
entry port, before any real traffic and in attack order, so S.pops order no longer
decides who gets a full port. A port the victim cannot reach still fills.
2026-10-28 20:09:18 +01:00
Frederic Jung
d69e340f9a
Standing orders: transit never comes from a provider that breaks a customer's requirement, a covenant or the Spat 2026-10-28 20:07:08 +01:00
Frederic Jung
a0a492f19e
Standing orders: a re-hired intern starts on a fresh month's budget 2026-10-28 20:03:25 +01:00
Frederic Jung
ad07bfeada
CHANGELOG: puzzle budgets get tighter pack by pack, and a cable fails as a whole 2026-10-28 20:02:02 +01:00
Frederic Jung
3fa3b3e579
Puzzles: results pull you on to the next one
After three stars, Next puzzle is the one big button (and has the focus); the
results card counts the stars still to win in the pack; and when one more link
within budget would earn the third star, the card and the results say so.
2026-10-28 20:01:58 +01:00
Frederic Jung
6d839102b5
Pinned attack flows route at their entry port's own rank, not a cone rank
base() now takes the target network; pinned junk has none, so coneOf() called every
PNI a cone route and the flood was routed late (behind real traffic) or not at all.
Pinned flows use the port's own rank (low preference still last), those ranks join
RSET, and the reference allocation in the routing test does the same.
2026-10-28 19:58:25 +01:00
Frederic Jung
f4980dc098
Puzzles: bigger buttons and clearer city chips on phones
On phones the puzzle card's Undo, Reset, Back and menu buttons are 40 px touch
targets and stay pinned at the foot of the sheet when longer languages make it
scroll. Goal cities show a leading mark (○ to reach, ◐ POP open, ✓ joined)
instead of a trailing one that looked cut off.
2026-10-28 19:56:55 +01:00
Frederic Jung
0c4d9c0869
Infra tab shows the redundancy kit as one line instead of repeating its rows (#192) 2026-10-28 19:51:21 +01:00
Frederic Jung
2a5a26a831
Merge performance work into v2: faster routing and sales trials 2026-10-28 19:50:33 +01:00
Frederic Jung
28743698a3
Puzzles: a city to avoid reads as a rule
You cannot build in it anyway, so the card shows "Rule: not via Frankfurt"
instead of a goal that could never be failed.
2026-10-28 19:50:08 +01:00
Frederic Jung
9902599a23
Puzzles: main-game toasts and buttons no longer reach into a puzzle
Toasts are cleared when a puzzle starts and when you leave it, and every
main-game action (ops, inbox, bank, building, routers and the rest) does
nothing while a puzzle is on; only the puzzle's own actions, menus and
settings work there.
2026-10-28 19:48:11 +01:00
Frederic Jung
499862b140
Redundancy check routes once, against the live routing (#62) 2026-10-28 19:47:19 +01:00
Frederic Jung
ed4d029ba1
CHANGELOG: connectivity prices without naming data providers 2026-10-28 19:42:35 +01:00
Frederic Jung
837c56c13e
Connectivity prices for the 47 cities that had no data (#94) 2026-10-28 19:42:35 +01:00
Frederic Jung
66652576e5
Puzzles: the best spend in the list is the cheapest build at your best stars
Progress is recorded on every change, not only when the stars go up: more stars
start the best spend again, and a cheaper build at the same stars replaces it.
2026-10-28 19:41:10 +01:00
Frederic Jung
d3f550cc3e
Puzzles: budgets follow a difficulty curve
The first pack leaves 16-18% over the cheapest three-star build, the Pacific and
speed packs about 10%, and the N-1 Club 6-7%. The first pack no longer promises
no budget. A brute-force check in the tests keeps each reference build the cheapest.
2026-10-28 19:39:00 +01:00
Frederic Jung
e3534cad4b
Custom metric panel updates on Safari after switching multiplier and cost (#131) 2026-10-28 19:38:55 +01:00
Frederic Jung
e0a02276a2
Only Spätzle-IX asks for 50% reach, now that Tier 1 cones count 2026-10-28 19:37:40 +01:00
Frederic Jung
843811956b
Puzzles: a POP in a thin market counts its higher monthly rent
The puzzle price and the city panel now use the city's own monthly POP rent
(Suva is 1.5x), not the plain one, matching the higher setup already charged.
2026-10-28 19:36:12 +01:00
Frederic Jung
19a9c60fd5
Puzzles: a cable fails as a whole in the N-1 check
Two waves on the same cable now share one failure, as in the main game's
diversity checks. Kiwi Fruit Salad gets Los Angeles as a stepping stone (Seattle's
only cable south is Hawaiki), Samba Sprint's budget rises to $1.06M, and the
weekly reference ring never puts two hops on one cable.
2026-10-28 19:35:29 +01:00
Frederic Jung
9279908f7d
Say which Australians sit in a Tier 1 cone, and test exactly those 2026-10-28 19:35:27 +01:00
Frederic Jung
db429b1d74
Badge upgraded toast follows the collection on this device 2026-10-28 19:34:41 +01:00
Frederic Jung
cc898ea282
Badge variants are looked up as own keys, never through the prototype 2026-10-28 19:34:00 +01:00
Frederic Jung
6693d734e6
Traceroute shows every network down a customer cone, one hand-off per step 2026-10-28 19:32:53 +01:00
Frederic Jung
92d276bdc5
Network panel names the peer that really carries a cone-reached network 2026-10-28 19:32:53 +01:00
Frederic Jung
f69a0a526f
Merge main (1.37.0) into v2 2026-10-28 19:31:09 +01:00
Frederic Jung
2873ee3435
Sales trial: run the pass with the offer first, and skip the other when it cannot change the answer
With events booked ahead the trial routed the network twice: without the offer (who is happy now)
and with it. compute() only reads the previous result for scenic circuits, so without those the
order of the two passes does not matter. With the offer first, a failing offer or one nobody is
unhappy with needs no second pass. The same offers are signed (tests/sales-trial.test.js checks
over 100 seeded offers against the original trial, scenic or not).
2026-10-28 19:14:51 +01:00
Frederic Jung
462e783599
Every city has its country code; the 2x border toll stays an African thing 2026-10-28 19:00:58 +01:00
Frederic Jung
7def8113f4
Routing: remember each list's first exit group per source city while its exits have room
Most flows from one city ask the same rank list for the same nearest group of exits. Exits only
fill up while routing, so while every exit in that group still has room the scan would find it
again; it is reused instead. Networks with identical exit lists share one list, so the memory
serves them all. Same groups, same order, same result (routing-reference and speed tests).
2026-10-28 18:51:09 +01:00
Frederic Jung
2d12a20e34
Routing: a flow scans only the exits on its own island
The big fixture is a dozen islands (POPs no backbone joins). Each flow scanned every exit in its
rank's list and threw away the unreachable ones, two thirds of the scan. Lists are now split per
island once per compute; with one island nothing changes. Same exits, same order, same result
(routing-reference gains a network-of-islands case).
2026-10-28 18:36:44 +01:00
Frederic Jung
1f182b0df9
Pinned attack flows are routed even when RouteScript moves every other exit off their rank
The rank loop skips ranks no list uses (RSET), but flows pinned to an entry
port route at the port's plain rank. With 'prepend transit' or 'prefer transit'
moving every transit to 2.9/4.4, rank 3 was skipped and the flood vanished.
Fixes tests/routing-reference.test.js, which failed on v2.
2026-10-28 18:16:31 +01:00
Frederic Jung
de8ce0a6c3
Merge v2: standing orders, resolved as v2 has it 2026-10-28 18:16:30 +01:00
Frederic Jung
946da17c8b
Merge Puzzles, Tier 1 by customer cone and badge variants into v2 2026-10-28 18:14:56 +01:00
Frederic Jung
47fbd1c124
Standing orders: one sales trial per shift, so a big network's day stays fast 2026-10-28 18:13:48 +01:00
Frederic Jung
d0fbbed96a
Merge v2 (the eight community PRs) under the ruleset, puzzles and Tier 1 by cone
Integration base for performance work: origin/v2-orders' merge of v2 and the
ruleset, onto v2-doors. Pinned attack flows (#153) route at their port's plain
rank (no customer cone), and that rank is always tried even when RouteScript
moved every other exit off it.
2026-10-28 18:05:45 +01:00
Frederic Jung
829d3a4ba6
CHANGELOG and architecture notes for standing orders 2026-10-28 17:52:42 +01:00
Frederic Jung
c3c25fe565
Tests for standing orders: each order costs what the clicks cost; budget, pause, saves, fat fingers, phones 2026-10-28 17:52:37 +01:00
Frederic Jung
08413b53a3
Tests: #185 sales and repair run as standing orders; batches open from the Ops sheet 2026-10-28 17:46:16 +01:00
Frederic Jung
4717bc0f75
Standing orders in German, Spanish, French, Italian and Portuguese 2026-10-28 17:43:12 +01:00
Frederic Jung
7c8fa68659
Standing orders: a NOC intern runs the player's orders once a day (#98) 2026-10-28 17:40:22 +01:00
Frederic Jung
48e6200c53
German, Glowball Sakura Lager, CN-Too premium in Moscow (1.37.0) 2026-10-28 17:24:18 +01:00
Frederic Jung
39ef7c13bb
Merge Tier 1 by customer cone and badge variants 2026-10-28 17:08:10 +01:00
Frederic Jung
6489db146e
Tier 1 by customer cone (#85), and badge variants per ruleset preset
Cones: a PNI or IX session reaches the peer and its transitive customer cone,
precomputed once at load (CONE/CONE_S/DOWN/ANC). Cone routes rank after direct
peering and before transit (CONE_RANK 2.5), so peering widely still pays. The
long tail and several real eyeballs get real-world upstreams. Cones only add
reach, so the rule is easier for every save and needs no version flag.

Badges: S.achP[id] records the preset variant (freeze/oncall/bgp), sanitized,
default 'oncall' for old saves; the device hall of fame records every variant
earned. Harder presets upgrade a badge; toast, list, collection shelf and the
share card show it. Sandbox and puzzles earn none.
2026-10-28 16:54:19 +01:00
Frederic Jung
8df1b82a2e
Puzzles behind the Puzzles door: merge v2-puzzles onto the ruleset
Puzzles run on the puzzle preset (clock off); the temporary title button is gone and the door opens the puzzle list.
2026-10-28 16:39:05 +01:00
Frederic Jung
78100bd158
Puzzles: landscape framing, toasts beside the card, CHANGELOG (#190) 2026-10-28 16:24:06 +01:00
Frederic Jung
7fc8d0f080
Puzzles: small, calm network builds with stars, packs and a weekly puzzle (#190) 2026-10-28 16:21:25 +01:00
Frederic Jung
fa4e30692e
Merge the ruleset and four doors into v2 2026-10-28 15:45:09 +01:00
Frederic Jung
33c84964fa
Architecture: where the ruleset lives 2026-10-28 15:30:13 +01:00
Frederic Jung
66e13d2fc3
Saves made as puzzles load with the puzzle rules 2026-10-28 15:29:22 +01:00
Frederic Jung
531f90f107
One game, four doors: a per-save ruleset with Change Freeze, On-call and BGP at 3 a.m., a real Sandbox, and a new start screen 2026-10-28 15:27:04 +01:00
Frederic Jung
370ac536f6
Merge #192: Add bulk peering, cache and PoP redundancy utilities (Columbo818) 2026-10-28 15:25:15 +01:00
Frederic Jung
35fb35103f
Merge #185: auto sale + auto repair automation (Logfro) 2026-10-28 15:23:07 +01:00
Frederic Jung
96463577b9
Merge #181: Add bulk PNI ordering across networks and POPs (Logfro) 2026-10-28 15:21:01 +01:00
Frederic Jung
327749e0cf
Merge #177: Add editable optic counts for land and subsea fiber (LookedPath) 2026-10-28 15:17:42 +01:00
Frederic Jung
624f12bfd4
Merge #153: Overhaul the DDOS Attack system (FHRNet) 2026-10-28 15:15:36 +01:00
Frederic Jung
1b12a2c014
Merge #94: Calibrate city prices with PeeringDB and Hurricane Electric data (clayberF) 2026-10-28 15:04:40 +01:00
Frederic Jung
a6829b3d66 Merge #131: Custom routing metric for links (MurphysHub) 2026-10-28 14:58:12 +01:00
Frederic Jung
0fb3d3ab96
Merge #62: Add on-demand single-link redundancy checks (Flol0) 2026-10-28 14:58:12 +01:00
Frederic Jung
c011022203
Merge main: German; the Moscow premium note in German 2026-10-28 14:25:39 +01:00
Frederic Jung
f5e15e427f
China Telecomet's premium crossing in Moscow, at the Hong Kong price (#195) 2026-10-28 14:13:15 +01:00
Frederic Jung
7949cfd2c7
Merge main
# Conflicts:
#	CHANGELOG.md
2026-10-28 14:11:40 +01:00
Frederic Jung
7a8ad272d1
Merge pull request #193 from luckylucab0/add-german
Add German translation

# Conflicts:
#	CHANGELOG.md
2026-10-28 14:02:12 +01:00
Frederic Jung
7cfadaa6ae
Glowball Sakura Lager: only its real hubs, dearer far from home, no transit for Australians 2026-10-28 13:57:10 +01:00
Frederic Jung
3458e43583
Merge #191: Glowball Sakura Lager, a Tier 2 carrier (thesysadmindev) 2026-10-28 13:39:33 +01:00
Luca
77e906fe6f
German: test the translated How the Internet Works card 2026-10-28 12:14:52 +00:00
Luca
1f28654069
German: smoother wording after a full review
A read-through of every German text against the English fixed a few
mistranslations (buying out a bank, customers being "let go", a reversed
subject in a peering note, a conference bonus that reads as delayed) and
evened out the rest: sessions are "up"/"down", "der Cross-Connect",
"transitfrei", "de-peert", "Paid Peering", "Faserbruch", "Stromnetz" for
the power grid, "Spitzenlast" for peak traffic, and shorter labels where
German ran long.
2026-10-28 12:06:24 +00:00
Luca
b98dd33c09
German: wording from playing it, eyeballs are Privatkunden
Start screen, How to play, goals and tutorial use the wording a native
speaker picked while playing: "Baue deinen eigenen ISP auf", two-finger
zoom, "Zieh von einer Stadt zur anderen" and "Preisschock". Eyeballs are
now always "Privatkunden" in German.

The "How the Internet Works" card title is now a label, so German can
show "Wie funktioniert das Internet?"; the other languages keep the
English name.
2026-10-28 12:00:01 +00:00
Luca
1a0a70e575
Add German translation
Series of Tubes now speaks German. site/i18n/de.js translates all 3,063
labels in informal "du". Networking terms that German engineers say in
English stay English (Peering, Transit, Dark Fiber, Wave, Port, POP, IX,
Route Server, LAG, PNI and so on); plain "fiber" is "Glasfaser" and
"fiber pair" is "Faserpaar". RouteScript syntax stays English, as in the
other languages.

German is registered in the language list and the offline cache, so a
German browser starts in German. Every per-language test now covers it,
and the German style notes are in the add-strings skill and in the
dictionary header.
2026-10-28 11:41:57 +00:00
Logfro
39063acce7
Merge branch 'main' into main 2026-10-28 12:06:40 +01:00
Charles Miller
ce83c01f83 Distribute odd cache totals evenly between sites 2026-10-28 10:54:16 +00:00
Charles Miller
0f1db884c2 Balance PoP caches and request missing caches per site 2026-10-28 10:51:54 +00:00
Charles Miller
2f5a924d6a Add bulk IX peering and PoP redundancy utilities 2026-10-28 09:51:37 +00:00
Christopher Hawker
cc7ebe1ad5 Add Glowball Sakura Lager, a Tier 2 carrier with downstreams on every continent
A transit, PNI and open-peering network with a PoP in every city the big
content networks reach (not China, Russia or Pitcairn, where no provider
may sell so that you must land your own cable). It is not a Tier 1: it
buys from Level Tree, Cogentle and Not That Telecom, and 24 smaller
networks, four on each continent, buy theirs from it, so one PNI with it
reaches about 5% of all traffic.

It is added to the Australian transit sellers by design (3x price, well
under Telstraya) and peers at the main Australian exchanges. Saves from
before it get the usual courtesy route to new networks.

The Australian-sellers test now lists it, and the Latin American and
African reachability test asks for at least one Tier 1 upstream instead
of only Tier 1 upstreams.
2026-10-28 20:24:28 +11:00
LookedPath
9a01b3d415 Merge main and resolve optics PR changelog conflict 2026-10-28 09:03:53 +00:00
Frederic Jung
8e36b22351
Standby links, start anywhere, a language dropdown, new games at half speed (1.36.0) 2026-10-28 10:01:04 +01:00
Frederic Jung
3ead04b34d
Title screen: start button across the top, the other three the same size 2026-10-28 09:36:41 +01:00
Frederic Jung
51ba71567d
Home cities as a compact stack, the dropdown last; a shorter Sydney line 2026-10-28 09:25:47 +01:00
Frederic Jung
8b8bfadbaa
Start anywhere: pick any city with transit as your home 2026-10-28 08:30:17 +01:00
Frederic Jung
87fac683f0
Language is a dropdown on the title screen and in Settings 2026-10-28 08:18:56 +01:00
Frederic Jung
3b8bd4e534
New networks start at half speed (#186) 2026-10-28 07:53:36 +01:00
Frederic Jung
b4f8d9c7f5 Put a link on standby; the routing metric stays per city pair (#122)
A backup-only link next to a normal one still carried traffic, because
parallel links merge into one edge. The metric stays on the city pair
(S.pairMet), and any link can go on standby: it adds capacity that
fills only after the active links, so it idles as a backup, takes the
overflow when they are full and carries the traffic when they are down.
Build order no longer matters, and adding a link never idles the
others. Old saves keep each pair's lowest metric with every link
active, which is how they routed before. The panel says what a standby
link is doing, the redundancy list tags it, the map draws it dashed
while idle, and traceroute shows the active link.
2026-10-28 07:11:47 +01:00
Frederic Jung
da69c5d843
Subsea cables stay at sea, bug and idea links (1.35.1) 2026-10-28 06:30:42 +01:00
Frederic Jung
29ad74743c
Subsea cables stay at sea: fix the date-line wrap and routes across land (#183)
Eight Pacific pairs added in 1.35.0 had waypoints that jumped from +180 to
-180 longitude, so the renderer drew them across the whole map. Waypoint
longitudes are now continuous, as the hand-drawn routes always were.

A scan of all 475 cable pairs found 147 that cut across land with sea on both
sides (the Horn of Africa, Arabia, India, Brazil, Newfoundland, ...). Those
now follow the game's own sea router, simplified only as far as the line
stays off land; inland endpoints route between the coastal ends and keep
their overland leg. 27 more pairs into inland cities now come ashore at the
nearest coast. Hibernia Express is traced by hand south of Ireland to Brean
so it stays the straightest Atlantic crossing. Left alone on purpose: the
Suez Canal and Dardanelles crossings, Quintillion's overland Alaska leg and
Celtix's Welsh landing.

Tests: no pair jumps the seam and none crosses more than 160 km of land
mid-route. EIG is now 8,613 km, so overland is 9.97x subsea instead of
10x+; Lisbon-Lagos fits 1.6T directly at 5,914 km.

Thanks to mindolo for the report and the analysis in #183.
2026-10-28 06:17:39 +01:00
Frederic Jung
daa1ad0b05
Bugs and ideas go to GitHub: a card in the menu and How to play; Signal is for chatting 2026-10-28 06:00:55 +01:00
logfro
dd82737af8 Show auto-accept countdowns only for ready offers
Hide the countdown when an offer has unmet requirements, missing locations,
expired terms or insufficient service capacity. Keep manual acceptance
available with its existing behavior.

Share capacity previews across the Deals, city and fiber views, reuse them
between automatic checks, and invalidate them after actions or incidents.
Check changing requirements immediately and always perform a fresh full
validation before automatically signing a contract.

Add regression tests for blocked offers, requirements becoming fulfilled
or unfulfilled, capacity changes and preview reuse. All 17 automation tests
pass; the full independent branch passes 314 of 315 tests, with only the
pre-existing locale-dependent subsea formatting failure remaining.
2026-10-28 02:55:12 +01:00
logfro
abe92fe3b1 Add real-time sales automation and automatic paid repairs
Add independent toggles for auto-accept in Deals and auto-pay repairs in
NOC. Save both settings and default them off for older or malformed saves.

Check sales every five wall-clock seconds regardless of game speed, and
show a small countdown on Accept buttons in Deals, city offers and fiber
broker offers. Only sign when all requirements, locations, equipment and
service capacity are ready. Trial the added demand before accepting it,
protect healthy existing customers and account for booked future events.

Use the existing paid repair action for affordable active incidents,
including slow router reboots. Skip expired incidents, removed equipment,
DDoS attacks and repairs that were already rushed. Pause both automations
with the game, hidden pages and open dialogs.

Translate the controls into all five supported languages and cover timing,
countdowns, capacity, budgets, repair payments, persistence, mobile controls
and trial rollback with deterministic tests. Chromium checks verify about
five real seconds at both 0.5x and 8x game speed and exercise the supplied
large save without changing the save file.
2026-10-28 02:19:47 +01:00
logfro
4932b3f93a Add bulk PNI ordering across networks and POPs
Add two actions to the NOC Traffic tab:
- Order PNIs with one network at every shared POP.
- Order PNIs with all eligible networks at every shared POP, including
  long-tail peers.

Both actions offer a selectable port size and preview new connections,
upgrades, total setup costs, additional monthly charges and blocked sites.
Upgrade smaller PNIs while preserving larger connections, pending orders
and existing LAG members. Reserve router capacity across the batch and
account for pending speed and LAG augments to avoid overbooking ports.

Require the full setup budget before placing any orders. Reuse normal
peering policies, minimum port sizes and provisioning delays, then
recompute and save once for the entire batch. Keep large global previews
compact with collapsible network and blocked-connection lists.

Translate the new UI into all five supported languages and add tests for
single-network and global ordering, capacity, budgets, repeated clicks,
save migration, and mobile keyboard interaction.

Validation:
- Build and translation checks pass.
- 308 of 309 tests pass. The existing subsea reach test also fails on
  origin/main because the Windows locale uses a dot as the thousands
  separator where the assertion expects a comma.
- Chromium desktop and phone checks pass with the supplied save.
- Big-network benchmark against origin/main: dashboard tabs take
  16.8 -> 17.6 ms on desktop and 77.1 -> 80.7 ms on a simulated phone
  (median of 15 runs). Routing results are identical, with no slowdowns
  beyond the benchmark's noise threshold.
2026-10-28 01:44:17 +01:00
Frederic Jung
ad94833ad1
Caribbean, Arctic, Indian Ocean, more cables and networks, Spanish, capacity conferences (1.35.0) 2026-10-27 22:39:28 +01:00
Frederic Jung
9df1835f70
More real cables: North Sea, Baltic, Tampnet, Indian Ocean and Asia-Pacific
North Sea and Baltic: Kristiansand, Esbjerg and Riga as new landings.
Havfrue's Danish and Norwegian landings, HAVSIL, Skagenfiber, Norfest and
NorSea Com (Tampnet, past the Draupner and Ekofisk platforms to
Lowestoft), CeltixConnect-2 and North Sea Connect, C-Lion1's real
Rostock landing, GlobalConnect's Digital E4, Eastern Light, the Elisa
cables, Latvia-Sweden and BCS. Baltic cables carry an anchor flag that
makes them cut more often (it used to be a list of two ids).

Indian Ocean and Asia-Pacific: Muscat, Malé and Fukuoka as new landings.
SJC2, ADC, ASE, APCN-2, EAC-C2C, FLAG and its North Asia loop, SEA-ME-WE 5,
Unity, TGN-IA, TPE, Hong Kong-Guam, MIST, IAX, TIC, TW1, MCT and KJCN as
puns; the missing real landings on SEA-ME-WE 4 and 6, AAE-1, PEACE, APG,
SJC, PLCN, NCP, FASTER, JUPITER, Indigo, Bifrost, 2Africa Pearls and the
Oman Australia cable. Existing pairs are untouched so saved links keep
their cable. Routes come from the game's own sea router.

Tests that relied on Colombo having one cable and Oslo having none now use
St Helena and Zurich.
2026-10-27 22:29:32 +01:00
Frederic Jung
5538e5109b
Merge fix/176-gzip: compress huge saves with the browser's gzip (#176) 2026-10-27 21:47:46 +01:00
Frederic Jung
146fae0faf
Compress huge saves with the browser's gzip (#176) 2026-10-27 21:34:35 +01:00
Frederic Jung
75f343f019
Caribbean, Indian Ocean, Pitcairn, Alaska and Russia's Far East; more US and Australian eyeballs (#125, #152, #124, #145, #155, #154)
Caribbean: San Juan, Santo Domingo, Kingston, Havana, Nassau, Port of Spain,
Bridgetown, Fort-de-France and Willemstad on their own islands, with
ARCOS, Americas-II, ECFS, Southern Caribbean Fiber, ALBA-1, CFX-1,
Fibralink, BICS, AMX-1 and EC Link as puns. Exchanges only where one runs
(PR-IX, JIXP, TTIX, AMS-IX Caribbean).

Indian Ocean: Réunion (REUNIX as Rougail SAUCIX), Mauritius, Madagascar
and the Seychelles on SAFE, LION, METISS, EASSy, SEAS and PEACE.

Pitcairn: no cable and no provider; cables may land there and the UK pays
a monthly grant while the islanders are served.

Alaska, Prince Rupert and Russia's Arctic and Pacific: towns with no road
in are their own landmass. Real cables only (Quintillion, AU, AKORN,
AU-Aleutians, Topaz, Connected Coast, Sakhalin-Kamchatka-Magadan,
Petropavlovsk-Anadyr, RJCN, HSCS). Polar Express never got past Amderma,
so its towns have a beach for your own cable instead.

Eyeballs: AT&Tease (a Tier 1 for new games only, t1v 3), Tee-Hee Mobile,
Coax, Pessimum, Final Frontear, GFibber, Sonic Boomer; Neptoon, Lawn-tel,
Pent-Up Net, Dive-Bomb Magpie, Internope; Musklink in the US. Coax merges
into Spectre-um on day 365, Final Frontear into Very-Zone on day 730.
Coastlines refined from Natural Earth around the new places.
2026-10-27 21:34:09 +01:00
LookedPath
66ae4be72d Add editable optic counts to fiber link panels 2026-10-27 20:30:20 +00:00
Frederic Jung
8c3ac4e9df
Merge fix/176-save-size: warn when saving fails, smaller saves (#176) 2026-10-27 21:19:18 +01:00
Frederic Jung
9853ebe4fc
CHANGELOG: smaller saves are not faster to write 2026-10-27 21:13:57 +01:00
Frederic Jung
d36426a8ae
Smaller saves: leave customer defaults out and rebuild them on load (#176) 2026-10-27 21:13:25 +01:00
Frederic Jung
cbe11339a7
Tell the player when the game cannot save (#176) 2026-10-27 21:11:17 +01:00
Frederic Jung
1e1864a173
Merge remote-tracking branch 'origin/main' 2026-10-27 20:55:26 +01:00
Frederic Jung
5a51b84bf7
Merge main
# Conflicts:
#	CHANGELOG.md
2026-10-27 20:48:57 +01:00
Frederic Jung
f80e491713
Merge remote-tracking branch 'origin/main' 2026-10-27 20:44:52 +01:00
Frederic Jung
4c499de742
Merge #158: smoother huge networks, map and autosave (huguesdelamure)
Capacity deals now record customer names with useName() too, and the
#156 CHANGELOG bullet moves to Unreleased where it belongs.
2026-10-27 20:43:46 +01:00
Frederic Jung
1f4b0af36a
Fix the padded yellow progress bars
The slow-city warning box used a plain .warn class, which also matched
the yellow .bar.warn progress bars and gave them its padding and
border. The box is .latwarn now; a test checks a yellow bar has no
padding.
2026-10-27 20:42:12 +01:00
Frederic Jung
b107d3fa03
Name São Paulo's exchange IX.brrr São Paulo like the rest of Brazil (#166) 2026-10-27 20:38:42 +01:00
Frederic Jung
c914f5d234
Merge #156: look fiber customers up by link id (huguesdelamure)
Kept the capacity deals from #168 in the fast path: fiber-pair contracts
count as a sold trench in fiberUse(), and pending deals still skip revenue.
2026-10-27 20:34:01 +01:00
Frederic Jung
0510df1816
Merge #174: Spanish translation (JMF-Alex)
Resolved CHANGELOG and README against main, translated the 26 labels added
since the PR branched, and added Spanish to the peering language loop.
2026-10-27 20:31:19 +01:00
Frederic Jung
6b04a530e8
Conference sponsorships and yearly capacity conferences with build-to-order carrier deals (#168) 2026-10-27 18:48:58 +01:00
Frederic Jung
239682720e
Allow up to 16 routers per POP, with a cage extension past six (#157) 2026-10-27 18:48:58 +01:00
Frederic Jung
5b5e011f69
README: drop the Translations section 2026-10-27 18:27:29 +01:00
Frederic Jung
c557bb554b
README: drop the file tree 2026-10-27 18:26:56 +01:00
Frederic Jung
a93f54cb8a
README: add star history, drop Releasing, Hosting setup and Analytics; Signal is for chat, issues for anything meaningful 2026-10-27 18:26:07 +01:00
Frederic Jung
20bc35123b
CONTRIBUTING: the PR limit is enforced by GitHub, drafts count 2026-10-27 18:17:57 +01:00
Frederic Jung
7eff0ba307
CONTRIBUTING: only issues labelled implement, at most 4 open PRs, no AI agents 2026-10-27 18:14:12 +01:00
JMF-Alex
288c78e9a0 feat: Spanish translation 2026-10-27 16:31:58 +01:00
Frederic Jung
e7ae3b18bf Merge origin/main into codex/ddos-scaling-and-mitigation 2026-10-27 13:21:51 +00:00
Hugues
a3dd1dd810 Busy maps: no link labels or fiber dots above 1,000 lines on screen
On a save with 2,700 lines on screen, Firefox spent about 95% of each
frame painting, and the dotted line on lit fiber (~160 ms) and the link
labels (~55 ms) were half of it, in a tangle where neither can be read.

draw() now counts the lines it would paint (linesOnScreen(), same box and
margin as its own culling, boxes cached on the geometry) and above
MAP_BUSY = 1000 leaves out both. They come back as soon as fewer lines
show, zooming in for instance. The selected link keeps its label.

Firefox Developer Edition headless, 1600x900 at DPR 2, player save, median
of 3x9 frames: save view 414 -> 214 ms, pan 472 -> 238, zoom 0.6 269 -> 181,
New York zoom 2 213 -> 107, selected link 412 -> 201. Under the threshold
pixels are identical (canvas SHA-1): zoom 3.2 and 6 on the player save, six
views of the big-network fixture.
2026-10-27 14:03:04 +01:00
Filip Hruska
330dbd5935 Merge latest main into codex/ddos-scaling-and-mitigation 2026-10-27 13:01:22 +00:00
Filip Hruska
925e7c1798 rewrite changelog 2026-10-27 13:01:14 +00:00
Filip Hruska
744b769000 Rework DDoS generation, mitigation accounting and NOC reporting
Scale normal attacks with network demand, level and gaming exposure, with
randomized sizes, durations, overlapping attacks and distributed ingress.
Set average sizes to three times the non-gaming baseline at one gaming
customer and eight times at fifty. Keep Flood Season escalating after its
challenge ends.

Add gaming-specific vectors, Memcached amplification and ACK floods.
Account for upstream scrubbing, Flowspec and shared scrubbing capacity in
sequence. Show precise mitigation totals and one destination-based
scrubbing detour in existing live attack cards.

Keep each source-to-scrubbing route distinct in link traffic breakdowns,
including the source label, Open button and map highlight.

Include deterministic tests, old-save migration and translations.
2026-10-27 13:00:57 +00:00
Hugues
22817c83c5 Remember each used customer name once
S.usedNames only answers "was this name used?", but every offer pushed its
name again, also once all names were taken: a 5,500-day save holds 560,345
entries for 129 names, 11.8 of its 22.4 million characters. Names are now
added once (useName), and sanitize() drops duplicates from older saves.

Player save, 30 days from load, against main: routing and the whole state
except usedNames identical, usedNames identical as a set; save 22.4 -> 10.6
million characters, first save in Firefox 95 -> 55 ms, JSON.stringify 68 ->
42 ms. Still over Firefox's quota on this save.
2026-10-27 13:45:06 +01:00
Hugues
d7301747f7 Saves too big for the browser: wait before retrying
A late-game save of ~22 million characters is over Firefox's localStorage
quota, so every save failed, yet the game rebuilt it with JSON.stringify(S)
every 5 seconds, every 10 days and after every action: ~95 ms each in
headless Firefox, 300-570 ms in a player's browser, all thrown away.

After a failed save the autosave now waits 1 minute before trying again,
then 2, 4, at most 5. A save that works resets this, so normal games still
save every time. Leaving the page, exporting, reloading for an update or a
language and a new game (a new S) still try at once.

Player save in Firefox: first save 95 ms as before, the next autosaves 0 ms.
2026-10-27 13:44:57 +01:00
Hugues
ecb862e70d Map of huge networks: fiber capacity once per frame, skip links off screen
draw() asked dfCap() three to five times per fiber link and per frame (width,
colour, label, up or down), each time over all its channels: on a save with
3,140 dark fibers of 18 channels on average that was about half of draw()'s
JavaScript. dfCap() now keeps its answers in DFC while one frame is drawn
(cleared in a finally, so a failed frame keeps nothing), and the link label is
built once per line instead of once per world copy. Links entirely above or
below the screen are skipped like those left or right of it already were.

Player save (202 POPs, 3,142 links), jsdom: draw() 40 -> 25 ms; perf-bench
"Map at three zoom levels" 89.7 -> 47.1 ms. Canvas call log identical at
every zoom without the vertical skip; Firefox pixels identical (SHA-1 of the
canvas) in 7 views. Firefox still spends ~95% of the frame painting.
2026-10-27 13:44:47 +01:00
Hugues
456062284f Faster days on big networks: look fiber customers up by link id
compute(), the daily mood check and new alien-wave/fiber-pair offers asked
S.links.find() or S.biz.filter() once per customer or per link. On a save
with 2,950 links and 18,000 customers (16,000 alien waves) that was ~150 ms
per compute, ~250 ms more per day, and ~650 ms when a wave offer spawned.

linkIds() and fiberUse() build the lookups in one pass; fiberOk, bizSf,
soldSlots, freeCh and pairFree take them optionally, and give the same
answers as before (first link with the id wins, sums in S.biz order).

Player save (202 POPs, 2,958 links, 17,967 customers), median of 15:
compute 323 -> 124 ms, dayTick 545 -> 133 ms, after 356 -> 149 ms.
Big-network fixture: unchanged. Routing results identical to main.
2026-10-27 12:26:10 +01:00
Frederic Jung
97b195dd91
Smaller translation downloads (1.34.1) 2026-10-27 12:11:13 +01:00
Frederic Jung
5158491b79
Add a Code of Conduct: welcoming, no harassment, be excellent to each other
Covers GitHub, the Signal group and anywhere the project is represented.
Reports go to Frederic privately on Signal. Linked from the README and
CONTRIBUTING.
2026-10-27 11:51:54 +01:00
Frederic Jung
81f0915a7e
Changelog: smaller translation downloads 2026-10-27 11:30:40 +01:00
Frederic Jung
a4f89491e6
Docs: the single-file page and English keys lasted until 1.34 2026-10-27 11:28:17 +01:00
Frederic Jung
f454c71fda
Merge remote-tracking branch 'origin/main' into refactor/split-page 2026-10-27 11:27:15 +01:00
Frederic Jung
0057e74472
Ship short ids instead of labels; checker, tests and docs for labels
The build swaps every label for a short id in the shipped page, the inlined
English and the translation files (scripts/lib/compile-labels.js). Labels
passed to N_() stay whole because saves keep them. Against 1.33: page +4%
gzipped (321 -> 335 KB), translations -40% (it.js 143 -> 85 KB); routing,
day, panels, dashboard, map and boot time unchanged.

- i18n-check rejects labels the build cannot see (outside tr/trn/N_)
- tests/pages.test.js plays the shipped page in English, Italian and French
- docs/adr/0003, add-strings skill, ARCHITECTURE, README, CONTRIBUTING,
  CLAUDE.md describe labels
2026-10-27 11:27:11 +01:00
Frederic Jung
9043af5ab0
port-branch: keep English for labels your side still uses 2026-10-27 11:06:29 +01:00
Frederic Jung
315ab1fac5
port-branch: merge English entry by entry, like the translations 2026-10-27 11:06:11 +01:00
Frederic Jung
76d3d7d199
port-branch: compare plural entries by value 2026-10-27 11:05:35 +01:00
Frederic Jung
e817beed1a
Translations keyed by labels instead of English text
tr('pnis.delivery_2_to_6_weeks') instead of tr('Delivery: 2 to 6 weeks'): the
English lives once, in src/i18n/en.js (inlined into the page at build, so no
extra request), and it/pt/fr map the same labels. Changing English wording no
longer renames a key in every dictionary.

- 2,899 labels, made from where each text is used and its first words; short
  shared words are common.*
- plurals are one label with {one, other}: trn('label', n)
- static markup: data-i18n="label", data-i18n-aria-label, data-i18n-title
- saves from 1.33 and older stored English text in a few places; tr() still
  resolves it
- i18n-check: undefined/unused labels, markup drift, plural shape; i18n-add.js
  works on labels and --rename updates src/ too
- the old-branch port tool gives old English-keyed code and dictionaries the
  same labels
2026-10-27 11:05:09 +01:00
Frederic Jung
171e0fe16a
Peering policy, raise-all max-prefix and a slimmer Brazil (1.34.0) 2026-10-27 10:53:46 +01:00
Frederic Jung
d0ba85ef8f
Merge main (peering policy) into the split layout via port-branch 2026-10-27 10:30:21 +01:00
Frederic Jung
a2e7e9dcc5
Peering policy (Open to all / Selective / Closed) and raise-all max-prefix
Open (default, as before): route servers count, and incoming requests
are accepted on arrival. Selective: 70% of the requests, answered by
hand, and route server sessions stop counting, so you request peers at
each IX yourself. Closed: no requests, reputation sinks to -6, and
customer offers arrive 40% less often. The IX panel says when your route
server sessions are off because of the policy.

"Raise all max-prefix limits" answers every alert at once; leaks among
them become route leaks as usual, and the toast counts them.
2026-10-27 10:23:47 +01:00
Frederic Jung
dbbbdaa1e3
Merge main (city density rule) into the split layout via port-branch 2026-10-27 10:23:42 +01:00
Frederic Jung
6f95539b2d
port-branch: work in both merge directions 2026-10-27 10:23:33 +01:00
Frederic Jung
05ff4ea7ad
Docs and guard rails: GitHub Pages only, where code goes, updated skills
- docs/adr/0001: GitHub Pages is the only host, not open for renegotiation
- docs/adr/0002: source in many files, shipped as one page assembled at build
- tests/pages.test.js: builds stay static files Pages can serve, all local
  references resolve, only release.yml deploys and only via the Pages actions
- tests/build.test.js: partial naming and layout rules
- new skills: github-pages, edit-the-game; add-strings, performance, release
  and write-tests updated for src/, sorted dictionaries and --base-ref
- CLAUDE.md, ARCHITECTURE.md, CONTRIBUTING.md (incl. porting older branches),
  README.md and the PR template describe the new layout
2026-10-27 10:15:12 +01:00
Frederic Jung
052fdd713f
port-branch: keep code after the ACT block in very old versions 2026-10-27 10:11:07 +01:00
Frederic Jung
657e7b8083
port-branch: also handles branches started from older versions of the page 2026-10-27 10:10:56 +01:00
Frederic Jung
c64b139a86
Fewer merge conflicts: actions by area, one city per line, sorted dictionaries
- ACT is split by area into game/90-actions/*.js (const ACT in the first file,
  Object.assign in the rest)
- CITY_LL, CITY_NUDGE and LANDS_LL have one entry per line; the id-keyed ones
  are sorted
- site/i18n/*.js are sorted, one entry per line; i18n-check enforces it and
  --fix (npm run i18n:fix) restores it; scripts/i18n-add.js adds, removes
  and renames entries in place
- scripts/legacy/port-branch.js moves a branch's site/index.html edits into
  src/ during a merge with main
- perf workflow and PR template build the base page with scripts/lib/page.js
2026-10-27 10:10:16 +01:00
Frederic Jung
3d469d9a93
City density rule: retire 15 crowded Brazilian cities from new games
A small city (P < 60) may not sit within 300 km of a bigger city in the
same country unless it is a cable landing or a capital (Canberra gets a
capital flag); a test enforces it everywhere. The 15 Brazilian cities
that broke it get off:true: still in the data so saves keep their POPs,
routing and links there, but new games do not draw them, offer them to
customers, list them in network presence, or let you build a POP there.
Brazil goes from 40 to 25 cities (Europe has 44). Order and Progress now
needs 15 IX.brrr ports.
2026-10-27 10:09:12 +01:00
Frederic Jung
67a40942b4
Split the game page into partials under src/, assembled into one index.html at build
site/index.html (900 KB of HTML, CSS and JS in one file) becomes src/: a shell
(src/index.html), styles/ and game/, concatenated in path order by
scripts/lib/page.js. The assembled page is byte-identical to the old file, so
load time and in-game performance are unchanged.

- scripts/build.js replaces build.sh (same env vars, same output)
- npm run dev: a zero-dependency dev server that assembles on every request
- tests assemble the page in memory; npm test runs every tests/*.test.js
- perf-bench takes --base-ref to build a git ref's page
- scripts/legacy/split-index-html.js is the splitter, kept for older branches
2026-10-27 10:05:56 +01:00
Frederic Jung
295e68cc46
Australia, supply chain, sold-out waves and quicker PNIs (1.33.0) 2026-10-27 09:39:49 +01:00
Frederic Jung
1b691ca9af
Supply chain: hardware prices drift up, shortages come and go, spares and price locks
hwMul() scales new purchases of routers (routerCost, swapCost), optics
(optCost, on top of tariffs) and own builds (dfBuildCost, ownCabCost):
free for 180 days, then +4%/year, capped at +30%. Monthly costs of what
you own do not move.

Shortages are a new random event after day 180, never two at once:
optics +50%, routers +40% or builds +30%, for 45-75 days. Counter-moves:
stock spare optics from a dark fiber link at today's price, or buy a
365-day price lock from the NOC (80k + 30k per POP, double during a
shortage), which freezes today's trend and ignores shortages.

Measured on a 16-POP European network ($530k/mo revenue): the curve
adds ~5% of revenue a year in year 1 and ~23% by year 5 if every dollar
is reinvested in hardware; a lock costs about a month of revenue.
2026-10-27 09:25:47 +01:00
Frederic Jung
1c42c41df0
PNIs: usually a month, 15% stuck for 6-12 months; routes sometimes sold out of a wave size
Big-network PNIs and augments now take 30 days, with a 15% chance of
6 to 12 months (still halved at a conference). Help and order text say
so.

Leased waves can be sold out on a route for a while: a stable verdict
per route, cable, size and 90-day window (2% for the smallest, rising
to 10% for the biggest), with a reason. The link window greys out sold
out sizes with the days left. Never in the first 90 days or the
tutorial.
2026-10-27 08:54:12 +01:00
Frederic Jung
fbd0f133ba
Don't repeat the city after an exchange that is named after it (#134)
IX.brrr Campinas, Equinox Ashburn IX and friends already say where they
are, so peering tips, IX LAG labels, the max-prefix leak incident, the
de-peering toast and the route server hint drop "in {city}" for them.
2026-10-27 07:30:02 +00:00
Frederic Jung
813e8d95e3
Merge pull request #142 from LookedPath:fix/subsea-upgrade-scheduling 2026-10-27 07:19:21 +00:00
Frederic Jung
28036a7be2
Merge pull request #146 from andrewnyr/feat/crowdflare-rackstar 2026-10-27 06:44:43 +00:00
Frederic Jung
b7dcd3177b
Merge pull request #143 from huguesdelamure/stack-alien-wave-contracts 2026-10-27 06:44:26 +00:00
Frederic Jung
e5d7c1406b
The South Island joins the map, old Australian saves hear what changed, crowded POP names wait for zoom
Christchurch (Garden-City-IX) and Invercargill on the South Island, which
had a coastline but no land to build on. Cook Strait Talking from Auckland
to Christchurch, and Lord of the Tasman Rings from Invercargill to Sydney,
Melbourne and Auckland, after the planned Tasman Ring Network that lands at
the Southland data centre campus. Kea, sandflies, post-hole diggers, ferry
anchors and the smelter's grid.

Saves with Australian POPs from before #148 get one notice: pricier transit,
fewer sellers, and Telstraya and Floptus sessions at the exchanges ended.

A POP name that would land on another name hides until you zoom in, unless
it is selected, hovered or home.
2026-10-27 07:22:31 +01:00
Frederic Jung
65a7135983
Down Under: upside-down routers, BrisVegas, Next-Door-DC and everything trying to kill you 2026-10-27 07:05:03 +01:00
Claude
c73665a1bc
Merge pull request #147 from mxhob1/broadband-price
The broadband panel shows each city's real price per gigabit

# Conflicts:
#	CHANGELOG.md
#	site/index.html
2026-10-27 07:05:03 +01:00
Frederic Jung
2636b23ab5
Merge pull request #148 from mxhob1/australia-hard-mode
Start in Sydney on hard mode

# Conflicts:
#	CHANGELOG.md
2026-10-27 07:04:54 +01:00
Frederic Jung
a2213b6610
Answer @claude mentions on issues and PRs, including PRs from forks 2026-10-27 07:01:38 +01:00
Frederic Jung
6137034d2b
Atlantic islands, peering inbox, slow PNIs, backhaul latency and more (1.32.0) 2026-10-27 06:29:35 +01:00
Michael Hobl
3e65215608
Start in Sydney on hard mode: Australian pricing, carriers and exchanges that follow PeeringDB, Adelaide, Canberra and Hobart, new cables, Australian outages and the Fibre to the Basement scenario 2026-10-27 13:05:34 +10:00
Michael Hobl
33d23c1fe4
The broadband panel shows each city's real price per gigabit and real revenue, not the base rate 2026-10-27 11:56:55 +10:00
Andrew Asciutto
e353040899 Add Crowdflare Rackstar embedded caches 2026-10-26 20:33:20 -05:00
Hugues
542b61c581 Stack a carrier's alien waves on one fiber into one contract
Every broker sale of 1-4 alien waves became its own customer, so a large
fiber-resale business grew to tens of thousands of tiny contracts. A real
save reached 124,966 alien-wave contracts and 49 MB: localStorage stopped
accepting it (save() swallows the quota error) and every compute() walked
the whole list.

A carrier that already rents waves on a fiber now grows its contract:
slots, monthly rate and the description add up. migrate() folds older
saves the same way, keeping the unhappier mood and the earliest start.
The same spectrum is sold and the same revenue is billed.

On that save: 124,966 -> 2,190 contracts, 49.3 MB -> 4.2 MB.
2026-10-26 23:48:34 +01:00
LookedPath
2a83892de8 Fix subsea upgrade scheduling and add one-click construction rush 2026-10-26 22:47:13 +00:00
Frederic Jung
e7fcb041be
Merge main
# Conflicts:
#	CHANGELOG.md
#	site/i18n/fr.js
#	site/i18n/it.js
#	site/i18n/pt.js
#	site/index.html
2026-10-26 23:34:24 +01:00
Frederic Jung
68b3d0b839
Far-away transit backhaul is slow, and slow is bad service
Each transit flow's backhaul round trip over your own links (2× the path
latency to the exit) now affects service: free up to 20 ms (~1,500 km),
up to 20% worse at 50 ms, and half the service value past 50 ms. sfOf()
multiplies delivery by it, so revenue, broadband growth and business
customers all feel it. Peering, PNIs and caches are exempt.

City panel chip and Transit-tab warning name the far exit and the round
trip; the NOC lists slow cities. Two tests updated: Moscow on Frankfurt
transit is still fully delivered but now slow, and the Red Sea test pins
Asian demand that would otherwise churn away on Marseille transit.
2026-10-26 23:29:49 +01:00
Frederic Jung
37038e922d
NOC notifications: the last 10 minutes, readable, foldable and openable
The NOC's 'Recent events' (S.log) becomes the notification inbox instead of
a separate one. Entries now keep a wall-clock time, a title, a repeat count
and what they are about, and the NOC shows the last ten minutes right after
the incidents rather than at the bottom: title, short text, 'n min ago',
x N for repeats within a minute, and Open.

Open targets come from the notice itself (incidents via their ref, DDoS,
badges, goals, exchange ports and sessions, resolved incidents), then from
its own navigation button, then from the city or link its text names; 45 of
46 notices in a 60-day test game get one. A link or customer that is gone
says so. Unread counts show on the NOC chip and the phone NOC tab (not red:
red stays for incidents). Entries are validated in sanitize().
2026-10-26 22:56:44 +01:00
Frederic Jung
4643adb2ea
Merge main
# Conflicts:
#	package.json
#	site/i18n/fr.js
#	site/i18n/it.js
#	site/i18n/pt.js
2026-10-26 22:42:18 +01:00
Frederic Jung
8db8cb1f7a
Peering inbox, PNI lead times and minimum sizes, Microsnoft US East
Peering inbox (Networks tab): requests from small and made-up networks
arrive with every IX port, max-prefix alerts take bilateral sessions
down for a few weeks unless answered (raise the limit for growth, keep
it down for a leak; raising it on a full table is a route leak).
Unanswered mail costs reputation, which makes selective networks up to
10% pickier. The Large Peering Model agent costs $20M a year and gets
about a third of its decisions wrong, with a log to prove it.

PNIs are ordered, not instant: 2 to 6 weeks for small networks, 6 to 12
months for big content networks, Tier 1s and big eyeballs, for new PNIs
and augments alike (halved during a conference). Content networks and
Tier 1s start at 100G; Doitsche Telekomm sells 1G. Microsnoft refuses
PNIs and IX sessions in Ashburn, New York, Boston, Atlanta and Miami.
Only delivered PNIs carry traffic, bill, or count for goals and Tier 1.
2026-10-26 22:37:51 +01:00
Frederic Jung
c0ccbb4e01
Merge #133 branch head (its upstream merge matches what is on main) 2026-10-26 22:19:31 +01:00
Frederic Jung
56f2d446ea
Sea routing: Suez and Panama crossings, great circles, fastest design back on par
After #133 the coastline router treated Egypt and Panama as solid land, so
Marseille–Singapore sailed round Africa (21,440 km instead of 12,175) and
Miami–Lima round Cape Horn (17,700 km for a 4,220 km hop). Real systems
cross both by land: Port Said to Suez beside the canal, and Panama
(PAN AM). These are now overland edges in the sea graph, priced as the
distance they cover. The Red Sea Crisis shuts Suez, and routes are cached
per set of open passages, also in the survey worker.

Long open-water legs follow the great circle where it stays at sea,
instead of a straight line on the map. The low-latency design may land
further off and backhaul overland, and may follow the corridor of the
fastest in-service cable on the pair when that is shorter, so it matches
Hibernia again (London–New York 25.3 ms, Halifax–London 20.9 ms) and
beats cables that take detours (Lagos–Bude 32.2 against 37.6 ms).

Tests: main's expectations restored where #133 had loosened them
(Marseille–Singapore needs no upgrades, New York–Sydney needs terminals,
express equals the fastest cable); the marine check knows the passages;
new checks for Suez, Panama, the crisis and the corridor rule.
2026-10-26 22:13:16 +01:00
LookedPath
a20f970fc9 Merge upstream main and resolve ocean-routing conflicts 2026-10-26 21:00:39 +00:00
Frederic Jung
656e904e05
Merge #133: route new subsea cables around coastlines 2026-10-26 21:52:59 +01:00
Frederic Jung
682b6c99f4
RouteScript: AI button, help page and ready-made scripts
The editor gets a help page (how exits are picked, the workflow, every
rule with its real-router equivalent) and seven ready-made scripts
filled in from the live network: Shields Up, Customer Care, Peering
First, Penny Pincher, Prepend Diet, Maintenance Window and Keep Calm.

Slop it with AI dry-runs its favourite recipes against live traffic,
keeps the best, and signs it with a pun-named model and a confident
remark. The glossary mentions RouteScript too.
2026-10-26 21:44:59 +01:00
Frederic Jung
ab079e70dd
Atlantic islands and Halifax: real landings and shorter crossings (#120)
Halifax, Bermuda, Ponta Delgada (Azores), Tenerife, Praia (Cape Verde)
and St Helena, the islands each their own landmass with outlines on the
map. Exchanges only where one runs today (CVIXP in Praia, HFXIX in
Halifax); none in Bermuda, the Azores, the Canaries or St Helena.

Cables follow real landings: new pairs on Hibernia Express (Halifax),
Nuvem (Bermuda), Columbus III (Azores), EllaLink (Cape Verde), Equiano
(St Helena), SAT-3, ACE, 2Africa and WACS (Canaries, WACS also Cape
Verde), existing pairs untouched so saves keep their links. New: Sol
(Florida, Bermuda, Azores, Santander), Atlantis-2 (Las Toninas,
Fortaleza, Praia, Dakar, Tenerife, Sesimbra) and Canalink as puns.

Crossings just over the 6,000 km 1.6T reach now split at the islands:
Miami-Madrid, Atlanta-Lisbon, Lisbon/London-Lagos and Fortaleza-Madrid
go from 1.2T to 1.6T per wave hop by hop.

Island networks with Tier 1 upstreams (One Communications, CV Telecom,
Sure South Atlantic, Eastlink as puns), MEO in the Azores, Bell in
Halifax, Bermuda Triangle cuts, and the Mid-Atlantic Accent scenario.
Broadband in a town smaller than 8 Gbps now starts at its ceiling
instead of above it.
2026-10-26 21:17:21 +01:00
MurphysHub
5914711f2c
Merge branch 'main' into weights 2026-10-26 21:05:05 +01:00
Marvin
8a25ebdb95 Custom routing metric for links
A link's routing metric could only be one of four presets (Prefer,
Normal, Avoid, Backup only). Links now also get a Custom option, closer
to how real networks tune IGP metrics:

- Multiplier mode scales the distance cost, (km + 60) × 0.1 to 100.
- Cost mode sets an exact cost, 1 to 65535 like an OSPF metric.

The preset buttons stay plain. Picking Custom explains how a link's cost
is worked out and lists what each preset comes to on that link. Choosing
Custom starts from the current preset and switching modes keeps the
effective cost, so nothing moves until the player changes the value.
Like the presets, it applies to every link between the two cities.

The cost formula lives in one helper, linkW(), used by compute() and the
traceroute paths. Custom links store mk/mv, which sanitize() repairs and
clamps; old saves load unchanged. The link panel skips its daily
re-render while the number field has focus, and Enter applies the value.

Tests cover routing equivalence with the presets, rerouting by cost,
mode switching, input clamping, saves, and the panel at desktop and
phone width. French, Italian and Portuguese for the new strings.
Perf on the big network: no change beyond noise, routing identical to
main.
2026-10-26 20:55:12 +01:00
Frederic Jung
673b5159b0
Zoom in further, and pick short links between close cities (#126)
Porto Alegre and Florianopolis are 65 px apart at the old maximum zoom,
and each city grabbed taps within 38 px, so the link between them could
not be selected at all. The maximum zoom goes from 6x to 16x (city icons
stop growing at 1.35x, so dense regions spread out), and a city now wins
a tap outright only on its icon; in the rest of its tap circle a link
right under the pointer wins. The hover cursor follows the same rule.
Dragging from a POP still draws a new link.
2026-10-26 20:42:01 +01:00
LookedPath
8ac420c4c8 Route new subsea cables around coastlines 2026-10-26 19:33:08 +00:00
Frederic Jung
729d4d303d
French, subsea cable designs, Road to Tier 1 and more (1.31.0) 2026-10-26 17:59:37 +01:00
Frederic Jung
18f3936058
Sell spare dark-fiber capacity from the fiber itself (#51)
Wholesale alien waves and spare-pair leases already existed, but only as
random offers, and the fiber only said how many channels were sold. Each
dark fiber in service now has a 'Selling spare capacity' section: free
channels, who rents what and for how much, a pending offer with Accept,
and 'List it with a capacity broker', which creates an offer for that
fiber at once at the usual price minus a 10% broker cut (alien waves on
free channels first, then a spare pair in your own trench). One listing
per fiber at a time. Random offers use the same helpers and draw the same
random numbers in the same order, so seeded games are unchanged.
2026-10-26 17:47:51 +01:00
Frederic Jung
42b3e95386
Red Sea Crisis needs a month of traffic into Asia; Luxembourg gets Poste Restante (#113, #84)
- #113: the goal was a Marseille-Singapore path and 300 Gbps served
  anywhere, which broadband with local transit reached on day 0. It is now
  the path plus 80 Gbps on your links between Asia and the rest of your
  network for 30 days in a row (S.stats.asiaRun). A 100G route around Africa
  gets there in about two months and costs about 590k a month against 2.5M
  of starting cash, so it is a real challenge. The scenario card shows
  today's traffic and the streak.
- #84: Poste Restante, Luxembourg's eyeball network, at LU-SICK in
  Bettembourg (selective, buys transit from Tier 1s, so Tier 1 reach holds).
  Citrus Belgium's blurb now says it is Tangerine's Belgian daughter.
- The wave seller and wholesale customer 'GTT (Got Tangled Twice)' used a
  real company name; it is now 'G&T (Gin and Transit)'.
- The scenario start toast puts a full stop after the goal.
2026-10-26 17:31:22 +01:00
Frederic Jung
086502b782
Scrubbing centers in many POPs, with real backhaul (#117)
S.scrubAt/S.scrubTier become S.scrubs, one center per city, each with its
own size and monthly fee; old saves carry theirs over in sanitize().

An attack goes to the nearest working center with a backbone path, and
spills to the next when it is full. A remote center's flood (plus a share
of the victim's own traffic) is reserved along the backbone path after
the L2 circuits, like a circuit: it fills those links, the round trip is
shown in the NOC, and what the links cannot carry is not scrubbed and
lands on the city. Local centers behave as before.

DDoS protection customers lose mood while their attack detours 30+ ms,
with the reason in their row; a new requirement asks for a center on the
customer's continent. The Infra tab names the nearest center and its
distance, and How to play explains it.
2026-10-26 16:47:55 +01:00
Frederic Jung
9d6ad94035
Road to Tier 1: what is missing, and where to meet each network (#111, #121, #12)
Goals gets a Tier 1 card once it is the current goal (or the title was
lost): transit ports left, Tier 1 PNIs with the missing ones named, the
club requirements they wait for, and reach without transit with the
networks you would lose. The Networks tab gains an 'out of reach without
transit' filter and a single-network view with every PNI city and
exchange, your POPs first, then nearest. The NOC transit to-do list names
the nearest city and links to the network.

Routing counts reach without transit in the same pass. Places and
distances are cached until the POP set changes, and exchange membership
once per routing pass, so the Networks tab costs what it did.
2026-10-26 16:24:08 +01:00
Frederic Jung
c336e963a5
Merge main (Spätzle-IX fix, #114) 2026-10-26 16:20:14 +01:00
Frederic Jung
6ddbc6ec7d
Subsea cable designs, fixed against today's main (#65, #78)
- Upgrades take effect: the optic speed cache from #89 is now kept per cable
  state (subsea, terminals in service, engineering in service), so a cable
  no longer stays at 400G after both upgrades are commissioned.
- Refunds: a cable remembers what was paid for it, design and upgrades
  included. Calling off a 7x low-latency cable returned 10% of its price.
  'Unusable' now means no optic lights it even with both upgrades.
- Length limit: #88 counts the shortest design and both upgrades. The order
  screen says which upgrade a route needs and will not order without it;
  the order action checks the same. New York to Sydney needs terminals.
  No leased-wave payback hint where no leased wave reaches.
- Choices start fresh when you open the own-cable view and after ordering.
- The 'consider terminals or engineering' hint only on cables you own.
- Low-latency builds take 1.7x as long (London-New York ~2.9 years), not
  3.5x; optimized 1.3x. Each design is one tappable card.
- The low-latency factor is worked out once per route instead of on every
  latency lookup. 'Number.isFinite' alone, no repeated guard in seaQuote,
  the express factor folded into seaLatencyFactor, '+{n} days' as one
  translatable string.
- Portuguese and French for the new strings; one CHANGELOG bullet (#65).

Big network vs main: no slowdowns, identical routing.
2026-10-26 16:07:08 +01:00
Frederic Jung
e76d68fc90
Merge #78: subsea cable designs and transmission upgrades (#65) 2026-10-26 15:39:30 +01:00
Frederic Jung
c08a7b22cc
Only Spätzle-IX can be won with peering alone (#114)
New goal: 45% reach and 300 Gbps served, with reach shown on the
scenario card. Games already in progress pick up the change on load.
2026-10-26 15:35:43 +01:00
Frederic Jung
59cbd66d6f
French for Düsseldorf's city note 2026-10-26 15:24:58 +01:00
Frederic Jung
46e558d5ff
Merge main (Düsseldorf) into the French translation 2026-10-26 15:18:31 +01:00
Frederic Jung
8f135c5713
French: a top-bar label that fits on a phone
"Caisse · Banque" wrapped onto two lines in the phone's top bar at 360 px
and cut off the monthly line under the cash. "Cash · Banque" fits on one
line like the Italian and Portuguese labels do.
2026-10-26 15:16:09 +01:00
Frederic Jung
d2b7aa0ed7
Merge #112: French translation (French for the 43 strings added since, two unused labels removed) 2026-10-26 15:16:09 +01:00
Frederic Jung
268e9a1f03
Düsseldorf: pun name in the CHANGELOG, and a city note the numbers support
The CHANGELOG named Vodafone instead of Voda-Phony. The note claimed more
carrier-neutral data centers than Hamburg and Munich together; #108 only
says more than each of them.
2026-10-26 15:13:38 +01:00
Frederic Jung
dbc212dccb
Merge #116: Add Düsseldorf with the Altbier-IX (#108)
# Conflicts:
#	CHANGELOG.md
2026-10-26 15:08:22 +01:00
Frederic Jung
a1f895d754
PNI upgrade buttons show the monthly fee too (#110)
After #115: upgrading an existing PNI, in the Peering tab and in the NOC's
connection list, also showed only the one-off cost. Both now read
'Upgrade 100G $2.3k + $350/mo', like transit. The two old labels without a
monthly part are no longer used and leave it.js and pt.js.
2026-10-26 15:01:07 +01:00
Frederic Jung
afc5ba3c37
Merge #115: PNI buttons show the monthly port fee next to the setup cost (#110) 2026-10-26 14:52:40 +01:00
clayberF
13e5a5d94b Add Düsseldorf with the Altbier-IX (#108)
Networks follow PeeringDB's 14 Düsseldorf facilities: NTT, Tell-Ya,
Cogentle, Drizzle, Voda-Phony, Doitsche Telekomm and the Crowdflare,
Amazin', Microsnoft and BiteDance clouds (NetChill and Akamaybe are
everywhere already). No nudge needed: 27+ map units from Frankfurt,
Amsterdam and Brussels.

The #16 shark test compared .land, which ignores Cairo's land2, so a
valid overland Mumbai-Cairo ask counted as crossing an ocean once the
extra city shifted the seeded draws. It now uses isSub like the game.
2026-10-26 10:28:59 -03:00
clayberF
497f970eac PNI buttons show the monthly port fee next to the setup cost (#110)
The buy buttons only showed the one-off setup (1500 + setup/2), so a
$1.8k cross-connect read like a monthly bill, while the real monthly
fee (PORT[i].pni) was shown nowhere. Reuse the existing translated
'{port} <small>{cost} + {mo}/mo</small>' label, like transit and IX.
2026-10-26 10:16:43 -03:00
clayberF
6de56f79eb Calibration: drop a redundant guard and a one-caller helper 2026-10-26 10:08:50 -03:00
clayberF
af155f27bb Calibrate city prices with PeeringDB and Hurricane Electric data
CITY_PDB holds, per city, the carrier-neutral facilities and network
presences from PeeringDB (within 50 km or same city name) and the ASN
count of its country from bgp.he.net, pulled 2026-10-25.

- Transit: the regional multiplier is scaled by competition, up to 1.8x
  where few networks are present. Hubs (1000+ presences) are unchanged,
  and hand-set markets (Korea, Belgian red tape) keep their price.
- POPs: 1.25x to build and run with one or two facilities, 1.5x with none.
- Offers: countries with 2000+ ASNs bring extra ISP customers.
2026-10-26 10:08:50 -03:00
Frederic Jung
b0684bca82
Pacific islands, faster routing on big networks and five fixes (1.30.0) 2026-10-26 14:02:43 +01:00
Frederic Jung
a164b512ba
Pacific islands: twelve cities, island landings and faster transpacific hops
Honolulu, Guam, Koror, Majuro, Port Moresby, Honiara, Noumea, Suva,
Nuku'alofa, Apia, Pago Pago and Papeete, each its own landmass with its
real outline on the map. Exchanges only where one runs today (DRF IX,
Guam IX, Fiji-IXP, CAN'L IXP, Solomon Islands IX); PNG and Tonga have
none active, Samoa's is still planned.

Cables follow real landings: new pairs on Southern Cross, Hawaiki, AJC,
JGA, Bifrost and Humboldt (existing pairs untouched, so saves keep their
links), plus SEA-US, AAG, Echo, HANTRU-1, Coral Sea, Gondwana-1, Tonga
Cable, Tui-Samoa, ASH, Honotua, Manatua and SX NEXT as puns.

Subsea waves have no regens, so a POP on an island splits a crossing into
shorter spans: California-Sydney 400G -> 1.6T per wave via Honolulu and
Suva, LA-Hong Kong/Manila 400G -> 800G via Guam, Santiago-Sydney
400G -> 800G via Tahiti (1.2T on own fiber). LA-Tokyo stays 800G leased:
Honolulu-Guam is just over the 6,000 km 1.6T reach.

Twelve island networks, all with Tier 1 upstreams so Tier 1 players keep
their reach. PacNOG in Suva, unreliable power in Guam, Port Moresby and
Honiara, volcano cuts for Tonga, and the Stepping Stones scenario
(1.6T hop by hop from Los Angeles to Sydney).
2026-10-26 13:42:21 +01:00
Frederic Jung
4682f16730
Routing makes far less garbage: no temporary arrays or closures in its hot loop
The group split runs over an index range with one scratch array instead of
map/reduce/forEach and slice, leftover exits go into one reused array and are
sorted in place (insertion sort for short lists; both sorts are stable, so
the order is the same), flows are split without per-flow arrays, and the hot
loops use indexes instead of for...of. Without Auto-TE, exits whose path is
already full are not called at all. One routing pass on the big network
allocates 23 MB in Chromium instead of 66 MB.

Routing results are identical. The speed test's plain path now also uses the
original group split and sort, and a new test routes around a full 10G link
with Auto-TE (and a spill script) and compares both paths; planted bugs in
the split, the sort and both full-path skips are caught.

Big network vs main, two runs: headless routing -23% to -30%, Chromium
desktop -14% to -27%, phone -15% to -27%. Steps 2-4 together vs c76dd4d:
Chromium desktop routing -49%, phone -34%, a game day -26% and -30%.
2026-10-26 13:41:13 +01:00
Frederic Jung
2c0d69379a
Routing skips paths that are already full and finds the nearest exit in one scan
Capacity only shrinks while traffic is routed, so a path with one full link
or node fits nothing for the rest of the pass: push marks it and later tries
return at once (92% of pushes on the big network went into such paths). The
nearest group of exits is found in one scan instead of two, and exits that
filled up are dropped from the shared lists once a quarter of a list is full.

Routing results are identical to before. The speed test's plain path now also
runs without these, with Auto-TE and with a RouteScript that keeps headroom on
every link; planted bugs in each of the three are caught.

Big network vs main, two runs: headless routing -51% to -58%, Chromium
desktop -22% to -31%, Chromium phone -15% to -29%.
2026-10-26 12:35:15 +01:00
Eliot
fbfbf8deb3 Add French translation
Adds site/i18n/fr.js with all 2541 strings, registers Français in the
language list (picked automatically for fr-* browsers), caches it in the
service worker, and runs the full screen tour and the Signal-link check
in French in the tests.
2026-10-26 12:20:07 +01:00
Frederic Jung
c76dd4d556
Benchmark in real Chromium too, and only call a row slower when the samples say so
npm run perf -- --browser times the same workloads in Chromium as a desktop
and as a phone (390x844 at 3x, CPU slowed 4x), one browser per version. Each
run collects garbage first and ends by forcing layout and the map canvas, so
deferred work counts. The jsdom DOM is about 30x slower than a browser's and
has no layout, so the interface rows need this.

Shared machines swing single runs by 30% on identical code, CPU time
included. A row now counts as slower or faster only when it moved 15% and a
Mann-Whitney U test gives p < 0.01 (15 runs a side by default). Identical
code: no flags in three full runs; a routing slowdown planted in a copy is
flagged in jsdom and on the phone.

The panel workload renders both selections every run instead of alternating,
which split its samples in two. CI drives the runner's Chrome through
playwright-core, no browser download.
2026-10-26 12:04:57 +01:00
Frederic Jung
c88bad3eef
Let the 3.2T transponder fall back to 1.2T like the 1.6T one (#107)
Its fallback ladder skipped 1.2T, so between 4,000 and 5,500 km on land
(6,000-8,250 km subsea) it carried 800G while the cheaper 1.6T optic
carried 1.2T. A test now checks that a bigger optic on the same line
system never carries less than a smaller one at any distance.
2026-10-26 10:28:28 +01:00
Frederic Jung
92b24fd2ad
Label mixed-size parallel waves per size instead of N × total (#56)
800G + 400G on one route was drawn as "2 × 1.2T", which reads like two
1.2T waves. Mixed groups now list each size, largest first, e.g.
"2×800G + 400G"; equal sizes keep "4×800G".
2026-10-26 09:23:57 +01:00
Frederic Jung
3cd30aa473
Fix five bugs: unlightable cables, own-IX sites, idle router swaps, loan badge, cable-less cities
- #88: own subsea cables longer than the best subsea optic reach are refused
  with a reason; cancelling one mid-build refunds 75% of the unlaid part, and
  an unusable one from an old save is refunded in full.
- #36: your own IX picks building A, B or both (second switch, +50% fabric
  fee) instead of showing site and LAG buttons that did nothing.
- #105: no maintenance window or incident when swapping the only router in a
  POP nothing depends on yet.
- #104: declining a loan redraws the top bar and saves.
- #50: a city with no cable landing names the nearest landing station.
2026-10-26 09:12:01 +01:00
Frederic Jung
f1322f2cd2
Africa, Brazil, Portuguese and a faster game on big networks (1.29.0) 2026-10-26 08:49:19 +01:00
Frederic Jung
e5deb90968
Routing reference test runs on today's routing loop; perf bench reads exported saves
The reference test from #106 now patches the loop as it looks after #96
(business-first passes) and also covers prefer, prepend and protect
customers. It catches an exit index that ignores RouteScript preferences,
which the shortcut test in speed.test.js cannot see.

npm run perf -- --save accepts files from the in-game Export save, so
scripts/benchmark-performance.js and its README section are not needed.
The performance skill documents --save, both equivalence tests and how to
handle noisy runs.
2026-10-26 08:40:20 +01:00
Frederic Jung
2366bb9a8f
Merge #106: routing reference test and save-file benchmark 2026-10-26 08:34:19 +01:00
Frederic Jung
04626cf1a9
African networks buy transit from Tier 1s
Liquid Lunch, Sea-Comedy, Angle-a, Djibouti Calling, Empty-N, Air-Tell,
Ethio-Tele-Calm and Atlas Shrugged get upstreams, so a Tier 1 with PNIs to
the other Tier 1s still reaches everyone, and their traffic stops falling
through to transit (routing on the big network: +10% to +1% vs main).
The Africa changelog bullet now opens with a short first sentence.
2026-10-26 08:13:12 +01:00
Frederic Jung
9303740311
Merge #93: Africa, twenty-one more cities, seven cables, border costs and Cape to Cairo (Portuguese for the 41 new strings) 2026-10-26 08:03:30 +01:00
Frederic Jung
97e3a70f87
Advertise the Signal group in the game and on GitHub
A chat card in the menu and How to play, a footer link on the title screen
(Italian and Portuguese included), plus README, CONTRIBUTING and a contact
link in the issue chooser.
2026-10-26 07:41:50 +01:00
Frederic Jung
207426f61c
Latin American networks buy transit from Tier 1s
Without an upstream, the seven networks from #92 could only be reached by
peering in Latin America, so every Tier 1 would lose reach (and the
title) once the courtesy route for new networks ran out.
2026-10-26 07:28:36 +01:00
Frederic Jung
a44ff68186
Merge #92: Brazil's forty IX.br locations and twelve more Latin American cities
Portuguese for the 52 new strings.
2026-10-26 07:22:42 +01:00
Frederic Jung
1473fb0627
RouteScript optimizer: smarter tips after #96
Suggest protect customers only where IP customers would get unhappy
(under 95% served): it costs a second routing pass, about +65% on a big
network. Point at the exchange the network actually peers at, where you
have no port yet, instead of the city's main IX. And the draft admits it
has never been paged at 3 a.m.
2026-10-26 07:14:21 +01:00
LookedPath
ffb8c50895 Add routing reference regression and exported-save benchmark 2026-10-26 06:11:12 +00:00
Frederic Jung
1858098a4d
Merge #96: RouteScript local-pref, AS-path prepending, protected customers and an optimizer
Ported onto #89's routing loop: the prepend share is its own transit exit,
local-pref and prepending get their own ranks, and protect customers runs
business flows through every rank before home users. Portuguese for the
five new strings.
2026-10-26 07:01:33 +01:00
Frederic Jung
308c3f7045
Performance benchmark on a big network, posted on every PR
scripts/perf-bench.js times routing, a game day, an action, panels, the
NOC dashboard and the map on tests/fixtures/big-network.json (104 POPs,
950 PNIs, 832 caches), base and head in alternating turns, and says
whether routing results changed. perf.yml runs it on every PR against
the base; perf-comment.yml posts the table as one updated comment.
New performance skill, CLAUDE.md rule, PR template and docs.
2026-10-26 06:39:23 +01:00
Frederic Jung
ad8b1bebcb
Portuguese: the four counter strings added after #91 was branched 2026-10-26 06:18:38 +01:00
Frederic Jung
6f765b2088
Merge #91: Brazilian Portuguese translation 2026-10-26 06:13:35 +01:00
Frederic Jung
4e95b9b397
CI: translation coverage job
A separate 'translations' job runs the i18n checker on every push and
PR and writes a coverage table per language to the run summary, with
the missing, broken and unused keys listed. The checker now also fails
when a language file is not offered in SOT_LANGS or cached in sw.js.
2026-10-26 06:04:28 +01:00
Frederic Jung
0ecce20dec
Test that #89's fast routing matches the plain path
Builds a copy of compute() with the own-exits shortcut, the first-group
scan and the per-network exit index switched off, and compares both on a
busy network with Auto-TE, preferred and backup exits, two upstreams per
city, route servers and two cache boxes per CDN. Verified it fails when
either shortcut is deliberately broken.
2026-10-26 05:56:15 +01:00
Frederic Jung
4a6af1a348
Merge #89: make big networks fast (routing, panels and map drawing) 2026-10-26 05:43:22 +01:00
clayberF
14ae22cee9 RouteScript: local-pref, AS-path prepending, protected customers and an optimizer
- prefer/avoid transit PROVIDER: per-upstream local-pref (ranks 2.9 and
  3.5, so never ahead of peering).
- prepend transit PROVIDER 1-3: moves 35/60/75% of that upstream's port
  to a last-resort share. Prepending is a hint, not an order.
- protect customers: business flows take every rank first, and IP
  business customers are judged on their own served share.
- Optimize: drafts a script from live traffic (spill, protect, cheapest
  and priciest upstream) plus comments for IX and PNI opportunities.
2026-10-25 23:15:24 -03:00
clayberF
bca2858c89 Africa: twenty-one more cities, seven cables, border costs and Cape to Cairo
Cities in nineteen countries, each with a pun IX and a country code (cc).
Overland fiber between two African countries costs 2x. Kinshasa, Lusaka
and Harare get blackout, Durban load shedding.

Cables follow real landing points (submarinecablemap.com): ACE, SAT-3,
MainOne, Maroc Telecom West Africa, SAIL, SEACOM and DARE1 as puns, plus
new pairs on 2Africa, WACS, Equiano, EASSy, TEAMS, PEACE, AAE-1, Glo-1,
Medusa and SACS. All pairs are drawn from one sea track around Africa.
Existing pairs are untouched, so saves keep their links.
2026-10-25 22:27:59 -03:00
clayberF
9cde4c432c All forty IX.brrr locations and twelve more Latin American cities
Brazil gets every IX.br location (ix.br/localidades/atuais), each with a
cheap nonprofit IX.brrr. Overland fiber into the Amazon costs 2x. New
national networks (Oi Oi, TIM-TIM Mobile, Brisanada) and a scenario,
Order and Progress: ports on 20 IX.brrr exchanges including Manaus.

Latin America: Montevideo, Asuncion, Cordoba, La Paz, Quito, Medellin,
Caracas, Guatemala City, San Jose, Queretaro, Monterrey, Guadalajara,
with Moviestar, Liberty Latte America, Antelope and Tiger Mobile.
SAm-1 gains a Salvador landing and Tannat a Montevideo one (new pairs
only, so old saves keep their links).

Dense clusters are spread apart with display-only CITY_NUDGE entries;
Rio no longer needs its old nudge, which put it north of Vitoria.
2026-10-25 22:15:48 -03:00
Frederic Jung
47c7c19402 Rest the map while the dashboard covers a phone screen
On a phone the NOC dashboard, scrolled past its top edge, fills the whole
screen, but the map underneath was still drawn every frame: about 4 ms per
frame on a big network on a fast PC, several times that on a phone. While a
panel covers the map completely it is no longer drawn, and it comes back as
soon as any of it shows. At the top of the dashboard the strip of map above
the card keeps moving, and on desktop, where the map shows around the
dashboard, nothing changes. No payday floaters are made while the map is
hidden, so they cannot pile up out of sight.
2026-10-26 02:00:33 +01:00
clayberF
6d145faa25 Add Brasília, Belo Horizonte, Curitiba and Porto Alegre
Four more Brazilian cities, each with an IX.brrr exchange (nonprofit, cheap
ports) and provedor offers. Clarovision and Viva Vivo serve them, and
Capybara Connect stops in Porto Alegre. The Samba Peering achievement now
names its three exchanges instead of saying "all three".
2026-10-25 21:44:19 -03:00
Frederic Jung
e026836169 Rest the map while paused, and fade payday floaters after a pause
- Payday floaters were stamped with performance.now() but aged with the map's
  animation clock, which stops while paused. After a pause they never faded:
  they sat off-screen and were drawn every frame, about a hundred more per
  payday on a big network, so long sessions got slower and slower. They are
  stamped with the animation clock now.
- While paused or with animations off, the map is only redrawn when the camera,
  the selection, hover or drag, the network or a new day changes it, plus once
  a second and while the land picture catches up after a zoom. A paused frame
  drops from ~4 ms to ~0.05 ms.
- After a day ends, the open panels update on the next frame, so one frame does
  not carry both the day's simulation and the panels. With a day on every frame
  they still follow, one frame behind.
2026-10-26 01:29:17 +01:00
Frederic Jung
9b1ed2f776 Show long NOC dashboard lists 100 rows at a time
The Connections tab drew every connection at once: 1,486 rows with their
buttons came to 32,000 elements, and laying them out again after every day
took about half a second while the dashboard was open (far longer on a phone).
The Connections and Customers lists now show 100 rows and a "+100 more"
button. Filters, sorting and totals still cover every row, and changing a
filter or the sort starts the list short again.
2026-10-26 00:42:37 +01:00
Frederic Jung
566dfcdbee Merge branch 'main' into faster-big-networks 2026-10-26 00:03:12 +01:00
Frederic Jung
a887b65a2f Make big networks fast: routing, panels and map drawing
A network with a hundred POPs and a thousand peering ports froze the game for
most of a second every day and after every click, because routing checked all
~1,800 exits for each of ~14,000 flows. Now:

- compute(): exits are asked once per network which networks they reach, each
  flow scans only those, and the first ECMP group is found without sorting. The
  graph runs on city indices with a typed-array Dijkstra (same heap moves, same
  ties), routers and per-link traffic are kept in typed arrays, the diverse-path
  check reuses one live-link graph, and R.ef is put together when a link is read.
  Results are bit-identical to before.
- Panels and the NOC dashboard are patched in place (morph) instead of being
  rebuilt, so the browser no longer restyles 1,500 rows every tick. Buttons whose
  action changed are swapped out, keeping #44's tap protection.
- The Networks tab works out each IX port's sessions once instead of once per
  network.
- draw() reuses screen-point buffers, a per-frame pair index and cached label
  widths, strokes the dotted fiber line on the path it already has, and uses
  native roundRect: about a third fewer canvas calls per frame, same output.
2026-10-26 00:03:05 +01:00
clayberF
eb7f4a8f8c Add Portuguese (Brazil) translation
Adds site/i18n/pt.js with all 2429 strings, registers Português in the
language list (picked automatically for pt-* browsers), caches it in the
service worker, and runs the full screen tour in Portuguese in the tests.
2026-10-25 19:58:05 -03:00
LookedPath
d58ca2b14a Add subsea cable designs and transmission upgrades 2026-10-25 20:57:53 +00:00
Frederic Jung
388b12d901
Gentler bends for links between nearby cities
The curve that dodges other cities wanted 24 map units of clearance and
picked the most distant of up to 3.8x curves when nothing cleared, so
short links in dense regions looped wide. Clearance now scales with link
length, offsets are capped at about a third of it, and a modest curve
wins over a giant one when nothing clears.
2026-10-25 21:56:21 +01:00
Frederic Jung
7e3ea0cefe
Router trade-ins, one swap a day, and speed-based requirements (#82)
Swaps and removals sell the old chassis for 30% (optics get 40%, #45),
and buttons show the net price. A POP accepts one model swap per game
day so a double click cannot chain two upgrades. Optic and wave
requirements name the port speed, since side-grades qualify too.
2026-10-25 21:49:51 +01:00
Frederic Jung
6c2d5da5b8
Add Munich with the Brezn-IX 2026-10-25 21:11:55 +01:00
Frederic Jung
8c44bb6459
Put Stuttgart and Frankfurt back in place, add Hamburg
Display nudges had pushed Stuttgart 30 units east and Frankfurt west of
Zurich. Small nudges now keep Frankfurt, Stuttgart and Zurich apart in
their real order. Hamburg gets the Moin-IX and the usual carriers.
2026-10-25 21:08:56 +01:00
Frederic Jung
c21a603765
Release 1.28.0 2026-10-25 20:51:16 +01:00
Frederic Jung
1418994233
Benelux: Brussels, Oostkamp and Bettembourg (#79)
Belgian red tape (POPs +30k, transit 1.5x), the Flanders duopoly
(eyeball growth at 35% unless an ad campaign runs), five networks reached
through their upstream Tier 1, the Clementine cable London-Oostkamp with
trawler cuts, and a wood-pellet cooling failure in Bettembourg.
2026-10-25 20:44:50 +01:00
Frederic Jung
05bb2b680a
NOC: incidents first, paid one-click fixes at the top (#63) 2026-10-25 20:34:00 +01:00
Frederic Jung
19e89456b2
Split embedded caches across both metro sites (#69)
Cache boxes get a site, default A (old saves too). New boxes balance
across the two buildings, a control moves boxes between them, a site
outage only takes out its own boxes, and dropping the second site moves
everything back to A.
2026-10-25 20:30:52 +01:00
Frederic Jung
daf922c5fe
Russian Goggle throttling shrinks demand instead of counting as unserved (#70)
The flow was carried in full and then halved on delivery, capping every
Russian city at about 93.5% served, under the 95% customers need. Halve
the Goggle share of demand at the source instead.
2026-10-25 20:27:15 +01:00
Frederic Jung
3a0de5d31a
Kansas City, Calgary, Vancouver and Ottawa, plus Tell Us and Bodgers (#76)
New cities with pun IXs and data centers; Ottawa has frequent power
cuts. Two Canadian eyeball networks, reachable over a PNI with the Tier 1
they buy transit from (new 'up' field), so Tier 1 players keep 100%
reach. Bell and the big carriers extend to the new cities. Cuts on
Canadian links can be beavers, with a badge.
2026-10-25 20:16:00 +01:00
Frederic Jung
1dbb0dea81
Show why Tier 1 is lost, and stop rounding reach up to 100% (#73)
Tier 1 needs reach above 99.9%, but the HUD rounded 99.5-99.9% to 100%,
and the reason only appeared once in a toast. Reach now shows one decimal
below 100%, t1Why names the unreachable networks, and the level card in
the Goals tab says why you are not Tier 1 while it lasts.
2026-10-25 20:07:37 +01:00
Frederic Jung
354100777e
Let new waves join any existing overland route (#77)
Same trench always joined the first link's trench and Diverse always dug
a new one, so a second route could never get a second wave. With two or
more routes the wave window lists each one plus a new diverse route;
joining keeps that route's price.
2026-10-25 20:03:44 +01:00
Frederic Jung
860fa9a76b
Merge #75: opening a link from the NOC closes the sheet on phones and tablets 2026-10-25 19:37:05 +01:00
LookedPath
1d2819e18e Dismiss the mobile NOC sheet when opening link details 2026-10-25 18:16:01 +00:00
Frederic Jung
d4034bca06
Release 1.27.0 2026-10-25 19:10:32 +01:00
Frederic Jung
7c88f74387
Merge #74: skip route-diversity requests the map cannot provide 2026-10-25 19:02:00 +01:00
Frederic Jung
172c593acf
Leased lines: only count savings your glass can carry, and price the optics
Review follow-up to #72. Moving leases onto your own fiber or a leased
IRU now needs free channels for their capacity and costs the optics both
routers take; a full fiber says so instead of showing savings. Cancel
from the Connections list passes an explicit confirmed flag instead of
setting the POP panel's confirm state.
2026-10-25 18:59:19 +01:00
Frederic Jung
e845812600
Merge #72: leased-line savings and connection management in the NOC dashboard 2026-10-25 18:51:07 +01:00
Silas Rech
8238606483
Add leased-line savings and connection management to the NOC dashboard
A new "Leased lines" tab groups every leased wave, fabric circuit and
dark fiber IRU between your POPs by route and prices it against leasing
dark fiber, digging your own fiber or laying your own subsea cable,
including the line system, amplifiers, regen sites and optics for
today's capacity. It shows the savings and payback, explains why a
route can't be replaced, and plans the build in one tap.

The Connections tab can now upgrade, grow and cancel every connection:
the next port size and another LAG member for transit, PNIs and IX
ports, another cache box, a bigger fabric port, and a cancel button
with the same confirm step as the POP panel. Your own exchange has
none. The dashboard refreshes after any action while it is open.
2026-10-25 17:40:00 +00:00
LookedPath
0b14d44665 Skip impossible route diversity requirements 2026-10-25 17:26:48 +00:00
Frederic Jung
ef3dc0e8f8
Merge #59: Go there opens the first city still missing a POP 2026-10-25 18:26:17 +01:00
Frederic Jung
c900f2878d
Merge #54: local PNIs count as local breakout while Tier 1 (#20) 2026-10-25 18:23:38 +01:00
Frederic Jung
930e62869d
DKNOG gets its own evening 2026-10-25 18:08:29 +01:00
Frederic Jung
3ba35a8399
Add DKNOG in Copenhagen to the conference calendar 2026-10-25 17:57:07 +01:00
Frederic Jung
cfb5fb5f8e
Draw subsea cables when zoomed in (#49), release 1.26.1
The world layer only includes cables below zoom 1.7, but drawCables
skipped its own lines whenever any cached layer existed, so zoomed in
nobody drew them. The layer now records whether it holds the cables.
2026-10-25 17:34:48 +01:00
Frederic Jung
c181065d9f
Release 1.26.0 2026-10-25 17:23:53 +01:00
Frederic Jung
cd5d851f6c
One set of subsea optics rules for owned and leased cables (#66, #67, #68)
Subsea glass is engineered for its route, so optics reach 1.5x further on
it; the 1.6T transponder gets a 1.2T long-haul mode. Leased subsea waves
are capped by the fastest carrier any optic can run over the cable's
length (6.4T = 4x1.6T carriers), existing waves are grandfathered. Own
subsea cables can be laid between landing stations on the same landmass
when cables already run there. Also translate the long-haul note.
2026-10-25 17:01:33 +01:00
Frederic Jung
27c1d73b56
Stop buttons behind a modal firing from the keyboard
A declined PNI returned without redrawing, so its stale button stayed
focused. With a DE-KICKS quote open (game paused, nothing redraws),
Enter or Space kept pressing it, and each press toasted another decline.
Redraw after a decline, move focus into a modal when it opens, and
ignore activations of anything outside an open modal.
2026-10-25 16:49:39 +01:00
Frederic Jung
055a975851
Customer levels 5 to 13
Levels now run to 13, driven by a requirements table (peak, POPs,
continents). Each unlocks something: seven router models up to 3.2T with
3.2T ports and 12.8T waves, C+L line systems, 3.2T transponders, eight
pairs per land trench, a 102.4T fabric, 100T scrubbing, six customer
types, and free PNIs from paid-peering networks. Four traffic eras raise
the eyeball ceiling so the higher levels are reachable on a 47 Tbps map.

Default router upgrades follow the badge-less main line per class; port
and wave tiers past 1.6T/6.4T only show once unlocked. Old saves keep
their level; land trenches clamp to four pairs below level 12.
2026-10-25 16:40:17 +01:00
Frederic Jung
99e73cb897
Space parallel links by drawn line, not by link count (#64)
Every link not following a commercial cable curved out by its index among
all links on the city pair, though waves sharing a trench or cable draw as
one line. With a busy trench, leased or own fiber swung out in loops several
times the route length on about half of all routes. Index by drawn line and
scale the spacing with route length.
2026-10-25 16:07:03 +01:00
Frederic Jung
b96d5681e2
Draw your own subsea cable beside its route (#64)
It was drawn as a curve offset by how many links shared the city pair, so
with eight waves on Dublin-London it swung far out to sea. It now follows
the commercial cable on the route, eased sideways, or a gentle curve when
there is none.
2026-10-25 16:00:14 +01:00
Frederic Jung
faba573637
Stricter credit, revenue share on big loans, weird new lenders and conditions 2026-10-25 15:50:28 +01:00
Frederic Jung
5422116f36
Release only when Frederic asks 2026-10-25 15:40:15 +01:00
Frederic Jung
95cb4eeb7c
Release only when there is something worth shipping 2026-10-25 15:39:27 +01:00
Frederic Jung
683b7bad3c
Shorter in-app release notes with a link to GitHub, one release per hour at most 2026-10-25 15:38:49 +01:00
Florian Krieger
13a29c2c2a Add on-demand single-link redundancy checks 2026-10-25 15:38:10 +01:00
Frederic Jung
6b0f3d6eeb
Release 1.25.2 2026-10-25 15:25:28 +01:00
Frederic Jung
2041ca7908
Let Tier 1 networks lay their own subsea cables
Fixes #22
2026-10-25 15:25:28 +01:00
Florian Krieger
e3aebd3efa Navigate deal offers to the first missing POP 2026-10-25 15:04:54 +01:00
Frederic Jung
fd189afc0a
Add issue forms for bugs, features, balance and translations 2026-10-25 14:54:20 +01:00
Frederic Jung
07d12b931d
Release 1.25.1 2026-10-25 14:48:49 +01:00
Frederic Jung
856ecfbb37
Stop loan offers once you have half a billion in the bank
Fixes #52
2026-10-25 14:48:49 +01:00
Florian Krieger
5f432aefc9 Accept local PNIs for Tier 1 customer breakout 2026-10-25 14:37:12 +01:00
Frederic Jung
bfe12cca7d
Release 1.25.0 2026-10-25 14:35:35 +01:00
Frederic Jung
b929ccdd75
Light more fiber pairs in your own trench
Fixes #35
2026-10-25 14:35:35 +01:00
Frederic Jung
7be8b19832
Release 1.24.0 2026-10-25 14:32:01 +01:00
Frederic Jung
353e9a816e
Add the Flood Season scenario, keep overlapping DDoS attacks apart 2026-10-25 14:32:01 +01:00
Frederic Jung
b53d7613cf
Release 1.23.0 2026-10-25 14:08:55 +01:00
Frederic Jung
8e921693c5
Steadier taps, lighter map drawing, Sinai land route, live Tier 1, courtesy route, optics spares
Fixes #43, fixes #44, fixes #45, fixes #46, fixes #47
2026-10-25 14:08:55 +01:00
Frederic Jung
6a8df55dd9
Release 1.22.0 2026-10-25 12:34:28 +01:00
Frederic Jung
bfd895cc20
Show scenario and level progress, add tabs to the NOC dashboard
Fixes #34
2026-10-25 12:34:28 +01:00
Frederic Jung
31372c0205
Draw date-line links on both edges of the share card
Fixes #42
2026-10-25 12:26:06 +01:00
Frederic Jung
9d53436cb7
Release 1.21.0 2026-10-25 12:03:58 +01:00
Frederic Jung
838ade2c8b
Leave the tiniest islands off the zoomed-out map 2026-10-25 12:03:58 +01:00
Frederic Jung
ac8b12ef17
Merge pull request #41 from aulmaru/main
Real coastlines for the world map
2026-10-25 11:52:24 +01:00
Aulmaru
9549601b00
Add files via upload 2026-10-25 17:18:03 +07:00
Frederic Jung
f2379bf72c
Settings screen, pause on furious customers, customer happiness overview (1.20.0)
Fixes #13, fixes #14, fixes #15
2026-10-25 10:29:49 +01:00
Frederic Jung
dfa28506a7
Release 1.19.0 2026-10-25 10:10:09 +01:00
Frederic Jung
933d57228a
Pitch installing the app to phone players before a new game 2026-10-25 10:08:26 +01:00
Frederic Jung
cf3d333b81
Add a connections overview and show where each network is connected
Fixes #31, fixes #33, fixes #38
2026-10-25 10:03:17 +01:00
Frederic Jung
11118ed5e1
Keep the iPhone home-screen height fix applied, add a viewport readout (1.18.4) 2026-10-25 09:00:11 +01:00
Frederic Jung
a46c9f9694
Fill the screen as an iPhone home-screen app (1.18.3) 2026-10-25 08:47:50 +01:00
Frederic Jung
6b5fe3f14c
Add a petabit-per-second badge (1.18.2)
A new legendary badge for serving 1 Pbps — a thousand terabits — the tier
above Hundred Terabits. Italian and a test included.
2026-10-25 07:36:49 +00:00
Frederic Jung
c445fbd0ba
Add a DDoS-defence goal and badges (1.18.1)
A goal to build your first scrubbing center, and badges for weathering an
attack, holding a multi-terabit flood, running a clean-pipe or a sacrificial
PNI, blackholing your own city, and landing a HackBack that works. New stats
track the hold/monster/hack-win counts; Italian and a test included.
2026-10-25 07:33:49 +00:00
Frederic Jung
a2ab478386
Scrubbing tiers, clean-pipe, sacrificial PNI, IX blackhole, SLA (1.18.0)
Rounds out the DDoS toolbox. Scrubbing centers come in 100G/1T/10T tiers and
clean only up to their capacity; always-on or cheaper on-demand (which lags a
couple of days). A transit clean-pipe add-on scrubs a flood upstream before it
reaches you. A Chinese PNI can be marked sacrificial: a flood over it dies on
the small port instead of the core, at the cost of half its legit capacity. A
new IX-blackhole mitigation drops about half the junk while keeping the victim
up. Selling DDoS protection now carries an SLA penalty when a protected
customer still goes down. Italian and tests included.
2026-10-25 07:03:03 +00:00
Frederic Jung
bc9d2baee1
Price overland intercontinental waves above subsea, drop the cache box cap
Fixes #40, fixes #39
2026-10-25 07:49:13 +01:00
Frederic Jung
5036f1a5a8
Tie Flowspec filtering to the router's TCAM (1.17.1)
Flowspec was a flat network-wide licence. In reality the drop rules live in
hardware TCAM, and the budget differs by platform, so flowspec is now a
router-model capability: none on the used Rusty, a little on merchant-silicon
and whitebox models, full on the big chassis. The flood is filtered only where
the attacked POP's router can do it, and a bigger TCAM knocks it down further.
The licence is gone; the NOC shows how many POPs are capable and the attack
panel names the chassis doing the filtering.
2026-10-25 06:39:36 +00:00
Frederic Jung
c3b99df788
Shape DDoS attacks and add a mitigation toolbox (1.17.0)
DDoS was one flat random event. Now each attack has a vector (DNS, NTP,
CLDAP, SYN, HTTP), a size from a few Gbps to a multi-terabit monster, a
target POP, a duration and an entry point among that city's uplinks.

The NOC grows a live attack panel and a toolbox: RTBH (free, instant, but
the victim goes dark too), a one-time Flowspec licence that drops known UDP
floods at the edge but cannot touch an HTTP flood, the existing scrubbing
center, and HackBack 3000, which sometimes ends the attack and often
flattens an innocent for a fine. New Vigilante and Collateral Damage badges,
Italian translations, and tests for the attack, each tool and old saves.
2026-10-25 06:18:51 +00:00
Frederic Jung
a3bef257c5
Ask for small, human-reviewable pull requests and in-game review of translations 2026-10-25 07:07:10 +01:00
Frederic Jung
443202876a
Add MIT license, contributing guide, CLAUDE.md, architecture notes and repo skills 2026-10-25 07:07:00 +01:00
Frederic Jung
06576357c9
Add customers that connect over interconnection fabrics (1.16.0)
Fabric customers buy transit, or a circuit to one of your POPs, over
Megapork, PocketFabric or Consolation Connect. They come in through your
NNI port in their city and count against its capacity.
2026-10-25 06:29:33 +01:00
Frederic Jung
1d6ec48bf3
Zoom levels of detail, grouped parallel waves, POP decommissioning (1.15.0)
Zoomed out, cities become dots and POPs small router pills with thinner
links and fewer labels. Up close a POP shows the router instead of the
skyline, with a router B for a second site. Parallel waves on one cable
draw as one line with a combined label. POPs can be decommissioned one at
a time or in bulk, with early-termination penalties for affected
customers. Dark fiber panels can add parallel links. NLNOG Day joins the
conferences.

Closes #37
Closes #19
Closes #32
2026-10-25 06:22:20 +01:00
Frederic Jung
7e20a1a2f0
Add Manchester, Edinburgh, Bude and Stavanger with North Sea cables (1.14.0)
New UK and Norway POPs with local eyeball networks, and nine cables:
NO-UK-Way, Celtic Norsemen, Havhingsten Hoofbeat, Shefa Sheep Line,
Oil Rig Wi-Fi, Pas de Câble, Apollo 13, Yellow Brick Road and
Glo-in-the-Dark.
2026-10-24 23:19:46 +02:00
Frederic Jung
8260ce4dde
Keep the update notice small on phones (1.13.2)
The phone layout moved the notice to the bottom but kept its top offset,
so it stretched over the whole screen.
2026-10-24 23:10:20 +02:00
Frederic Jung
e34a389d6d
Release 1.13.1 2026-10-24 23:02:58 +02:00
Frederic Jung
19742ec8fb
Redraw the app icons for home screens
The apple-touch and maskable icons now fill the whole square with the sky
blue and keep the tube inside the safe zone, so iOS rounding and Android's
round and squircle masks no longer show a frame inside a frame or clip the
pink end of the tube.
2026-10-24 23:01:04 +02:00
Frederic Jung
c129883642
Release 1.13.0 2026-10-24 22:56:42 +02:00
Frederic Jung
5786f76ed9
Rework the phone layout and make the game installable
Phones get a one-row status strip, a bottom tab bar (play, speed, goals,
deals, NOC, networks) and draggable bottom sheets; in landscape the sheets
slide in from the side. Toasts can be tapped away, dialogs become bottom
sheets and the title screen keeps its start button in reach.

Adds a service worker for offline play and an install button (the
browser prompt on Android, instructions on iOS).
2026-10-24 22:52:55 +02:00
Frederic Jung
cc28dfeb74
Add Korea's sender-pays market, Sparkly Seabone as a Tier 1, and release 1.12.0
Seoul transit costs four times the usual price and the three Korean
incumbents only peer over paid PNIs billed per gigabit sent. Glitch can
leave Korea and Faceplant can reroute it via Hong Kong. Adds the Gangnam
Style Peering scenario and the Sender Pays badge.

Sparkly Seabone becomes a Tier 1 across the Mediterranean, Europe and the
Americas; older saves keep the five Tier 1s they were playing for.

A wave supplier's optical control plane can melt down and take every
leased wave in a region dark at once.

Closes #23
2026-10-24 22:39:36 +02:00
Frederic Jung
5e0ee53617
Add LACP trouble, partial packet loss and PMTUD black holes
LAG members can flap out, hash onto one member or take the bundle down
with an eager min-links. Links can lose a few percent of packets, which
costs far more goodput than it looks, unless deep-buffer routers absorb
the microbursts. Filtered ICMP or a missing MSS clamp black-holes part of
the traffic to one network.
2026-10-24 22:27:29 +02:00
Frederic Jung
9315b37b82
Keep the top bar on one row in every language
Longer Italian labels wrapped the HUD over the side panels on laptop
widths. fitHud() now hides the less important readouts until the bar fits,
whatever the language. Also shortens two Italian HUD labels and translates
the How the Internet Works links.
2026-10-24 22:21:17 +02:00
Frederic Jung
f1ea017b39
Merge pull request #26 from daniloctdev/feat/i18n-italian
Add Italian translation and a language switch.
2026-10-24 22:18:28 +02:00
Frederic Jung
3afdd116b7
Point players to How the Internet Works
The title screen, the help page and the victory screen now link to Thomas
Kjær Aabo's interactive guide to how the internet really works, and so do
the README and llms.txt. Also removes debug screenshots that had slipped
into the deployed site folder.
2026-10-24 22:12:38 +02:00
Frederic Jung
c59be2d16d
Release automatically when the version on main changes
A new auto-release workflow runs the tests, tags v<version>, publishes a
release with that version's changelog section and starts the deploy from
the tag. It skips versions that are already tagged and refuses older
versions or ones without notes.
2026-10-24 21:54:52 +02:00
Danilo Carbonaro
febded70d0 Translate the strings that changed on main
The "-ish" renames, the rival-exchange messages and the free community
exchange ports changed English text that is a dictionary key, so it.js
follows the new wording. The Catnip-IX and JINXED-IX blurbs, the Medusa
Stare cable, the tick-error toast, the "Another one" name button, the
scenic-routing split note and the regen-site messages are new and go
through tr() too.
2026-10-24 21:52:27 +02:00
Danilo Carbonaro
42acec3f07 Let the title-screen language buttons work before a game exists
The click dispatcher only lets a short list of actions through while there
is no game yet, so picking a language on a fresh title screen did nothing.
The test now clicks the button instead of calling the action.
2026-10-24 21:52:27 +02:00
Danilo Carbonaro
42711456e2 Tidy the i18n layer after review
- Badges that react to sharks, anchors, crocodiles and llamas read the
  English text of the incident again, so they unlock in every language.
- Scenario names are looked up when shown, so they follow a language switch.
- Fall back to English (and lang="en") when the dictionary did not load,
  and version the dictionary URL so a release never pairs with a stale one.
- Share the segmented-button helper between settings and the title screen,
  merge keys that only differed in a placeholder name, and slim the check
  script.
- Tests: guard the hooks the tour patches into fireFailure/fireEvent, and
  cover the dictionary fallback and the scenario name.
2026-10-24 21:52:27 +02:00
Danilo Carbonaro
04eb32e0a5 Add Italian translation and a language switch
English stays the source text and the default. Player-facing strings go
through tr()/trn(), which look the English up in a per-language dictionary
(site/i18n/<lang>.js) and fall back to it unchanged. The dictionary is only
loaded when the game runs in that language. The language follows the
browser on the first visit and can be switched under Settings or on the
title screen; the choice is remembered.

- site/i18n/it.js: complete Italian translation (~1900 entries)
- scripts/i18n-check.js / npm run i18n:check: lists missing or stale entries
  and translations that drop a {placeholder} or HTML tag
- tests/i18n.test.js: language selection, fallback, dictionary integrity,
  and a tour of every screen, failure and event in English and Italian
2026-10-24 21:52:27 +02:00
Frederic Jung
37a83c2b3f
Release 1.11.0 2026-10-24 21:51:33 +02:00
Frederic Jung
71dbc6e37b
Light up very long dark fiber with long-haul modes and regen sites
Optics past their full-rate reach now drop to a slower, longer-reaching
modulation instead of refusing to fit, so fibers over 4,000 km are usable.
Regeneration sites split a route into shorter optical spans for full speed,
at a cost per site and per channel. The order screen warns about routes
longer than any optic's full-rate reach.

Closes #17
Closes #30
2026-10-24 21:46:48 +02:00
Frederic Jung
7457acef1e
Stop scenic routing from flapping between paths
Scenic routing measured how busy a link was including the customer's own
traffic, so it fled its own load every day. Judge links without it, split
over two paths that are about as quiet, and keep the previous choice
unless a new one is clearly better.

Closes #28
2026-10-24 21:43:05 +02:00
Frederic Jung
ceaf4dbb93
Punch up the random network names
Swap the real PTT Telecom for Post, Telegraph & Tubes, make the carrier
pigeon an RFC 1149 one, drop the names without a twist and add a batch of
networking puns. Adds a test for the name picker.
2026-10-24 21:35:29 +02:00
Frederic Jung
3009ad8385
Merge pull request #27 from NickBouwhuis
Add random network names and an "Another one" button.
2026-10-24 21:32:38 +02:00
Frederic Jung
364fe7c242
Replace the "-ish" names with real names or proper puns
Conferences and the RIPE NCC use their real names. Data centers are named
after their streets and districts, or get a pun when they are a company.
Cables, carriers, routers and hyperscaler campuses get puns of their own.
2026-10-24 21:23:34 +02:00
Frederic Jung
ecdc0b5cc3
Polish the community exchanges and wire up Barcelona
Bring back the best jokes in the KleyWrecks, FRIES-IX and IX Strayla
blurbs, keep Bento-IX as Tokyo's cheaper challenger, and give Barcelona
the Medusa-ish cable to Lisbon and Marseille plus CDN coverage.
2026-10-24 21:16:27 +02:00
Frederic Jung
4753429327
Merge pull request #18 from NickBouwhuis/add-fries-ix
Add Barcelona and Catnip-IX, as well as second community IXs.
2026-10-24 21:14:23 +02:00
Frederic Jung
25749472d3
Only ask for shark-free routes that can stay on land
The "afraid of sharks" requirement was offered for any two cities,
including ones on different continents. Requirements can now say who
they make sense for, and old saves drop the impossible ones.

Closes #16
2026-10-24 21:11:22 +02:00
Frederic Jung
988e0c5d15
Fix the max-prefix freeze at rival exchanges and keep the loop alive
The max-prefix incident looked up an exchange id as a city, the same
bug as #24. Both messages now name the exchange and its city.

frame() now schedules the next frame first and catches a failing day
tick or draw, so one bad lookup shows a warning instead of freezing the
game.
2026-10-24 21:02:08 +02:00
Frederic Jung
16e1f95d1b
Merge pull request #25 from daniloctdev/fix/rival-ix-depeer-crash
Fix the game freezing when a peer drops you at a rival exchange
2026-10-24 21:00:10 +02:00
Nick Bouwhuis
a179836969 Add random network names and an Another one button 2026-10-24 18:23:04 +02:00
Danilo Carbonaro
ba1c1e1a35 Fix the game freezing when a peer drops you at a rival exchange
Peering sessions at a second or third exchange in a city are keyed like
"drz@mil~2". The de-peering toast looked the city up as CITY['mil~2'],
threw, and the exception stopped the animation loop for good: time and
the map froze until a reload.
2026-10-24 18:18:47 +02:00
Nick Bouwhuis
9e9ecca1ad Remove duplicate NYC exchange and retain NY-Yikes 2026-10-24 16:46:33 +02:00
Nick Bouwhuis
4c88e00434 Correct exchange pricing claims 2026-10-24 15:34:26 +02:00
Nick Bouwhuis
e0e1500b8e Merge upstream main and reconcile community exchanges 2026-10-24 15:15:22 +02:00
Frederic Jung
56e15d10dd
Make the test suite fully deterministic
Seed Math.random before the game script loads, keep the game's own
seeded-games wrapper in place, and seed the scenario test too. Random
events during dayTick could replace the deadline modal and fail CI.
2026-10-24 07:12:23 +02:00
Frederic Jung
8fd79ef122
Release 1.10.0 2026-10-24 06:47:10 +02:00
Frederic Jung
0e5abd5c6a
Make router ports finite and add more router models
Every port, wave and fibre channel now takes a router port, and new ports
are refused when a POP is full. POPs take up to six routers, and six new
models can be swapped in from the Infra tab, including the Arrrhipster
7280R-ish and 7800R-ish.
2026-10-24 06:40:08 +02:00
Frederic Jung
5e88e44a0a
Add Italy, Portugal, Greece and more US cities; rival IXes and a long tail of small peers
New POPs in Milan, Rome, Palermo, Lisbon, Athens, Atlanta, Denver, Phoenix,
Boston, Houston and Salt Lake City, with cables and local networks.

Big metros get challenger exchanges with overlapping but different members.
IX state is now keyed by exchange id instead of city. Sixty small networks
sit on random exchanges. EU ports are cheaper and see price wars, and
Voda-Phony moves to paid peering only.
2026-10-24 06:29:19 +02:00
Frederic Jung
cc6d328511
Freeze map animation while paused
Packet dots, waves and clouds run on a clock that only advances while
the game is playing.

Closes #11
2026-10-24 06:07:33 +02:00
Frederic Jung
23b72dcb92
Realistic router ports, North Sea cables and dark fiber, own IX fabric upgrades, regional wave markets, the Gulf, tablet layout
Closes #10
2026-10-23 20:39:48 +02:00
Frederic Jung
b9bfab51f7
Split ports across both metro sites; keep the top bar on one row
Closes #8
2026-10-23 18:47:41 +02:00
Frederic Jung
aad255d193
Release 1.9.0 with RouteScript 2026-10-23 18:29:17 +02:00
Frederic Jung
d99addad88
RouteScript: a safe rule language for the Auto-TE controller 2026-10-23 18:26:43 +02:00
Frederic Jung
46fe9e4eba
WIP: RouteScript rule language for the Auto-TE controller 2026-10-23 18:20:53 +02:00
Frederic Jung
400d47e3e0
Release 1.9.0 2026-10-23 18:16:12 +02:00
Frederic Jung
f9d89ac815
NOC legend, sortable network table and transit insights
Closes #7
2026-10-23 18:02:06 +02:00
Frederic Jung
f49c60155b
Tests: run the real draw code against a recording canvas 2026-10-23 17:58:17 +02:00
Frederic Jung
494d71793e
Fix map wrap, touch and keyboard input; harden build and release workflow; docs 2026-10-23 17:56:34 +02:00
Frederic Jung
f51c68a8ac
Fix simulation bugs found in review, faster routing, deterministic tests 2026-10-23 17:50:31 +02:00
Frederic Jung
8b64570b8e
Harden saves and imports, escape button arguments, validate actions, fix loan and repair exploits 2026-10-23 17:38:39 +02:00
Frederic Jung
ba6981bda8
Deeper zoom and half speed 2026-10-23 17:13:01 +02:00
Frederic Jung
7587a56b46
Release 1.8.1 2026-10-23 16:33:43 +02:00
Frederic Jung
86de7d79e9
Settings: animations on, off or auto, and sound 2026-10-23 16:26:44 +02:00
Frederic Jung
dd2352e497
Release 1.8.0 2026-10-23 16:06:17 +02:00
Frederic Jung
2cfdaa13e4
Conferences, guided tutorial, Kyiv; changelog 2026-10-23 16:00:48 +02:00
Frederic Jung
0ae6f881c1
Scenarios, weekly challenge, sandbox, traceroute and share card 2026-10-23 15:54:49 +02:00
Frederic Jung
0ca92556dc
Release 1.7.0 2026-10-23 15:44:00 +02:00
Frederic Jung
9d73d6d449
16 more badges 2026-10-23 15:41:53 +02:00
Frederic Jung
bbc9f39c8c
Auto-TE: spill overflow onto alternate paths 2026-10-23 15:29:45 +02:00
Frederic Jung
ea00bd30f1
Release 1.6.0 2026-10-23 15:21:38 +02:00
Frederic Jung
e9c4d1726f
Badges with rarities and a hall of fame; five new goals 2026-10-23 15:16:29 +02:00
Frederic Jung
c2febdc5b1
Hyperscaler and AI cloud deals: AI WANs, multi-site training, ingests, fiber pairs 2026-10-23 15:13:09 +02:00
Frederic Jung
de79fbd0a7
Metro diversity with second sites; more Asia-Pacific and Eastern Europe POPs 2026-10-23 15:07:50 +02:00
Frederic Jung
f93c7de191
Add South America, Taiwan, more India, the UAE and Cape Town; game menu; more incident variety 2026-10-23 14:57:48 +02:00
Frederic Jung
de313bda0b
Release 1.5.0 2026-10-23 14:25:20 +02:00
Claude
706dc92e8f
Add second exchanges in seven more cities, and Barcelona with Catnip-IX
Paella-NIX (Madrid), KleyWrecks (Frankfurt), LO-NAPS (London),
DE-KICKS New York, JINXED-IX (Johannesburg), IX Strayla (Sydney) and
BB-Kicks (Tokyo) join FRIES-IX in XIX. Exchanges can now discount ports
with a fee multiplier. When a city has several, each IX section is
headed with its name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZpEGw99npYwAWtMVXQYgo
2026-10-23 12:23:48 +00:00
Frederic Jung
8649495b50
Slow-booting routers and the Junipurr PacketOinker 2026-10-23 14:23:45 +02:00
Frederic Jung
c3322cc47b
Balance load across equal exits, export/import saves, show full ports on map and NOC
Closes #4, closes #5, closes #6
2026-10-23 14:21:22 +02:00
Claude
001ff7a180
Add FRIES-IX, a second exchange in Amsterdam with free ports
IXs are now keyed separately from cities: a city's main exchange keeps
the city id, extra ones live in XIX under 'city:name'. Existing saves
load unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NZpEGw99npYwAWtMVXQYgo
2026-10-23 12:18:32 +00:00
Frederic Jung
bc32d59728
Release 1.4.0 2026-10-23 14:00:58 +02:00
Frederic Jung
507fe70e25
DE-KICKS: hidden prices, haggling, harmonisation, auto-enrolled add-ons, retention offers 2026-10-23 13:38:22 +02:00
Frederic Jung
22bdaf9f9b
Discourage remote peering: reseller markup, oversubscribed ports, refusals 2026-10-23 12:42:40 +02:00
Frederic Jung
f20f460c81
Let big peers refuse or tear down peering in some cities 2026-10-23 12:39:39 +02:00
613 changed files with 102304 additions and 2865 deletions

View file

@ -0,0 +1,85 @@
---
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

@ -0,0 +1,79 @@
---
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

@ -0,0 +1,102 @@
---
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

@ -0,0 +1,70 @@
---
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

@ -0,0 +1,104 @@
---
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

@ -0,0 +1,109 @@
---
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

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

10
.dockerignore Normal file
View file

@ -0,0 +1,10 @@
# 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 Normal file
View file

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

87
.github/ISSUE_TEMPLATE/1-bug.yml vendored Normal file
View file

@ -0,0 +1,87 @@
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

54
.github/ISSUE_TEMPLATE/2-feature.yml vendored Normal file
View file

@ -0,0 +1,54 @@
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

40
.github/ISSUE_TEMPLATE/3-balance.yml vendored Normal file
View file

@ -0,0 +1,40 @@
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

@ -0,0 +1,42 @@
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

8
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View file

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

39
.github/dependabot.yml vendored Normal file
View file

@ -0,0 +1,39 @@
# 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"

14
.github/pull_request_template.md vendored Normal file
View file

@ -0,0 +1,14 @@
<!-- 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. -->

117
.github/workflows/auto-release.yml vendored Normal file
View file

@ -0,0 +1,117 @@
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,23 +1,142 @@
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:
test: # Splits the test files into parts of about equal time, once, so every part works from the same plan. The times
# 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@v7 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-node@v7 with:
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 }}

35
.github/workflows/claude.yml vendored Normal file
View file

@ -0,0 +1,35 @@
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 }}

187
.github/workflows/docker.yml vendored Normal file
View file

@ -0,0 +1,187 @@
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

43
.github/workflows/perf-comment.yml vendored Normal file
View file

@ -0,0 +1,43 @@
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"

58
.github/workflows/perf.yml vendored Normal file
View file

@ -0,0 +1,58 @@
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,38 +2,63 @@ 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, add a CHANGELOG entry, merge, then publish a GitHub release # package.json and date its CHANGELOG section; auto-release.yml then tags,
# tagged v<version>. # publishes the release and starts this workflow from the tag. Publishing a
# 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:
types: [published] # "released" also fires when a pre-release is promoted to a full release.
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: ${{ github.event_name == 'workflow_dispatch' || !github.event.release.prerelease }} if: ${{ always() && (github.event_name == 'workflow_dispatch' || !github.event.release.prerelease) && (needs.tests.result == 'success' || needs.tests.result == 'skipped') }}
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@v7 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with: with:
ref: ${{ env.TAG }} ref: ${{ env.TAG }}
- uses: actions/setup-node@v7 - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with: with:
node-version: 24 node-version: 24
cache: npm cache: npm
@ -45,28 +70,80 @@ 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
- run: npm test # This release's prices may no longer fit a week already published: --check regenerates every week not over
# 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}" npm run build run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build
- uses: actions/upload-pages-artifact@v5 - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
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@v5 uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1
# 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).

88
.github/workflows/weekly-puzzle.yml vendored Normal file
View file

@ -0,0 +1,88 @@
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,3 +1,4 @@
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 Normal file
View file

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

60
CODE_OF_CONDUCT.md Normal file
View file

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

153
CONTRIBUTING.md Normal file
View file

@ -0,0 +1,153 @@
# 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 Normal file
View file

@ -0,0 +1,21 @@
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 real-ish subsea cable systems, - **Infrastructure:** leased waves on around 40 subsea cable systems modelled on real ones,
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,86 +24,63 @@ 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 with no build step for development: It is a single static page, assembled from the files in `src/` by a small Node script:
```sh ```sh
open site/index.html # or: npm run serve npm ci
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 deployable site to _site/ with version and date stamped in npm run build # writes the site for GitHub Pages 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)
```
## Releasing Come hang out in the **[Series of Tubes Signal group](https://signal.group/#CjQKIJwvEt5fYt1pvw7J2pV664CyUyGJXmAJLV8ia3nUdAD7EhA_FzdxflEzkNmcvDHdVgLQ)**. Share screenshots of your
network, suggest cities, and argue about peering policy with other players.
There are fewer backhoes there than in the real thing.
Only published releases reach [seriesoftub.es](https://seriesoftub.es). Pushes to Signal is for chatting. Bugs, feature requests and anything else that should not get
`main` run CI and nothing else. lost go into a **[GitHub issue](https://github.com/fjaeckel/seriesoftubes/issues/new/choose)**.
1. Bump `version` in `package.json` (semver) and add a `CHANGELOG.md` entry. ## Star history
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`.
The release workflow checks that the tag matches `package.json`, runs the tests, <a href="https://star-history.com/#fjaeckel/seriesoftubes&Date">
builds, deploys to GitHub Pages and pings IndexNow. Pre-releases never deploy. <picture>
To redeploy an existing release, run the workflow manually with its tag. <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=fjaeckel/seriesoftubes&type=Date&theme=dark" />
<img alt="Star history of Series of Tubes" src="https://api.star-history.com/svg?repos=fjaeckel/seriesoftubes&type=Date" />
</picture>
</a>
## Hosting setup ## Contributing
GitHub Pages serves the site with **Source: GitHub Actions** and the custom domain 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.
`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.
```
Once DNS resolves, enable **Enforce HTTPS** in the repository's Pages settings. [MIT](LICENSE) © 2026 Frederic Jung
## 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"]
```

28
docker/Dockerfile Normal file
View file

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

@ -0,0 +1,55 @@
#!/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"

374
docs/ARCHITECTURE.md Normal file
View file

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

238
docs/MCP.md Normal file
View file

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

222
docs/MULTIPLAYER.md Normal file
View file

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

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

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

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

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

View file

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

179
docs/plans/next-session.md Normal file
View file

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

@ -0,0 +1,123 @@
# 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]`.

1433
docs/plans/server-run.md Normal file

File diff suppressed because it is too large Load diff

884
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,17 +1,37 @@
{ {
"name": "seriesoftubes", "name": "seriesoftubes",
"version": "1.3.0", "version": "3.5.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": { "type": "git", "url": "git+https://github.com/fjaeckel/seriesoftubes.git" }, "repository": {
"scripts": { "type": "git",
"test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js", "url": "git+https://github.com/fjaeckel/seriesoftubes.git"
"build": "bash scripts/build.sh", },
"serve": "npm run build && npx --yes serve@14.2.4 _site" "scripts": {
"test": "node scripts/test.js",
"test:timings": "node scripts/test-timings.js",
"build": "node scripts/build.js",
"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": {
"jsdom": "24.1.3" "@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/server": "2.4.0",
"jsdom": "31.0.0",
"playwright-core": "1.65.0",
"ws": "8.22.1"
} }
} }

115
scripts/agent/relay.js Normal file
View file

@ -0,0 +1,115 @@
#!/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 };

73
scripts/build.js Normal file
View file

@ -0,0 +1,73 @@
#!/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}/`);

View file

@ -1,31 +0,0 @@
#!/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/"

88
scripts/dev.js Normal file
View file

@ -0,0 +1,88 @@
#!/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);
});
}

76
scripts/gpu-bench.js Normal file
View file

@ -0,0 +1,76 @@
#!/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.');
});

69
scripts/i18n-add.js Normal file
View file

@ -0,0 +1,69 @@
#!/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`);
}

167
scripts/i18n-check.js Normal file
View file

@ -0,0 +1,167 @@
#!/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);
}

138
scripts/legacy/labels.js Normal file
View file

@ -0,0 +1,138 @@
// 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

@ -0,0 +1,134 @@
#!/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

@ -0,0 +1,187 @@
#!/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

@ -0,0 +1,120 @@
// 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

@ -0,0 +1,52 @@
// 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 };

49
scripts/lib/dict.js Normal file
View file

@ -0,0 +1,49 @@
// 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 };

216
scripts/lib/fuzz-page.js Normal file
View file

@ -0,0 +1,216 @@
// 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

@ -0,0 +1,155 @@
// 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

@ -0,0 +1,5 @@
// 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

@ -0,0 +1,64 @@
// 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 };

283
scripts/lib/mcp-game.js Normal file
View file

@ -0,0 +1,283 @@
// 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

@ -0,0 +1,36 @@
// 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 };
})();

650
scripts/lib/mp-sim-acts.js Normal file
View file

@ -0,0 +1,650 @@
// 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

@ -0,0 +1,271 @@
// 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 };

565
scripts/lib/mp-sim-realm.js Normal file
View file

@ -0,0 +1,565 @@
// 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

@ -0,0 +1,408 @@
// 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 };

448
scripts/lib/mp.js Normal file
View file

@ -0,0 +1,448 @@
// 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 };

136
scripts/lib/page.js Normal file
View file

@ -0,0 +1,136 @@
// 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

@ -0,0 +1,89 @@
// 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

@ -0,0 +1,72 @@
// 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 };

217
scripts/lib/route-fuzz.js Normal file
View file

@ -0,0 +1,217 @@
// 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

@ -0,0 +1,54 @@
// 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

@ -0,0 +1,77 @@
// 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

@ -0,0 +1,18 @@
// 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';
};

240
scripts/mcp.js Normal file
View file

@ -0,0 +1,240 @@
#!/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 };

117
scripts/mp-server.js Normal file
View file

@ -0,0 +1,117 @@
#!/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);

127
scripts/perf-bench.js Normal file
View file

@ -0,0 +1,127 @@
#!/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); });

99
scripts/perf-browser.js Normal file
View file

@ -0,0 +1,99 @@
// 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 };

39
scripts/perf-fixture.js Normal file
View file

@ -0,0 +1,39 @@
#!/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);

19
scripts/perf-stats.js Normal file
View file

@ -0,0 +1,19 @@
// 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,10 +1,12 @@
#!/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]; const version = process.argv[2], story = process.argv.includes('--story');
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}]`));
@ -16,4 +18,15 @@ 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();
} }
} }
process.stdout.write(JSON.stringify(notes)); if (story) {
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));

84
scripts/route-fuzz.js Normal file
View file

@ -0,0 +1,84 @@
#!/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();

58
scripts/test-timings.js Normal file
View file

@ -0,0 +1,58 @@
#!/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)` : ''}`);
});

104
scripts/test.js Normal file
View file

@ -0,0 +1,104 @@
#!/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);

242
scripts/weekly-architect.js Normal file
View file

@ -0,0 +1,242 @@
#!/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));
}
}

413
scripts/weekly-puzzle.js Normal file
View file

@ -0,0 +1,413 @@
#!/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})`);
}
}

298
scripts/weekly-scenario.js Normal file
View file

@ -0,0 +1,298 @@
#!/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: 8.2 KiB

After

Width:  |  Height:  |  Size: 4.9 KiB

Before After
Before After

View file

@ -0,0 +1 @@
{"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

@ -0,0 +1 @@
{"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

@ -0,0 +1 @@
{"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

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

5391
site/i18n/de.js Normal file

File diff suppressed because it is too large Load diff

5389
site/i18n/es.js Normal file

File diff suppressed because it is too large Load diff

5389
site/i18n/fr.js Normal file

File diff suppressed because it is too large Load diff

5389
site/i18n/it.js Normal file

File diff suppressed because it is too large Load diff

5389
site/i18n/pt.js Normal file

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