seriesoftubes/docs/plans/server-run.md
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

134 KiB
Raw Blame History

Server-run simulation for multiplayer builds: design

Where this stands (2026-11-09)

The goal: in a multiplayer build, the session server runs every network's days, and the page only shows them and sends the player's clicks. This is the design of that work, written on 2026-11-07. It is kept as it was, apart from this status, the corrections in the next section, the answers marked where the questions are asked (sections 0, 1 and 14) and the names of the probes and reports it cites. Those probes and reports were working files of the design session and are not kept; their names are left so the reasoning can be followed. Code citations are for main at 69328ce. T1, T2 and the upstream merges up to 3.3.0 have moved many lines since, so find code by name.

Track State Commits
T1, game prerequisites and shared contracts merged d1e127d "Server-run play, part 1: game prerequisites and shared contracts"
T2, the engine merged, on top of the upstream 3.3.0 merge (61e31c5) 065c922 "Server-run play, part 2: the engine", then c5c7ea9 (a restored network plays on exactly as before), 72f31e8 (every call answers, and a crashing load gets its own worker), 3b8c331 (Auto-TE and the chaos monkey's leaving written as a reload makes them), 9597d89 (review fixes), 77f4035 (six actions look up their city among the network's own POPs only), 3e30621 (test timings)
T3, host and protocol not started waits for the user's go
T4, the client not started waits for the user's go
Integration not started waits for the user's go

Nothing of it is switched on yet: no server code calls the engine, src/game/98-server-play/ holds only a comment, and the plain build is unchanged.

The user's answers (2026-11-09) to the four questions of section 14:

  1. A player who joins an old session starts on the session's date: one shared calendar for the whole session. This changes the design and the game (see "What Q1 changes" below).
  2. Single player in a multiplayer build runs on the server by default; "this device" stays an option on the title screen. The CPU and data table of integration step 4 is still owed, as a report rather than as the gate on the default.
  3. An empty session that wakes runs at 1×.
  4. Phase-1 sessions start fresh: nothing is migrated. They keep running as phase 1 in the new build (section 8).

Open with the user (asked on 2026-11-09, not answered yet; next-session.md has the full list of nine):

  • A late joiner meets the session's economy from day one. In a session about five years old (day 1868), hardware costs about 18% more and customers pay about 34% less, and the 180-day beginner grace is long over. Keep it so, or give a grace or extra starting cash counted from the joiner's own start? Answered 2026-11-11: "late joiners get a late joiners bonus and a year of double income per Gbps of FTTP sold/provided". Built (see "What Q1 changes"): a network that begins after day 180 gets a starting-cash top-up as large as the rise in hardware prices and its first 365 days of home broadband income matched (60-features/81-late-joiners.js, gameplay rule F11).
  • Other players' POPs and links drawn on your map (from their cards): part of this work, or later?
  • Sandbox, scenarios, puzzles and the weekly stay on the device in a multiplayer build (section 1). Is that fine, or should sandbox (or all of them) run on the server too?

On hold until the user says go: #97 co-op companies, multiplayer phase 2 and #144 directional traffic.

Also for T3 and T4, from upstream 3.3.0 (merged after this design was written):

  • A slot save of 200 KB or more is compressed through rwGzip(), which starts the full route worker (80-simulation/28-route-worker.js), and frame() warms up the diverse-paths map and the latency floors (diversityWarm(), latWarm(), 99-loop.js). Neither checks srvOn(), so a big server network's mirror page would start the route worker and run the warm-ups. Section 6.3's "the route worker: never started for a server network" holds only once T4 guards them.
  • The day-pace line in Diagnostic info measures only the days the browser runs itself. T4 shows the server's pace there, or hides the line when srvOn().

Corrections from building T2

Where the design below is now wrong, and what replaced it. The code is the authority: the header comments of scripts/lib/mp-sim-engine.js, mp-sim-worker.js and mp-sim-realm.js give the engine's API, replies and error codes exactly as built, and scripts/lib/mp-sim-acts.js the act tables. The message table of 4.2 is an outline now (for example, load takes a list [{nid, env?, begin?, lang, prefs, rng?}], and the replies carry epoch and ms).

A checkpoint needs more than route memory (2.2, 4.1, 4.6, 4.7; row C4 of section 15)

The srvLoad row of 4.1 says that seeding the route memory and then calling compute() equals 15 straight days, and row C4 calls restore fixed that way. That is false. Checkpointed after day 1, 2 or 5, the big scenic network had a different R right after loading (business demand at Ashburn 6426 in straight play, 26 after the restore), and a different S from the next day on (cash, eyeball growth). The first restore test checkpointed only after day 10, where a failure or an event routed again at the end of the day, so it passed by luck. There were three causes:

  1. R after a day cannot be made again from the saved S. It is the R of the day's last routing, made before the end of the day changed S (customers who left or signed, moods, bills, transit history), and routed from the memory of the R before it. Routing the saved S again gives another R, and the next day reads it (sfOf for eyeball growth, the peering share).
  2. The sales desk's memory is outside S. UI.slTried (an offer that did not fit waits a week) was forgotten by a fresh realm, so the desk tried other offers.
  3. Key order. A save and a reload give some keys back in another order (a customer's defaults go last, the intern's weekly tally comes back in its own order), and the intern's week report lists items in that order.

The plain game drifts across a save and a reload too (the page routes a reloaded S with an empty R and keeps no desk memory). That is a property of the game, so the engine carries what is missing, and nothing under src/ changed for it.

