From 8068a45abda0d6e2dc1358116ecfc6b2baf0eb05 Mon Sep 17 00:00:00 2001 From: jvanvik Date: Mon, 9 Nov 2026 22:47:43 +0100 Subject: [PATCH] Plans: the server-run design in the repo, what is left now, and the fork's files - docs/plans/server-run.md: the server-run design, which lived only outside the repo, with a status at the top (T1 and T2 merged, T3, T4 and the integration waiting for the go; the four answers; the questions still open) and a section on what building T2 changed: a checkpoint needs more than route memory (rt carries pt, sl, ord and rk), who a worker exit counts against, the budgets now over, the contract additions, the open path-window question and what the shared calendar changes. The answers are marked where sections 0, 1 and 14 ask; probes are named, not pathed. - docs/plans/next-session.md: rewritten to match main at 3e30621: what is built, the answers, the holds, the nine open questions, what is in progress and next, and only the limitations that still hold. - docs/ARCHITECTURE.md: a table of the fork's own files (build standard, dark mode, IPv4, IPv6-only, express fiber, satellites, multiplayer, server-run play, the session server and the engine), kept apart from upstream's tables so merges stay clean. - docs/MULTIPLAYER.md: server-run play is being built and not switched on. --- docs/ARCHITECTURE.md | 22 + docs/MULTIPLAYER.md | 11 + docs/plans/next-session.md | 190 +++-- docs/plans/server-run.md | 1418 ++++++++++++++++++++++++++++++++++++ 4 files changed, 1578 insertions(+), 63 deletions(-) create mode 100644 docs/plans/server-run.md diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3416923..db08733 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -93,6 +93,28 @@ Development runs on `npm run dev` (assembles the development page on every reque | `scripts/weekly-scenario.js`, `scripts/lib/scenario-bot.js`, `site/scenarios/weekly/` | The weekly scenario generator, its reference player and its output (see below) | | `docs/adr/` | Decisions: GitHub Pages only (0001), one page assembled at build (0002), translations by label (0003), development-only code (0004) | +## This fork's own files + +This copy adds features upstream does not have. They follow the same rules as the rest of `src/`, and are listed here +apart so that upstream's tables above merge cleanly. The multiplayer server is for self-hosted copies only: a plain +build stays the static page described above. + +| Path | What it is | +| --- | --- | +| `src/game/60-features/96-pop-standard.js` (grown from upstream's POP standard), `src/game/90-actions/88-build-standard.js`, `src/game/93-ui/59-build-standard.js` | The build standard: one target for every POP, port and fiber (`BSTD`, saved sparse in `S.popStd`), what is below it and what bringing it up costs (`bstdPlan()`, `bstdQuote()`), the sheet, "Bring everything up now" (`bstdApply`) and the intern's "Keep to the build standard" order (`std`, in `95-standing-orders.js`). The router model and the line system are picked here and nowhere else | +| `src/game/93-ui/15-theme.js`, `src/styles/05-theme.css`, `src/game/96-map/15-palette.js` | Dark mode (#80): Light, Dark or Auto per device (`sot-theme`), set on `` before the first paint; the panels' dark colours as CSS custom properties; the map's colours per theme | +| `src/game/60-features/33-address-space.js`, `src/game/90-actions/54-address-space.js`, `src/game/94-dashboard/72-address-space.js` | IPv4 address space (#150): blocks held, bought, leased in and leased out (`S.ip4`), customers' blocks, CGNAT and its ratio; the bank's Address space section | +| `src/game/60-features/34-ipv6-only.js`, `src/game/90-actions/55-ipv6-only.js` | IPv6-only broadband: a city's home routers swapped for 464XLAT, and the NAT64 pool next to CGNAT | +| `src/game/80-simulation/65-express.js`, `src/game/90-actions/87-express.js`, `src/game/93-ui/72-express.js`, `src/game/96-map/51-express-geometry.js` | Express lightpaths (#58): a link of kind `xp` from A to C over a chain of ROADM fibers, passing the cities between as light; its rules, actions, panels, the link window's Express tab, and how the map draws it | +| `src/game/10-catalog/75-satellites.js`, `src/game/60-features/45-teleports.js`, `src/game/90-actions/87-teleports.js`, `src/game/93-ui/72-teleport-panels.js` | Satellites (#83): teleports at POPs (`p.tele`) and rented GEO and MEO circuits (links of kind `sat`): the birds and their reach, the rules and money, the actions and the panels | +| `src/game/60-features/89-multiplayer.js`, `src/game/95-modals/48-multiplayer.js`, `src/game/90-actions/92-multiplayer.js`, `src/styles/41-multiplayer.css` | Multiplayer, only in a copy built with `MP_API` ([MULTIPLAYER.md](MULTIPLAYER.md)): `S.mp`, saves and cards sent to the session server, the `#mp=` link; the title screen's door, the session panel and the HUD chip; `srvOn()`, false until server-run play is switched on | +| `src/game/98-server-play/`, `src/styles/43-server-play.css` | The page's side of server-run play (T4), only in a multiplayer build's page; a comment so far ([plans/server-run.md](plans/server-run.md)) | +| `scripts/mp-server.js`, `scripts/lib/mp.js` | The multiplayer session server: the command line and the built site, and the API with its storage. `npm run dev -- --mp` mounts the API in the development server | +| `scripts/lib/mp-sim-acts.js` | Server-run play's act tables (SEND, ASK, VOTE, LOCAL, CONFIRM, DRAFTS, TEXT, WINDOWS…) and the envelope check every request passes | +| `scripts/lib/mp-sim-engine.js`, `scripts/lib/mp-sim-worker.js`, `scripts/lib/mp-sim-realm.js` | The server-run engine (merged, not wired in yet): worker threads, each holding a vm realm per network that runs the plain page's game, behind the promise API the session host will use ([plans/server-run.md](plans/server-run.md)) | +| `tests/lib/mp-sim-*.js`, `tests/fixtures/mp-sim/` | Server-run play's contracts for the tests: the shape checker, the fake engine, the fixtures and their generator, the button crawl, and the player that plays a realm against a page | +| `docs/plans/next-session.md`, `server-run.md`, `multiplayer-phase2.md` | What is left and what waits for a decision; the server-run design and its status; the phase 2 design (on hold) | + ## Globals - **`S`**: the whole saved game (one JSON object). Cash, day, POPs, links, transit, diff --git a/docs/MULTIPLAYER.md b/docs/MULTIPLAYER.md index 37adcc3..db9ae2d 100644 --- a/docs/MULTIPLAYER.md +++ b/docs/MULTIPLAYER.md @@ -38,6 +38,14 @@ is switched on only when the build is told where the session server lives. Not yet (phase 2): peering, transit and competition between players inside the simulation. The card already carries what that will need (POPs, links, exchanges, transit, peering policy, reach). +## Being built: the server runs the game + +Work has started on server-run play. In a multiplayer build, the session server will run every network's days, so all +players of a session share one calendar and one speed, and the page will only show the network and send the player's +clicks. The engine that runs networks on the server is in the source (`scripts/lib/mp-sim-*.js`), but nothing uses it +yet and it is not switched on: sessions work exactly as this page describes, with each network simulated in its own +player's browser. The design and how far it has got are in [plans/server-run.md](plans/server-run.md). + ## Build ```bash @@ -209,3 +217,6 @@ Cards are what each player's browser says: nothing on the server checks that a n `src/game/95-modals/48-multiplayer.js` (door, sheets, panel, chip), `src/game/90-actions/92-multiplayer.js` (actions), `src/styles/41-multiplayer.css`. The build stamps `MP_API` into `src/game/00-core/20-analytics.js`. - Tests: `tests/mp-server.test.js`, `tests/multiplayer.test.js`. +- Server-run play (being built, not switched on): the act tables `scripts/lib/mp-sim-acts.js`, the engine + `scripts/lib/mp-sim-engine.js`, `mp-sim-worker.js` and `mp-sim-realm.js`, the page's side `src/game/98-server-play/` + (a comment so far), and the tests `tests/mp-sim-*.test.js` and `tests/server-sim-prereqs.test.js`. diff --git a/docs/plans/next-session.md b/docs/plans/next-session.md index 4f100dc..d1228d9 100644 --- a/docs/plans/next-session.md +++ b/docs/plans/next-session.md @@ -1,75 +1,139 @@ -# What is left (as of 2026-11-07) +# What is left (as of 2026-11-09) -Work in this fork, pushed to the `vanvik` Forgejo remote (never to `origin`). Built so far: the build standard (the only -place for the router model and line system), multiplayer phase 1, dark mode (#80), IPv4 address space (#150) with -IPv6-only broadband and NAT64, express fiber (#58) and satellite teleports (#83). Everything below is planned or known, -not built. Items 5 and 6 wait for the owner's go. +Work in this fork, pushed to the `vanvik` Forgejo remote (never to `origin`). `main` is at 3e30621. Nothing below is +switched on or built unless it says so. -## Promised and not done yet +## Built so far -1. and 2. are built: the router model and the line system are picked in the Build standard sheet only (the `routers` and - `optup` orders read `bstd().g` / `bstd().sys`; sanitize moves an old setting into `S.popStd`), and `std` takes a fiber - dark on `optup`'s routing test (`opsDark()`), sharing its budget a night, with one owner per fiber a shift (`X.fib`). +On top of upstream, merged up to 3.3.0 (61e31c5 "Merge upstream: Lambda Bazaar, traffic badges, moving customers and +faster routing (3.3.0)"; earlier merges 032470f and 4b922ab): +- **Build standard**: 2b48a6a "A build standard for the whole network, kept by the intern", and fbae6fc "The build + standard owns the router model and the line system; one owner per fiber" (the router model and line system are + picked in the sheet only; the `routers` and `optup` orders read them from there). +- **Multiplayer phase 1** for self-hosted copies: 95aa9b6 "Multiplayer for self-hosted copies: sessions, server-side + saves, a leaderboard" (`docs/MULTIPLAYER.md`). +- **Dark mode (#80)**: 2cd6b71 "Dark mode: Light, Dark or Auto under Settings › Theme". +- **IPv4 address space (#150)**: eac0604 "IPv4 address space: scarce, bought, leased, leased out; IPv6 is free", and + 69328ce "IPv6-only broadband: 464XLAT city by city, a NAT64 pool next to CGNAT". +- **Express fiber (#58)**: 8e1f2d6 "Express fiber: light a wave through a city without its router". +- **Satellite teleports (#83)**: e1ae8e0 "Satellite teleports: GEO and MEO circuits for islands and remote towns". +- A fix after the 3.1.0 merge: e8808f6 "The connections list no longer breaks on a 400G fabric port". +- **Server-run play, parts 1 and 2** (merged, not switched on): T1 is d1e127d "Server-run play, part 1: game + prerequisites and shared contracts". T2 is 065c922 "Server-run play, part 2: the engine" with its fixes c5c7ea9, + 72f31e8, 3b8c331, 9597d89, 77f4035 and 3e30621. The design, its status and what building T2 changed in it are in + `docs/plans/server-run.md`. -## Next features +## The user's answers (2026-11-09) -3. **The server runs every game of a multiplayer build** (decided 2026-11-07, being designed and built). In a page built - with `MP_API`, each network's days run on the session server, not in the browser, so every player of a session is on - the same day at the same speed. A single-player game in that build is a session of one and runs there too; old local - saves keep working in the browser, and the plain build stays exactly as it is (static, no server, no requests). - - **Speed:** 1× by default (one day per `DAY_MS`, 2.5 s). Players vote for another speed, pause included; alone in a - session your vote decides at once. The world pauses while no player is connected. - - **Absent players:** while anyone plays, the networks of those away keep running on the server (their intern's - standing orders help), so nobody falls behind. - - **Why:** the same day for everyone, which phase 2's trades need, and less work for phones at higher speeds (at 1× the - day is about 10–15% of a phone's CPU on the big test network, at 8× about half; map and panels stay in the browser). - - **What stays in the browser:** map drawing and panels. The flow tables (`R.ef`/`R.fl`, about 3 MB per routing on the - big network) cannot be shipped every day, so what reads them (a selected link on the map, the link panel, PNI value, - puzzles) has to ask for them. - - **Phase 2 gets simpler:** with every world in one server process, its wall-clock timing (tenders that close after 10 - real minutes, `idle` ≥ 300 s, notice on each player's own clock) can move to game days. -4. **IPv6-only broadband, the follow-up** (after the server-run game, or alongside it: it touches the build standard and - the intern, not the server). A build-standard row "Broadband: IPv6-only" (cities with broadband start the swap) and the - intern's `std` order rolling it out when there is money, busiest CGNAT cities first. `ip6Go`/`ip6Stop` and the city - panel are in `src/game/60-features/34-ipv6-only.js`; the row goes into `BSTD` and `bstdPlan` (96-pop-standard.js). -5. **Wave B: #97 co-op companies** (several players run one network with roles, budgets and approvals), host-authoritative - over the multiplayer server, and **multiplayer phase 2** (players as carriers in each other's simulations: transit, - peering, PNIs, shared fiber): design in `docs/plans/multiplayer-phase2.md`. -6. **Wave C: #144 directional traffic**, last and on its own: keep the totals, split them by traffic profile, utilization is - the busier direction. It comes after #58 because both touch link capacity (express channels now count too). +The four questions of the server-run design: +1. A player who joins an old session starts on the **session's date**: one shared calendar. The game's day-0 rules + then have to count from each network's own start (`server-run.md`, "What Q1 changes"). +2. Single player in a multiplayer build runs **on the server** by default; "this device" stays an option. +3. An empty session that wakes runs at **1×**. +4. Phase-1 sessions **start fresh**: nothing is migrated. + +## On hold until the user says go + +- **#97 co-op companies** (several players run one network, with roles, budgets and approvals). +- **Multiplayer phase 2** (players as carriers in each other's simulations: transit, peering, PNIs, shared fiber): + design in `docs/plans/multiplayer-phase2.md`. When it restarts, that design needs rework for the shared server clock: + it assumes each player's own clock, and tenders and notice timed in real minutes. +- **#144 directional traffic**, last and on its own: keep the totals, split them by traffic profile, utilization is the + busier direction. It comes after #58 because both touch link capacity (express channels count too). + +## Open questions waiting for the user + +Asked on 2026-11-09, not answered yet: +1. **Late joiners' prices and beginner grace.** With one calendar, a friend who joins an old session meets its economy + from day one: at day 1868, hardware about 18% dearer and customer prices about 34% lower, with the 180-day beginner + grace long over. Keep that, or give a grace or extra starting cash counted from the joiner's own start? +2. **Other players' POPs on the map.** Draw other players' POPs and links on your map (from their cards) as part of + the server-run work, or wait for phase 2? +3. **The other modes in a multiplayer build.** Sandbox, scenarios, puzzles and the weekly keep running on the device. + Fine, or should sandbox (or all of them) also run on the server? +4. **Dark mode and the build standard upstream.** Upstream contributors have said they will open pull requests for a + dark mode (#80) and a bulk redundancy kit (#317), and a three-tier router standard sits on another contributor's + branch (#315). Offer the fork's dark mode and build standard upstream before those land, or keep them fork-only and + settle the clash at the next merge? +5. **#58 whole-fiber splicing.** Is the express lightpath enough, or should a whole fiber pair also splice through a + city (one dark fiber A–C through B, with no ROADM at B)? The issue asks for "waves and/or entire fibers". +6. **#83 WISP zones and a rented LEO tier.** Add island demand pools served remotely on top of the existing island + cities, and a tier between MEO and Pie in the Sky that rents LEO capacity from a partner network? Or are teleports + with GEO and MEO circuits enough? +7. **Investors' cut of IPv4 lease income.** Should investors on a revenue-share loan take their cut of the income from + leasing out IPv4 blocks too? Today they do not (dark fiber sold to customers is in their share). +8. **Founding an exchange on a basic router.** Founding your own exchange gives a 400G port even where the POP's router + only takes 100G, though the shop would not sell that port. Document it as a limitation, block founding until the + router takes 400G, or found at the router's largest port size? (`tests/server-sim-prereqs.test.js` asserts today's + behaviour.) +9. **The six old wip worktrees.** They hold nothing `main` lacks. Delete them and their branches? + +## Next + +- **In progress** (another builder is on these right now): + - the build standard's "Bring everything up now" and the intern follow one rule for fibers that carry sold alien or + managed waves (today the button can take such a fiber dark for a day, while the intern refuses any fiber with a + customer, leased pairs and IRUs included, which a line-system swap cannot hurt); + - dark mode: the capacity market's hot and cool tags, and red `--bad` text that is below AA contrast on dark cards; + - IPv4 notices in the notification log get their "Address space" button; + - the "no subsea cable lands here" hint (#321) mentions a satellite circuit where a teleport can reach the city; + - express fiber: a regen site added later charges for the express channels on its fiber, and loss incidents on a + fiber reach the expresses on it; + - selective peers react to peering that rides a GEO link; + - the intern's two small standing-orders fixes in `opsRun()` (the shift's log keeps an uncapped list of broken + orders, and the week's tally makes an empty list of places for a job that names none); `opsTidy()` stays after the + shift until `tests/canonical-state.test.js` passes without it; + - IPv6-only broadband in the build standard: a "Broadband: IPv6-only" row, with the intern's `std` order rolling it + out busiest CGNAT cities first (`ip6Go`/`ip6Stop` are in `src/game/90-actions/55-ipv6-only.js`, the panel and day + logic in `src/game/60-features/34-ipv6-only.js`; the row goes into `BSTD` and `bstdPlan` in + `src/game/60-features/96-pop-standard.js`). +- **After the user's go:** T3 (host and protocol), T4 (the browser client) and the integration of server-run play, + as `docs/plans/server-run.md` describes them, with the corrections at its top. That includes the Q1 work: the game's + `S.day0` and day-0 rules, a start day for a new network on the server, and `CLOCK.off` taken out of the contract. ## Known limitations of what shipped -- **Multiplayer:** other players' POPs are not drawn on the map (no clean hook yet); cards are what each browser reports, - the server does not verify them; a save over ~60 KB sends only the card when the tab closes; the HUD chip in phone - landscape wider than 760 px was not measured. Behind a reverse proxy, run the server with `--trust-proxy`, or every - player shares one address for the rate limits. -- **Build standard:** the game menu has 8 tiles in a multiplayer game (7 otherwise), so the last row is not full. The - sheet's quote and "Bring everything up now" still judge a line-system swap without routing (`bstdDarkOk()`: a quiet - fiber, under 10% of its capacity, or a parallel link with room; any express with traffic holds its fibers, - `bstdXpBusy()`), so the quote is the bill; only the intern routes to test. A quiet fiber with no way around can still - go dark from the button. An old save's `routers.model` moved into the standard (only from a running order with an - intern hired; a paused one's is dropped) also becomes what new POPs get. A model or line system in the standard is a - ceiling for the `routers` and `optup` orders (their next-one-up rule only applies with "keep"), as an order's own - model was before; `optup` has no per-POP exceptions, so it moves fiber at POPs excepted from `std` too. -- **Dark mode (#80):** red error text on dark tinted cards is about 3.8–4.3:1 (bold, but below AA 4.5); the share card PNG - and the web manifest stay light; the WebGL map was checked by tests only, not by eye in a real GPU browser. -- **IPv4 (#150):** the intern does not manage addresses (optional in the issue); transfers are instant; lease-out income - is not in the investor revenue share; blocks granted to old saves can be sold after two years (a one-off windfall); - CGNAT annoyance costs refunds but does not slow broadband growth; the NOC window's address-space button does nothing. -- **IPv6-only broadband:** no one-off grumble while a city's home routers are swapped; the swap and the NAT64 ratio are - not in the build standard or the intern's orders yet (item 4); a new home in an IPv6-only city pays its router even - when cash is short (a running cost, so a finished city never looks like a stopped swap). -- **Express fiber (#58):** splicing a whole fiber pair through a city was left out on purpose (every fiber end is a POP; - expresses cover the need); loss and MTU incidents on a fiber do not reduce the expresses on it; the fiber panel's - "n of max channels" line does not count express slots (the Express section does); regen sites added later do not charge - regen cards for express channels. -- **Satellites (#83):** no WISP zones, no satellite incidents (rain fade, sun outage), no footprints on the map, no - satellite tab in the drag-to-link window (ordering is from the city panel); GEO/MEO losses and prices are design - numbers; well-cabled islands (Wellington, Hobart) also count as "can be served"; MEO needs 5° elevation (10° would drop - 416 pairs); Pitcairn's $120k satellite grant stays Pie-only. +- **Multiplayer (phase 1):** each browser runs its own clock, so the players' worlds drift apart (server-run play fixes + this for new sessions only); other players' POPs are not drawn on the map (open question 2); cards are what each + browser reports, and the server does not check them; a save over ~60 KB sends only the card when the tab closes, and + the save goes with that device's next push; a session network still makes its save on the page, so it misses 3.3.0's + smoother saves in the worker; the capacity market and path moves are each player's own, with no market shared + between players; the HUD chip in phone landscape wider than 760 px has not been checked by eye (worth doing when T4 + changes the chip). Behind a reverse proxy, run the server with `--trust-proxy`, or every player shares one address's + rate limits. +- **Server-run engine (merged, not switched on):** a checkpoint is over its size budget, and so are a snapshot, a big + realm's memory and a small network's day; a checkpoint written before c5c7ea9 restores close to exact, not exact; the + engine has no per-call deadline of its own; a worker of its own whose session's loads all fail stays idle until the + next unload; the path window would read routes the page never gets (`server-run.md`, "Corrections from building + T2"). +- **Build standard:** the game menu's last row of tiles is not full (7 tiles, or 8 in a multiplayer game, in rows of + 3). The sheet's quote and "Bring everything up now" judge a line-system swap without routing (`bstdDarkOk()`: a + quiet fiber, under 10% of its capacity, or a parallel link with room; any express with traffic holds its fibers, + `bstdXpBusy()`), so the quote is the bill; only the intern routes to test. A quiet fiber with no way around can + still go dark from the button for a day. An old save's `routers.model` moved into the standard (only from a running + order with an intern hired; a paused one's is dropped) also becomes what new POPs get. A model or line system in the + standard is a ceiling for the `routers` and `optup` orders (their next-one-up rule only applies with "keep"), as an + order's own model was before; `optup` has no per-POP exceptions, so it moves fiber at POPs excepted from `std` too. +- **Dark mode (#80):** the share card PNG and the web manifest stay light; the WebGL map was checked by tests only, not + by eye in a real GPU browser. +- **IPv4 (#150):** the intern does not manage addresses (optional in the issue); transfers are instant (real ones take + weeks); lease-out income is not in the investor revenue share (open question 7); blocks granted to old saves can be + sold after two years (a one-off windfall); CGNAT annoyance costs refunds but does not slow broadband growth. +- **IPv6-only broadband:** no one-off grumble while a city's home routers are swapped; a new home in an IPv6-only city + pays its router even when cash is short (a running cost, so a finished city never looks like a stopped swap). +- **Express fiber (#58):** a whole fiber pair does not splice through a city (every fiber end is a POP; expresses + cover the need; open question 5). +- **Satellites (#83):** no WISP zones and no rented LEO tier (open question 6); the rented GEO and MEO circuits never + fail (no rain fade or sun outage; Pie in the Sky has its own); no island volcano or Caribbean and Pacific hurricane + events; no "Island Hopper" scenario; no footprints on the map; no satellite tab in the drag-to-link window (ordering + is from the city panel); GEO/MEO losses and prices are design numbers; well-cabled islands (Wellington, Hobart) also + count as "can be served"; MEO needs 5° elevation (10° would drop 416 pairs); Pitcairn's $120k satellite grant stays + Pie-only. ## Housekeeping - `npm run perf -- --browser` runs with `PERF_CHROME=/usr/bin/chromium`. -- The merged worktrees under `.claude/worktrees/` and their `worktree-wf_*` branches can be removed. +- The phase-1 playtest on port 8090 runs from its own checkout outside the repo, with its data in + `mp-data/playtest`: leave it alone unless the user asks. Its one session can go once a server-run build replaces it + (answer 4). +- The six old wip worktrees under `.claude/worktrees/` wait for the user's answer (open question 9). diff --git a/docs/plans/server-run.md b/docs/plans/server-run.md new file mode 100644 index 0000000..5b270cd --- /dev/null +++ b/docs/plans/server-run.md @@ -0,0 +1,1418 @@ +# 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? +- 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: +- **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 +`