What replaced it: the envelope keeps its shape {s, uidN, rt, last, day}, but rt now carries more than R's own route memory (load, l2route, efg):

  • pt, the routing point: the memory the last routing started from, the keys whose value at that routing differs from the save (at), and the keys S did not have then (gone). The realm keeps this for every R that compute() makes. srvLoad rebuilds that S, routes it from that memory and switches back to the loaded S: the same R, byte for byte.
  • sl, the sales desk's tried offers that are still on the table.
  • ord, the live text of each key a reload gives back in another order. On load it is taken only where it equals what sanitize() made of the save, so only the order comes from it.
  • rk, a flag: R is the routing of S as it stands (the game's "skip this routing" memory, UI.rk and UI.rkR), so a reloaded or rolled-back network skips the same routings as one that kept going.

An envelope written before this change (no pt) loads as before: close, not exact. pt.at is routed without passing through sanitize() (only its types are checked), which is acceptable because rt is written by the server and never comes from a client.

The restore test (tests/mp-sim-determinism.test.js) now checkpoints the scenic big network and the same network busy (the intern on every order, the sales desk signing on its own, failures, events, an attack) after days 1, 2, 5 and 10, two of them right after an action and a what-if, and compares S and R as text right after loading and 10 days later (SIM_LONG=1: after every day up to 30). It fails on the old engine, and without any one of the three parts.

Costs: rt is 7–29 KB of gzip, not 7 KB (the whole R would be 375 KB); srvSave takes 7–8 ms instead of 2–2.5; a load routes once more (30–90 ms). A day with its mark costs the same as before.

Who a worker exit counts against (4.2, the "Worker dies" row of section 9, row C7 of section 15)

The design counts an exit against every session on the worker: two in an hour give a session a worker of its own, and when that one exits too, the session is not loaded again until a restart. As built (died() in mp-sim-engine.js):

  • An exit counts against the session the worker was running (the worker names it before each job and step), else against the sessions whose load was under way, else against every session it held. A worker that never started blames nobody.
  • Sessions that only shared the worker lose their realms (the host loads them again), but get no exit against them and keep their place in the pool.
  • Two exits in an hour give a session a worker of its own, at most opts.maxOwn of them (4 by default). Past that cap, or when its own worker exits too, the session is given up: its loads answer GAVE_UP until the engine is made again.
  • A worker that exits before it is ready is started again after a pause that doubles. After 5 such starts in a row, every call answers SIM_DOWN.
  • A realm that has to be built again (after a timeout, a changed built-in or a failed mark) is tried once more without the packed R. If that fails too, the network is dropped: its calls answer NO_REALM, and opts.onLost tells the host.
  • "Every call is answered" holds for the worker's queue and for realm calls, which have their time limits. The engine has no per-call deadline of its own: a call waits at most for the jobs ahead of it, and a load can take up to 30 s per network. A per-call deadline belongs to the host (T3) or a later change.
  • Not fixed: a worker of its own whose session's loads all fail stays alive, idle, until the next unload.

Budgets now over (section 12)

Measured at the end of T2, on the big network and on a small one:

Item Budget Measured
Checkpoint envelope, big ≈ 45 KB gzip ≈ 69 KB gzip (91.8 KB as written, in base64)
Snapshot, big ≤ 60 KB gzip 75.8 KB gzip
Live memory per big realm ≤ 30 MB 31.8 MB (22.1 MB heap, 9.7 MB array buffers)
Small network day ≤ 1 ms 1.1 ms

The envelope and the snapshot grew with rt (above). The checkpoint-write row of section 12 ("12 big networks: one ≈ 45 KB write each per minute while running, ≈ 32 MB an hour") becomes about 69 KB each: about 50 MB an hour counted in gzip bytes, or about 66 MB an hour as written, since base64 adds a third (the design's estimate left that out too). The cost line of 4.6 (43 KB gzip for the big network, route memory 2.6 KB gzip) is out of date the same way, and so is the "≤ 60 KB gzip" snapshot of 5.10.

Within budget: big network day 33.2 ms (≤ 45), day mark 1.07 ms (≤ 2.5), pull 4.8 ms (≤ 15), gate 6.9 ms (≤ 10), an update's S 21.9 KB and R 29.5 KB gzip (≤ 25 and ≤ 35), a small network's update 7.0 KB (≤ 8), load 286 ms (≤ 500, plus 30–90 ms for the extra routing), an action's round trip through the engine 65 ms.

Contract additions (4.2, 5.8, 10, 13 "T2")

The engine has the API of T1's fake engine (createEngine with load, day, act, ask, pull, sub, prefs, greet, save, card, unload, stats), and these additions:

  • ctx.win and WINDOWS. A request's ctx may name the window the page has open, ctx.win = {k, ui?}, from WINDOWS in mp-sim-acts.js (bstd, routing, charter, ops, pie), with the view state only the page holds (the intern's POP opsCity, the pie window's pieTab and pieCity), checked in the realm. Without it, a button sent from inside a window could act on the wrong window. The stand-in elements answer querySelector from what was written into them and have a working classList (closest() stays inert), and the stand-in window is hidden again after each act. T4 sends ctx.win, naming the window the way winOf() in tests/lib/mp-sim-play.js does. WINDOWS is not alphabetical on purpose (entries with a marker come before their class siblings), and T4's copy of the tables (98-server-play/40-acts.js) carries it.
  • TEXT.xpBuild = {via: 256}, so a six-span express fits.
  • NO_REALM means reload. For a network the host believes is loaded, NO_REALM means "load it again from its checkpoint". opts.onLost(code, nids, why) says so as it happens, and engine.has(code, nid) tells whether a network has a realm.
  • Error codes: SIM_DOWN (no worker can start; the host answers 503), GAVE_UP (above), CLOSED (every call after engine.close()), EXIT (a call pending on a worker that exited), ERR (a malformed call).
  • opts.maxOwn (default 4): T3 adds a --sim-max-own flag for it.
  • engine.mem(): each pool worker's heap and RSS. Per-worker heap in stats() was not built.
  • ms on replies: actDone, askDone and pulled carry the worker's time for the call, without the wait behind other calls. That is what section 10's worker-time rate limit counts.
  • Loads. A load that names no network, or one network twice, is refused whole (ERR) and changes nothing. A network without a usable save answers {t:'loaded', nid, err:'no save to load'}, and the others load. A network in a language this server has no dictionary for plays in English, as the page does.
  • Only server networks load. srvLoad refuses a save unless S.mp.sim === 1 and the mode is Normal (no scenario). So T3's import ("Move to the server" in section 8, POST /sessions with import) must stamp the save first, writing mp = {code, pid, asn, seed, preset, color, title, seq: 0, sim: 1} into it, as STAMP in tests/mp-sim-acts.test.js does.
  • Built-ins. The envelope check and the realm both refuse '__proto__', 'constructor' and 'prototype' as values in args, arrays and drafts (free text may still say them). After every realm call the realm's built-ins are checked, and a realm whose built-ins changed answers {srvErr, polluted} and is replaced from the worker's mark, like one that timed out.
  • fx survive a fresh realm. A fresh realm takes over the badges, windows and toasts the old one held (the mark's after a failed call, all of them after a read).
  • One game text. The realm runs the plain page's game, as 4.1 says, while SIM_ID names the multiplayer page. The engine reads the game once at start (a src/ that does not compile makes createEngine throw), and every worker, including one started after an exit, compiles that same text.

Smaller differences: the canonical-state test of section 11 is tests/canonical-state.test.js (T1), not part of server-sim-prereqs.test.js; T2 added tests/act-args-builtins.test.js. The game fixes T2 found are already in, which covers integration step 2: buyTE and the chaos monkey's leaving write S.te and S.monkey as a reload makes them (3b8c331), and six actions take their city only from the network's own POPs (77f4035).

Open contract question: the path window (for T4)

pathOpen (moving a customer to another path, new in upstream 3.3.0) is LOCAL: the page draws the window from its own copy. But the window reads R.l2route (pathNow() and circuitTargets() in 60-features/37-customer-paths.js), which slim R never sends (5.5; SIM_RNEVER in mp-sim-realm.js). On the big network, one of eight scenic circuits would show a short path it is not on, instead of the 14 hops it rides, and different alternatives. Nothing is corrupted, since the server checks pathPin again, but the window misleads. There are two ways out: make pathOpen an ASK, or send a circuit's l2route entries on demand. Not decided yet; it is T4's to settle.

What Q1 (one shared calendar) changes

The design assumes each network keeps its own date (sections 0 and 1, 4.3 "Calendar", p.net.off in 4.6, 4.7, 14 and row F4), and T1 and T2 were built that way. Under the answer:

Built (2026-11-12, dormant until T3 passes a start day): the game's S.day0 and netAge(), every day-0 rule below counted from the network's own start (and the scrubbing offers, the loan offers, the broker's first calls and the "since you started" lines of the supply chain, the bandwidth market and the wave prices), beginState's o.day (lateStart(): the schedules, the home POP and the first IPv4 block stamped with it), srvBegin's begin.day (an integer from 0, else the begin fails), the fake engine's start day, CLOCK.off out of the shape checker, the fixtures (their network begins on day 473) and the contract test, and the late joiner's head start (60-features/81-late-joiners.js). The card's day (mpCard()) stays the calendar date, which phase 1 compares; the market and the calendar stay the session's. Left for T3: the host sends begin.day (the session's day; a session's first network keeps 0, a fresh network after bankruptcy is late again), checks after each tick that every reply's day is d (lost and broken networks excepted), drops off from the live session and p.net, and replaces the line-up of 4.7; "Move to the server" makes a session of one at the save's own day and keeps its day0.

  • Begin needs a start day. srvBegin calls beginState with no day, and the begin message carries none. Both take the session day, passed on as beginState's o.day. The fake engine begins at the given day.
  • CLOCK.off goes, or is pinned to zeros: in tests/lib/mp-sim-shape.js, the fixture generator tests/lib/mp-sim-fixtures.js with tests/fixtures/mp-sim/clock.json, and the check in tests/mp-sim-contract.test.js. So does off in the live session (4.3) and in p.net (4.6). After each tick, the engine or the host checks that every network's S.day is the session day.
  • The line-up of 4.7 lets a network more than 200 days behind run 200 of them and has its off take the rest. With one calendar there is no offset to take it, so T3 needs another rule (for example, every missing day, muted and in chunks, before the clock runs).
  • The game's day-0 rules. Several rules count from day 0, so a network begun on day 500 skips them. A probe showed that migrate() drops the charter choice, the first day runs a failure and an event, the tutorial skips a step, and the grace periods for DDoS, sold-out routes, route leaks and events are already over. The fix:
    • A new field S.day0, the network's start day: a default in newGame() and a repair in sanitize() (int(s.day0,0,s.day,0)), so old saves load. tests/canonical-state.test.js must still pass.
    • beginState(nm,city,o) takes o.day and sets S.day = S.day0 = D, nextFail = D+45, nextEvent = D+40 and the home POP's day.
    • These sites count the network's age, S.day - S.day0, instead of S.day (lines as of 61e31c5): the charter window (60-features/36-specialist.js:72,108, 88-days/10-day-tick.js:30); scrubbing offers after day 60 (88-days/10-day-tick.js:139); the tutorial (60-features/40-tutorial.js:6); DDoS, none before day 40 and capped in size before day 180 (85-incidents/10-incidents-and-ddos.js:80,72); route leaks after day 60 and RPKI after day 30 (85-incidents/20-failures.js:20,31); geopolitical events after day 50 and control-plane events after day 90 (85-incidents/30-events.js:8,12); sold-out routes (70-rules/70-sold-out.js:6); the badges "Tier 1 within three years" and "within two years" (88-days/20-badges.js:40,56); the day counts in the win, lose and baron windows (95-modals/60-help.js:23,24, 60-features/37-cable-broker.js:25); and the card's day (60-features/89-multiplayer.js:54).
  • The economy stays on the session's date (hardware prices, customer prices, waves, the capacity market): one market for everyone, which is the point of the answer. Whether a late joiner gets a grace or extra cash is open with the user (above).

The design as written on 2026-11-07

Status: design, revised after review, 2026-11-07. Code citations are for main at 69328ce (e25f843, the tip now, changed only docs/plans/next-session.md). Written for the implementers of four tracks (section 13). Sources: the four code reports (actions, dayout, engine and client), the context file, the designer's checks (section 2), the two reviews (correctness, items C1–C22, and feasibility, items F1–F20) and the revision probes. Section 15 says what happened to every review item. Paths are under src/game/ unless they start with another folder. "Big network" means tests/fixtures/big-network.json (104 POPs).

0. What this builds, in one page

In a page built with MP_API and served by scripts/mp-server.js (or npm run dev -- --mp), every Normal network of a server session runs on the server. The browser shows it and sends clicks. It never runs a game day and never calls compute() for it. Sessions made by phase 1 keep running as phase 1 (section 8).

User decision (context file) How the design meets it
The server runs the simulation; all players of a session on the same day at the same speed One session clock on the server. Each tick gives every network of the session exactly one day (lockstep, section 4.3), at one speed. Each network keeps its own calendar date, so a friend who joins later starts on day 0 of their own calendar: open question 1. Resolved 2026-11-09: one shared calendar; a friend who joins later starts on the session's date (see "What Q1 changes" at the top).
Less CPU on the client, even alone On a big network the phone stops routing: about 150 ms of CPU per game day leaves the phone's second core (today the route worker does it). The main thread pays about 7 ms to apply an update instead of about 12 ms for a day today, so frame rate barely changes: the gain is battery and heat. Small networks save almost nothing. Mobile data is the price: about 70 MB an hour at 1× on a big network, about half with the data saver. Section 12; a real-Chromium total-CPU measurement at integration decides the single-player default (open question 2). Resolved 2026-11-09: the server is the default; the measurement is still owed, as a report.
Single player in an MP build also runs on the server A new Normal game in an MP build is a session of one by default (section 7).
Old local saves keep working; local play stays possible Saves without S.mp load and play locally exactly as today. The title screen offers "Runs on: this device" (sections 7, 8).
Default 1×; speeds 0.5–8; votes; a pause is a speed Sessions start at 1×, and come back at 1× after nobody was active (open question 3; resolved 2026-11-09: 1×). Votes by majority of active players; alone, your vote decides at once (section 4.5).
Pause at 0 active players Active means a visible page used in the last 10 minutes (section 4.4). No active player, no days.
Absent players' networks keep running While anyone is active, every network of the session ticks, absent ones too, with their standing orders (section 4.3).
Plain build unchanged The client code lives in src/game/98-server-play/, which the build leaves out of a page built without MP_API (section 6). The plain page changes only by T1's refactors, which change no behaviour (tested).
Phase 2 and #97 are later, not blocked All networks of a session live in one worker, so phase 2 can hand data over at the day barrier. Network ids are kept apart from player ids (section 1).

1. Scope

In scope

  • Server engine: realms, worker pool, session clock, presence, votes, checkpoints, restart.
  • Protocol: stream of updates, actions, what-if questions, votes, presence, network settings.
  • Client view mode for server networks, the session of one, "Move to the server", the data saver.

Out of scope (do not build now, do not block)

  • Multiplayer phase 2 (docs/plans/multiplayer-phase2.md): players as carriers in each other's games. The design keeps every network of a session in one worker and runs days at a barrier, so phase 2 can read other networks' published state from the previous barrier as plain JSON.
  • #97 co-op companies. The server keys networks by nid (today nid = the founding player's pid) and stores owners:[pid] per network, so a second owner is a list entry later. No roles, budgets or approvals now.
  • Sandbox, scenarios, the weekly, puzzles and Architect on the server. They stay on the device (mpSanitize already keeps sessions Normal-only, 60-features/89-multiplayer.js:27). Asked on 2026-11-09 whether that is fine or sandbox (or all of them) should run on the server: open with the user.
  • Turning phase-1 sessions into server sessions. They keep running as phase 1 (section 8). Resolved 2026-11-09 (question 4): phase-1 sessions start fresh; nothing is migrated.
  • A render or frame-rate cap for local play. It would help phones, but it changes the plain build (section 12).
  • --sim-max-live, moving a session between workers, placement by measured cost, splitting one session over workers.
  • Starting late joiners on the session's calendar date (open question 1). Resolved 2026-11-09: now in scope. Late joiners start on the session's date (see "What Q1 changes" at the top).
  • Any change to hosting of the public game. The plain build stays a static GitHub Pages site.

What the plain build keeps

  • Everything. MP_API is '' (00-core/20-analytics.js:12), and the new client folder is not in the page at all.
  • No request, no stream, no "Runs on" choice, speed buttons as today (tests/multiplayer.test.js:75-92, extended).
  • npm run perf -- --base-ref origin/main (and --browser, Chromium is installed) on the plain build shows no slower frame loop.

2. Corrections

2.1 To the reports (checked by the designer)

Claim in a report What is true Consequence
Engine: run actions through the agent facade (TUBES.call('act')), which validates arguments A probe ran apiValidate on 234 real button payloads from the crawl: 219 pass, 15 fail. ip4Nat sends v:"8" (a string, from the change handler 96-map/95-clicks.js:6). utilityKit/utilityCaches send modal:true, which the game reads (90-actions/88-utilities.js:6,13). buildLink, orderDf, decomGo, renameGo, traceRun arrive without their draft fields. Probe: argcheck.js The server does not use the facade. It runs the click path (ACT[name](args) with the button's own args, like nocRun, 94-dashboard/90-noc-window.js:32-38) after setting a typed, whitelisted set of UI drafts. Validation is the server's own (section 10). The realm loads the plain page; the agent's tables are used only by tests.
Engine: give the realm the host's setTimeout/setInterval Host timers would run realm code outside the worker's message handling Realm timers are no-ops that count calls. A test audits that no sim path schedules one (section 11).
Engine: real wall time keeps uid() unique across restarts uid() is 'i'+(Date.now()%1e7).toString(36)+(uidN++) (50-state.js:8). The time part repeats every 2.8 hours and uidN restarts at 1 The engine keeps uidN inside each network's checkpoint and sets it when it loads a realm (section 4.6).
Dayout/client: make S.tut client-owned soldOut reads S.tut (70-rules/70-sold-out.js:6); the step checks TUT[i].ok() read only S (60-features/40-tutorial.js:2-9) Split renderCoach into tutAdvance() (state, run by the server) and coachDom() (DOM only). S.tut stays in S and on the server (section 6).
Engine and client disagree: SSE vs WebSocket Both work SSE read through fetch() streaming, plus POST (section 5.1). Ordering is solved by one version counter per network.
Engine: lockstep means a day of all realms in one synchronous message True, but an action then waits for the whole session's day The worker runs each realm's day as its own task; actions for a realm can land between other realms' days, never inside their own realm's day (section 4.3).

Verified by the designer (probe vmtimeout.js): in Node 24, vm.createContext(vm.constants.DONT_CONTEXTIFY) gives each realm its own intrinsics; a precompiled trampoline Script.runInContext(ctx,{timeout}) stops an endless loop with ERR_SCRIPT_EXECUTION_TIMEOUT; the realm still answers afterwards.

2.2 To this design's first version (from the reviews, checked against the code)

First version said What is true Now
Set UI.sel to a sentinel to see whether an act writes it after() → renderAll() → renderPanel() (90-actions/90-action-helpers.js:49, 93-ui/10-dom.js:25, 93-ui/40-hud-and-panels.js:93): a city-like sentinel makes cityPanel throw (93-ui/50-city-panel.js:2), anything else is set to null by linkPanel (93-ui/70-link-panels.js:147) The page sends its real sel/tab/left; the realm reports a key when it differs afterwards; renderPanel and renderLeft are no-ops in the realm (5.8)
Roll back in place after a timeout A vm timeout skips finally (probe vmfinally.js): opsQuiet would leave after, toast, sfx, floater as no-ops (60-features/95-standing-orders.js:122-123), dayStep would leave UI.tick=true (88-days/10-day-tick.js:14) After a timeout the realm is replaced (4.2)
The sanitize gate adopts migrate's copy when it differs Live S is not what migrate makes of it on 90 of 90 days of a mature network (probes gate*.js) T1 makes live S canonical; the gate checks only the keys the act changed, rolls back and never adopts (5.4, 5.8)
Checkpoint + fresh realm + N days = N straight days False with scenic circuits: compute() reads yesterday's R.l2route, R.efg, R.load (80-simulation/30-compute.js:137,152-163) The checkpoint carries that route memory, 7 KB (4.1, 4.6; probe restore-rt.js)
The phone pays 168 ms of dayTick() per day today That is the synchronous path. Players run days through the route worker (99-loop.js:31): 12 ms on the main thread, the routing in the worker Sections 0 and 12 rewritten
ASK = linkCheck, teCheck, teOpt teOptimize runs no routing (80-simulation/20-routescript.js:46-57); teSlop runs up to 5 (:85-91) ASK = linkCheck, teCheck, teSlop; teOpt stays local (5.9)
An ASK leaves S unchanged On the server Math.random reads and advances S.rng (60-features/20-scenarios.js:3-4), and teSlop draws from it (90-actions/30-route-script-and-tools.js:6); teTrial routes with the trial R as yesterday (20-routescript.js:127-129) An ASK restores S, R, S.rng and uidN (5.9)
R.fl is built only while a Peering tab is open The intern and the build standard value PNIs during days (pniVal: 60-features/95-standing-orders.js:271, 96-pop-standard.js:117) Corrected (5.6)
Each update makes a new S object Caches key on the S object: save-failure backoff (91-save.js:13,22-24,54), floaters (96-map/60-draw.js:129) Updates apply in place; only a snapshot makes a new S (6.2)
167 acts are sent 69328ce added ip4Nat64 (90-actions/54-address-space.js:30), ip6Go and ip6Stop (90-actions/55-ipv6-only.js): 170 The list is generated and checked by a test, never counted by hand (5.8)

3. Architecture

 phone / desktop page (MP build)                     node process: scripts/mp-server.js (or dev.js --mp)
 ┌──────────────────────────────┐   GET  stream (SSE over fetch)   ┌──────────────────────────────────────┐
 │ S, R are mirrors              │ ◀─────────────────────────────── │ mp.js        routes, tokens, storage │
 │ ACT wrapper: local or send    │   POST act/ask/vote/here/prefs   │ mp-sim.js    host: clock, presence,  │
 │ renders map, panels, HUD      │ ───────────────────────────────▶ │              votes, streams, pulls,  │
 │ mirror save in its slot       │                                  │              checkpoints             │
 │ (src/game/98-server-play/)    │                                  │   │ worker messages (section 4.2)     │
 └──────────────────────────────┘                                  │ mp-sim-worker.js  (small fixed pool, │
                                                                    │   default 2 workers)                 │
                                                                    │   realm per network: plain game      │
                                                                    │   script + prelude + epilogue        │
                                                                    └──────────────────────────────────────┘

New server files (all under scripts/lib/, no new dependency, package.json unchanged):

File Owner track Role
mp-sim-acts.js T1 (a contract) Tables as plain data: SEND, ASK, VOTE, CONFIRM, SRV_ARM, DRAFTS, TEXT, QUOTE; checkEnvelope(kind, body). Used by the realm epilogue (T2), the host (T3) and the client tests (T4).
mp-sim-realm.js T2 The realm prelude (DOM stand-ins, flags, no-op timers) and the epilogue (the srv… functions inside the realm, the capture rebinds). Plain JS strings, like scripts/lib/mcp-headless.js.
mp-sim-worker.js T2 The worker: compiles the game script once, holds realms, answers messages, replaces broken realms.
mp-sim-engine.js T2 Promise API over the worker pool, used by the host. Every pending promise rejects when its worker exits.
mp-sim.js T3 The host: live sessions, clock, presence, votes, streams, pulls, checkpoints, restart.
mp-sim-clock.js T3 Pure functions for votes, presence and holds (unit-testable).

New client code: the folder src/game/98-server-play/ and src/styles/43-server-play.css (T4), only in MP pages (section 6).

4. Server engine

4.1 The realm (one per network)

Script. assemble({dev:false, mp:false}) (scripts/lib/page.js:55; mp is T1's new option), the largest inline <script> block: the plain page's game, labels as in src/, without the client folder. Compiled once per worker as a vm.Script. The server runs the same game code players get, and never depends on src/agent/ (ADR 0004).

Build id. SIM_ID = the first 12 hex digits of sha256 of assemble({dev:false, mp:true}).html (game and client together, so a change to either is a new id). scripts/build.js stamps it into MP builds next to MP_API (scripts/build.js:53-55; new placeholder /*__SIM_ID__*/'' next to MP_API at 00-core/20-analytics.js:12) and adds simId to _site/version.json. The server computes the same hash from its own src/ at start. When --site's simId differs, see 4.9. dev.js --mp stamps the hash of the page it serves.

Context. vm.createContext(vm.constants.DONT_CONTEXTIFY) (2.4–2.8× faster than a contextified context; engine report §1). The worker refuses to start without vm.constants?.DONT_CONTEXTIFY (Node < 22.8) with a clear message.

Load order in a realm: prelude → dictionary site/i18n/<lang>.js (only when lang≠'en'; English is inside the game script) → game script → epilogue. LANG is read once at load (00-core/10-language.js:7), so a realm has one language: the network's (p.net.lang, 4.6).

Prelude (start from common.js prelude({mode:'record'}), which kept S byte-identical to jsdom over 30 big-network days):

  • self=window=globalThis; __TUBES_WORKER__=1 (so RW_IN: no boot(), no theme, no NOC channel, inline compute; 80-simulation/28-route-worker.js:9,14, 99-loop.js:68); __TUBES_TEST__=true (no charter modal from renderAll, 60-features/36-specialist.js:96; no auto tutorial, 40-tutorial.js:10; no fitHud).
  • document: createElement and getElementById return recording elements that keep innerHTML, hidden, value and answer textContent (tags stripped, entities decoded) and firstElementChild; firstChild/nextSibling are null and child lists empty (or morphKids loops forever, 93-ui/10-dom.js:14-24). Everything else is the inert Proxy of 28-route-worker.js:18.
  • localStorage/sessionStorage: in-memory per realm.
  • setTimeout, setInterval, requestAnimationFrame, queueMicrotask: no-ops returning 0 that count calls.
  • performance.now, Date.now: the host's real ones (tests pin Date.now). Math.random: the realm's own; every server network has S.rng, so the game's seeded wrapper is used (60-features/20-scenarios.js:3-4).
  • BroadcastChannel, WebSocket, EventSource: undefined; fetch returns a promise that never settles; navigator is a plain object with the network's language. The worker installs an unhandledRejection handler that logs with the network id instead of exiting.
  • innerWidth, innerHeight, matchMedia(...).matches: writable, set from the request's viewport (5.8), so isPhone() (93-ui/20-phone.js:2) builds the same window HTML the viewer would.
  • console: a logger that prefixes the network and is rate-limited.

Epilogue (server code that runs in the game's global scope; names srv…, never inside src/game/):

  • Rebinds (top-level function declarations are writable globals; opsQuiet and nocRun do the same, 60-features/95-standing-orders.js:122-123, 94-dashboard/90-noc-window.js:36):
    Global Server version Goes to the client as
    toast(h,k,a,o) logNote as before (the log line is state), then push an fx ["toast",{h,k,a,o,tick}] (tick = UI.tick, 95-modals/10-toasts.js:5)
    sfx(n), haptic(n) push fx ["sfx",n], ["haptic",n]
    floater(x,y,t,c) push fx (at most 40 per update; otherwise FLOATS grows forever on a page that never draws) ["floater",[x,y,t,c]]
    track(n,once) push fx ["track",[n,once]]
    autoPause() returns ALONE (set by the day message); when true sets UI.resumeSpeed to the session's last speed above 0 (the day message's last), records the wish ["pause",1]; when alone the host also pauses the world (4.5)
    openModal(h,c) records {h,c}, sets the stand-in #modal visible the act's ui.modal
    closeModal() original (it clears UI.pending, 95-modals/30-modal-and-names.js:4), then records closed ui.closed
    showWin, showLose, showBaronWin push fx, do not open ["modal","win"|"lose"|"baron"]; the client calls its own builder (95-modals/60-help.js:23-24, 60-features/37-cable-broker.js:25)
    mkStart, mkRun, mkEnd push fx ["mk",{e,c|link,felt|ok}]
    renderPanel, renderLeft no-ops: their output is never shown, and linkPanel would clear a selection it cannot find (93-ui/70-link-panels.js:147); the page heals its own selection (6.2) –
    save() no-op (checkpoints are the engine's; UI.slot is null anyway, 91-save.js:10) –
    badge hall of fame (88-days/20-badges.js:97-108) unchanged (writes the realm's storage) and push fx ["badge",{id,v}]
  • The fx buffer is a ring of 200; when it overflows, the oldest entries go except badge and modal, which are kept (at most 32). A network nobody watches drops fx as they come except those two (5.11).
  • Keeps the other render functions: against the stand-ins renderAll() costs 0.3 ms (engine report, after.js). No render code draws random numbers (only the title's asnSuggest, 95-modals/40-title.js:15), so the no-ops do not change S.rng; the determinism test proves S is the same as in jsdom with real renders.
  • Sets UI.clockLocked=true, UI.started=true, UI.speed = the session speed before each day.
  • Defines the realm API (one trampoline Script per name, input in globalThis.__in as a JSON string, output a JSON string; the worker never touches realm objects):
    Function Does
    srvLoad({save,uidN,rt,prefs}) S=migrate(JSON.parse(save)); give S.rng if missing (crypto value from the host); uidN=…; PREFS=…; R=emptyR() seeded with the route memory rt as rwServe seeds it (80-simulation/28-route-worker.js:86), then compute(); returns {day,lost}. Probe restore-rt.js (big fixture, its 8 L2 customers set to scenic): seed + compute() equals 15 straight days; unseeded, or seeded without compute(), it does not
    srvBegin({name,home,preset,asn,mp,tut}) beginState(...) (T1), S.mp.sim=1, S.tut=tut?0:null, compute()
    srvMark({keys,day}) the realm's restore point: keeps JSON.stringify(S) (0.9 ms big; with keys, for actions, each top-level key's JSON instead, ≤ 3 ms, whose join is the same string), uidN, S.rng, the R object itself (no copy) and UI.sel/tab/left/confirm in realm globals; with day, also the route memory (srvRt()). It returns the string, uidN and any route memory, which the worker keeps too
    srvRestore({day}) back to the mark, in place. S is parsed back from the string only when it differs from it, so the S object stays on every normal path. R becomes the marked R object with R.ddos[].attack looked up again by id (ddosAll(S,false), as rwUnpack does, 28-route-worker.js:81; attacks are R's only references into S, which is why rwPack turns only them into ids, :77). After a failed day (day), R is instead rebuilt from the day mark's route memory and compute(), the load path that restore-rt.js checked, because a half-run day may have changed the old R. Then uidN, S.rng, the UI keys. A parse resets UI.slTried (keyed on the S object, 60-features/39-sales-auto.js:33): failure paths only
    srvRt({mark}) the route memory of the current R (with mark, of the marked one): {load:R.load, l2route:R.l2route, efg} with efg cut to the scenic keys l2:<id> and its Maps written as arrays. Big network with 8 scenic circuits: 4.0 + 1.0 + 1.9 KB, 2.6 KB gzip (all of rwEfgOut(R.efg) would be 168 KB; probe rt-size.js, which also shows the cut keeps restores exact)
    srvDay({speed,alone,last,mute}) dayTick() (88-days/10-day-tick.js:22), then tutAdvance(); mute drops the day's fx (catch-up days); returns {day,lost,pause}
    srvAct(msg) the action pipeline (5.8)
    srvAsk(msg) the what-if pipeline (5.9)
    srvPull({snap,views}) the only place a network's version advances (5.10): S key diff since the last pull, packed R if it changed, fx since the last pull, acts; with snap, a full snapshot at the same version; with views, the flow records for those views (5.6)
    srvSave() {txt:JSON.stringify(packSave(S)),uidN,rt:srvRt(),day,lost}
    srvCard() mpCard() (60-features/89-multiplayer.js:46)
    srvGreet() bootNotes() (T1: the one-shots of 99-loop.js:57-58), so their toasts become fx
    srvPrefs({prefs}) sets PREFS (the three that change S: pauseFurious, warnUnhappy, pauseIncident; 96-map/30-settings.js:12-14)

4.2 The worker and its messages

  • Pool: --sim-workers workers (default 2, at least 1; not one per core: this host has 32). A live session goes to the worker with the fewest realms, and all its realms stay in that worker (phase 2 needs this).
  • resourceLimits.maxOldGenerationSizeMb per worker: --sim-heap-mb, default 1536.
  • The worker handles one message at a time. A session's day is one task per realm (setImmediate between realms), so an action for realm X can run between realm Y's and realm Z's days, never inside X's day.
  • Inside a session day: the list of realms is fixed when the day starts. load, begin and unload for that session wait until its dayDone. An act or ask for a realm that is loading or catching up (4.7) waits until it is ready.
  • Every realm call goes through script.runInContext(ctx,{timeout}): 2000 ms for a day, 1000 ms for an action, 3000 ms for an ask, 1000 ms for a pull or a save.
  • A call that throws has run its finally blocks: srvRestore() (srvRestore({day:true}) for a day) puts the realm back in place.
  • A call that times out has not (probe vmfinally.js), so the realm is never used for play again. The worker builds a fresh realm with srvLoad from the mark's string and uidN (which the worker holds) and the mark's route memory (≈ 0.3–0.5 s big), and drops the old one. A day mark holds its route memory; for an action or ask the worker asks the old realm with srvRt({mark:true}) (it still answers, vmtimeout.js), and if it no longer does, takes the route memory of the last day mark: nothing applied is lost, and only scenic paths may differ for a day.
  • The worker exits (out of memory, crash): the engine rejects every pending call of that worker; the host treats its sessions as unloaded and reloads them on the next tick (4.7). A session that was in a worker that exited twice within an hour gets a worker of its own; if that one exits too, the session is not reloaded until the server restarts, its players see the server-error window (6.4) and the log says why.
Host → worker Worker → host Notes
{t:'load', code, nid, save, uidN, rt, lang, prefs, rng?} {t:'loaded', nid, day, lost, err?} rng only when the save has none; err marks the network broken (4.7)
{t:'begin', code, nid, begin:{name,home,preset,asn,mp,tut}, lang, prefs} {t:'loaded', …} then a saved New network for a new or joining player
{t:'day', code, d, speed, last, alone:[nid], nets:[nid], mute?} {t:'dayDone', code, d, nets:{[nid]:{day,lost,pause?,err?,retried?,ms}}} nets = admitted, loaded, not broken, not lost; each realm is marked before its day (4.3)
{t:'act', code, nid, msg} {t:'actDone', nid, rid, outcome, why?, v, upd} upd: the update made right after the act, version v (5.10)
{t:'ask', code, nid, msg} {t:'askDone', nid, rid, modal?, ui?, err?} S, R, S.rng, uidN restored (5.9)
{t:'pull', code, nid, snap?, views?} {t:'pulled', nid, v, upd?, snap?, subs?} strings, ready to write
{t:'sub', code, nid, views} {t:'subbed', nid, v, subs} a view changed (5.6)
{t:'save', code, nid} {t:'saved', nid, txt, uidN, rt, day, lost} host wraps (4.6), gzips and writes
{t:'card', code, nid} {t:'card', nid, card} host runs cleanCard (scripts/lib/mp.js:67)
{t:'prefs', code, nid, prefs} – a language change is an unload and load instead
{t:'greet', code, nid} {t:'pulled', …}
{t:'unload', code, nid?} {t:'unloaded', …} after a save
(any failure) {t:'err', code, nid, rid?, what, msg} timeout, throw, out of memory

4.3 The session clock and the lockstep day

The clock, presence and votes live on the host's main thread (they must answer at once while a worker is busy).

live session (in a Map in mp-sim.js, never on the session object that persist() writes, mp.js:199-204):
  { code, worker, nets: Map(nid → {owners, epoch, loaded, broken, off, last, lang, prefs, lastCp, dirty}),
    speed and last (persisted as s.sim.speed, s.sim.last), votes: Map(pid → {speed, at}),
    streams: Map(dev → {pid, nid, res, heard, hidden, hiddenAt, idle, hold, usedAt, view, saver, rAt}),
    lostAt: Map(pid → {ms, hold}), day (s.sim.day), nextAt, inFlight, eff, runMs }

every 50 ms, for each live session:
  run = active players ≥ 1 and speed > 0 and not (every active player holds)
        and every admitted network is loaded or broken
  if run and not inFlight and now ≥ nextAt:
     inFlight = true
     try:   dayDone = await engine.day(code, {d: day+1, speed, last, alone, nets})   // nets fixed here
     catch: inFlight = false; reload the session (4.7); continue          // the worker exited
     day++ ; persist s.sim.day lazily ; for each net that ran: net.last = day
     if any net asked for a pause and its owner is alone: speed = 0, clock event
     pull every net with a visible stream whose last pull is ≥ 1 s ago (5.11)
     every 60 s of running: checkpoint every net (4.6); every 5 days: cards
     nextAt = max(now, nextAt + DAY_MS / speed)     // DAY_MS = 2500 (10-catalog/10-economy.js:4)
     eff = measured days per DAY_MS over the last 10 days ; inFlight = false

The host keeps no version counter: versions belong to the realm's pulls (5.10).

  • The clock waits for the day, never the other way round, as runClock does (99-loop.js:26-33). A session that cannot keep its speed plays slower and reports eff (the HUD shows "8× · running at 5×").
  • Lockstep: every admitted, loaded, not-broken, not-bankrupt network gets day d in tick d. Order inside a tick: sorted nid. Realms are independent today, so order does not matter (a test proves it).
  • Calendar: each network keeps its own S.day. off = S.day − sim.day is fixed for a network from the tick it joins. Networks started together share the date (open question 1).
  • A failed day. The worker marks each realm before its day (srvMark({day:true}), with the route memory; kept until the next mark). When a day throws or times out, the realm goes back to the mark (srvRestore({day:true}) in place after a throw, a fresh realm after a timeout, 4.2), the failed attempt's fx are dropped, and the day runs once more. Actions already applied are in the mark, so nothing the player was told is undone. A failure that is not deterministic (a GC pause on a loaded host) passes on the retry. If the retry fails too, the network is marked broken at its pre-day state: it stops ticking, its owners see "Your network hit a server error" with Export and "Play the copy on this device", the log has the stack, and the others play on.
  • Bankrupt: S.lost stops days by itself (10-day-tick.js:26, before S.day++). A lost network is left out of every day message and every line-up (4.7). It stays in the roster as bankrupt.

4.4 Presence, idle and holds

Term Rule
Stream One open GET …/stream of one page load (dev id per page load).
Heard A visible page sends POST /here at least every 20 s, and at once on any change. The server closes a visible stream it has not heard for 45 s (a vanished client is otherwise only noticed when a write fails, which can take minutes without a proxy, as on the LAN). Hidden streams are exempt: they follow the next row.
Hidden The page sends /here {hidden:true} at once on visibilitychange, with fetch(…,{keepalive:true}) as mpPush does on pagehide (89-multiplayer.js:120-123). A hidden stream gets no updates and is not active. The server closes it 60 s after that message: nothing waits for a suspended page to run code (iOS and Chrome suspend hidden pages). A page that shows again within 60 s gets a snapshot on its stream.
Idle A visible page with no input (pointer, key, wheel, touch) for 10 minutes sends /here {idle:true}; its first input sends {idle:false} at once. --sim-idle-min (default 10, 0 = off).
Active stream Open, heard, visible, not idle.
Active player Has an active stream, or lost one unexpectedly (closed without away) less than 15 s ago (a phone switching networks). During those 15 s the player keeps the hold state that stream had.
Holds A stream holds while its page shows a window ($('modal').hidden false), sent as /here {hold} debounced 300 ms. A player holds when their most recently used active stream holds, so a forgotten desktop tab does not override the phone in your hand.
  • The world runs only while at least one player is active, and pauses while every active player holds.
  • Alone: an open window, a hidden page, or 10 minutes without input stop the days. The first two are today's single player (99-loop.js:5,17). The third is new: a visible desktop tab left alone overnight would otherwise run 11,520 days at 1× for every network of the session.
  • With others: your window, hidden page or idle tab stops nobody, and hidden or idle players do not count toward votes.
  • Phase 1's seen (mp.js:267) stays for the roster.

4.5 Votes

  • Speeds: [0, 0.5, 1, 2, 4, 8]; 0 is pause. New sessions start at 1×. s.sim.last keeps the last speed above 0.
  • A session that wakes up from 0 active players comes back at 1× (open question 3).
  • POST /vote {speed, sim} sets the player's vote (null withdraws it). A vote lasts 120 s, or until the world's speed changes; then all votes clear.
  • The tally runs on every vote and on every presence change. The world takes speed X as soon as more than half of the active players have a vote for X younger than 120 s (need = floor(active/2)+1). Alone, need is 1: your vote decides at once. A change caused by someone leaving is announced like any other (clock event why:'vote', a short toast "Speed: 4× (votes)").
  • Auto-pause (pauseFurious, pauseIncident; 88-days/10-day-tick.js:80, 85-incidents/20-failures.js:130):
    • Alone: autoPause() returns true in the realm and sets UI.resumeSpeed to s.sim.last, so the toast's Resume button (resumeAct, 96-map/30-settings.js:24) votes for the speed the world ran at. The host sets the speed to 0 after that day.
    • With others: autoPause() returns false (the toast has no "paused"), and the fx pause makes the page show a small toast with a "Vote pause" button.
  • --sim-max-speed (default 8) caps the speeds a server accepts, for small hosts.

The clock event (5.3) carries everything the HUD needs, the votes per speed and need included, so a pending vote can say "waiting for 1 more".

4.6 Persistence

  • Files: phase 1's layout (mp.js:6-9,167-168): DIR/<CODE>.json per session, DIR/<CODE>.<pid>.save per network, written by writeAtomic in the session's queue (mp.js:185-197).
  • The checkpoint is one envelope in one atomic write: the .save file of a server network holds sim: + base64 of gzip of {"s":<save text>,"uidN":n,"rt":{…},"last":d,"day":n}. s is phase 1's save text, JSON.stringify(packSave(S)); rt is the route memory (4.1). readSave recognises the prefix; GET /save (mp.js:371-376) hands out s, which loads on any device. uidN, the route memory and the save can never disagree (they were separate writes in the first version).
  • Session file additions (small, persisted): s.sim = {v:1, day, speed, last, created}; per player p.net = {off, last, lang, prefs:{pauseFurious,warnUnhappy,pauseIncident}, owners:[pid], broken?}. The server is the writer of p.sv and bumps seq per checkpoint.
  • When a network is checkpointed: every 60 s of running (a cadence of 10 session days would be every 3 s at 8×, about 600 MB of writes an hour for 12 big networks); at most 5 s after an action that changed it; when the world pauses (a pause vote, or nobody active); before unload; on SIGTERM.
  • Language and the three S-changing preferences belong to the network (p.net.lang, p.net.prefs). They are set at creation from the creating device and change only by POST /prefs, which the page sends when the owner changes one of them in the settings. Opening a stream never changes them: with two devices set differently, warnUnhappy (it writes b.warn60, 88-days/10-day-tick.js:82) and pauseFurious (:80) would otherwise depend on which device spoke last, and a language difference would reload the realm on every reconnect. A language change checkpoints and reloads the realm (≈ 0.4 s; the same future, thanks to the route memory). Server toasts arrive in the network's language.
  • Unload: a session with no active player for 10 minutes is checkpointed and its realms dropped. Never while someone is active, even behind a window. An empty worker is stopped (keep one warm).
  • Shutdown: SIGTERM checkpoints every live network first, then mp.flush(). The 3 s cap of mp-server.js:115 grows to 3 s + 50 ms × live networks.
  • Cost: packSave + stringify 1.8 ms, gzip 2.0 ms, 257 KB / 43 KB gz for the big network (wire.js); route memory 7 KB / 2.6 KB gz.

4.7 Loading a session, line-up, restart

  • After a restart nobody is connected, so every session is paused. Nothing runs until someone attaches.
  • Loading a session (the first attach after a restart, after a worker exit, after an unload): every network of the session is loaded from its envelope (the attaching player's first), in its p.net.lang. A network whose save does not load (a migrate that throws) is marked broken; its owners see the server-error window; it never holds up the others.
  • Line-up. The session day D becomes the largest last among the session's networks, read from the envelopes (the s.sim.day in memory may have been up to 60 s ahead and is set back to D). A network whose last is below D, and that is neither lost nor broken, runs D − last plain days with fx muted, at most 200 of them (≈ 8 s for a big network). A network further behind runs 200 and its off takes the rest: its calendar lags a little, and nothing depends on it in this phase. Lost and broken networks never run and never count, so the line-up always ends.
  • Then the clock may run. Each realm load has a new epoch, so every page takes a snapshot; when days ran again, its since says so ("The server restarted: the last 12 days ran again").
  • What a crash loses: at most 60 s of world time, which runs again with the same dice and the same route memory (so the same days again, unless actions in it were lost), and the actions of the last 5 s.
  • Deterministic restore is a test, with scenic circuits (section 11). The engine's first restore probe passed only because the big fixture has no scenic customer.

4.8 Cards and roster

  • Cards are computed on the server by mpCard() in the realm, cleaned by cleanCard and applied with applyCard (mp.js:67,278). They are now verified. PUT /card on a server session answers 200 with the roster and ignores the card.
  • Roster changes (join, leave, cards, presence, votes) go to every stream of the session as a roster event, at most every 2 s. The page's 5 s roster poll (95-modals/48-multiplayer.js:57) stops while a stream is open.

4.9 Operations

  • Log: one line a minute per live session: code, networks, speed and eff, ms per day (median and max), pull ms, bytes sent that minute, worker RSS.
  • Deployment: the realm compiles from src/ and the source dictionaries site/i18n/*.js (the built ones use compiled short ids, scripts/lib/compile-labels.js:1-9), so the server runs from a checkout, and "pull, then build" is one step in docs/MULTIPLAYER.md. When --site's version.json has another simId than the server's own, phase 1 keeps serving, server sessions answer 503 {sim:'stale'} (the page says "The server is being updated" and offers Export), and the log prints the exact command (MP_API=/api/mp npm run build).
  • --sim off: no engine. Phase 1 works as today; server sessions answer 503 {sim:'off'}; a new game in the page falls back to "this device". Useful during playtests.
  • Flags: --sim-workers (2), --sim-heap-mb (1536), --sim-max-speed (8), --sim-idle-min (10), --sim off. Deferred: --sim-max-live and its 503 busy, placement by measured cost, --sim-gzip.

5. Protocol

5.1 Transport

Pick: Server-Sent Events read with fetch() streaming, plus POST.

Constraint SSE over fetch + POST WebSocket
mp.js and mp-server.js have no dependencies (mp.js:2, mp-server.js:4) node:http only ws would become a runtime dependency (it is a devDependency, package.json:35)
The owner's reverse proxy config Works unchanged: the server sends X-Accel-Buffering: no; Caddy flushes event streams by itself nginx needs Upgrade/Connection headers added (docs/MULTIPLAYER.md:88-104)
Token never in a URL fetch sends Authorization: Bearer <pid>.<token> as phase 1 does (89-multiplayer.js:39) needs an in-band first message
Service worker Requests with authorization bypass it (site/sw.js:19) bypasses it
Traffic shape ~99% server → page either
  • Response headers: content-type: text/event-stream; charset=utf-8, cache-control: no-store, x-accel-buffering: no, x-content-type-options: nosniff, and content-encoding: gzip when the request accepts it (one gzip stream per response, flushed with Z_SYNC_FLUSH after every event).
  • A comment line : hb every 15 s (proxies cut idle streams at 60 s).
  • Events: event: <type>, id: <epoch>.<v>, data: <one JSON line>. The page's parser is ~15 lines.
  • Docs: docs/MULTIPLAYER.md gets a note that proxy_read_timeout above 30 s is needed (the default 60 s is fine).

5.2 Routes

All under MP_API (default /api/mp), JSON, Authorization: Bearer <pid>.<token> except create and join. Existing routes stay (mp.js:315-426); the route regex ^\/sessions\/([^/]{1,32})(\/[a-z]+)?$ (mp.js:333) already admits the new ones. "Server session" = a session with s.sim; the others are phase-1 sessions and keep phase 1's routes.

Method, path Body / query Answer
POST /sessions {net:{name,home}, preset, title?, solo?, asn?, lang, tut, prefs, import?:{data}} 201 {code,pid,token,seed,asn,preset,color,title,sim:1}; the server has built the network (srvBegin, or srvLoad of import); 503 {sim:'off'|'stale'}
POST /sessions/:code/join {net:{name,home}, lang, tut, prefs} server session: 200 {…, sim:1}, the server built the network; phase-1 session: 200 as today (no sim), and the page joins the phase-1 way
GET /sessions/:code/stream ?dev=<id>&sim=<SIM_ID>&saver=0|1 200 event stream; 409 {old:true} (SIM_ID differs); 409 {phase1:true}; 401/404 gone; 503 {sim}
POST /sessions/:code/act section 5.8, with sim 200 {rid, outcome, v, why?}; 400 {error} (envelope); 409 {old}; 409 {stopped} (bankrupt or broken); 429
POST /sessions/:code/ask section 5.9, with sim 200 {rid, modal:{h,c}, ui?}; 400, 409 {old}, 429
POST /sessions/:code/vote {speed, sim} 200 clock; 409 {old}
POST /sessions/:code/here {dev, hidden?, hold?, idle?, away?, view?:{link?,peer?}} (the viewport travels with each act and ask) 200 {} (send() always writes a JSON body, mp.js:152-157)
POST /sessions/:code/prefs {prefs?:{pauseFurious,warnUnhappy,pauseIncident}, lang?} 200 {}; the network's settings (4.6)
PUT /sessions/:code/save as phase 1 phase-1 sessions only; a server session answers 409 {sim:true}
GET /sessions/:code/save – the last checkpoint's save text (the envelope's s)
DELETE /sessions/:code/me – as phase 1; also unloads the network, and drops a session whose last player left

5.3 Stream events

event: snap      (on open, when a hidden page shows again, after a realm reload)
data: {"t":"snap","epoch":"k3f9","v":412,"now":1731000000000,"S":{…live S…},"r":{…slim R…},
       "clock":{…},"roster":{…},"since":{"days":37,"again":0},"keep":[["badge",{…}],["modal","win"]]}

event: upd       (state changed: days, actions; the same bytes for every stream of the network)
data: {"t":"upd","from":411,"v":412,"now":…,"day":431,
       "s":{"day":431,"cash":1234.5,…},"del":["capDeal"],"r":{…slim R…}?,"fx":[["toast",{…}],["sfx","coin"]]?,
       "acts":[{"rid":"…","dev":"…","ui":{"sel":{…}|null,"tab":"…","left":"…","confirm":null,"closed":1,
                                          "modal":{"h":"…","c":"…"}}}]?}

event: sub       (this stream's flow records: after its view changed, or after an update with a new r)
data: {"t":"sub","v":412,"ef":{…},"egd":{…},"pf":{…}}

event: clock
data: {"t":"clock","speed":1,"eff":1,"run":true,"why":null|"empty"|"hold"|"slow"|"loading"|"vote",
       "votes":{"<pid>":4},"tally":{"4":1},"need":2,"active":["<pid>",…],"hold":["<pid>"],"idle":["<pid>"],
       "day":518,"last":1,"max":8}

event: roster    (phase 1's roster shape, mp.js:271-275, plus "on":["<pid>"])
event: bye       {"t":"bye","why":"gone"|"old"|"moved"|"slow"|"shutdown"}
  • fx kinds: toast, sfx, haptic, floater, track, pause, modal (win/lose/baron), badge, mk, told (a day-one-shot already toasted). Unknown kinds are ignored by the page.
  • acts lists every action the update contains (two quick taps can land in one update). A page applies the ui of the entries whose dev is its own.
  • keep carries the badge and modal fx that came while nobody watched the network (at most 32).

5.4 S on the wire

  • Live S, not the save shape. packSave drops customer defaults that only sanitize puts back (91-save.js:46-51); deltas skip sanitize, so they must be live S.
  • Unit: top-level keys. srvPull stringifies each top-level key and compares with the string it sent last (cost ~3 ms on the big network). Changed keys go in s as raw JSON, removed keys in del. A day changes about 12 of 86 keys: 94 KB / 21 KB gzip on the big network (dayout report §C2). Finer patches save only 3–7 KB gzip.
  • Canonical live S (T1). The snapshot's migrate() on the page and the action gate (5.8) both need live S to be what migrate makes of its save. Today it is not: over 90 days of the big fixture, packSave(migrate(copy)) differs from live S on every day (probes gate.js, gate2.js, gate3.js): stats.ddT gets its full shape (80-simulation/50-sanitize.js:14,89; live code creates it bit by bit, 85-incidents/10-incidents-and-ddos.js:99, 90-actions/80-security-and-china.js:12), ev gets sac/sla and loses ddos:null, and ddosStarts is trimmed to 7 days at once (50-sanitize.js:103) where live code trims at the next attack (85-incidents/10-incidents-and-ddos.js:82). migrate itself is idempotent. T1 makes the live code write those shapes where it writes them, without changing play, and a test proves packSave(migrate(packSave(S))) equals packSave(S) after 365 seeded days with every feature on.
  • Snapshot: the full live S (271 KB / 42 KB gzip big). The page runs migrate() on it once (it never trusts state it did not check, CLAUDE.md); with canonical S that is a no-op (tested).
  • Server-only memory stays on the server: UI.slTried (keyed on the S object, 60-features/39-sales-auto.js:33, one reason the realm keeps its S object on every normal path), OPTUP_NO, the intern's UI (dayout report §A2).

5.5 Slim R

srvPull packs R only when R is a new object since the last pull (an action that re-routed, or a day):

  • Start from rwPack(R).o (28-route-worker.js:77: ddos attacks by id, no ports).
  • Drop: ef, fl, efp, flc, efg, egDesc, l2route, bbF, peered, cityBlocked (compute inputs or internals, or sent on demand; dayout report §B1).
  • tNet: keep the top 4 networks per transit port (what the city panel asks, 93-ui/50-city-panel.js:50 calls transitTop([t.id],4)); add tTop8 = transitTop(all transit ids, 8) computed on the server (the dashboard, 94-dashboard/60-dashboard.js:26).
  • Numbers that are not integers: 6 significant digits. Thresholds the page checks (sf<0.95, HOT=0.9) stay within ~5e-7.
  • Size on the big network: about 90 KB / 30 KB gzip. Small network (4 POPs): 8.7 KB / 2.8 KB gzip.
  • The packed text is cached per R object, so all streams of a network cost one pack.
  • If the integration measurement shows R dominates the data, usePni (28 KB), useCache (24 KB), netEg (24 KB) and demTo (9.5 KB) move behind the view subscription and the server ships a computed hot list instead (hotPorts reads usePni and useCache; dayout §B). Not built unless measured.

5.6 Flow tables on demand

Each stream tells the server what its page shows with POST /here {view}. The host keeps a view per stream, asks the realm for the records of the union of its streams' views, and sends each stream a sub event with its own records only: at once when its view changes, and after every update that carried a new r.

Page shows view Server sends Size (big) Page reads it at
A selected link (panel and map highlight) {link:id} ef:{[edgeKey]:R.ef[edgeKey]} plus egd: the R.egDesc entries its eg keys name ≤ 7 KB R.ef[edgeKey(l)], unchanged (93-ui/70-link-panels.js:59, 96-map/60-draw.js:99)
A city's Peering tab {peer:city} pf:{[city]:pniFlows(city)} ≤ 5.3 KB, avg 1.4 KB the rebound pniFlows(c) returns R.pf[c] (6.1)
  • The page keeps its records by key in SRV.sub and puts them into every R it builds. A record is replaced only when a sub brings a new one, so an update with a new r and no sub yet keeps the old records ("No traffic right now", 70-link-panels.js:61, does not flash). A newly selected link shows "No traffic right now" for one round trip (accepted, so linkPanel needs no edit).
  • R.fl (40,560 flows on the big network) is built during days on the server anyway when the intern or the build standard values PNIs (pniVal: 60-features/95-standing-orders.js:271, 96-pop-standard.js:117); a Peering view adds only its pack.

5.7 What the page does with fx

fx The page
toast toastPop(h,k,a,tick) (T1 split of toast, 95-modals/10-toasts.js:2-10): pops it with its own Quiet setting (quietOn()) and box size; never writes S.log (the server's S.log already has it)
sfx, haptic plays unless muted
floater only if animOn() and the map shows; made after the update is in place. Updates apply in place (6.2), so floaters live their full 1.6 s (96-map/60-draw.js:129 drops floaters of another S object)
track track(n,once) (does nothing without ANALYTICS.host)
pause with others active: a toast with "Vote pause" (vote 0)
modal showWin(), showLose() (and drops the mirror slot as it does today), showBaronWin(); queued while another window is open
badge updates sot-badges on the device. Known limit: the badge toast was worded on the server, whose hall of fame (88-days/20-badges.js:97-106) is empty, so it says "unlocked" where this device would say "upgraded"
mk the chaos-monkey animation (96-map/87-chaos-monkey.js:9-18)

A snapshot whose S is lost shows the lose window when this device has not shown it for this network yet. The lose fx can be gone (a restart, a network nobody watched), and save() refuses lost games (91-save.js:10), so without this the device would keep a stale mirror and never say why the map froze.

5.8 Actions

Request POST …/act:

{ "rid":"a1b2c3d4e5", "dev":"9f8e7d6c", "sim":"3f2a9c01be47",
  "act":"buildLink", "args":{"tier":2},                          // the button's own data-args, unchanged
  "ui":{"pending":{"a":"fra","b":"par"},"route":"","via":"","cnPrem":false},   // only DRAFTS[act]
  "confirmed":true?,                                              // only for CONFIRM acts
  "ctx":{"sel":{"type":"link","id":"l7"}|null,"tab":"up","left":"noc",
         "modal":true,"w":390,"h":844,"coarse":true} }

Which acts are sent (scripts/lib/mp-sim-acts.js, T1, derived from the actions report, §7, and checked by a test):

  • SEND: the agent's API_CMD minus the 15 pz* and minus teCheck, traceRun, closeModal, plus connCancel, pieRename, tutSkip. 167 at 032470f, 170 at 69328ce. The test generates the list; nobody counts it by hand.
  • ASK (3): linkCheck, teCheck, teSlop (what-ifs that run compute(); 5.9). teOpt is local.
  • VOTE (3): speed, phonePlay, phoneSpeed.
  • QUOTE: acts that charge a total the player saw in a window but plan at click time. With others active the world keeps running under open windows (alone it never does, 99-loop.js:17), so the plan can change. They take the shown total as q and refuse a different one, as utilityKit already does (90-actions/88-utilities.js:6-8). pniAll (90-actions/40-sites-peering-caches.js:23) gets this in T1; T1 checks the other window acts that plan at click time and lists them.
  • Local: everything else (views, drafts, settings, slots, session acts, puzzles, teOpt). The page keeps an explicit SRV_LOCAL set; anything not in it is sent (a forgotten entry costs a round trip and a refusal, never a desync).
  • A new ACT (the standing-orders track adds some) fails the "every ACT classified" test with: "ACT. is not classified: add it to SEND, ASK, VOTE or LOCAL in scripts/lib/mp-sim-acts.js". Until then the server refuses it.

CONFIRM table (the first click arms locally; only the second is sent, with confirmed:true):

Kind Acts Server does
arg cancelTransit, cancelIx, cancelPni ACT[a]({...args, ok:1}) (90-actions/20-pops-transit-ix.js:11,14)
preset rmLink, cancelVxc, rmSite, dkOptOut, dropBiz, salesFire, ip4Sell, repayLoan, rmScrub, teleRm, opsFire, connCancel UI.confirm = SRV_ARM[a](args), the key the first click writes, computed from the args (for example 90-actions/60-links.js:6,42, 40-sites-peering-caches.js:3, 94-dashboard/90-noc-window.js:37), then once. Running the act twice, as the first version did, repeats every refusal that comes before arming (two "fiber busy" toasts, 60-links.js:6; also teleRm, dropBiz, ip4Sell)

DRAFTS table (the only UI keys a client may set; each typed and checked against the realm's catalogs):

UI key Type Acts
pending {a,b}, both city ids (isCity) buildLink, orderDf, orderCable
route one of the route picker's values (90-actions/85-routing-and-routers.js:13), or '' buildLink
via '' or a cable id (CABLES) buildLink
cnPrem boolean buildLink
dfSrc 'lease'|'build'|'cable' orderDf
dfSys a key of DF_SYS orderDf
seaDesign a key of SEA_DESIGNS orderCable
seaterminal, seaengineering boolean orderCable
decom array (≤ 200) of city ids; becomes a Set decomGo
slop boolean: the script came from the AI button; the server sets UI.slop=args.script teDeploy
pieIns, pieLas boolean pieLaunch

TEXT args (after T1 makes the five field readers take an argument first, falling back to the field): teDeploy/teCheck {script} ≤ 4000 characters (the game cuts at 4000, 30-route-script-and-tools.js:12); metricSet {id, v} with v ≤ 16; renameGo {name} ≤ 64 (the game cuts at 24, 90-actions/91-slots.js:27); pieRename {name} ≤ 64 (cut at 40, 90-actions/97-pie.js:30).

Server pipeline (srvAct, in the realm; the host has already run the envelope check, section 10):

  1. act must be in SEND (a Set lookup, then Object.hasOwn(ACT, act)). S.lost → stopped.
  2. srvMark({keys:true}).
  3. Set the drafts from ui (DRAFTS[act] only). Set UI.sel, UI.tab, UI.left to the page's own values from ctx: sel must be null, a city (isCity) or a link in S.links, else it becomes null. Set the viewport from ctx; set the stand-in #modal to visible when ctx.modal. Apply the CONFIRM rule.
  4. Run per the CONFIRM table, else ACT[act](args). Then tutAdvance().
  5. Compare JSON.stringify(S) with the mark. Same → no_effect (or rejected if a bad toast was emitted; the toast's log line then made S differ, which is fine).
  6. Changed → the sanitize gate. S2 = migrate(JSON.parse(JSON.stringify(packSave(S)))), a throwaway: uidN and S.rng are put back after it (sanitize stamps ids on entries without one, 80-simulation/50-sanitize.js:23,83, and the seeded Math.random reads the live S.rng). For every top-level key whose JSON the act changed (against the mark), packSave(S2)[k] must deep-equal packSave(S)[k]. A difference means the act built a state sanitize would repair (a bug or an attack): srvRestore(), outcome error, log "sanitize would repair : ". The gate never adopts S2: that would swap S for a new object without compute(), leaving R.ddos[].attack pointing into the old S (28-route-worker.js:77,81) and resetting UI.slTried. Keys that only days changed are not the act's doing; T1's canonical test covers them, and in tests (SIM_STRICT=1) the same gate runs after every day too. Then the size guard: the save text ≤ 4 MB (MAX_SAVE, mp.js:25) and at most 256 KB larger than before, else srvRestore(). Outcome applied. Budget ≤ 10 ms on the big network.
  7. A throw: srvRestore() (its finally blocks ran). A timeout: a fresh realm from the mark (4.2). Outcome error, stack logged (rate-limited). The page shows "The server could not do that".
  8. ui = each of sel, tab, left, confirm whose JSON now differs from what step 3 set; closed if closeModal() ran; modal {h,c} if openModal() ran (the opsHire, salesHire, bstdSet, coreUp, ddosAuto, utility* and De-Kicks sheets). rmLink writing null over the sent link is a difference and is reported.
  9. Pull at once (srvPull): the update carries {rid, dev, ui} in acts; the host sends it to every stream of the network right away.

Reply {rid, outcome:'applied'|'no_effect'|'rejected'|'error'|'stopped', v}: v is the version of the update that contains the result.

Busy state and duplicates.

  • The page keeps SRV.busy, keyed by act and JSON.stringify(args). The wrapper sends nothing for a busy key (a second tap is dropped, with a haptic). The key clears only when an update with v ≥ reply.v, or a snapshot, has been applied: then the panel already shows the result. (Clearing on the reply, as the first version did, left the old enabled button on screen while the bigger update was still on its way: a double tap bought twice.)
  • The busy look is a generated CSS rule on [data-act="…"][data-args="…"] (a small spinner, pointer-events:none), so a panel re-render keeps it and no element has to remember it. Other buttons stay live. btn() is a const (93-ui/10-dom.js:3) and needs no change.
  • The host records each rid when it arrives (the last 64 per network). A repeat while the first one runs waits for its reply; a repeat afterwards gets the same reply and is not run again.
  • A lost reply (the phone switched networks, the server restarted): the page says "Not sure that went through. Check before you try again", keeps the key busy until the next snapshot, and never repeats the action by itself.

Actions and days. Actions for a network run in arrival order, between that network's days. The game's own checks decide what still works (cash, existence, quotes). A queue of more than 32 waiting actions per network answers 429.

5.9 What-ifs on the server (ASK)

  • linkCheck {id}, teCheck {script}, teSlop {} run after srvMark(), and afterwards R goes back to the marked object and S.rng and uidN to their marked values. Needed because the seeded Math.random advances S.rng (60-features/20-scenarios.js:3-4) and teSlop draws from it (90-actions/30-route-script-and-tools.js:6, and pick() inside aiSlop), and because teTrial routes with the trial R as yesterday (80-simulation/20-routescript.js:127-129), which would move live scenic paths. S itself is compared with the mark and stays the same object when it matches, which it does: linkTrial puts S and R back itself (93-ui/70-link-panels.js:49), teTrial and aiSlop put S.te back (20-routescript.js:89-91,127-129). A mismatch is a bug: logged, and S is parsed back from the mark (srvRestore()). So an ask during a DDoS keeps R.ddos[].attack pointing at the live attack, and the sales desk keeps its memory.
  • They answer with the window they opened ({modal:{h,c}}, built with the request's viewport so isPhone() agrees) and, for RouteScript, ui.teDraft (and ui.slop for teSlop). The page opens it with openModal(h,c).
  • This moves linkTrial's routing (93-ui/70-link-panels.js:39-41), teTrial and aiSlop's up to five routings (20-routescript.js:85-91) off the phone. teOpt stays on the page: teOptimize routes nothing (20-routescript.js:46-57) and reads only R.netEg and sfOf, which slim R carries.
  • A timeout replaces the realm (4.2). teSlop: timeout 3 s, one per 5 s per player.

5.10 Order and versions

  • Each network has epoch (new per realm load) and v. Only srvPull advances v: a pull with something to send is version v+1, relative to v. Days and actions change state; they are not versions. The host keeps no counter.
  • Every update of a network goes to all of its visible streams, so every stream sees every version (a hidden one gets a snapshot when it shows again). A page applies an update only if from equals its v and the epoch matches; otherwise it reopens its stream and takes a snapshot.
  • No replay ring: every (re)connect gets a snapshot. A snapshot (≤ 60 KB gzip) costs about what two updates do.
  • A new stream on a network: the host first pulls (so existing streams get everything up to now), then sends the new stream a snapshot at that same v.

5.11 Cadence, data saver and backpressure

  • One cadence per network. The host pulls a network at once after an action, and after days when at least one of its streams is visible and its last pull is at least 1 s old. Every stream of the network gets the same bytes (no per-stream merging).
  • A network nobody watches is not pulled. Its realm drops fx as they come, except badge and modal, which it keeps (at most 32) for the next snapshot's keep, and it forgets its key baseline (the next stream starts with a snapshot). Its memory stays flat however long the absent player stays away.
  • fx cap per update: 60. Over it, floaters go first, then sfx, then the oldest toasts. modal, badge, pause and mk end events are never dropped.
  • Data saver. A stream opened with saver=1 gets s, del, fx and acts in every update, but r at most every 10 s (always the newest; R is whole, so skipping one is safe). The page sets it when navigator.connection.saveData is on or navigator.connection.type is cellular (where the browser has them), or when the "Save mobile data" setting (sot-saver) is on. The session panel shows the data received this session.
  • Backpressure: when res.write() returns false, the host skips that stream; if it has not drained within 10 s or 2 MB are waiting, it sends bye {why:'slow'} and closes; the page reconnects and takes a snapshot.

6. The client in view mode

Where the code lives. All new client code is in src/game/98-server-play/ (T4). assemble({mp}) (scripts/lib/page.js, T1) leaves that folder and src/styles/43-server-play.css out unless mp is true, the same way it leaves out @include-dev parts (scripts/lib/page.js:6-9,24,67). scripts/build.js passes mp: !!MP_API; dev.js --mp and the tests that need it pass mp:true. The folder name fits the layout rule (tests/build.test.js:50) and sorts before 99-loop.js, which matters: boot runs while the script loads (99-loop.js:68; slotBoot → slotMigrate can call back at once, 91-slots.js:127-128,139-142).

The folder hooks in by rebinding top-level function declarations of earlier files, as opsQuiet and nocRun do (60-features/95-standing-orders.js:122-123, 94-dashboard/90-noc-window.js:36), and extends ACT with Object.assign. A const arrow cannot be rebound (btn, isPhone, quietOn, pzOn, mpIs); the design needs none of them changed. runClock and boot live in the later 99-loop.js: there T1 adds the only two checks, against function srvOn(){return false;} which T1 declares in 60-features/89-multiplayer.js and the folder rebinds. So every top-level value still uses only earlier files, and edits to existing game files shrink to T1's (6.1), which lowers the cost of the next upstream merge (upstream rewrote the loop and the route worker in #313).

One switch. srvOn() = MP_API && S && S.mp && S.mp.sim===1 && !pzOn() && mpTok(S.mp) (89-multiplayer.js:16,22). The server sets S.mp.sim on networks of server sessions, and T1 lets mpSanitize keep it (it rebuilds S.mp field by field, 89-multiplayer.js:26-29). Phase-1 networks (no sim) keep phase 1's code paths. A session save without a token (exported, imported) is not a server network: opening it offers "Play on this device" (S.mp=null, as mpLeave does, 90-actions/92-multiplayer.js:24-26). Connection state: SRV.st = connecting | live | lost | away | gone | old | stale.

Names: nothing in src/game may be called api…, API_… or TUBES (tests/build.test.js:60-73); use srv…/SRV_…. New files are NN-name.js (build.test.js:50). Do not use HOOKS or UI.clockLocked (they belong to agent mode, 50-state.js:4-7, src/agent/75-mode.js:77-80).

6.1 What changes, by file

Edits to existing game files (all T1; no behaviour change in any build, tested):

File Change
99-loop.js:17 &&!srvOn() in the runClock condition
99-loop.js:54 S=migrate(sv);if(!srvOn())compute(); (a server network shows its mirror with R=emptyR(); the rebound mpResume, called at :55, opens the stream)
99-loop.js:57-58 moved into bootNotes(), declared in an earlier file; the page calls it, and the folder rebinds it to do nothing on a server network (the server calls it on attach)
60-features/89-multiplayer.js function srvOn(){return false;}; mpSanitize keeps sim:1
60-features/20-scenarios.js:46-61 beginState(nm,city,o) (lines 46-52 without UI: newGame, ASN, mode, S.mp, S.rng, rules, scenario) and beginShow(city,o) (the presentation tail, 55-61, with an option to skip tutorialStart()); beginGame calls both
60-features/40-tutorial.js:11-16 tutAdvance() (the loop at :13-14: writes S, toasts at the end) and coachDom(); renderCoach() calls both
95-modals/10-toasts.js:2-10 toastPop(html,kind,actions,tick); toast() = logNote + toastPop
90-actions/30-route-script-and-tools.js, 60-links.js:50, 91-slots.js:27, 97-pie.js:30 the five text acts take their text as an argument first, then the field
00-core/20-analytics.js:12 const SIM_ID=/*__SIM_ID__*/'';
where stats.ddT, ev and ddosStarts are written (5.4) canonical live S
90-actions/40-sites-peering-caches.js:23 and its sheet pniAll takes q and refuses a changed total; the same for any other QUOTE act T1 finds

The folder src/game/98-server-play/ (T4):

File Contents
10-state.js SRV; rebinds srvOn; the busy model and its generated CSS rule
20-stream.js the stream reader (fetch, SSE parser, backoff 1, 2, 4, 8, 15 s then every 30 s, at once on online or visibilitychange); /here (every 20 s while visible, hidden, hold debounced 300 ms, idle after 10 minutes without input, away on pagehide, view, viewport); /prefs when a network setting changes
30-apply.js srvApply (6.2), fx replay, the clock model, the mirror save cadence
40-acts.js SRV_LOCAL, and the page's copies of what it needs from T1's tables (SRV_ARM as a key template over each act's args, SRV_DRAFT, SRV_FIELD, SRV_QUOTE; a test checks they match scripts/lib/mp-sim-acts.js); srvWrap(), installed by the rebound mpBoot, which every page load calls at 99-loop.js:68 once every ACT entry exists (the puzzle wrapper at load misses later acts, 90-actions/95-puzzles.js:61-67); the wrapper acts locally whenever srvOn() is false; srvSend, srvAsk, srvVote; new acts srvRetry, srvInvite, runsOn, srvMove, srvLocal, srvSaver; overrides of ACT.start, ACT.mpStart, ACT.mpJoin, ACT.speed, ACT.phonePlay, ACT.phoneSpeed (Space and 0–4 reach the last three, 96-map/90-input.js:45)
50-hooks.js the rebinds below
60-ui.js the status banner, the "Runs on" choice, the session panel's Clock section and data counter, the vote badges, the "Move to the server" sheet
src/styles/43-server-play.css vote ring and count badge, busy spinner, banner (bottom on phones, as #update, 60-phone.css:72)

Rebinds (each wraps the original and changes behaviour only when srvOn()):

Function On a server network
after (90-actions/90-action-helpers.js:49) renderAll() and renderDash() only (no purgeInc, routeIfChanged, checkGoals, save)
save (91-save.js:7) the mirror: written every 30 s and on pagehide, no S.uiSpeed, no mpSave; the camera goes to sot-cam:<code>.<pid>
toast (95-modals/10-toasts.js:2) toastPop only (S.log is the server's)
autoPause, playPause, setSpeed (96-map/30-settings.js:19,21,23) nothing; a vote; ignored (the speed comes from the clock)
renderHUD (93-ui/40-hud-and-panels.js:4) original, then on the speed buttons: .on = the world's speed, a ring on my vote, a "2/3" badge when more than one player is active (absolutely placed, so fitHud sees no width), title/aria-label "Vote 4× (2 of 3)"
renderTabbar (93-ui/20-phone.js:4) original, then Play shows the world's state (a tap votes pause or resume) and Speed the world's speed ("→4×" and a count while my vote is pending; sent 400 ms after the last tap)
renderCoach (60-features/40-tutorial.js:11) coachDom() only (the server advances the tutorial); stores sot-tut when S.tut turns null
pniFlows (70-rules/38-pni-value.js:13) `R.pf[c]
transitTop (93-ui/70-link-panels.js:192) R.tTop8.slice(0,k) for more than one id
mpSave, mpPush, mpResume, mpBoot (60-features/89-multiplayer.js:103,108,138,159) no saves or pushes; mpResume (called when a save loads, 99-loop.js:55) shows the mirror and opens the stream; mpBoot installs srvWrap on every page load, and for a #mp= link of a server network stores the token and opens the stream instead of fetching the save
slotOpen (91-slots.js:104) a server network's slot opens the stream instead of compute()
doorsHtml (95-modals/40-title.js:49) "Runs on" in the Normal door
mpPanelHtml, mpHud (95-modals/48-multiplayer.js:46,62) Clock section, "Invite friends", data counter; chip "🖥️" for a session of one, "🌐 #1/3 · 3 online" otherwise
pzBegin (60-features/92-puzzles.js:131) and the way back close the stream (away) first; on leaving, reopen it and take a snapshot, never restore from UI.pzKeep
bootNotes (T1) nothing

Also T4: src/agent/75-mode.js:35-44 (agent mode refuses to lock the clock on a server network; development page only), every new string in src/i18n/en.js and site/i18n/*.js through scripts/i18n-add.js.

Dropped from the first version: the server-time skew for "x min ago" (95-modals/20-notifications.js:19,21; the device clock is normally seconds off) and the "…" placeholder in linkPanel (5.6).

6.2 Applying an update

  1. Ignore it if S is not this network (S.mp.code/pid). If from or epoch do not match: resync (snapshot).
  2. In place: Object.assign(S, s), then delete the del keys. In local play S is also changed in place, so the caches keyed on the S object keep working as they do there: the save-failure backoff and its once-per-game toast (91-save.js:13,22-24,54), floaters (96-map/60-draw.js:129), spots() and solRoutes() (60-features/36-specialist.js:13,84, which also key on S.day and counts). A snapshot makes a new object: S = migrate(snap.S).
  3. If r: keep it as SRV.R0 (plain), then R = Object.assign(emptyR(), SRV.R0); rebuild R.ddos[].attack from ddosAll(S,false) with ports=new Map() (90-noc-window.js:45); put the records of SRV.sub in (R.ef, R.egDesc entries, R.pf). A sub event alone makes a new R from SRV.R0 with the new records. R is always a new object: five caches key on its identity (pniIdx, ixHas, mapLinks, mapStill, routeIfChanged).
  4. RW.gen++ (the TERR cache, 80-simulation/60-requirements.js:30). UI.hotMap = hotByCity() (0.44 ms).
  5. Heal the UI: UI.sel dropped if its link or city is gone (the rule at 95-standing-orders.js:123); UI.decom filtered to S.pops; UI.confirm cleared when its target is gone. Drafts (pending, drag, snap) stay: the server checks them when they are sent. An update never closes a window.
  6. For each entry of acts whose dev is this page: apply sel, tab, left only where the page's value is still the one it sent (the player may have moved on), confirm, closed → closeModal(), modal → openModal(h,c). Clear every busy key whose reply v is at most this update's v.
  7. Replay fx (5.7).
  8. Render as the day end does: UI.ticking=true; renderHUD(); UI.ticking=false; UI.panelsDue=true; NOC.dirty=true (28-route-worker.js:72, 99-loop.js:15). A finger on a panel is respected (pressing, 96-map/95-clicks.js:2-3). An update with this page's action result renders at once, like after().

6.3 What stays as it is

  • Every renderer, the map, panels, dashboards, the NOC window (it gets S and R from the game window as today, 90-noc-window.js:16-23, and its clicks reach the game window's ACT, which sends them).
  • Local networks, phase-1 networks, puzzles, Architect, scenarios, the weekly, sandbox, settings, slots, export, import.
  • The route worker: never started for a server network.

6.4 Status the player sees

State Shows Works
connecting mirror, frozen dots, chip "🌐 …" views; actions answer "Connecting…"
live as today everything
lost < 5 s nothing (quiet retry), dots frozen views
away phone: one line above the tab bar, "Server lost · retrying · Try now"; desktop and the session panel: "Lost the server. Your network is safe there: it runs on while others play, and waits while nobody does. Trying again in 8 s · Try now" views; actions toast "Not connected"
back snapshot, then "While you were away: n days" (and "the last n days ran again" after a restart) everything
not sure after a lost action reply: "Not sure that went through. Check before you try again"; that button stays busy until the snapshot everything else
vote pending the badge says "waiting for 1 more" everything
gone (401/404) window: "This network is no longer on the server" · Export the last copy · Play the copy on this device · Your networks –
old (409 {old}) the update banner (95-modals/50-release-notes.js:13-19), not postponable; read-only until reload views
stale / off (503 {sim}) "The server is being updated" · Export views
server error on this network (broken) window with Export and Play the copy here views

All of it at 360 px, portrait and landscape, with the phone tab bar and bottom sheets.

7. Single player as a session of one

  • Title, Normal door (95-modals/40-title.js:49-53, the rebound doorsHtml): "Runs on: 🖥️ the server (default) | 📱 this device", with one note line: "Less battery on big networks, any device, invite friends later. Uses mobile data." / "Works offline". Remembered in localStorage sot-runs. The default follows open question 2.
  • Start on the server: the page shows the pitch first if due (as beginGame does, 20-scenarios.js:46), then POST /sessions {solo:true, preset, net:{name,home}, asn?, lang, tut, prefs}.
    • The server checks the typed AS number with the game's asnOk in the realm (the title's own number, #135), and keeps it as the network's S.asn and the roster's asn. Friends who join later get a different one: newPlayer already avoids every player's asn (mp.js:292-294).
    • tut is true when this device has not finished the tutorial (sot-tut, 40-tutorial.js:10).
    • The server builds the network (srvBegin), checkpoints it, answers with the token. srvBegin also makes the welcome toast (20-scenarios.js:58) in the realm, so it is in S.log as today and reaches the page as an fx.
    • The page stores the token, opens the stream, makes the slot from the snapshot, and runs beginShow(home,o) (T1) without tutorialStart() (which writes S.tut=0, 40-tutorial.js:10; the server already set it): camera on home, selectCity, charterAsk, renderCoach().
    • Server away, off or stale: the sheet offers "Play on this device instead".
  • Limits: solo sessions count against --max-sessions, with their own creation limit (30 per hour per address). They are pruned like any session after 60 untouched days, saves included (mp.js:216-230); the "Runs on" note's details and the session panel say so ("Kept while you play at least every 60 days; this device keeps a copy").
  • Session of one in the UI: chip "🖥️", no code toast, menu tile and panel offer "Invite friends" (shows the code).
  • "Start a new network" on a server network asks: delete it on the server (DELETE /me) or keep it there and only start another.
  • Local play: "this device" starts today's local game (½× speed, 20-scenarios.js:55-56). Local networks load and play exactly as today in an MP build.

8. Old saves

Save What happens
Local network (no S.mp) Untouched: slotBoot, slotOpen, save, loadSave unchanged
Phase-1 session network Stays phase 1. It has no S.mp.sim, so srvOn() is false and phase 1's code runs it as today (each browser runs its clock and pushes saves). The server keeps phase 1's routes for sessions without s.sim; a server route on such a session answers 409 {phase1}. Nothing is uploaded or overwritten, so no device loses progress
Joining a phase-1 session As today (join answers without sim; the page runs mpBegin → beginGame)
Session save without a token "Not in session" (mpFail, 89-multiplayer.js:78); offer "Play on this device"
Local or phase-1 Normal network, "Move to the server" (menu tile and slot menu, 45-slots.js:19-22) A sheet explains. POST /sessions {solo:true, import:{data}} with the save gzipped like mpPush (≤ 4 MB). The server loads it with migrate, refuses sandbox/scenario/puzzle with the reason, gives S.rng and S.mp (with sim:1). The local slot becomes the mirror; nothing is deleted. A phase-1 network becomes a new session of one; its owner invites friends again
Export of a server network The mirror, fresh after the last update
Import A local network, as today
The mirror opened by an older build Its mpSanitize drops sim, so it loads as a phase-1 network and plays locally (tests/multiplayer.test.js:85-87); its pushes get 409 {sim:true}

The sessions on the playtest server that runs now (section 13) are phase-1 sessions: they keep working in the new build, as phase 1.

9. Failure modes

Case What happens
Page loses the stream Retry 1, 2, 4, 8, 15 s, then every 30 s; at once on online/visible. A snapshot on reconnect. Never simulates locally (that would fork the world).
Server restart Streams drop; pages reconnect; first attach loads realms (≈ 0.3–0.5 s per big network) and lines them up (4.7); new epoch → snapshot. Actions in flight: "Not sure that went through".
Server process crash As restart; at most 60 s of world time runs again, at most 5 s of actions lost.
A realm throws or times out in a day Back to the pre-day mark, retried once; a second failure marks the network broken at its pre-day state (4.3).
A realm throws in an action or ask srvRestore() in place; outcome error.
A realm times out A fresh realm from the mark; the old one is dropped (4.2).
Worker dies (out of memory, crash) Pending calls are rejected; its sessions reload from checkpoints with a line-up; twice in an hour → a worker of its own; once more → not reloaded until restart, players see the error window.
A save will not load That network is broken; the others play.
Slow instance eff < speed; clock why:'slow'; HUD "running at 5×". --sim-max-speed caps votes.
Action arrives while the realm's day runs It waits (worker is serial); it lands between days of its own realm. At most ~60 ms for a big network.
Action based on an old view Runs on the current state; the game's checks refuse what no longer works (toast); QUOTE acts refuse a changed total.
Double tap The second tap is dropped until the first one's update is on screen.
Two devices of one player Two streams, same updates. Both may act; actions run in arrival order. UI effects apply only on the sending device. Votes are per player; the hold follows the device used last. Language and the S-changing settings belong to the network and change only on purpose.
Two tabs in one browser The slot's Web Lock stays (91-slots.js:65-75).
Page hidden Not active at once; the server closes the stream after 60 s.
Visible but untouched for 10 minutes Idle: not active, not counted in votes.
Phone in a pocket, page suspended Hidden (sent before suspension) or, failing that, unheard for 45 s: gone.
Slow or stalled reader Over 2 MB waiting or 10 s without drain → bye slow, reconnect, snapshot.
Network nobody watches fx dropped as they come except badge and modal (≤ 32, sent with the next snapshot).
Old client after an upgrade 409 {old} on stream, act, ask and vote → update banner.
Server pulled but not rebuilt 503 {sim:'stale'} for server sessions; phase 1 works; the log prints the build command.
Language change Explicit (POST /prefs); the realm reloads once in that language. Old log lines keep their language.
Bankrupt Days stop (S.lost); fx modal lose, or the lose window from the snapshot; the network stays on the leaderboard.

10. Security

Tokens. Phase 1's: Authorization: Bearer <pid>.<token>, the server stores only sha256(token) and compares in constant time (mp.js:260-266). The stream uses fetch, so the token never goes into a URL or a proxy log. #mp= links keep the token in the fragment (89-multiplayer.js:154-159). No cookies, so no CSRF; no CORS headers.

Rate limits (limiter, mp.js:86-101; per player unless said):

What Limit
act 10 per second, 300 per minute, and at most 200 ms of worker time per second averaged over 10 s (an act with its re-routing, gate and pull costs about 65 ms on a big network); ≤ 32 waiting per network
ask 1 per 2 s (teSlop 1 per 5 s), 20 per minute
vote 5 per 10 s
here 10 per 10 s (the 20 s heartbeat fits)
prefs 5 per minute
stream opens 20 per minute per player; ≤ 4 open per player; ≤ 16 per address; ≤ 2000 in all
solo session creation 30 per hour per address
body size act 16 KB, ask 8 KB, here 2 KB, prefs 1 KB, vote 256 B

Untrusted actions: validated like sanitize validates a save; nothing is ever evaluated.

  1. Envelope (host, checkEnvelope in mp-sim-acts.js): a JSON object; rid, dev match ^[a-z0-9]{8,16}$; sim matches ^[0-9a-f]{12}$ and equals the server's (else 409 {old}); act in SEND (a static list); args a plain object of ≤ 12 keys matching ^[A-Za-z][A-Za-z0-9]{0,15}$ (never __proto__, constructor, prototype), values a finite number, boolean, null, a string ≤ 64 characters (TEXT args: their own cap), or an array of ≤ 64 such primitives; no nested objects (a test crawls every button to prove none is needed); ui only DRAFTS[act] keys; confirmed only for CONFIRM acts; ctx: sel null or {type:'city'|'link', id} with an id ≤ 40 characters, tab and left matching ^[a-z0-9]{1,16}$, modal and coarse booleans, w, h 200–4000.
  2. Realm: the drafts and ctx.sel are checked against the game's catalogs and S (isCity, S.links, CABLES, DF_SYS, SEA_DESIGNS, the route values). The action runs as a button click: the game's handlers refuse impossible moves as they do for a player.
  3. The sanitize gate after every action that changed S (5.8 step 6): the keys the act changed must come through the save path unchanged. Otherwise the action is rolled back and logged; the gate never adopts a repaired copy.
  4. Rollback on a throw, a timeout (1 s; a fresh realm) or a size guard failure.
  5. Data in, data out: input reaches the realm as a JSON string parsed inside it; results come back as JSON strings. No code string is ever built from client data (unlike the probes' ev(\ACT[${…}]`)`).
  6. Isolation: each network has its own realm with its own intrinsics, so a polluted prototype stays in that player's own game. vm is not a security boundary against hostile code, but only our game code runs there; clients send data only.
  7. What a client can never send to a server session: S or R. The only state upload is "Move to the server" (an import into a new session), through migrate, the 4 MB limit and the Normal-mode check. (PUT /save stays for phase-1 sessions only.)
  8. Privacy: a stream carries only its own player's networks; others see roster and cards, as in phase 1.

11. Tests

Every track adds its own tests/<name>.test.js. Tests are seeded and pin Date.now; nothing depends on luck. The determinism and restore tests use the big fixture with its L2 customers set to scenic, since plain routes hide the route-memory problem.

Test (owner) Proves
server-sim-prereqs.test.js (T1) beginState + beginShow give the same S and screen as beginGame; tutAdvance then coachDom equals today's renderCoach; the five text acts give the same S with the argument as with the field; bootNotes matches today's boot; SIM_ID is stamped only with MP_API; assemble({mp:false}) contains nothing from the folder or its CSS; mpSanitize keeps sim:1; canonical S: packSave(migrate(packSave(S))) equals packSave(S) after 365 seeded days with every feature on (DDoS, failures, events, the intern on every order, the sales desk on auto, IPv6-only), and cash, customers and incidents equal a run of the page before T1's changes (node scripts/lib/page.js --ref <base>, scripts/lib/page.js:14); pniAll (and every QUOTE act) refuses a changed q
mp-sim-contract.test.js (T1) every fixture in tests/fixtures/mp-sim/ passes tests/lib/mp-sim-shape.js; the fake engine answers in the shapes of 4.2; checkEnvelope accepts every button the crawl finds for a SEND act and refuses the hostile cases of section 10
mp-sim-engine.test.js (T2) realm loads, days, actions, asks, pulls, saves; the capture table produces each fx kind; a timeout inside opsQuiet leaves the next realm with working toast and after; a throw restores in place; a worker exit rejects every pending call; an ASK (teSlop included) leaves S (the same object), R, S.rng and uidN as they were, and an ASK during an active DDoS keeps R.ddos[].attack === ddosFind(id); a rolled-back action re-links R.ddos[].attack to the restored S; ui.sel is reported only when it changed (rmLink on the selected link → null; buyTransit with a city selected → nothing); a begin sent mid-day waits for dayDone; an unwatched network's fx stay bounded; a polluted prototype in one realm does not reach another
mp-sim-determinism.test.js (T2) Realm vs jsdom: the scenic big fixture, seeded, Date.now pinned and stepped 2500 ms a day, 60 days with actions interleaved (buildPop, buildLink with drafts, buyTransit, rmLink confirmed, renameGo, teDeploy); the jsdom arm runs each action by its click path (which ends in after()) and calls renderHUD() after each day, as a browser does; S and R byte-identical. Restore: 20 days straight vs 10 + envelope + fresh realm + 10, identical in play. Retry: a day that fails once (an injected throw and an injected timeout, both after the day's DDoS step with an attack active) gives the same network as no failure. Order: a session of three networks in two realm orders: each network identical. Timer audit: 365 days with failures, events, the intern on every order and the sales desk on auto, plus every SEND button the crawl finds: the no-op timer counter stays 0 on sim paths, and S does not change after a following macrotask. Gate: no act in that run is rolled back by the gate
mp-sim-acts.test.js (T2) SEND = API_CMD − pz* − {teCheck, traceRun, closeModal} + {connCancel, pieRename, tutSkip} (loaded with {agent:true}); the CONFIRM table matches the code; SRV_ARM keys equal what each act's first click writes; every DRAFTS key is the full set the act reads; for each draft and text act, the server pipeline gives the same S as the click path in jsdom
mp-sim-clock.test.js (T3) votes (alone at once, majority, expiry, clear on change, tally on presence change, inactive and idle players ignored), presence (visible streams closed when unheard for 45 s, hidden streams exempt and closed by the server 60 s after the hidden message without the page, idle after 10 minutes, the 15 s grace keeps the hold, the most recently used stream decides the hold), waking at 1×, last as the Resume target
mp-sim-server.test.js (T3) the HTTP protocol against T1's fake engine and against the real one: auth, envelope refusals, 409 {old} on act/ask/vote/stream, rate limits (worker time included), SSE framing and heartbeats, gzip flush per event, snapshot on a gap and on every reconnect, rid de-duplication (a duplicate in flight waits), two actions in one update (acts), per-stream sub (two streams on two links), a saver stream gets r at most every 10 s, backpressure bye, phase-1 routes unchanged on a phase-1 session and 409 {phase1} on its server routes, the envelope round trip and GET /save, a line-up after a restart with a lost and a broken network that ends, a worker killed mid-day (the session goes on), 503 {sim} when stale or off; every event it writes passes T1's shape test
mp-sim-soak.test.js (T3, long run behind SOAK=1, a 60 s version in CI) 2 big + 6 small networks at 8×, random valid actions over HTTP, 3 readers (one reconnecting every 20 s, one hiding and showing), one network never watched: no errors, RSS growth < 15% after warm-up, every reader's S equals the server's S at the end, checkpoints load; prints ms per day per realm, pull ms, update bytes and client apply ms
mp-sim-client.test.js (T4) jsdom MP page (load({mp:true})) with T1's fake streaming fetch: the gates (no runClock, no compute, no mpPush, no 5 s autosave); snapshot and in-place updates; R a new object each update; migrate(snapshot) is a no-op on server S; floaters and the save-failure backoff survive an update; UI healing; toasts replayed without logNote; the action wrapper (local, send, confirm arming, drafts gathered, ask); busy keys (a second tap is dropped until the update with v ≥ reply.v; a lost reply says "not sure"); sub records kept across an r without sub; a snapshot with S.lost shows the lose window once; votes in the HUD and the phone bar at 360 px, portrait and landscape; every status row of 6.4; the empty-R render (empty-r.js); mirror fidelity: a page fed by the real engine for 50 days has JSON.stringify(S) equal to the server's
mp-sim-local-acts.test.js (T4) SRV_LOCAL ∪ SEND ∪ ASK ∪ VOTE ∪ puzzle acts = every ACT key, disjoint, with the message of 5.8 when not; SRV_LOCAL ⊆ the agent's API_VIEW ∪ API_BOUND ∪ API_SESSION ∪ API_DENY (except DENY:time) ∪ {closeModal, traceRun}, minus {connCancel, pieRename, tutSkip, teSlop}; clicking every SRV_LOCAL button the crawl finds leaves JSON.stringify(S) unchanged apart from rng
multiplayer.test.js (T4, extended) plain build: no folder, no door, chip, tile, "Runs on" choice; no fetch stream, EventSource or WebSocket ever made; ACT.speed and phonePlay as today; still not one request. MP build: a phase-1 network still runs phase 1 (its own clock, pushes)

Commands that must stay green: npm test, node scripts/i18n-check.js ("0 missing, 0 unused, 0 broken"), npm run build, MP_API=/api/mp npm run build.

12. Performance budget

The user's condition: less CPU on the client. Measured in real Chromium with the big network (day-worker.js, panels-idle.js; the phone profile is 390×844 at DPR 3 with CDP's 4× CPU throttle, which does not slow workers):

Per big-network game day Phone profile today Desktop today Server-run, phone profile Server-run, desktop
Main thread for the day, as players run it (route worker on, 99-loop.js:31) 12 ms (7.6–30), of which 6.7 ms copying S to the worker and 2.5 ms unpacking R 2.2 ms apply ≈ 7 ms (6–15) 1.4 ms
Routing, in the route worker 42.5 ms measured; ≈ 150 ms on a real phone 4× slower (estimate) 34 ms 0 0
A sales trial or intern fiber test in the day + ≈ 6.7 ms main thread each (S sent again, 28-route-worker.js:44-48) plus its routing 0 0
Day-end render (99-loop.js:15): panels unchanged / changing 2–6.5 ms / ≈ 186 ms 47 ms changing the same, once per update
Map draw (2D fallback; WebGL, which most phones use, not measured) 52 ms at zoom 3.2, 149 ms at zoom 1.1 unchanged
Mobile data (estimates from the measured update sizes; measured at integration) 0 big: ≈ 20 KB/s at 1× (≈ 73 MB an hour), ≈ 50–60 KB/s at 8× (≈ 200 MB an hour); with the data saver ≈ 11 and ≈ 28 KB/s. Small network ≈ 1.5 KB/s

(The perf bench's "day" row is a synchronous dayTick() with the worker off, scripts/perf-bench.js:41, scripts/perf-browser.js:30, 28-route-worker.js:14; its "panels" row is two renders, :43, and "map" three draws, :45. The first version compared against those numbers.)

What this means:

  • The phone's main thread saves about 5 ms a day, plus about 7 ms per sales trial or fiber test. Nobody will feel it.
  • The real saving is the routing: about 150 ms of CPU per big-network day leaves the phone. At 1× that is about 6% of one core, at 8× about half a core. That is battery and heat, not frame rate. Small networks, most games in their first hours, save almost nothing (a small day is about 0.5 ms on desktop).
  • Panels and the map stay on the phone. At 1× a server network renders panels once per update, every 2.5 s, like local 1×, and twice as often as a new local game, which starts at ½× (60-features/20-scenarios.js:55-56). At 8× the 1 s update cadence caps panel renders at 1 a second instead of 3.2: that saving comes from the cadence, which only server networks have. A render or frame-rate cap for local play would help phones too, but it changes the plain build, so it is not part of this work (propose it upstream, measured on a real phone with WebGL).
  • Mobile data is the price, and the radio stays awake for the stream, which eats into the battery saved.
  • Verdict against the condition: total client CPU goes down on big networks, so the condition holds there, but the first version overstated it. Integration step 4 measures it (section 13), and the user decides the single-player default with those numbers (open question 2).

Budgets (fail a review if exceeded without a reason):

Item Budget
Server, big network day in a realm ≤ 45 ms (measured 38–41)
Server, small network day ≤ 1 ms
srvMark per realm per day, big ≤ 2.5 ms with the route memory (T2 measures it; per action, with per-key strings: ≤ 3 ms, inside the gate's 10 ms)
One worker thread, 12 big networks days ≈ 480 ms; pulls ≤ 15 ms per watched network per second; an action with re-routing (after(), 90-actions/90-action-helpers.js:49), gate and pull ≈ 65 ms; an ask up to 5 routings. About 3× sustained with every network watched; 8× holds for about 4 big networks or many small ones. Reported as eff
Server memory ≤ 30 MB live per big realm (25–64 MB of RSS each, engine report): about 1 GB of RAM and one core per busy 12-player session of big networks
Realm load ≤ 0.5 s per big network
srvPull (S key diff + slim R pack), big ≤ 15 ms; only when something changed
Sanitize gate per action, big ≤ 10 ms
Wire per update, big network S ≤ 25 KB gzip + R ≤ 35 KB gzip; small ≤ 8 KB
Snapshot, big ≤ 60 KB gzip
Checkpoint writes 12 big networks: one ≈ 45 KB write each per minute while running (≈ 32 MB an hour)
Client apply ≤ 5 ms desktop, ≤ 20 ms phone
Action round trip LAN ≤ 150 ms for a big network (worker wait ≤ 60 ms, act 2–32 ms, gate ≤ 10 ms, pull ≤ 15 ms, apply); mobile data adds 200–500 ms. Meanwhile the pressed button shows a small spinner, the panel keeps its pre-click state, other buttons stay live. Measured from the user's phone on the LAN at integration
Plain build npm run perf -- --base-ref origin/main and --browser (Chromium, desktop and phone): no slower; numbers in the summary

13. Build plan

Four tracks. T1 first (alone; it now also delivers the shared contracts). Then T2, T3 and T4 in parallel worktrees, each against T1's contracts. Then one integration pass. File ownership is disjoint; a track that needs a change in another track's file asks the integrator. tests/harness.js belongs to T1, CHANGELOG.md to T4. No track edits 60-features/95-standing-orders.js or 96-pop-standard.js (the design only cites them).

Playtest while building (the user's request)

Running now, and untouched by the tracks: a separate checkout pinned at e25f843 (outside the repo), built with MP_API=/api/mp, served by node scripts/mp-server.js --host 0.0.0.0 --port 8090 --site <that checkout>/_site --data mp-data/playtest. It is phase 1 (each browser runs its own clock). Its sessions keep working in the new build, as phase-1 sessions (section 8). Nobody restarts it unless the user asks; the integration playtest uses another port and data directory.

T1. Game prerequisites and shared contracts (first)

Owns Delivers
src/game/60-features/20-scenarios.js beginState(nm,city,o), beginShow(city,o); beginGame calls both
src/game/60-features/40-tutorial.js tutAdvance(), coachDom()
src/game/95-modals/10-toasts.js toastPop(html,kind,actions,tick)
src/game/99-loop.js bootNotes() moved to an earlier file; the two srvOn() checks (6.1)
src/game/60-features/89-multiplayer.js srvOn() stub; mpSanitize keeps sim
src/game/90-actions/30-route-script-and-tools.js, 60-links.js, 91-slots.js, 97-pie.js the five text acts take their text as an argument first
the files that write stats.ddT, ev, ddosStarts canonical live S (5.4)
src/game/90-actions/40-sites-peering-caches.js (and any other QUOTE act) quote checks (5.8)
src/game/00-core/20-analytics.js SIM_ID placeholder
scripts/build.js, scripts/lib/page.js simId(html); stamping in MP builds; simId in version.json; assemble({mp}) leaving out the folder and its CSS
scripts/lib/mp-sim-acts.js SEND, ASK, VOTE, CONFIRM, SRV_ARM, DRAFTS, TEXT, QUOTE as plain data; checkEnvelope(kind, body)
tests/fixtures/mp-sim/*.json, tests/lib/mp-sim-shape.js snap, upd-day, upd-act (two entries in acts), sub, clock, roster, and the shape checker T3 runs on its real output and T4 on the fixtures
tests/lib/mp-sim-fake-engine.js the engine API of T2 with canned answers, for T3
tests/harness.js load({mp:true}); a fake streaming fetch for T4
tests/server-sim-prereqs.test.js, tests/mp-sim-contract.test.js section 11

No behaviour change in any build. No new strings. CHANGELOG: none (refactor).

T2. Engine (after T1)

Owns Interface it offers
scripts/lib/mp-sim-realm.js, mp-sim-worker.js, mp-sim-engine.js createEngine({workers, heapMb, root, log}) → { load(code, nets:[{nid, env?, begin?, lang, prefs}]), day(code, {d, speed, last, alone, nets, mute}), act(code, nid, msg), ask(code, nid, msg), pull(code, nid, {snap, views}), sub(code, nid, {views}), prefs(code, nid, {prefs}), greet(code, nid), save(code, nid), card(code, nid), unload(code, nid?), stats() }, all promises of the worker replies in 4.2, each rejected when its worker exits
tests/mp-sim-engine.test.js, mp-sim-determinism.test.js, mp-sim-acts.test.js

If T2's timer audit or the gate finds a sim path that needs a game change, T2 reports it to the integrator (it does not edit src/game). T2 adds no player-facing strings.

T3. Host and protocol (in parallel with T2, against T1's fake engine first)

Owns Interface it offers
scripts/lib/mp-sim.js, mp-sim-clock.js createSim({mp, engine, opts}) → { route(req,res,s,sub,me) → handled?, attachAll(), flush() }
scripts/lib/mp.js delegates /stream /act /ask /vote /here /prefs to sim for server sessions; session create/join build the network through the engine; the checkpoint envelope in readSave/GET /save; PUT /save only for phase-1 sessions; PUT /card ignored for server sessions; exposes its internals to sim (load, authed, persist, queue, writeAtomic, saveFile, readSave, roster, applyCard, event, limiter, readJson, send, fail)
scripts/mp-server.js flags --sim-workers, --sim-heap-mb, --sim-max-speed, --sim-idle-min, --sim off; the SIM_ID check against --site (4.9); SIGTERM checkpoints; the per-minute log line
scripts/dev.js stamps SIM_ID and serves assemble({mp:true}) with --mp (next to MP_API, dev.js:35); mounts the engine; on a change under src/: checkpoints, recreates the engine, and lets pages reload (no realm hot reload)
docs/MULTIPLAYER.md (and a fork ADR docs/adr/0005-mp-server-runs-the-world.md) the new behaviour, API, proxy notes, "pull, then build", the 60-day prune of solo sessions
tests/mp-sim-clock.test.js, mp-sim-server.test.js, mp-sim-soak.test.js, and updates to tests/mp-server*.test.js

T4. Client (in parallel with T2 and T3, against T1's fixtures)

Owns Uses
src/game/98-server-play/, src/styles/43-server-play.css, src/agent/75-mode.js, every new string in src/i18n/en.js and site/i18n/*.js (via scripts/i18n-add.js) The protocol of section 5; T1's fixture streams and fake fetch until integration
tests/mp-sim-client.test.js, mp-sim-local-acts.test.js, multiplayer.test.js (extended)
CHANGELOG bullets under ## [Unreleased] (player-facing: "Multiplayer builds run every network on the server…", the speed vote, "Runs on", the data saver)

Integration (one agent, last)

  1. Wire T2 + T3 + T4; record streams from the real server (they must pass T1's shape test) and replace the fixtures; run the mirror-fidelity and soak tests.
  2. Apply any game fixes T2's audit or gate reported.
  3. npm test, i18n check, both builds, npm run perf -- --base-ref origin/main and --browser; numbers into the summary.
  4. CPU and data acceptance: real Chromium, phone profile and desktop, big and small networks: total CPU per real minute (main thread and workers, from Performance.getMetrics or a trace) and bytes per minute, for local ½×, local 1×, server 1×, server 8× and server 1× with the data saver. The table goes to the user before "Runs on: the server" stays the default (open question 2).
  5. LAN playtest on a second port with its own data: MP_API=/api/mp npm run build && npm run mp -- --site _site --host 0.0.0.0 --port 8091 --data mp-data/sim-playtest, phone on the same LAN at http://<host-ip>:8091. The phase-1 playtest on 8090 keeps running. Measure the action round trip from the phone.
  6. Commit as the fork's rules say; push to the vanvik remote only.

14. Open questions for the user

All four were answered on 2026-11-09; the answers follow each question. The questions still open with the user are in the status at the top.

Need an answer before T3 starts (each has a default the build uses meanwhile):

  1. Same day, own date. Decision 1 says everyone of a session is "on the same day". The design puts everyone on the same session day and speed (one day per tick each), but each network keeps its own calendar date, so a friend who joins a 500-day-old session starts on day 0. A shared date is a gameplay change (fail and event schedules are absolute days, 60-features/80-new-game.js:2-4; badges like "Tier 1 within three years" compare S.day, 88-days/20-badges.js:40,56). Recommendation and default: own date now; a shared date can come with phase 2. The offset is stored per network, so changing this later means migrating stored sessions. Resolved 2026-11-09: the session's date. One shared calendar: a player who joins an old session starts on the session's date, not on day 0, and the game's day-0 rules count from the network's own start ("What Q1 changes" at the top).
  2. The single-player default, given the honest numbers. On a big network the phone's main thread saves about 5 ms a day; about 150 ms of routing per day leaves the phone's second core (battery and heat); small networks save almost nothing; it costs about 70 MB of mobile data an hour at 1× on a big network. Default: "Runs on: the server", as you decided, confirmed or changed with the integration measurement. Or would you rather default to "this device" and offer the server? Resolved 2026-11-09: the server. Single player in a multiplayer build runs on the server by default, and "this device" stays an option. The integration measurement is still made, as a report.
  3. Speed after an empty session wakes up. Everyone left at 8×; the next player arrives alone. Default: back at 1×. Or keep the last voted speed? Resolved 2026-11-09: back at 1×.
  4. Phase-1 sessions, including the ones you create on the playtest server now. Default: they stay phase 1 (each browser runs its own clock) and keep working; "Move to the server" turns one network into a new server session of one. Must any of them become a server session with the same code and roster? Resolved 2026-11-09: they start fresh. Nothing is migrated; none becomes a server session with its code and roster.

Defaults the build uses (say if you want another): a speed change needs more than half of the active players, a vote lasts 2 minutes, alone it is at once; with others online the world keeps moving under your open window; a hidden page stops counting at once and its stream closes after 60 s; a visible page untouched for 10 minutes counts as away; with others online, a furious customer or an outage brings a toast with "Vote pause" instead of a pause; sandbox stays on the device; the data saver turns on by itself on cellular connections. Whether sandbox (and the other modes) should stay on the device was asked again on 2026-11-09 and is open with the user.

15. Changes after review

Reviews: the correctness review (C) and the feasibility review (F). "Fixed" means the design now does what the review asked; "fixed differently" says how; "not changed" says why.

Item Severity Outcome Where
C1 UI.sel sentinel breaks every action ending in after() blocker Fixed differently: the page sends its real sel/tab/left; the realm reports a key that differs afterwards (no accessors needed: rmLink's null differs from the sent link); renderPanel and renderLeft are no-ops in the realm 4.1, 5.8
C2 a vm timeout skips finally major Fixed: a timeout replaces the realm, built from the mark the worker holds; a throw restores in place, since finally ran. The in-place restore keeps the S object unless S changed, re-links R.ddos[].attack when it parses, and rebuilds R from route memory after a failed day 4.1, 4.2
C3 sanitize gate fires on every action; snapshot migrate not a no-op major Fixed: canonical live S in T1 with a 365-day test; the gate checks only the keys the act changed, rolls back and never adopts 5.4, 5.8, 11
C4 restore not deterministic with scenic circuits major Fixed: route memory (cut to scenic keys, 7 KB) in the checkpoint, seeded before compute() (probe restore-rt.js); scenic customers in the tests; unload only with nobody active 4.1, 4.6, 4.7, 11
C5 a failed day undoes applied actions major Fixed: pre-day mark, one retry, then broken at the pre-day state; the worker holds the mark, so even a realm that no longer answers is rebuilt without losing what was applied (only a worker death falls back to the checkpoint, and then pages are told the days ran again); fx of the failed try dropped; catch-up days muted 4.2, 4.3, 4.7
C6 line-up and run gate can loop or freeze major Fixed: line up from each network's last; lost and broken networks never run; a load failure marks broken; catch-up capped at 200 days; no partial admission (--sim-max-live deferred) 4.3, 4.7
C7 worker death freezes or misaligns major Fixed: pending calls rejected on exit; reload with line-up; twice in an hour → own worker, then stop reloading 4.2, 4.3, 9
C8 two owners of v; merged updates lose replies major Fixed: only srvPull advances v; one cadence per network, same bytes to every stream, so no per-stream from; acts:[…] 5.3, 5.10, 5.11
C9 double tap buys twice; lost reply looks failed major Fixed: busy keys cleared only by an update with v ≥ reply.v; rid recorded on arrival; "not sure it went through" 5.8, 6.2, 6.4
C10 presence trusts the page major Fixed: server closes hidden streams at 60 s, unheard ones at 45 s (20 s heartbeat); hidden and idle players are not active 4.4
C11 unbounded fx for unwatched networks; lose screen missed major Fixed: fx ring; unwatched networks drop fx except badge/modal (≤ 32, sent in the snapshot's keep); a snapshot with S.lost shows the lose window 4.1, 5.3, 5.7, 5.11
C12 vote and hold edge cases minor Fixed: tally on presence change; s.sim.last as the Resume target; the 15 s grace keeps the last hold state; the most recently used stream decides the hold; "alone" now says what it means 4.4, 4.5
C13 two devices change S or reload the realm by turns minor Fixed: language and S-changing preferences per network, changed only by POST /prefs 4.6, 5.2
C14 subscriptions per realm, used per stream; R.fl claim minor Fixed: a view per stream, records per stream in sub events, merged by key on the page; claim corrected 5.6
C15 caches keyed on the S object minor Fixed: updates apply in place; snapshots make a new S 6.2
C16 ASK and LOCAL swapped for RouteScript minor Fixed: ASK = linkCheck, teCheck, teSlop; teOpt local; after an ask R goes back to the marked object and S.rng and uidN to their values (the S.rng part was found in this revision), while S stays the same object 5.8, 5.9
C17 CONFIRM "run twice" repeats refusals minor Fixed: every double act is preset (SRV_ARM from the args), run once 5.8
C18 messages interleave inside a day minor Fixed: realm list fixed at day start; load/begin/unload wait for dayDone; acts wait for a loading realm 4.2
C19 claiming a phase-1 network can drop another device's progress minor Fixed differently: phase-1 sessions are not claimed at all; they stay phase 1 8
C20 pniAll has no quote check minor Fixed: QUOTE list in T1, pniAll first 5.8, 13
C21 uidN and the save written separately minor Fixed: one envelope per checkpoint 4.6
C22 actions carry no build id minor Fixed: sim on act, ask, vote; 409 {old} 5.2, 10
F1 the CPU claim uses the wrong baseline major Fixed: sections 0 and 12 rewritten with the route-worker baseline; acceptance is a total-CPU measurement at integration; open question 2 0, 12, 13, 14
F2 rendering is the phone's real cost; 1× doubles it vs ½× major Fixed (said plainly in 12). A local render or frame cap is not changed: it would alter the plain build, which must stay as it is; proposed for upstream separately 12
F3 mobile data not shown major Fixed: data in the table; data saver (saver=1, automatic on cellular, a setting); data counter in the session panel; the R-key move is an option if measured 5.5, 5.11, 12
F4 "same day" vs own date major Not changed in the design (own date stays the default); now open question 1, to be answered before T3 persists off 0, 14
F5 track split not parallel major Fixed: T1 delivers mp-sim-acts.js, fixtures with a shape test, a fake engine, beginShow, the harness; the classification test names the act and the file 13
F6 LAN playtest while building major Fixed (already running): pinned checkout at e25f843, port 8090, own data directory; its sessions stay phase 1; not restarted unless asked; integration uses 8091 8, 13
F7 an idle visible tab runs the world forever major Fixed: idle after 10 minutes without input, not active, not in need 4.4
F8 edits to about 25 game files major Fixed: client code in src/game/98-server-play/, left out of plain pages; hooks by rebinding earlier function declarations; the only edits to existing game files are T1's small, behaviour-neutral refactors, two of them srvOn() checks in 99-loop.js 6, 6.1
F9 the server budget leaves out pulls, actions, asks minor Fixed: in the budget; "about 3×" for 12 big watched networks; pulls only when something changed; action limit by worker time; "1 GB and one core per busy 12-player session" 10, 12
F10 checkpoints by session days at 8× minor Fixed: every 60 s of running plus the event triggers 4.6
F11 replay ring minor Cut: every reconnect takes a snapshot 5.10
F12 per-stream rates and merging minor Cut: one cadence per network; the data saver only skips r 5.11
F13 phase-1 migration machinery minor Cut: have=, 409 {upload} and the unclaimed state are gone; phase-1 sessions stay phase 1; open question 4 asks whether any must convert 8, 14
F14 placement, hot reload, flags minor Fixed: pool of 2 by realm count; dev restarts the engine on change; --sim-max-live, 503 busy, --sim-gzip deferred; --sim off added 4.2, 4.9, 13
F15 deployment needs src/ and a rebuild minor Fixed: "pull, then build" documented; on a mismatch phase 1 keeps serving and the log prints the command 4.9
F16 mobile round trip and busy look minor Fixed: a round-trip row with mobile data; the busy look specified; measured from the phone at integration 5.8, 12
F17 speed after an empty session wakes minor Fixed with a default (1×); open question 3 4.5, 14
F18 phone wording and layout minor Fixed: one-line banner on phones; "waiting for 1 more" 6.4
F19 solo networks pruned without notice minor Fixed: the note and the session panel say so 7
F20 operator observability minor Fixed: one log line a minute per live session 4.9