diff --git a/.claude/skills/edit-the-game/SKILL.md b/.claude/skills/edit-the-game/SKILL.md index bfacf0e..aca2564 100644 --- a/.claude/skills/edit-the-game/SKILL.md +++ b/.claude/skills/edit-the-game/SKILL.md @@ -14,6 +14,7 @@ load, so splitting code across files costs nothing at runtime. Why it works this src/index.html the shell: , static markup, ``, `` src/styles/NN-*.css CSS, in order (phones last) src/game/NN-area/NN-*.js the game script, in order (see the map in docs/ARCHITECTURE.md) +src/agent/NN-*.js the agent facade the MCP server drives: in the development page only site/ static files copied as they are (dictionaries, icons, service worker) ``` @@ -34,7 +35,8 @@ npm test -- tests/peering.test.js # one suite ``` A browser error points at a line of the assembled page; the dev server prints the `src/` file and line -next to it. `npm run page -- -o /tmp/page.html` writes the assembled page if you want to look at it. +next to it. `npm run page -- -o /tmp/page.html` writes the page players get if you want to look at it; +`npm run page -- --source --dev -o /tmp/page.html` the development page `npm run dev` serves. ## Where new code goes @@ -47,7 +49,17 @@ next to it. `npm run page -- -o /tmp/page.html` writes the assembled page if you anything runs after boot. When in doubt, put constants in an earlier file and logic in functions. - **Actions:** add `name:(args)=>{…},` to the matching `src/game/90-actions/*.js`. Only `10-interface.js` declares `const ACT={`; the others are `Object.assign(ACT,{ … });`. A new area can get - a new `NN-area.js` file of that second form. + a new `NN-area.js` file of that second form. The MCP server types every action: a new one also gets + an entry in `src/agent/20-commands.js` (a game command with its argument domains, a view, a draft, + a session action, or `API_DENY`); `tests/mcp-commands.test.js` fails until it has one. +- **Agent code** (`src/agent/`, the facade the MCP server plays through) is assembled into the + development page only (``): players never download it. Its top-level names + start with `api`/`API_`, and **nothing in `src/game/` may name them**: that would work in `npm run dev` + and break for players (`tests/build.test.js` checks). Tests load the players' page; a test of the + facade asks for `load({ agent: true })`. Where agent code must change what the game does (agent mode + locks the clock, adds a Settings section and a HUD badge), the game calls `HOOKS.x?.()` and reads + `UI.clockLocked` (`50-state.js`), and agent code fills them in: add a hook there rather than an `if` for + the agent in a game file. See docs/adr/0004-dev-only-code.md. - **Panels and modals:** `93-ui/` (HUD, side panels), `94-dashboard/` (NOC dashboard, bank), `95-modals/`. - **Styles:** the matching `src/styles/*.css`; phone rules go in `60-phone.css`. - **Data tables** (cities, cables, networks): one entry per line, and keep id-keyed objects such as diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md new file mode 100644 index 0000000..a5de18c --- /dev/null +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -0,0 +1,102 @@ +--- +name: gameplay-rules +description: The design rules of Series of Tubes, each with an id and the test that enforces it. Use whenever you add or change cities, countries, networks (NETS, upstreams, traffic shares, presence), cables, exchanges, data centers, customers, scenarios, puzzles, presets or rules, balance numbers or progression, and before committing any such change. +--- + +# Gameplay rules + +These are what the game promises, held up by `tests/gameplay-rules.test.js` (one `test()` per id, on the live +`CITIES`, `NETS`, `CABLES`, `SCN`, `PZ`, `PRESETS`…). Each rule is true of the intended design. + +## Procedure + +1. Changing anything above? Run `npm test -- tests/gameplay-rules.test.js` (under a minute) before committing. + Changing orbit prices, crusts, incidents or orbit customers? Also run `npm test -- tests/pie-balance.test.js` (O7's + game-loop half, about a minute). +2. A failure names what breaks the rule and how to fix it. Fix the data or the code. +3. Only when real life really is different, add an entry to `EXCEPTIONS` in the test (keyed by rule id, sorted, with + its reason in plain words). Never delete or loosen a check to make it pass. A stale exception fails too. +4. A new rule gets an id in the right section here, one line, a why, and its own `test('ID: …')`. + +## World + +| Id | Rule | Why | +| --- | --- | --- | +| W1 | Every city has a country code (`cc`, ISO 3166-1 alpha-2; territories have their own: PR, GU, RE, MQ, CW…), a region, a landmass and coordinates. | Borders, prices and the eyeball rule all hang off the country. | +| W2 | Every country on the map has at least two consumer networks of its own: an eyeball network, or a Tier 1 or Tier 2 incumbent that sells to homes, whose home markets (`cc` on the network) include that country and which has a PoP there. | Real countries have competing local ISPs, and peering locally is half the game. Add real operators in `src/game/30-networks/32-homegrown-eyeballs.js`. | +| W3 | Every city can buy transit from someone, or is a documented exception (Pitcairn: land your own cable, reach it through a pie dish, or rent a satellite circuit from a teleport; Stuttgart: peering only). | A start or an expansion must never be a dead end by accident. | +| W4 | Cable pairs join two distinct real cities, have a length, and cable ids are unique. | Broken landings break routing and the own-cable planner. | +| W5 | A city alone on its landmass has a cable or a beach to land one. | Islands are reachable. | +| W6 | Every island Wi-Fi zone (`WISP`, #83) hangs off a satellite city (`satRemote`) within 1,000 km of it, seen together with it by a GEO bird; its pool is 3 to 12 G of homes; its spur is at most 1,500 km, or there is none (`km:0`); ids are sorted. | A zone is the outer islands of the city they look to, reachable from the first teleport; smaller ones never pay, and pie terminals serve them. | + +## Networks + +| Id | Rule | Why | +| --- | --- | --- | +| N1 | Network ids and ASNs are unique; ASNs are public (the real one for real-world networks). | Saves key on ids; players look ASNs up. | +| N2 | Names are puns: no network, cable, exchange, data center, router, optic, satellite or satellite operator, cable ship or maintenance club is called by a real name (blocklist `REAL_NAMES` in the test), and no lazy "-ish" names. | CLAUDE.md. Add the real name to the blocklist whenever you add its pun. | +| N3 | Every non-Tier-1, non-content network is in a founding Tier 1's customer cone (`up`), or is a documented island (transit-free incumbents, China, Korea, Australia…). Upstreams exist and are never content. | Tier 1 by customer cone (#85): a new network outside the cones makes Tier 1 harder for every save, old ones included. | +| N4 | No upstream cycles. | Cones must be trees, not loops. | +| N5 | Traffic shares are positive and below 20%; `NSH` and the regional tables sum to 1; content carries at least 30%. | Shares drive every flow; eyeballs mostly ask for traffic. | +| N6 | Every network has a type, a peering policy (selective ones state `minIx`/`minPni`), a colour and a translated blurb; carriers have a price. | Panels and the peering rules read them. | +| N7 | PoPs are real, distinct cities; exchange ports only where the city has an exchange and the network has a PoP. | Presence follows PeeringDB-style reality. | +| N8 | A POP's traffic to the networks that sell to homes (`cc`) goes mostly to those whose users live near it: at home above the world share, on other continents below (`locSh()`, `45-home-markets.js`). Only that split moves: a city's total and every network without home markets keep their shares. | People mostly talk to people near them, and peering with an eyeball where its users are must beat hauling its traffic to two cities (#48). | + +## Modes and rules + +| Id | Rule | Why | +| --- | --- | --- | +| M1 | On-call is the classic game: it equals `RULE_DEF`, and a save without rules loads as On-call. The seeded suites (`tests/game.test.js`, `tests/rules.test.js`) are its behaviour. | Old saves never change under them. | +| M2 | Presets are ordered: Best Effort never harsher than Change Freeze, Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market; and a seeded year of incidents). Only Best Effort mends sea cuts without ships, skips conferences, rescues instead of game over, has patient customers and instant PNIs. | The names promise it. | +| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, sold-out routes, de-peering and hardware prices (`market`), lead times (`lead`), the clock, cable ships (`sea`), conferences (`confs`), going broke (`broke`), customer patience (`moods`), PNI delivery (`pnis`), scarce IPv4, CGNAT and IPv6-only homes behind NAT64 (`ip4`, On-call and BGP at 3 a.m. only; scenarios opt in), and the day's toasts (quiet notifications). A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. | +| M4 | Scenarios and the weekly challenge always run On-call plus their own `S.scn.rules`. | Fair scores. | +| M5 | Sandbox has no locked feature: open gates, every level, own cables, endless money. | It is a sandbox. | +| M6 | A Normal game picks its charter once, when it starts (sandbox, puzzles and scenarios never do). A charter changes what you set out to do, never what things cost: the Cable broker gets glass (fiber, line systems, optics, own subsea cables and the routers to light them) from day one at the prices everyone pays at the top level, and everything else by level. | Same prices and rules for every charter (#300). | + +## Content + +| Id | Rule | Why | +| --- | --- | --- | +| C1 | Every scenario has a name, a goal, an `ok()` its progress card (`SCN_PROG`) shows, and cannot be won on day 0; so does every committed weekly scenario (`site/scenarios/weekly/`, its goal type's card in `WS_GOALS`). | A goal must need play. | +| C2 | Every puzzle has a 1-star and a 3-star reference solution in `REF` of `tests/puzzles.test.js`, which builds and scores them. | Every puzzle is solvable and every star reachable. | +| C3 | Every player-facing string is translated in every language (`node scripts/i18n-check.js`: 0 missing, 0 unused, 0 broken). | CLAUDE.md; see `add-strings`. | +| C4 | Every Architect run, handmade (`REF` in `tests/architect.test.js`) or weekly (`ref` in its file, `scripts/weekly-architect.js --check`), has a reference build that passes every brief's chaos monkey review and earns three stars; every weekly brief takes at least one change (a tube, a bigger tube, a move), and later briefs' cities stay hidden until they come. | A run you cannot finish, or a brief that asks for nothing, is not a puzzle; knowing the next brief makes it a chore. | + +## Fun and fairness + +| Id | Rule | Why | +| --- | --- | --- | +| F1 | A new network gets a gentle start (counted from the network's own first day; hardware prices hold for the calendar's first 180 days, see F11): no outage before day 45, no event before day 40 and only good news before day 50, nothing sold out for 90 days, hardware prices hold for 180, and a new customer loses no mood for 15 days. Its first IPv4 block covers the start: no home behind CGNAT, no IPv4 bill and no IPv4 warning before day 50, even signing every offer that fits. | New players learn before they get punished. | +| F2 | On On-call, a simple build in a start city (broadband, the cheapest 100G transit, an exchange port with the route server) makes money within 3 months, in Frankfurt, New York, Singapore and Johannesburg. | Seeded today it turns a profit in month 1 or 2; a balance change that breaks this makes the start too hard. | +| F3 | A specialist path (#187) only brings a customer type in below its level when the network can already serve it, or nearly: the spotted cities have POPs, the latency is met, the fiber carries at least three quarters of the smallest order. | Capability, not luck: an offer you cannot fulfil with a reasonable build is a trap. | +| F4 | The chaos monkey visits only On-call and BGP at 3 a.m. (never Change Freeze, Sandbox, puzzles or scenarios), not before day 180, for 120 to 240 days; while it is here its snips replace the ordinary failures, each snip heals within a week, and it goes after tubes with no other way round first. | A test of resilience you can prepare for, not a pile-on: the reward goes to networks built with a second path. | +| F5 | Capacity you rent to other carriers never outgrows the route's market: the capacity market sells a listing over time as carriers between the two cities want it, never past what they want that day (both cities' eyeballs, a landing town counting the big city it serves, grown about 15% a year up to 8 times, and at most 2.5 times its usual size on its hottest day), and a random offer never past what the eyeballs alone support. | Rent that scales with your own glass and not with demand is a money machine (#203); a market that never moves or grows makes no decisions. | +| F6 | An alien wave rents for at most 30% of what its fiber costs a month (lease plus amplifiers), each wave sold between two cities is never dearer than the one before, and a route sold out to its market earns less than eight times that cost. | A buyer would lease the fiber rather than pay many times its price; the old price made one wave worth the whole fiber and a full route 11 to 35 times its lease (#203). | +| F7 | Extra crews cut a build on land to half its planned time at most. | Permits, rights of way and trenching set the pace; a 1,000-day build finishing tomorrow made lead times meaningless (#203). | +| F8 | In the capacity market (Lambda Bazaar), a managed wave comes out of capacity you lit yourself (your own traffic gets that much less, and the customer suffers when your optics cannot carry it), rides one channel (an 800G or 1.6T wave needs an optic that big), and is priced against its fiber: a 400G wave 2.7 times a 100G one on land and 3.8 times on subsea, each bigger size cheaper per bit. Spectrum lists at 30% of the fiber's monthly cost, and heat moves any price by at most −30% to +35%. | Selling lit capacity must cost capacity, or every fiber sells twice; the ratios are 2025 market prices (TeleGeography), so bigger waves win on volume, not on price per bit. | +| F9 | A strict latency contract (`BIZ_T.lowlat`, #137) comes only from customer level 7, is 1.6T or 3.2T and never grows past 3.2T, has a latency limit something you can build meets (`latMaxOf`, as trading links), pays more per Gbps than any other big circuit on the same route even with all their extras, and once its 15-day grace is over credits a day's fee and loses patience faster for every day over its limit. | Real low-latency routes sell at a premium for guaranteed milliseconds and pay service credits when they miss; the cap keeps one contract from carrying a level. | +| F10 | Growth goes sideways, plus one paid way up: a PNI bundles eight members per router at its POP, up to 32 (`pniLagMax()`); transit, exchange and fabric LAGs stay at eight (`LAG_MAX`). Giant AI circuits land at campuses (`MEGA`) in at least 30 metros, no metro more than two, picked less often where giant circuits already crowd the city. | Raising caps only moves the wall; a fatter PNI costs a router (its price and its port slots), and the late game's demand spreads over many metros as real AI and cloud campuses do (#61, #323). | +| F11 | A network that joins a server session after its first 180 days starts on the session's date with F1's gentle start, the charter and the tutorial counted from its own first day, a starting-cash top-up as large as the rise in hardware prices (START_CASH × (hwTrend − 1), at most $60k), and its first 365 days of home broadband income matched (after wholesale cuts, outside investors' share); the market stays on the session's date. | One market for everyone, and a friend who joins late still gets a fair start. | +| F12 | Island Wi-Fi (#83), on a zone's own books at full take-up in era 1 (its homes at island prices less the towers' upkeep and the backhaul rent; the teleport, tracking antennas and a Starblink gateway are shared and left out), makes money on at least one way in; a spur earns more than any satellite option, MEO at least as much as GEO and LEO at least as much as MEO where both reach; spurs up to 250 km pay back within 5 years against the best GEO or MEO stage, up to 1,000 km within 10. | The ladder (GEO, then MEO or LEO, then your own cable) must be worth climbing, and its first rung must not lose money; the longest spurs are a choice, not a given. | + +## DDoS + +| Id | Rule | Why | +| --- | --- | --- | +| D1 | Attack sizes come from the world, never from your network: a heavy tail (median near 9 G, one in a hundred over 650 G) scaled by the era, capped at the era's record, and for the first 180 days (or with one POP) never more than twice your biggest port. Ten times the subscribers means the same attacks. | Sizes that grew with the network made every late-game flood larger than the internet's record (#242). | +| D2 | A flood enters on every port the internet reaches you on, by each network's share, and a port carries only what fits: everyone on a full port loses the same share. | Real floods are spread by geography; one fat port at a single POP is the weak spot (#242). | +| D3 | Only upstream tools (RTBH, clean pipe) and an engaged scrubbing center keep a flood off your ports. Flowspec acts on the ingress router, after the port, within that router's own rule budget. | Flowspec protects customers, not the external connections; TCAM is finite. | +| D4 | RTBH costs only the target: it goes dark (and its mood drops once), everyone else is saved, and the attack counts as sacrificed, not held. | RTBH is the tool that saves the network and is bad for that one customer, so it must be a real choice. | + +## Orbit (Pie in the Sky, `docs/plans/pie-in-the-sky.md`) + +| Id | Rule | Why | +| --- | --- | --- | +| O1 | The rocket company unlocks only on the Tier 1 win of a save started on its version (`S.pieV>=1`, set by `newGame()`; a save without it loads as 0), or from day 0 with open gates (sandbox). Never in puzzles, the Architect or scenarios. Losing Tier 1 keeps everything flying but builds nothing new. | An endgame for people who earned it; old won saves must not change under their players. | +| O2 | A crust under 40% coverage carries nothing; from 40% a half-baked crust carries a share that grows to all of its capacity at 60% (a slope, not a cliff), and orbit never carries more than the pie dishes' antennas (x rain, jamming): terminals and sky paths share each dish. | Satellites are not magic bandwidth; the ground segment is the bottleneck, as in real life. | +| O3 | A cut-off pie dish (its POP on an island the backbone does not reach) carries only its own POP's traffic (backhaul, to a landing dish on the backbone) and local terminals, never transit between other cities: no POP on the backbone routes through it. Backhaul is small (the dish's antennas, the landing dish's and the crust's room) and pays the orbit's latency. | Orbit extends your network to a town no cable reaches; it does not replace building one, and laying fiber stays the real fix. | +| O4 | Through space with lasers, light travels at c in vacuum (about 1.47 times glass), up and down at the shell's height; orbit never carries traffic between cities under 3,000 km apart and only latency-routed circuits fly: IP traffic, bulk and scenic circuits stay on fiber. | Real constellations win only on long routes, and their capacity is small. | +| O5 | Launches fail only with chaos on (`rule('chaos')`), and never in the first 90 days after the unlock; heavy test flights explode by design, not by chance. Orbit incidents and geopolitical spats (`pieChaos()`) follow the same rule. | Like F1: learn the thing before it punishes you. | +| O7 | A fresh Tier 1 cannot afford a full Shortcrust from its first year's money: even a big network's yearly profit plus the largest loan a bank would offer (and the Ex-Im Pie Bank's most) stays below the cheapest full build (`pieFullCost('short')`). And a full lasered Shortcrust, played through the game loop on the big-network save by a sensible policy (reusable rockets, two pads, no launches past the crust's size except replacements, safe mode in storms, dishes grown with demand at well-served POPs, every orbit offer signed), pays back on its own books (`S.pie.book`: every launch, replacement, dish, licence and running cost against orbit income) in 5 to 10 years, never sooner; government money (the Rural Digital Pie Fund, Pitcairn's satellite grant) brings that forward by at most two years, never under four (`tests/pie-balance.test.js`; `PIE_BALANCE_YEARS=10` prints the long run). | Obscenely expensive is the joke and the goal; a constellation in year one would be a cheat code. | +| O8 | Rented LEO (Starblink, #83) reaches only within `SAT_ORB.leo.km` of a gateway under its shell (`SAT_ORB.leo.lat`) at a POP on your fiber (the mainland, or an island with a lit wired link or transit); once a crust of your own carries traffic it sells nothing new (no gateway, circuit or growth), while circuits already rented keep running; and every size costs more per Gbps than any subsea wave over its whole reach. | A bent pipe is regional; the rented tier must not undercut your own constellation; and a cable stays the better buy wherever one can go. | + diff --git a/.claude/skills/github-pages/SKILL.md b/.claude/skills/github-pages/SKILL.md index 3eafcfb..52010f0 100644 --- a/.claude/skills/github-pages/SKILL.md +++ b/.claude/skills/github-pages/SKILL.md @@ -31,6 +31,13 @@ one, redesign the feature. - **Limits:** about 1 GB for the whole site, 100 MB per file. - **Paths:** the site lives at the domain root (`site/CNAME`), so `/` paths are fine; unknown paths get `404.html`. +- **Local tools are not hosting.** `npm run dev` and the MCP server (`npm run mcp`, also over `--http`) + run on a developer's own machine against a checkout; nothing they serve is deployed, and the game + never depends on them. Their code stays out of `_site/` (`src/agent/` is development-only, see + `docs/adr/0004-dev-only-code.md`). +- **The container image is a tool too.** `docker/` packages those tools; `docker.yml` publishes it to GHCR for releases + (version tags only, no `latest`) and never to Pages. Someone may run its development server where they like; that is + not a host of the game, and the game never depends on it. ## How it deploys @@ -40,6 +47,17 @@ publishes the GitHub release and starts `release.yml`: test, `REQUIRE_NOTES=1 np `pages: write`. Pushes to `main` and pull requests build but never deploy. The `release` skill has the steps. +**The one exception: the weekly puzzle.** Every Sunday at 03:37 UTC `weekly-puzzle.yml` commits the new +`site/puzzles/weekly/.json` to `main` (data only, no version bump) and starts `release.yml` for the **live +release tag** with `weekly=true`. That run rebuilds exactly the live release, with every weekly file from `main` +added, checks them with `scripts/weekly-puzzle.js --check`, and deploys it in the same `pages` concurrency group. +Players get no update banner (the version does not change). Every release build also copies all weekly files from +`main`, so a release never drops a published week, and regenerates (in the build, deterministically) any week +not over yet that the release's prices no longer fit. Weekly files are plain JSON the game fetches only when the +Puzzles list opens and never trusts; the service worker serves them network-first. The weekly scenario rides along in +the same run: `scripts/weekly-scenario.js` writes `site/scenarios/weekly/.json` (fetched when the Scenarios list +opens), committed and deployed with the puzzle, never by a second workflow. See `docs/ARCHITECTURE.md`. + ## Before you hand back a change that touches the build, deploy or loading ```bash diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index 79087df..157d3c1 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -5,13 +5,34 @@ description: Cut and ship a Series of Tubes release (patch or minor) from main v # Releasing Series of Tubes -Bumping `version` in `package.json` on `main` is the release button. The -`auto-release.yml` workflow tests, tags `v`, publishes a GitHub release with +Bumping `version` in `package.json` on `main` is the release button. CI tests the push +as usual; when it passes, `auto-release.yml` (which runs after every CI on `main`) sees +the new version, tags `v` on the commit CI tested, publishes a GitHub release with that version's CHANGELOG section as notes, and dispatches `release.yml`, which builds `_site/` (`npm run build`: the page assembled from `src/` plus `site/`) and deploys it to GitHub Pages (https://seriesoftub.es). GitHub Pages is the only host, ever: see the `github-pages` skill. +## Weekly puzzles are not releases + +`weekly-puzzle.yml` publishes a new puzzle every Sunday morning without a release: it commits the JSON under +`site/puzzles/weekly/` to `main` and redeploys the live tag through `release.yml` (`weekly=true`). Never bump the +version for a weekly puzzle. To publish or fix one by hand: `node scripts/weekly-puzzle.js --key 2026-W45 --force`, +`node scripts/weekly-puzzle.js --check`, commit to `main`, then run the "Weekly puzzle" workflow (or +`gh workflow run release.yml --ref -f tag= -f weekly=true`). A release includes every weekly +file on `main` when it builds. + +The weekly scenario (`site/scenarios/weekly/`, `scripts/weekly-scenario.js`) ships in the same run and the same way: +`--key`, `--force` and `--check` work alike. Its `--check` replays each week not over yet with the reference plan in +the file; a new par is just written, a week the reference no longer wins is regenerated with `rev` + 1. + +**Prices change, weeks follow.** `--check` re-solves every week not over yet with the game it runs; a week whose +budget no longer verifies is regenerated deterministically (the same puzzle with a new budget if that works, else a +fresh one for the same key) with `rev` + 1, which resets players' stars for that week only. Past weeks are left alone +unless the game rejects them. `release.yml` runs it before the tests on every deploy and fails only if a week cannot be +regenerated. A change to prices, cables or cities fails `npm test` until you run `node scripts/weekly-puzzle.js --check` +and commit the regenerated files with it (and `node scripts/weekly-scenario.js --check` for the scenarios). + ## Only release when Frederic says so Never bump the version on your own. Finished work is committed and pushed with its @@ -45,24 +66,23 @@ gh api repos/fjaeckel/seriesoftubes/releases/latest --jq '.tag_name+" "+.publish ## Steps -1. Make sure `main` is green: `npm test` and `node scripts/i18n-check.js` - ("0 missing, 0 unused, 0 broken"). +1. Don't run the test suite, the game or benchmarks before a release: CI tests the + version bump (a red CI releases nothing), and the Performance workflow benchmarks it. Just + check that the latest CI run on `main` is green (`gh run list --repo fjaeckel/seriesoftubes --limit 4`). 2. In `CHANGELOG.md`, move the bullets from `## [Unreleased]` into a new section right below it: `## [x.y.z] — YYYY-MM-DD` (em dash, today's date). Keep an empty `## [Unreleased]` heading above it. The build fails if the section has no bullets. 3. Bump the version in **both** files: - `package.json` → `"version"` - `package-lock.json` → top-level `"version"` and `packages[""].version` -4. `npm test` once more. - Then compare performance with the previous release and mention anything notable to Frederic: - `npm run perf -- --base-ref v`. +4. (Nothing to run here: the workflow tests the release before it tags it.) 5. Commit on `main` as Frederic, with no attribution trailers: ```bash git -c user.name="Frederic Jung" -c user.email="frederic@jc-ix.net" commit \ --author="Frederic Jung " -m "Short summary (x.y.z)" git push origin main ``` -6. Watch the workflows until both finish: +6. Watch the workflows until all three finish (CI, then Auto-release, then Release to GitHub Pages): ```bash gh run list --repo fjaeckel/seriesoftubes --limit 4 gh run watch --repo fjaeckel/seriesoftubes diff --git a/.claude/skills/write-tests/SKILL.md b/.claude/skills/write-tests/SKILL.md index efe406c..33f7aa9 100644 --- a/.claude/skills/write-tests/SKILL.md +++ b/.claude/skills/write-tests/SKILL.md @@ -7,7 +7,8 @@ description: Write deterministic jsdom tests for Series of Tubes features and fi Tests use `node:test` and `tests/harness.js`, which assembles the game page from `src/` (once per test file) and loads it in jsdom with the animation loop off, a seeded `Math.random` and a recording fake canvas. -Code runs inside the page through `ev()`. +Code runs inside the page through `ev()`. `load()` is the page players get; tests of the agent facade +(`src/agent/`, `window.TUBES`) ask for the development page with `load({ agent: true })`. ## Pattern @@ -44,12 +45,27 @@ pull requests collide. Run one file with `npm test -- tests/route-servers.test.j or set state directly (`S.day=…`, `S.ev.x=…`). - **Force a specific random failure or event** by patching the picker: ```js - ev("eval('('+fireFailure.toString().replace('const e=pick(opts);',\"const e='crash';\")+')')()"); + ev("runNow(eval('('+failureRun.toString().replace('if(only)type=only;',\"type='crash';\")+')')())"); ``` - Check the current source for the exact `pick` line first (`grep -rn "function fireFailure" src/game`); it may differ. + `failureRun()` is a generator (its yield is the routing): play it with `runNow()`. Check the current source for the + exact line first (`grep -rn "function\* failureRun" src/game`); it may differ. Or simply `fireFailure('crash')`. - **Drive the game through `ACT`** like a player would, then `compute()` or `dayTick()`. - **Saves:** for persistence changes, round-trip `JSON.stringify(S)` through `parseSave()`/`migrate()`, and test that an *old* save without the new field still loads. - **UI:** render with `renderAll()` and query `dom.window.document`; check phone layouts by setting `window.innerWidth = 390` before rendering. - Run `npm test`; the whole suite must pass, not just the new test. + +## Servers, sockets and anything async + +CI runs four parts at once, each with its files in parallel, so a test can wait seconds for things that take +milliseconds on your machine. Never sleep a fixed time and then assert: wait for the state with `tests/net.js`. + +- `until(() => condition)` resolves true as soon as it holds (false after 20 s); assert on its result. +- `freePort()` asks the OS for a free port; never a fixed or random one. +- `kill(child)` stops a spawned server and resolves once it is gone. +- Listen and connect on `127.0.0.1`, not `localhost` (it can resolve to `::1` only on a CI runner). +- For HTTP to a test server, pass `agent: false`: a kept-alive socket can be reset by the server's idle timer. +- A fixed wait is fine only to prove that something does *not* happen. + +Hunt a suspected flake before pushing: `npm test -- --stress 8 tests/x.test.js` runs 8 copies at once, busier than CI. diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..fbf5463 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +# The image takes only what docker/Dockerfile copies; everything else (git history, tests, docs, local saves, +# node_modules, _site) stays out of the build context. +* +!package.json +!package-lock.json +!src/ +!site/ +!scripts/ +!tests/harness.js +!docker/docker-entrypoint.sh diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..48e0a5e --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,39 @@ +# Keeps what the workflows and the container image pin up to date: every GitHub Action is pinned to a commit SHA +# (Dependabot moves the SHA and its version comment together), the image's Node base to a digest, and the npm tools +# to the lockfile. Updates come as pull requests, one group per ecosystem, once a week. +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + day: monday + groups: + actions: + patterns: ["*"] + commit-message: + prefix: "CI" + + - package-ecosystem: docker + directory: /docker + schedule: + interval: weekly + day: monday + # The image runs the Node major CI tests on (ci.yml); a new major comes with CI, by hand. + ignore: + - dependency-name: node + update-types: ["version-update:semver-major"] + commit-message: + prefix: "Container" + + - package-ecosystem: npm + directory: / + schedule: + interval: weekly + day: monday + groups: + tools: + patterns: ["*"] + update-types: [minor, patch] + commit-message: + prefix: "Tools" diff --git a/.github/workflows/auto-release.yml b/.github/workflows/auto-release.yml index 29bfba0..765105b 100644 --- a/.github/workflows/auto-release.yml +++ b/.github/workflows/auto-release.yml @@ -5,10 +5,15 @@ name: Auto-release # as notes, and starts the deploy. Releases created with the workflow token do # not fire the "released" event, so the deploy is started explicitly, from the # tag, which keeps the github-pages environment's v* tag rule happy. +# +# It runs when CI finishes on main, so a release never repeats the push's tests: +# CI green on the commit that bumped the version is the go. A red CI releases +# nothing. Started by hand, it has no CI result to go by, so it tests first. on: - push: + workflow_run: + workflows: [CI] + types: [completed] branches: [main] - paths: [package.json] workflow_dispatch: permissions: @@ -20,18 +25,26 @@ concurrency: cancel-in-progress: false jobs: - release: + check: + # After CI: only a green run of a push to main (not a PR's run, not a release's own call). + if: >- + github.event_name == 'workflow_dispatch' || + (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push') runs-on: ubuntu-latest env: GH_TOKEN: ${{ github.token }} + outputs: + skip: ${{ steps.v.outputs.skip }} + ver: ${{ steps.v.outputs.ver }} + tag: ${{ steps.v.outputs.tag }} + pre: ${{ steps.v.outputs.pre }} + # The commit CI tested (main may have moved on since); by hand, main as it is now. + sha: ${{ github.event.workflow_run.head_sha || github.sha }} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: + ref: ${{ github.event.workflow_run.head_sha || github.sha }} fetch-depth: 0 - - uses: actions/setup-node@v7 - with: - node-version: 24 - cache: npm - name: Work out the version and whether it is new id: v @@ -57,19 +70,48 @@ jobs: case "$ver" in *-*) echo "pre=true" >> "$GITHUB_OUTPUT";; *) echo "pre=false" >> "$GITHUB_OUTPUT";; esac echo "skip=false" >> "$GITHUB_OUTPUT" - - name: Test before releasing - if: steps.v.outputs.skip == 'false' - run: npm ci && npm test + # Only when started by hand: after a push, CI has already tested this commit. By hand the commit is main as it is + # (github.sha, what check.outputs.sha is then), named directly so CI never checks out a ref a workflow_run handed over. + tests: + needs: check + if: needs.check.outputs.skip == 'false' && github.event_name == 'workflow_dispatch' + uses: ./.github/workflows/ci.yml + with: + ref: ${{ github.sha }} + + release: + needs: [check, tests] + if: >- + always() && needs.check.result == 'success' && needs.check.outputs.skip == 'false' && + (needs.tests.result == 'success' || needs.tests.result == 'skipped') + runs-on: ubuntu-latest + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ needs.check.outputs.tag }} + VER: ${{ needs.check.outputs.ver }} + PRE: ${{ needs.check.outputs.pre }} + SHA: ${{ needs.check.outputs.sha }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.check.outputs.sha }} - name: Publish the release - if: steps.v.outputs.skip == 'false' run: | set -euo pipefail - pre=(); [ "${{ steps.v.outputs.pre }}" = "true" ] && pre=(--prerelease) - gh release create "${{ steps.v.outputs.tag }}" --repo "$GITHUB_REPOSITORY" \ - --target "$GITHUB_SHA" --title "${{ steps.v.outputs.ver }}" --notes-file notes.md "${pre[@]}" + awk -v v="$VER" 'index($0,"## ["v"]")==1{f=1;next} /^## \[/{f=0} f' CHANGELOG.md | sed -e '/./,$!d' > notes.md + pre=(); [ "$PRE" = "true" ] && pre=(--prerelease) + gh release create "$TAG" --repo "$GITHUB_REPOSITORY" \ + --target "$SHA" --title "$VER" --notes-file notes.md "${pre[@]}" - name: Deploy it - # Pre-releases are for testing and never go live. - if: steps.v.outputs.skip == 'false' && steps.v.outputs.pre == 'false' - run: gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "${{ steps.v.outputs.tag }}" -f tag="${{ steps.v.outputs.tag }}" + # Pre-releases are for testing and never go live. CI (or the tests above) already passed on this commit, + # so the deploy does not test it again (tested=true). + if: env.PRE == 'false' + run: gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG" -f tested=true + + - name: Publish the Docker image + # Same pattern as the deploy above: the image is built and pushed from the + # release tag by docker.yml. Pre-releases get one too: an image tag is + # pulled on purpose, so a test image costs nothing. + run: gh workflow run docker.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 47ba455..a70d674 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,35 +1,142 @@ name: CI +# Every push and PR, and the releases too (auto-release.yml and release.yml call this workflow), so the tests run +# one way, split over several runners, everywhere. on: push: branches: [main] pull_request: + workflow_call: + inputs: + ref: + description: The commit or tag to test (a release tag); the caller's commit when empty + type: string + default: '' permissions: contents: read +# A newer push to the same pull request makes the older run pointless: cancel it instead of queueing behind it. +# Runs on main always finish. A release's call gets a group of its own, so it never waits behind main's push run. +concurrency: + group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}${{ inputs.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +env: + # Runners for the tests. Standard GitHub-hosted runners (4 cores each) are the only free ones for a public repo, + # and a run may use up to 20 at once, so more parts is how the tests get faster. Each part costs ~30 s of setup. + PARTS: 6 + jobs: - test: + # Splits the test files into parts of about equal time, once, so every part works from the same plan. The times + # come from the last run on main (the cache, see "timings" below), else from the committed tests/durations.json. + plan: runs-on: ubuntu-latest + outputs: + parts: ${{ steps.plan.outputs.parts }} steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: tests/durations.json + key: test-durations-${{ github.run_id }} + restore-keys: test-durations- + - id: plan + run: echo "parts=$(node scripts/test.js --plan "$PARTS")" >> "$GITHUB_OUTPUT" + + part: + name: part ${{ strategy.job-index }} + needs: plan + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + files: ${{ fromJSON(needs.plan.outputs.parts) }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + cache: npm + - run: npm ci + - name: Tests + env: + FILES: ${{ matrix.files }} + # Word splitting on purpose: FILES is a space-separated list of tests/*.test.js paths. + run: npm test -- --timings "$RUNNER_TEMP/timings.json" $FILES + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: timings-${{ strategy.job-index }} + path: ${{ runner.temp }}/timings.json + retention-days: 1 + if-no-files-found: ignore + + build: + name: build + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm - run: npm ci - - run: npm test - name: Build (not deployed — only releases deploy) run: npm run build translations: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref }} + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm - run: npm ci - name: Translation coverage run: node scripts/i18n-check.js --summary "$GITHUB_STEP_SUMMARY" + + # The one check to look at: green only when the plan, every part, the build and the translations are. + test: + needs: [plan, part, build, translations] + if: always() + runs-on: ubuntu-latest + steps: + - name: Everything passed + run: | + echo "plan: ${{ needs.plan.result }}, parts: ${{ needs.part.result }}, build: ${{ needs.build.result }}, translations: ${{ needs.translations.result }}" + test "${{ needs.plan.result }}" = success && test "${{ needs.part.result }}" = success + test "${{ needs.build.result }}" = success && test "${{ needs.translations.result }}" = success + + # After a run on main: each file's time from this run goes into the cache, so the next run (main or a PR) splits + # its parts by today's tests. Nobody has to remember to refresh tests/durations.json. + timings: + needs: part + if: always() && github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.part.result != 'skipped' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: tests/durations.json + key: test-durations-${{ github.run_id }} + restore-keys: test-durations- + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: timings-* + path: ${{ runner.temp }}/timings + - run: node scripts/test-timings.js --merge "$RUNNER_TEMP/timings" + - uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: tests/durations.json + key: test-durations-${{ github.run_id }} diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index 8ff912c..10913c4 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -27,9 +27,9 @@ jobs: id-token: write actions: read steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 1 - - uses: anthropics/claude-code-action@v1 + - uses: anthropics/claude-code-action@61a9c274fa7110a66dfafc1bbbced03833eb25fe # v1.0.269 with: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml new file mode 100644 index 0000000..434307e --- /dev/null +++ b/.github/workflows/docker.yml @@ -0,0 +1,187 @@ +name: Container image + +# Publishes ghcr.io//: for releases, and nothing else: auto-release.yml dispatches this workflow +# with the new tag (pre-releases too). There is no :latest and no image per commit. Pushes and pull requests that change +# what goes into the image only build it and try both modes; they never publish. The image packages the MCP server and +# the development server; the game itself is hosted on GitHub Pages only (docs/adr/0001-github-pages-only.md). +on: + workflow_dispatch: + inputs: + tag: + description: Release tag to build and publish (e.g. v2.10.1) + required: true + push: + branches: [main] + paths: + - docker/** + - .dockerignore + - package.json + - package-lock.json + - scripts/** + - tests/harness.js + - .github/workflows/docker.yml + pull_request: + paths: + - docker/** + - .dockerignore + - package.json + - package-lock.json + - scripts/** + - tests/harness.js + - .github/workflows/docker.yml + +permissions: + contents: read + +concurrency: + group: docker-${{ github.event_name }}-${{ inputs.tag || github.ref }} + cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }} + +jobs: + # A push that bumps the version is a release on its way: once CI passes, auto-release.yml starts this workflow for + # the tag, which tests the same code before it publishes. Testing the push too would be the same run twice. + gate: + runs-on: ubuntu-latest + outputs: + run: ${{ steps.g.outputs.run }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.tag || '' }} + persist-credentials: false + - id: g + run: | + tag="v$(jq -r .version package.json)" + if [ "$GITHUB_EVENT_NAME" = push ] && ! git ls-remote --exit-code --tags origin "refs/tags/$tag" >/dev/null; then + echo "$tag is not tagged yet: the release will test this commit when it publishes." + echo "run=false" >> "$GITHUB_OUTPUT" + else + echo "run=true" >> "$GITHUB_OUTPUT" + fi + + test: + needs: gate + if: needs.gate.outputs.run == 'true' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.tag || '' }} + persist-credentials: false + + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - name: Build for this runner + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: docker/Dockerfile + platforms: linux/amd64 + load: true + push: false + tags: sot:test + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Try both modes + run: | + set -euo pipefail + init='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"ci","version":"1"}}}' + mcp() { curl -sS -o /tmp/out -w '%{http_code}' -X POST http://127.0.0.1:7777/mcp \ + -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' "$@" -d "$init"; } + until_up() { for i in $(seq 1 60); do curl -s -o /dev/null "$1" && return 0; sleep 1; done; docker logs "$2"; exit 1; } + + # Headless, with a token: refused without it, answered with it. + docker run -d --name sot-h -p 127.0.0.1:7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=ci-token sot:test + until_up http://127.0.0.1:7777/ sot-h + test "$(mcp)" = 401 + test "$(mcp -H 'authorization: Bearer ci-token')" = 200 + grep -q serverInfo /tmp/out + docker rm -f sot-h + + # No token given: the container makes one, says so, and wants it. + docker run -d --name sot-t -p 127.0.0.1:7777:7777 -e MCP_MODE=headless sot:test + until_up http://127.0.0.1:7777/ sot-t + test "$(mcp)" = 401 + tok=$(docker logs sot-t 2>&1 | sed -n "s/.*this run's token is //p" | head -1) + test -n "$tok" + test "$(mcp -H "authorization: Bearer $tok")" = 200 + docker rm -f sot-t + + # Browser mode: the development page and the MCP server. + docker run -d --name sot-b -p 127.0.0.1:8080:8080 -p 127.0.0.1:7777:7777 -e SOT_MCP_TOKEN=ci-token sot:test + until_up http://127.0.0.1:8080/ sot-b + test "$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/)" = 200 + until_up http://127.0.0.1:7777/ sot-b + test "$(mcp -H 'authorization: Bearer ci-token')" = 200 + docker rm -f sot-b + + # The server runs as node, not root. + test "$(docker run --rm --entrypoint id sot:test -u)" != 0 + + publish: + if: github.event_name == 'workflow_dispatch' + needs: test + runs-on: ubuntu-latest + timeout-minutes: 45 + permissions: + contents: read + packages: write + steps: + - name: Check the tag + env: + TAG: ${{ inputs.tag }} + run: | + [[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || { echo "::error::Not a release tag: $TAG"; exit 1; } + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.tag }} + persist-credentials: false + + - name: Work out the image name and version + id: meta + env: + TAG: ${{ inputs.tag }} + run: | + set -euo pipefail + want="v$(jq -r .version package.json)" + if [ "$TAG" != "$want" ]; then echo "::error::Release tag $TAG does not match package.json ($want)"; exit 1; fi + # Named after this repository (ghcr.io//, lowercased), so forks publish their own. + echo "image=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_OUTPUT" + echo "version=${TAG#v}" >> "$GITHUB_OUTPUT" + echo "revision=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + echo "created=$(git log -1 --format=%cI)" >> "$GITHUB_OUTPUT" + + - uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 + + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push the release's version + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: . + file: docker/Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }} + labels: | + org.opencontainers.image.title=Series of Tubes MCP server + org.opencontainers.image.description=The Series of Tubes MCP server and development server, so an AI client can play the game. + org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} + org.opencontainers.image.documentation=${{ github.server_url }}/${{ github.repository }}/blob/${{ inputs.tag }}/docs/MCP.md + org.opencontainers.image.version=${{ steps.meta.outputs.version }} + org.opencontainers.image.revision=${{ steps.meta.outputs.revision }} + org.opencontainers.image.created=${{ steps.meta.outputs.created }} + org.opencontainers.image.licenses=MIT + provenance: mode=max + sbom: true + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/.github/workflows/perf-comment.yml b/.github/workflows/perf-comment.yml index 2f6c286..a214fff 100644 --- a/.github/workflows/perf-comment.yml +++ b/.github/workflows/perf-comment.yml @@ -17,9 +17,11 @@ jobs: if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success' runs-on: ubuntu-latest steps: - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: perf + # Outside the workspace: the files come from a PR's run and are only ever read as text. + path: ${{ runner.temp }}/perf run-id: ${{ github.event.workflow_run.id }} github-token: ${{ secrets.GITHUB_TOKEN }} - name: Post or update the comment @@ -28,6 +30,7 @@ jobs: REPO: ${{ github.repository }} HEAD_SHA: ${{ github.event.workflow_run.head_sha }} run: | + cd "$RUNNER_TEMP/perf" pr=$(tr -cd '0-9' < pr-number.txt) [ -n "$pr" ] || { echo "no PR number"; exit 0; } # Trust the number only if that PR's head is the commit that was benchmarked. diff --git a/.github/workflows/perf.yml b/.github/workflows/perf.yml index 48c05e4..f2657ab 100644 --- a/.github/workflows/perf.yml +++ b/.github/workflows/perf.yml @@ -22,8 +22,8 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 40 steps: - - uses: actions/checkout@v7 - - uses: actions/setup-node@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm @@ -48,7 +48,7 @@ jobs: env: PR: ${{ github.event.pull_request.number }} run: echo "$PR" > pr-number.txt - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: github.event_name == 'pull_request' with: name: perf diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index da224da..213596f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -4,7 +4,8 @@ name: Release to GitHub Pages # Pushes to main run CI but never deploy. To ship: bump "version" in # package.json and date its CHANGELOG section; auto-release.yml then tags, # publishes the release and starts this workflow from the tag. Publishing a -# release by hand works too. +# release by hand works too. Every Sunday weekly-puzzle.yml redeploys the live +# release from its tag with the new weekly puzzle added (input weekly). on: release: # "released" also fires when a pre-release is promoted to a full release. @@ -18,6 +19,14 @@ on: description: Allow deploying a version older than what is live (rollback) type: boolean default: false + weekly: + description: Only the weekly puzzles changed (weekly-puzzle.yml); the release itself was tested when it shipped + type: boolean + default: false + tested: + description: The tag's tests already passed (auto-release.yml tests it before tagging) + type: boolean + default: false # Least privilege: only the deploy job can write to Pages. permissions: @@ -28,19 +37,28 @@ concurrency: cancel-in-progress: false jobs: + # The release's tests, split over several runners like every push (ci.yml). Skipped when auto-release.yml has just + # run them on this tag, and for a weekly redeploy (the build step below tests the weekly files against the tag). + tests: + if: ${{ (github.event_name == 'workflow_dispatch' || !github.event.release.prerelease) && !inputs.weekly && !inputs.tested }} + uses: ./.github/workflows/ci.yml + with: + ref: ${{ github.event.release.tag_name || inputs.tag }} + build: + needs: tests # Pre-releases are for testing and never go live. - if: ${{ github.event_name == 'workflow_dispatch' || !github.event.release.prerelease }} + if: ${{ always() && (github.event_name == 'workflow_dispatch' || !github.event.release.prerelease) && (needs.tests.result == 'success' || needs.tests.result == 'skipped') }} runs-on: ubuntu-latest env: TAG: ${{ github.event.release.tag_name || inputs.tag }} ALLOW_OLDER: ${{ inputs.allow_older || false }} GH_TOKEN: ${{ github.token }} steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ env.TAG }} - - uses: actions/setup-node@v7 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: 24 cache: npm @@ -63,16 +81,55 @@ jobs: if [ "$ALLOW_OLDER" != "true" ] && [ "$(printf '%s\n%s\n' "$live" "$new" | sort -V | tail -n1)" != "$new" ]; then echo "::error::$new is older than the live $live. Re-run with allow_older to roll back on purpose."; exit 1 fi + # Weekly puzzles are published on main between releases (weekly-puzzle.yml). Every deploy ships all of them, + # so neither a release nor a weekly redeploy ever drops a week that is already out. + - name: Weekly puzzles and scenarios from main + run: | + set -euo pipefail + git fetch --no-tags --depth=1 origin main + for d in site/puzzles/weekly site/scenarios/weekly site/architect/weekly; do + if git cat-file -e "FETCH_HEAD:$d" 2>/dev/null; then + rm -rf "$d" + git checkout FETCH_HEAD -- "$d" + echo "$d: $(ls "$d" | grep -c '^[0-9].*\.json$')" + fi + done - run: npm ci - - run: npm test + # This release's prices may no longer fit a week already published: --check regenerates every week not over + # yet whose budget no longer verifies (deterministically, so main's next weekly run commits the same files), + # and fails the deploy only if that fails. Before the tests, which check the weeks too. + - name: Fit the weekly puzzles to this release + run: | + set -euo pipefail + # A release from before the weekly puzzles ships the files without reading them: nothing to check. + if [ ! -f scripts/weekly-puzzle.js ]; then echo "This release does not read weekly puzzles yet."; exit 0; fi + node scripts/weekly-puzzle.js --check + if [ -f scripts/weekly-scenario.js ]; then node scripts/weekly-scenario.js --check; fi + if [ -f scripts/weekly-architect.js ]; then node scripts/weekly-architect.js --check; fi + # The weekly files come from main, not the tag. When they (after fitting) are the tag's own, CI already tested + # them with it; otherwise (a newer week, a refitted one) they are tested against this release here. + - name: Are the weekly files the tag's own? + id: weekly + run: | + if [ -z "$(git status --porcelain -- site/puzzles/weekly site/scenarios/weekly site/architect/weekly)" ]; then + echo "Same weekly files as the tag: tested with it already."; echo "same=true" >> "$GITHUB_OUTPUT" + else + git status --short -- site/puzzles/weekly site/scenarios/weekly site/architect/weekly; echo "same=false" >> "$GITHUB_OUTPUT" + fi + - name: Test the weekly puzzles against this release + if: ${{ hashFiles('scripts/weekly-puzzle.js') != '' && (steps.weekly.outputs.same != 'true' || !(inputs.tested || needs.tests.result == 'success')) }} + run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js $(ls tests/weekly-scenario.test.js tests/weekly-architect.test.js 2>/dev/null) - name: Build site run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build - - uses: actions/upload-pages-artifact@v5 + - uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0 with: path: ./_site + # A skipped job skips everything that needs it, even through build (which runs anyway): without always() here, a + # release whose tests auto-release.yml already ran built and never deployed (v3.2.0). deploy: needs: build + if: ${{ always() && needs.build.result == 'success' }} runs-on: ubuntu-latest permissions: pages: write @@ -82,12 +139,11 @@ jobs: url: ${{ steps.deployment.outputs.page_url }} steps: - id: deployment - uses: actions/deploy-pages@v5 - - # Tell IndexNow (Bing, Yandex, Seznam, …) about the new version, only after + uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1 # the site is live. indexnow: needs: deploy + if: ${{ always() && needs.deploy.result == 'success' && !inputs.weekly }} runs-on: ubuntu-latest env: # IndexNow keys are public by design (also served at /.txt). diff --git a/.github/workflows/weekly-puzzle.yml b/.github/workflows/weekly-puzzle.yml new file mode 100644 index 0000000..6cfa3d5 --- /dev/null +++ b/.github/workflows/weekly-puzzle.yml @@ -0,0 +1,88 @@ +name: Weekly puzzle + +# Every Sunday morning: make this week's puzzle (scripts/weekly-puzzle.js), scenario (scripts/weekly-scenario.js) and +# Architect run (scripts/weekly-architect.js), +# commit them to main as a data-only change, and redeploy the live release with them, once. Weeks start Sunday +# 06:00 Berlin time; 03:37 UTC is 04:37 in winter and 05:37 in summer, so the files are live before the week starts. +# +# No version bump, so no release: auto-release.yml only runs when package.json changes (and pushes made with +# the workflow token start no workflows at all). The deploy itself is release.yml, still the only workflow +# that can write to Pages, started from the live release's tag with weekly=true: it rebuilds exactly that +# release with every weekly puzzle from main added, in the same "pages" concurrency group as any release. +on: + schedule: + - cron: '37 3 * * 0' + workflow_dispatch: + inputs: + key: + description: Week to make, e.g. 2026-W45 (default the week starting this Sunday) + required: false + deploy: + description: Redeploy the live release with it + type: boolean + default: true + +permissions: + contents: write # commit the puzzle to main + actions: write # start release.yml + +concurrency: + group: weekly-puzzle + cancel-in-progress: false + +jobs: + puzzle: + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + GH_TOKEN: ${{ github.token }} + KEY: ${{ inputs.key }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + cache: npm + - run: npm ci + # Weeks already out that main's prices no longer fit are regenerated first, so the new week's history is current. + - name: Fit the published weeks to main + run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && node scripts/weekly-architect.js --check + - name: Make the puzzle and the scenario + run: | + set -euo pipefail + if [ -n "$KEY" ]; then + [[ "$KEY" =~ ^[0-9]{4}-W[0-9]{2}$ ]] || { echo "::error::$KEY is not a week key"; exit 1; } + node scripts/weekly-puzzle.js --key "$KEY" + node scripts/weekly-scenario.js --key "$KEY" + node scripts/weekly-architect.js --key "$KEY" + else + node scripts/weekly-puzzle.js + node scripts/weekly-scenario.js + node scripts/weekly-architect.js + fi + - name: Check every weekly puzzle + run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && node scripts/weekly-architect.js --check && npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js tests/weekly-scenario.test.js tests/weekly-architect.test.js + - name: Commit it to main + run: | + set -euo pipefail + git add site/puzzles/weekly site/scenarios/weekly site/architect/weekly + # Data only: anything else changed means something is wrong. + if git status --porcelain | grep -v -e ' site/puzzles/weekly/' -e ' site/scenarios/weekly/' -e ' site/architect/weekly/' | grep -q .; then git status --porcelain; echo "::error::unexpected changes"; exit 1; fi + if git diff --cached --quiet; then echo "Nothing new to commit."; exit 0; fi + git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \ + commit -m "Weekly puzzle and scenario $(git diff --cached --name-only | grep -o '[0-9]\{4\}-W[0-9]\{2\}' | sort -u | paste -sd ' ')" + git push origin HEAD:main + - name: Redeploy the live release with it + if: github.event_name == 'schedule' || inputs.deploy + run: | + set -euo pipefail + tag=$(gh release list --repo "$GITHUB_REPOSITORY" --exclude-pre-releases --exclude-drafts --limit 1 --json tagName -q '.[0].tagName') + [ -n "$tag" ] || { echo "::error::no release to redeploy"; exit 1; } + # Releases from before the weekly puzzles cannot take them (and their game would not read them). + if ! git fetch --no-tags --depth=1 origin "refs/tags/$tag" || ! git show FETCH_HEAD:.github/workflows/release.yml | grep -q '^ weekly:'; then + echo "::notice::$tag predates weekly puzzles; the puzzle is on main and ships with the next release."; exit 0 + fi + gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$tag" -f tag="$tag" -f weekly=true + echo "Redeploying $tag with the weekly puzzles." diff --git a/.gitignore b/.gitignore index 24c9945..9027294 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules/ _site/ .DS_Store +mp-data/ diff --git a/CHANGELOG.md b/CHANGELOG.md index eb2f3d5..01cce55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,367 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Investors on a revenue share now take their cut of your IPv4 lease income too, as they already did of fiber pairs you lease out (#150). Selling a block is still a one-off that is all yours, like the up-front price of a fiber pair, and the NOC dashboard's Investor revenue share row now includes the leases. +- Island Wi-Fi: bring the internet to 18 groups of outer islands, over satellite capacity first and your own spur cable later (#83). Each group looks to an island city, like Vanua Levu to Suva or Abaco and Eleuthera to Nassau: open a POP there and its Customers tab lists them. Rent capacity at the city's teleport and about a third of the islanders sign up over GEO, three quarters over MEO and nine in ten over Starblink from a gateway there; from level 3 a spur cable from the city lets everyone sign up, with upkeep but no rent. Islanders pay island prices, their homes are IPv6-only from day one, and their traffic rides the city's routers and links. A spur can be cut and the repair ship takes weeks: a satellite circuit kept beside it carries the islands meanwhile. Investors on a revenue share take their cut of what the islands pay. +- Rent low-orbit satellite capacity from Starblink from level 5: islands near your fiber get circuits at about 30 ms round trip (#83). Host a Starblink gateway at a teleport on your fiber, then rent 5 to 50 Gbps to small islands and remote towns within 1,200 km of it. Users hardly notice the lag, and selective networks peer over it as over a cable; next to a cable it waits on standby, and a GEO or MEO circuit to the same island waits on standby beside it. Every island behind a gateway leans on that POP's routers, fiber and transit, which its teleport section now shows, and a rare solar storm puts the circuits in safe mode for a day or two. Once your own constellation carries traffic, Starblink sells you nothing new. +- A POP you mark as a micro POP, medium POP or regional hub now keeps that kind's routers when you also have a build standard (#315). Its router model and count come from its kind: "Bring everything up now" and your intern no longer swap its routers or add more to meet the build standard, while the standard's other targets still apply there. The POP's router section says so. +- Send to another device now gives a multiplayer network its session link, on copies of the game you host yourself (#263). The link carries on with the network in the session on the other device, and pasting it under From another device opens it there too; the save file stays a copy that plays on alone. +- Buy it and sign no longer spends money on an offer your IPv4 space cannot take (#150). The button only shows once the deal's address block fits. +- Linking to an island or remote town where no subsea cable lands, like Iqaluit or Adamstown, now says that a satellite can get there too. The window has a button to the order sheet from your teleports that reach it, up to four of them; without one, it says where a teleport would have to go (#83). +- IPv4 notices in the NOC's notifications now have an Open button to the bank's Address space (#150). Notices like "Your IPv4 is full" already had that button when they popped up; now they keep it. +- Red warning text and the capacity market's Hot and Cool tags now read well in dark mode (#80). The red is a lighter one on the dark panels, and the tags take the night colours instead of staying bright pastel chips. +- The build standard can now take every broadband city IPv6-only while IPv4 is scarce (#150). Its new target, Broadband: IPv6-only, swaps the home routers of every city still on dual stack for 464XLAT ones, the cities with the most dual-stack homes first. "Bring everything up now" and your intern's Keep to the build standard order start a city's swap only with all of it to spare, and the intern counts it against the order's monthly budget. What the swaps under way still owe is set aside: the button's other jobs and every one of your intern's standing orders leave it alone, above the cash floor. +- "Bring everything up now" in the build standard no longer takes a fiber dark for a day while a customer's alien or managed wave rides it. Such a fiber keeps its line system and the sheet says why; the upgrade button on the fiber itself still does it when you choose. Your intern waits for those fibers too, but no longer skips fibers that only carry leased pairs or IRUs, which a line system swap never touches. +- Broadband cities can now go IPv6-only with 464XLAT, a second way to save IPv4 next to CGNAT. Start it from a city's Home broadband, which also says what it does to your monthly IPv4 bill: its home routers are swapped over a month or more, paid as each one goes in (new homes there get one too, at the same price), and the homes then need no IPv4 address of their own, only a share of a NAT64 pool at up to 256 homes per address, with fewer refunds than CGNAT at the same ratio. The bank's Address space section shows your homes as public, behind CGNAT and IPv6-only, with the NAT64 ratio next to the CGNAT one, and says which of the two to stretch when space runs out. +- CGNAT gets a little cheaper every year as the world moves to IPv6. About two points less of your homes' traffic needs IPv4 each year, so the CGNAT and NAT64 boxes carry less of it. +- The router model and the line system your intern standardizes on are now picked in one place, the build standard. Keep routers ahead and Upgrade optical transport take them from there and say so, with a button to the sheet. With a model or line system in the standard, both orders bring everything up to it and stop there (Upgrade optical transport on every fiber, even at POPs that Keep to the build standard skips); "Keep as is" leaves them to the next one up when busy. A model or line system you had picked in an order that was running moves into your standard, so new POPs get that model too. +- Your intern no longer takes a fiber dark for the build standard just because it looks quiet. Like the optical upgrade order, it first checks that every gigabit, circuit and express gets around the fiber for the day. The two orders share one line system swap a night (two for Kevin), never work on the same fiber in one shift, and a wave the standard just upgraded is no longer handed back the same day. +- Copies of the game you host yourself can now have multiplayer, with friends building their networks next to yours in the same world. They join your session with a six-character code, and the session has a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player. +- Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80). +- Express lightpaths: light a wave straight through the cities between your own dark fibers, without touching the routers there. Wherever two or more of your ROADM fibers on land meet, a fiber's panel lists where an express can go and the link window gets an Express tab; it uses ports only at its two ends, saves a hop of latency and takes one channel slot on every fiber it rides, and the light has to reach all the way between regen sites. A cut or a line system swap on any of those fibers darkens it, and a fiber can only be given up once no express rides it. (#58) +- Teleports bring satellites to small islands and remote towns, long before you have a cable there or a rocket company (#83). Build one at a POP from level 2 and rent GEO circuits (about 600 ms round trip, and users notice) or, with tracking antennas from level 3, MEO circuits (about 130 ms) to any island or town its satellites see. Next to an island's only cable a circuit waits on standby (whether the cable or the circuit came first) and carries the island when the cable is cut, and a city with no cable at all gets a POP and a circuit in one order. +- Set a build standard for your whole network: what every POP, connection and fiber should have, all in one sheet. It covers routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section. +- IPv4 is scarce now: business customers need public address blocks, and the homes that do not fit share addresses behind CGNAT. A new network starts with a /21 from its registry, enough for its first months; buy, lease or sell blocks from /24 to /16 on the transfer market in the bank's new Address space section, or lease spare ones out for a monthly income. An offer you have no addresses for says so and waits, a customer that wants to grow at renewal stays at its size until you have the addresses, CGNAT costs a little and annoys some gamers, and you pick how many homes share an address. IPv6 stays free for everyone. This is part of On-call and BGP at 3 a.m.; the gentler rules, Sandbox, puzzles and scenarios keep IPv4 plentiful, and saved games get the addresses they already use plus room to grow (#150). +- Express lightpaths now pay their share when you add a regen site, and a dirty connector on a fiber dims the expresses riding it too (#58). A regen site added to a fiber that already carries expresses needs a regen card for each of their channels, just as for the fiber's own, and the price on the fiber's button includes them. A dirty connector dims every wave in that fiber, and the express's panel says which fiber it is; an MTU mismatch, microbursts or a marginal optic stay with that fiber's own routers and optics, which an express passes by. +- Many selective networks now refuse to peer where a satellite circuit is your only way out (#83). On an island or in a remote town that only a satellite joins to the rest of your network, they would hand you traffic for your whole network to haul through orbit, so more of them turn down a GEO hop (about 600 ms there and back) than a MEO one (about 130 ms), and each says why on the exchange and PNI lists. Once a wave, fiber or cable to the island is lit they peer again. An exchange session you already had there pauses until then; a PNI you already have and the members of an exchange you run yourself keep peering. + +## [3.5.0] — 2026-11-11 + +- Alien waves you list on a fiber yourself now stay listed. With the capacity market selling for you, the broker used to cut your listing down to what its settings allowed the next day, or take it off altogether when the route's demand was below your minimum. Your own listing now stays put, and the broker adds what its settings allow on top (#340). +- The Connections list in the NOC dashboard no longer stays blank when you sort it by load or show only NNI ports while a fabric port runs at 400G. A 400G fabric port is the fastest there is, so the list now offers it one more LAG member instead of a faster port that does not exist. (#342) +- You can now start a link by typing where it goes: open one of your POPs, go to Infra and tap Link to a city, then type a city, country or exchange and pick it. You get the same link window as dragging between the two on the map, which is much easier on a crowded phone screen (#343). +- The Connections tab of the NOC dashboard can now shrink connections as well as grow them. Next to the upgrades, transit ports, PNIs and exchange ports get a downgrade to the next smaller port and a button to drop one LAG member, and a PNI that is still on order can be chased from the list, just like from the POP panel (#336). +- Once you have made Tier 1, conferences stop sending notifications. No more 30-day reminders, reports from the hallway track or notes from your sales engineer about bookings; you can still register and sponsor from the Deals tab, and everything a conference does works as before (#101). + +## [3.4.0] — 2026-11-10 + +- A PNI can now grow past eight ports: each router at the POP takes eight members of a PNI, up to 32, so a busier interconnect costs another router and its ports. Saves keep every LAG they have, and a router a PNI still needs stays until the PNI shrinks (#323). +- Your traffic to home internet providers now starts where their customers live: a New York POP talks a lot to Comecast and little to Doitsche Telekomm, Frankfurt the other way round. Peering with a big eyeball network in the cities its users are in now takes that traffic off your backbone, while peering in only two cities means hauling it there from everywhere else (#48). +- Giant AI circuits now come from campuses in more than 30 metros, from Oregon and Wyoming to Atlanta, Querétaro and Québec, and less often from cities already crowded with them. Ashburn stays a little busier than the rest, but no longer has to carry the whole late game with four other cities (#61). +- RouteScript can spill early onto detours within a latency budget: `spill at 80% within 10 ms` keeps a hot link at 80% and moves the rest onto the fastest detour that adds at most 10 ms and is itself under 80%. Stack them (`spill at 90% within 20 ms`) to spill further as links get hotter (#136). +- You can now send a network to another device straight from the game: open the menu, pick Send to another device, and send the save file with AirDrop, Quick Share, a chat with yourself or email, then open it there with Import a save. You can also copy a link that carries the whole network and paste it on the other device under From another device. Nothing is uploaded anywhere (#263). +- From customer level 7, low-latency wholesale routes call: 1.6 or 3.2 Tbps between two of your cities with a strict latency limit, paying about three times what a hyperscaler pays per Gbps on the same route. Every day over the limit (after the first 15) you pay back a day's fee as an SLA credit and they lose patience twice as fast as a trading link over its limit, so keep a fast path and a fast backup. They never grow past 3.2 Tbps, so one contract cannot carry a whole level (#137). +- From customer level 2, you can save up to three POP standards (micro POP, medium POP, regional hub), each a router model and a number of routers, and mark which POP is which. One button in a POP's Infra tab brings it up to its standard, and Utilities brings every POP of a kind up at once with the price shown first. A POP is never stepped down to a smaller model, and a busy POP with one router gets its second router before the swap, so the upgrade rolls instead of taking the POP down (#315). +- Utilities can now install the redundancy kit at every POP still missing part of it in one go, at one price shown on the button, from customer level 2. With a NOC intern you can also put the kit in the intern's new-POP template from there (#317). +- A customer asking for a backup generator, a second router or a second site at POPs you already have now shows what is missing and what it costs, with a button that buys exactly that and signs the deal. Nothing is bought unless you press it (#241). +- The NOC intern's "Light more fiber" order can now leave new fiber dark, so a fiber handed over in the night no longer pulls in traffic before you are ready for it. Fiber you light yourself still gets more optics when it runs hot (#316). +- The Transit and Peering tabs of a POP have a search box for a network's name or AS number and a "Connected only" switch, so you can find the one network you need in a long list, on phones too (#199). +- Decommissioning one of several links between the same two cities keeps the link panel open on the next one, so you can hand back a row of waves without reopening it each time (#119). +- A link that a closed border has taken down, like Doha to Dubai or Abu Dhabi while the neighbours have fallen out, now says so in its panel, with the days until it comes back, instead of showing nothing wrong. Leasing a new wave or fiber pair across that border during the spat warns you first that it will stay dark (#329). +- A customer asking for a discount at renewal now shows how much traffic they book and get, the price per Gbps now and asked, and any latency limit or path terms they signed for, each ticked or crossed as your network stands today (#292). +- The two city names at the top of a wave, dark fiber or virtual circuit panel now open that city, for example to upgrade the router there before a bigger link (#196). + +## [3.3.0] — 2026-11-09 + +- You can now move a customer to another path between the same two POPs, with the most diverse options listed first. Waves and leased fiber pairs move to another fiber with room for them, leaving alone what you keep back for your own traffic, and circuits can be pinned to a path of your choice, falling back to normal routing while a link on it is down. +- Routing a big network's day takes about half the work, with exactly the same results: on a network of 390 POPs with Auto-TE, a day's routing went from about 0.7 to 0.3 seconds on a computer. +- Big networks no longer freeze for a moment at every new game day, above all with a NOC intern on duty. The intern now plans cache boxes, router ports and PNIs for every POP in one pass. On a network of 190 POPs the intern's shift held the page for about a tenth of a second on a computer and half a second on a phone; it now takes a few thousandths, and a whole day holds the page a quarter as long. The game plays exactly as before. +- At ×8 a big network's autosave no longer holds the page: the game is packed, turned into text and compressed in the background, and less of each day's routing has to travel back to the page. The game plays exactly as before. +- While nothing moves on the map but its animations (packets, waves, clouds), it is drawn 30 times a second instead of at the screen's full rate, half the work on most screens and a quarter on 120 Hz phones. Moving the map, pointing at something or anything changing on the network still gets every frame, and the animations keep their speed. +- Linking to a coast where no subsea cable lands yet, like Iqaluit, now says how you can get there (overland, or with a cable of your own) instead of listing no cities to hop through (#321). +- A delay while your own subsea cable is being laid now holds the lay ship where it is, instead of sending it back to port and starting the laying over. The cable already on the seabed stays there, the build simply finishes later, and there is nothing to pay twice (#322). +- A paused game no longer rewrites its save every 5 seconds when nothing has changed. On a big network each of those writes held the page for 20 to 30 milliseconds. +- A low-latency boutique with a lot of its own fiber no longer stalls every day while it times its finance routes. On a big fiber network that check held the page for about a third of a second and now takes a few hundredths; checking customers who want a path without subsea or under a latency limit got quicker too. The game plays exactly as before. +- The NOC intern no longer holds a big network for more than half a second each time it weighs taking out a spare wave. Before it decides, it checks every customer promised diverse paths, no subsea or a latency limit, and on a network of 390 POPs that check now takes a few hundredths of a second. Spotting new sovereign cloud and trading offers is about ten times quicker too, and the game plays exactly as before. + +## [3.2.0] — 2026-11-07 + +- New badges for traffic: serve 1 Tbps and 10 Tbps on the way to the 100 Tbps and petabit ones, and carry a petabyte, 100 petabytes, an exabyte and a zettabyte in one game. The dashboard shows how much traffic your network has carried so far, and only the top step of each ladder is legendary: Hundred Terabits is now epic. +- Lambda Bazaar, a capacity market for your dark fiber, is a new tab in the NOC dashboard. Sell spectrum, managed 100G, 400G, 800G and 1.6T waves, and dark pair IRUs on every route you hold fiber on, and choose how much to keep back for your own traffic, from what demand the broker lists, and the price it never sells below. What each route wants moves all the time and grows every year: hot routes pay more, a fiber cut next door or a hyperscaler breaking ground sends demand up, buyers move from 100G to bigger waves over the years, and carriers already on your glass ask to move up a size. Short, straight routes earn more for fast waves. A Cable broker pays the broker 3% instead of 10%, and sees where each route is heading and which routes between its POPs are worth building. + +## [3.1.0] — 2026-11-07 + +- Whoever runs sales can now answer renewal haggles for you, each in their own way: switch it on at the sales desk. The engineer keeps nerdy customers at the market price and gives everyone else their discount, the shark refuses discounts and some customers walk, and the CEO settles it on the golf course, for better or worse. +- The three interns now each have something they are best at: Anycast Annie peers every day and orders PNIs twice a week, Kevin from the night shift swaps two line systems a night and never fat-fingers anything, and Tracy Route buys capacity as if traffic were already 10% higher. They run the same orders at the same salary. +- Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night. +- Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through. +- France gets seven more cities: Lyon, Toulouse, Lille, Bordeaux, Strasbourg, Rennes and Nantes, all but Nantes with an exchange of their own (#288). SF-Error Telecom and Boy-Egg Telecom bring home broadband and mobile, Ov-Hatch Cloud and Scale-Away bring French clouds, Tangerine Telecom and Free as in Beer reach the new cities, Cogentle reaches Toulouse, Lille, Bordeaux and Strasbourg, and Andorable Telecom comes up to Toulouse. The Atlantic cables now come ashore where they really do: Ami-Tea at Bordeaux and Dunno-ant at Nantes, and Dunno-ant starts at Virginia Beach. +- Big networks at ×8 no longer stop for a moment when a day reroutes, after a failure, an event, the intern's shift or the sales desk's signing. Every routing a day needs now runs in the background like the day's own, a long day lets the map draw between its steps, and the check for customers afraid of sharks no longer walks every land fiber for each of them. Quiet notifications now also apply while the game is running. + +## [3.0.0] — 2026-11-06 + +**Series of Tubes 3.0: Pie in the Sky.** You have wired up the planet with fiber, cables and routers. Now take your network to orbit: start your own rocket company, fill the sky with satellites (we call them pies) and sell internet to everyone your cables will never reach. + +**How to get there.** Become Tier 1 in a game started with 3.0, whatever your charter, and Pie Control opens from the NOC tab, right next to the NOC dashboard. Want to look around first? In Sandbox the rocket company is yours from day one. Games you started before 3.0 keep the rules they began with. + +**Rockets, pies and crusts.** Build a pie factory and a launch pad on the coast (the closer to the equator, the cheaper each launch), then fly rockets that carry pies into four orbital shells, the crusts. Once a crust is 40% full it starts carrying traffic: pie dishes at your POPs land it on your backbone, and homes and boats in the remotest places, airlines, cruise lines and even a Mars mission sign up. A town no cable reaches can join your network through orbit. You watch it all on a spinning cartoon globe, launches and fireballs included. + +**Space is not quiet.** Solar storms, food fights in orbit, failed launches and spats with governments over landing rights keep you busy, and the Founder of your rocket company does something daft every few months, so the markets get the jitters until it wears off. Governments pay for space too, in a new Government money section of the bank. Run it well and a full constellation pays for itself in about seven years. + +**Three charters.** A new game now starts by asking what you are building. **Global backbone** is the classic game: grow everywhere and become Tier 1. **Low-latency boutique** lives on speed: trading firms call more often and pay more, and you win Speed of Light by beating the fastest leased latency on finance routes with your own glass. **Cable broker** is new: lay fiber on land and cables under the sea from day one, light them and sell the capacity to other carriers, and win Glass Baron when your own cables land on five continents while carriers pay you $1M a month. Every charter can still become Tier 1, and so reach orbit. + +**Sales runs the deals.** Your salesperson can now sign deals for you, orbit customers included, each in their own style, while the NOC intern sticks to running the network. + +- Pie in the Sky: become Tier 1 and you can start your own rocket company, putting your network in orbit. Win Tier 1 in a game started from this version (any charter), and Pie Control opens from the NOC tab, next to the NOC dashboard; in Sandbox it is there from day one. Build a pie factory and a launch pad on the coast (near the equator, launches are cheaper), fly rockets that carry satellites ("pies") into four orbital shells ("crusts"), and watch it all on a spinning cartoon globe with a night side, laser links between pies and launches that either spill their pies into orbit or end in a fireball. +- A new game now starts by asking what you are building, with three charters to choose from (#300). Global backbone is the classic game: grow everywhere and become Tier 1. Low-latency boutique: trading firms and other latency customers call more often and pay more, and you win Speed of Light by beating the fastest leased latency on finance routes with your own glass. Cable broker is new: lay fiber on land and cables under the sea from day one, light them and sell the capacity to other carriers, with ten goals of its own and the Glass Baron win when your own cables land on five continents while carriers pay you $1M a month. Every charter can still become Tier 1, and with it reach Pie in the Sky. +- Your pies carry real traffic and earn money once a crust is 40% full. Pie dishes (ground stations) at your POPs land the traffic on your backbone, with landing rights bought country by country. Homes and boats in the remotest places (Pitcairn, the Arctic, the outer islands), airlines, cruise lines and even a Mars mission sign up, and a town no cable reaches can join your network through orbit. Before a crust carries anything, buoys and sensors that live with gaps in the sky pay a little; when it starts carrying traffic, a grand opening brings a month of daily calls. +- Space is not quiet, and neither is your Founder. Solar storms, food fights in orbit, rain over tropical dishes, failed launches and geopolitical spats over data and landing rights keep you busy, and the Founder of your rocket company does something daft every few months, so markets get the jitters until it wears off. A full constellation pays for itself in about seven years if you run it well. +- Deals belong to Sales now: your salesperson can sign deals for you, orbit customers included. The NOC intern sticks to the network. The engineer, the shark and the CEO each sign in their own style, and each sells orbit their own way, from careful deals where a pie dish has room to Mars missions agreed with the Founder on the golf course. +- Governments pay for space too, in a new Government money section of the bank (Cash · Bank): the Rural Digital Pie Fund auctions support for remote towns only your satellites reach, the Export-Import Pie Bank lends against launches with strings attached, and the UK pays a grant when Pitcairn is served from orbit. +- Pie Control helps you plan: the Launch tab says how long each crust takes to fill at your current pace and points to a better pad when your pads are the bottleneck, the Dishes tab tells you when dishes are worth building, and the Traffic tab shows who rides your satellites, how full each crust and dish is, and why a sky is still empty. Traceroute follows packets through orbit too. +- The NOC tab is tidier: Pie Control sits in its top row next to the NOC dashboard, traceroute moved into Routing & DDoS, and All connections lives in the NOC dashboard. +- From customer level 9 you can lay your own subsea cable without being Tier 1 first (#300). +- Traffic now leaves your network at the nearest peering, so a PNI in London no longer pulls New York's traffic across the Atlantic when the New York IX reaches the same network (#298). Where a PNI and an IX port reach a network in the same city, the PNI still goes first, and RouteScript's `prefer pni` still hauls everything to your PNIs. +- Fabric (NNI) ports now grow like your other ports: buy them at 10G, 100G or 400G (as fast as your router takes), and bundle up to eight into a LAG when one is not enough (#140). A fabric customer is no longer accepted, by hand or automatically, when its bandwidth would not fit on the port as well (#307). +- Pressing Space to play again after a pause now picks up at the speed you were playing, not always at 1× (#299). +- Your own subsea cables now land right on the city's dot, also in Fujairah, Dubai, Karachi, Barcelona, Osaka and other cities the map shifts slightly so they do not overlap (#305). +- Starting a new network no longer leaves the last one's "New POP!" and money pop-ups frozen all over the map until a reload. + +## [2.10.1] — 2026-11-05 + +- "Meet halfway" on a renewal now offers the price halfway between what the customer pays and what they ask, and the button shows it before you press (#293). +- Fujairah sits on the UAE's east coast again, where its cables land, instead of on top of Muscat (#295). +- Puzzles on phones no longer scroll. A bar at the top shows the stars, the money and the one thing to do next, with a chip for every flow that turns green once it all arrives; tap a chip to jump to its city. A city or a link opens a short card at the bottom, split into tabs (links, router, traffic; size, traffic, routing), so every button is on screen at once. Architect runs get the same bar, and Reset is in the ☰ menu on phones. + +## [2.10.0] — 2026-11-05 + +**The map now runs on your graphics card.** Panning, zooming and fast play stay smooth even on huge networks. If something looks wrong or your phone gets warm, switch back to the old map in **Settings › Map drawing › Always 2D**. Older browsers stay in 2D on their own, and Settings › Diagnostic info shows which one you have. + +**Customers sign contracts now.** When one ends they renew, grow, haggle or leave, and bandwidth gets cheaper every year. To bring in more deals, hire someone to run sales: an engineer who goes to every NOG, a shark who oversells, or the CEO, who thinks he sells best. + +**Also new:** a "No POP yet" tab on the dashboard, clearer puzzles on phones, Gothenburg, Malmö, Haparanda and Bilbao on the map, and tooltips on the NOC charts. + +- The map is now drawn by your graphics card, so panning, zooming and fast play stay smooth on big networks (#281). If it looks wrong or your device runs hot, go back to the old drawing in Settings › Map drawing › Always 2D. Browsers without WebGL2 stay in 2D on their own, and Settings › Diagnostic info shows which one you are on. +- Customers sign contracts, and when one ends they renew, grow, haggle or leave (#178). Bandwidth prices fall over the years and rise when hardware is short, and the dashboard shows who you won and lost each month. +- You can hire one person to run sales: an engineer, a shark or the CEO himself. Each brings different deals and leaves their mark on the customers they sign. +- The NOC dashboard has a "No POP yet" tab listing every city you could still expand to. +- Puzzles explain their goals in plain words, with a Show me button and marks on the map, and fit phones better. +- Sweden gets Gothenburg, Malmö and Haparanda (#206). +- Bilbao joins the map, where the transatlantic cables really land; Columbus III-and-a-half now lands near Cádiz. +- NOC charts have tooltips, and their legend can hide a series. +- Leasing dark fiber costs more, alien waves are priced against the fiber, and extra crews can only halve a land build (#203). +- Clean traffic sent back by a scrubbing center no longer shows as DDoS junk on your links (#289). +- In Firefox on a computer, the 2D map is up to three times as fast when zoomed in. +- Fixes: a link ordered by the AI tools can no longer end in a city the map does not show, and names from a save file always show as plain text. + +## [2.9.1] — 2026-11-04 + +- Jokes in the game now poke fun at networks, cables and routers, never at people, countries or beliefs. A few networks have new names (Atlas Hold-the-Line Telecom, Star-Blink, Telekom Malay-tency, Oh Yas Sénégal, Afghan Tele-Pass, Island-Hop Micronesia, Tel-One-derful, Tango Two-Step), so do three of the names for your own cables, and about forty descriptions of networks, cities, cables and events were rewritten. +- A network operators' meeting that hires you for its event network now meets only where it really does: NANOG in the United States, APRICOT in Asia Pacific and Oceania (not mainland China or Hong Kong), DENOG in Germany, UKNOF in the UK, RIPE in Europe, the Middle East and Africa, and DKNOG in Copenhagen. +- North Korea now moves well under 1 Gbps, and no customer of any kind calls from there. + +## [2.9.0] — 2026-11-04 + +- In Architect runs, a diverse second tube now takes the cheapest other route, as a new tube does, so the Euro Run's plain plan fits its budget again. A failed review also says that every site still connected after a cut needs room for its traffic, not only the mission-critical ones (#282). +- A new button next to the speed controls opens a NOC screen in a window of its own, to keep on a second display beside the map. It is a dark wallboard with a live world map of your links and POPs, traffic and money graphs, alarms, and your hottest ports with their upgrade buttons, which work on the running game; click a POP to see its ports. Details has the full dashboard, and Full screen fills the display. The new window only shows and sends clicks: your network is still played and saved in the game window. Phones do not show the button. +- Cities of one country on one piece of land can be joined by fiber over land, even where there is no road: Pevek to Anadyr or Moscow, Juneau to Seattle, Nuuk to Sisimiut. Inside one country, crossing from Europe into Asia (Moscow–Vladivostok, Istanbul–Ankara) is no longer priced as a crossing between continents. +- No circuit of any kind can be built between North and South Korea, and nothing leaves South Korea over land: every way out is a subsea cable. +- The map zooms in twice as far, for crowded regions like New England or around Washington. +- Cable ships at anchor sit a little further out from their port, and a tap on a city picks the city even with a ship close by. +- With a credit rating of AA or better you can now call a bank from the Bank window and ask for the amount you need. The better your rating, the lower the rate and the more they will lend, up to a limit based on your revenue and what you already owe, but weird conditions always apply. (#251) +- Agents playing through the Agent API can no longer start a link in a city where you have no POP, just as on the map. Before, an agent could sign a dark fiber IRU, lease a wave or lay a cable from such a city; now it is told why, and so is its dry run. +- Build POP in a small city that is off the map now says why it can't, and names a city nearby to build in instead. Founding your own exchange where you can't (mainland China, a city that already has one, a city with no POP) says why too. Before, both did nothing without a word, and an agent's dry run quoted a price. + +## [2.8.0] — 2026-11-04 + +- Every capital of the world is now on the map, with Africa's 33 capitals completing the set. They run from Porto-Novo, Bamako and Niamey to Khartoum, Juba, Mogadishu, Brazzaville, Tripoli, Rabat and Pretoria. Each country brings its real telcos, Nigeria gets its wholesale backbone up to Abuja, and the island capitals of the Comoros, São Tomé and Equatorial Guinea sit on their real cables. +- The NOC intern has a new order, Keep peering headroom, that adds capacity to your PNI and IX ports before they fill up (#234). A single port at a POP with several routers gets a second port in a LAG; any other port moves up to the smallest size that fits. It has the same Headroom and Budget dials as the transit order, and it waits out DDoS floods, link faults and PNI augments already on order. The monthly figure in the intern's log now counts IX ports too. +- An exchange port, a transit port or a PNI can now be stepped down one size from its panel, so shrinking a port no longer means leaving and rejoining (a PNI cannot while an augment is on order). +- The traceroute can follow the metrics, the lowest latency or the quietest links, like a customer circuit. +- Money now shows billions ($1.20B) and bandwidth shows petabits (1.00 Pbps) instead of running on in millions and terabits, including on the NOC graph and the fiber labels on the map. +- Latency customers only ask for a ceiling something you can build meets. Before, a Mars ground station could ask for 4.3 ms between Pevek and Anadyr, where the only sea route takes 7.7 ms at best. (#273) +- DE-Kicks ports stop getting dearer once they cost four times the list price. Before, the yearly price harmonisation kept compounding, so a long game ended up paying $100k a month for one port at Frankfurt or Mumbai. +- Your own subsea cable from Buenos Aires to Santiago now earns The Long Way Round, like a wave leased on the old ring round Cape Horn. (#272) +- Every capital in South, East and Southeast Asia and the Pacific is on the map: Thimphu, Kathmandu, Bandar Seri Begawan, Phnom Penh, Vientiane, Ulaanbaatar, Naypyidaw, Pyongyang, Dili, Hanoi and Wellington, with the island capitals Tarawa, Palikir, Yaren, Funafuti and Port Vila. Each country brings its real telcos, North Korea reaches the world only through China and Russia, and the islands hang on their real cables. +- Every capital in the Middle East, the Caucasus and Central Asia is on the map, from Yerevan and Baku to Kabul, Tehran, Baghdad, Jerusalem, Amman, Kuwait City, Beirut, Damascus, Sanaa and Manama, with Ankara and Islamabad. Each country brings its real telcos, and Bahrain is an island on the Gulf's cables. +- Every capital in Europe is on the map: Tirana, Andorra la Vella, Minsk, Sarajevo, Zagreb, Nicosia, Vaduz, Vilnius, Valletta, Chișinău, Monaco, Podgorica, Skopje, San Marino, Bratislava, Ljubljana and Bern. Each country brings its real telcos, exchanges sit only where real ones do, and Malta and Cyprus are islands on the real PEACE, MedNautilus and Blue cables. +- Every capital in the Americas is on the map: the eastern Caribbean islands, Central America, Haiti, Guyana, Suriname and Bolivia's constitutional capital Sucre. The islands land the real cables (ECFS and Southern Caribbean Fiber), Flow and Digicel serve all of them, and Belize, Guyana, Suriname and Haiti get their own national telcos. +- Every US state capital and Washington, DC are on the map, with every Canadian provincial and territorial capital and Greenland. Greenland's capital Nuuk and three towns up the coast hang on the real Greenland Connect cables; Iqaluit has only satellites, so land your own cable there. New carriers sell transit in the north and the Canadian provinces, and exchanges sit only where real ones do. +- If you run the game on your own computer, an AI agent can now play it in your browser while you watch. Turn the Agent API on in Settings (the section only appears in a copy of the game you run with npm run dev, never on seriesoftub.es) and point an AI client at the game's MCP server: every move happens live on your screen, and docs/MCP.md in the repository explains the setup. You choose the clock: a pace from one simulated day every 30 seconds to 5 minutes, which nobody can pause and which waits while no agent is connected, or the agent moves time itself. Your game, your settings and the windows you open stay yours. +## [2.7.0] — 2026-11-03 + +- Three new cities in northern Australia: Port Hedland, Townsville and Alice Springs (#255). Port Hedland lands a new cable up the coast to Darwin and a branch of Darwin's cable out to Singapore; Alice Springs has no sea at all. In the wet season, November to April, fiber cuts in the tropical north, Darwin included, take twice as long to reach. +- New keyboard shortcuts: the arrow keys and W A S D move the map, [ and ] step through your POPs, $ through the open offers, - and = zoom out and in, n opens the NOC dashboard, and ? lists every shortcut. A letter right after n opens one of the dashboard's tabs, such as n c for Connections, and Help links to the list too. +- You can pay to hurry the survey, permits and factory of your own subsea cable, 30 days at a time (#258). Money only goes so far: the cable still has to be made, about two months plus a day for every 80 km, before the lay ships sail. +- Traceroute no longer shows an "embedded cache in your rack" hop on paths that leave over transit, an exchange or a PNI. Only traffic that really ends at one of your cache boxes shows it now. + +## [2.6.0] — 2026-11-03 + +- New Best Effort mode, the gentlest way to play: rare outages, no DDoS, no chaos monkey, no conferences and no cable ships, with sea cuts that mend on their own. PNIs are up the moment you order them, customers are more patient, a rescue loan from the Ministry of Tubes replaces game over, builds take days and prices never spike. A new Quiet notifications setting, on by default in Best Effort and available in every mode, only pops up trouble and milestones; everything else goes into the NOC log. +- Backbone, Auto-TE and DDoS settings now open from a Routing & DDoS button at the top of the NOC tab. They used to sit at the very bottom, below every notification; a red dot on the button says when Auto-TE is paused. +- The Build POP button now shows the whole price of a new POP, including the routers of your standard POP (#261). Before, it showed only the site, although the standard routers were paid for on top; a note under the button now lists them, and the intern's one-tap template prices them in as well. POPs that come with a new wave, dark fiber, your own subsea cable or a consortium seat now get the standard routers too, and those offers show the price with them. +- The intern's "Light more fiber" order has a new Optics setting: light new fiber with the biggest optic it can afford, to save channels for later (#262). Once a fiber is lit, the intern still adds more of the same optic and never swaps what is in there. +- Networks you reach through an exchange's route server now stay "via RS" (#265). With an Open peering policy, the peering desk used to turn some of them into separate sessions of their own. +- The tabs above the left panel no longer run off its edge on smaller screens and tablets. Counts such as finished goals now sit on the corner of their tab. +- Gaming customers no longer warn that they attract attacks in modes without DDoS attacks, such as Change Freeze. + +## [2.5.0] — 2026-11-02 + +**Mostly a performance release.** Big networks route their traffic on about half the processor time, days no longer freeze the game, and clicks that change nothing about your traffic answer at once, so phones last longer. Same routes, same results, just faster. + +- Big networks use about half the battery they did: each day's routing takes half the processor time, and reuses what it worked out the day before when only demand has changed. Where traffic goes does not change. +- The game no longer freezes while it routes each day's traffic on big networks. A background thread of the game does the routing, so the map, panels and buttons keep responding while days go by; what the day brings is exactly what it was before. Clicks that change your network still route right away. +- On big networks, clicks that change nothing about your traffic now answer at once: dismissing an offer or renaming your network no longer works out every route again, which also saves battery on phones. +- The calendar is real now: months have 28 to 31 days and every fourth year has a 29 February (#257). Monthly prices, loan statements, the intern's budget and paydays follow calendar months, and conferences fall on the 10th of their month. +- Cache boxes are sized for the traffic each city really sends (#260): Russian and Chinese cities get boxes for the networks people there actually use, and none for networks they cannot reach. Boxes already installed stay; remove idle ones from the POP. +- A 1.6T transponder on routers with 800G ports now takes two ports at each end, one for each 800G it hands over, and the optics list says so (#256). Before, a full 1.6T fit into a single 800G port. On 1.6T routers it still takes one. +- A plug-in optic that is too short for your subsea cable no longer sends you to submarine terminals and optical engineering, which cannot stretch it (#253). The hint now names the optics that do reach, such as the Sienna WaveMagic 1.6T for Perth to Cape Town. Optics the upgrades can stretch still get the advice. + +## [2.4.0] — 2026-11-01 + +- Cable ships now sail out to fix your subsea cables, and you can watch them on the map. A cut at sea calls the nearest free ship of its region's repair club, from ports such as Cornwall, Curaçao, Cape Town, Marseille, Vancouver, Tokyo, Manila and Singapore. The cut lasts while the ship sails out (about 500 km a day), splices for 3 to 5 days in shallow water or a week or two in the deep, and in some countries waits weeks for a repair permit. A ship is busy until it is home again. +- Doitsche Telekomm and Tangerine Telecom are now Tier 1s, as in real life (#194). In new games, going transit-free means a PNI with both of them too; games you already started keep the Tier 1s they were playing for. Doitsche now sells transit at the highest price in Europe and still charges for peering, and like the other Tier 1s, Tangerine now starts its PNIs at 100G. +- Cache boxes now share router ports through an aggregation switch: one port carries as many 100G boxes as its speed holds, so 32 fit on a 3.2T port (#252). Each site gets its own. +- Pick a standard POP: in any POP's Infra tab, make its routers the standard, and every new POP gets that model and number of routers right away, while it is still empty (#240). +- Big networks run faster: the map skips links off screen without working out their shape, and the Networks tab and the zoomed-in map draw faster. Where traffic goes does not change. +- A network the game once failed to load is no longer stuck as damaged: the next version of the game tries it again, and its menu has a Try again button. Before, it could only be exported or deleted, even after the cause was fixed. +- Save files of very large networks import again: the limit went from 8 MB to 64 MB. +- 400G cache boxes: a POP whose routers have 400G or faster ports now gets 400G boxes, at $1,000 a month instead of $400 for 100G, so big caches need fewer boxes and cost less per Gbps. Boxes you already have stay as they are. +- Clarovision now peers only over paid PNIs, like the real carrier, and free only with networks at customer level 11 or above (#213). A PNI you already have with it starts paying the fee. +- Opening a link from a list now moves the map to it, zoomed so the whole line fits beside the open panel. +- Traffic for a carrier now leaves through that carrier's own transit port at the same POP, instead of being shared with every other transit port there. Networks that buy transit from the carrier get the same treatment, and a new switch on each transit port, Carry here, pulls that traffic across your network from POPs that have no port of that carrier. Prefer, Backup only and RouteScript still win, and Prefer only does so at the POP where you set it. +- When every ship of a region's club is out, a subsea cut waits for the first one back. A private charter of the quickest free ship anywhere jumps the queue for $1M plus $200 per km it sails; the NOC intern's rush-repair order can pay it within its budget. +- Building your own subsea cable now shows the survey, permits and cable factory first, then a lay ship laying about 150 km a day. Crews can no longer speed up a cable at sea: book a second lay ship before laying starts instead, for $3M plus $150k a day, and it lays from the other end to halve that part. +- Tap a cable ship on the map to see its name, its club and what it is doing. + +## [2.3.0] — 2026-10-31 + +- Clicking a city without a POP works again while the intern's transit order is set to Already connected (#249). Before, the city panel failed to open and the map stuck to the mouse. +- The intern's Accept free caches order, and the Request caches button, now add more cache boxes as demand to a network outgrows the ones you have (#248). Before, they stopped at one box per site. +- Manila gets real exchanges: GotchaFIX Manila, the free community Bayanihan-IX and In-Vitro-IX, run by PLDTea Time. Diverge, Smarty Pants, Ditto and RISE & Shine join as Philippine networks, and PLDTea Time and Globe-Trotter Telecom now sell transit. +- Cebu joins the map on its own island, with GotchaFIX Cebu and two domestic cables from Manila: the Pan de Sal Cable Network and the Philippines Long Distance Relationship. PLDTea Time, Globe-Trotter Telecom, Diverge and RISE & Shine reach Cebu, and typhoons can hit it too. +- Davao joins the map on Mindanao, with GotchaFIX Davao. Bi-Frosted and SEA-US Later now land in Davao, as the real cables do, instead of Manila; a link you already run on their old Manila landings keeps working as a plain subsea link. Three domestic cables reach Davao from Cebu: the Pan de Sal Cable Network, the Philippines Long Distance Relationship and the new Diverge VisMin Express. RISE & Shine peers at GotchaFIX Davao. The Pan de Sal Cable Network also runs straight from Manila to Davao. +- Transit in the Philippines now costs about twice the Asian rate, as it really does, and Philippine homes pay less for broadband. GotchaFIX ports cost what the real exchange charges, about $700 a month for 10G and $2,800 for 100G. In-Vitro-IX charges about double that. +- Waves between Philippine islands now cost more than waves out of the country: Manila to Cebu costs about twice Manila to Hong Kong. +- Manila, Cebu and Davao have more people online, in line with their real populations. +- Cable names on the map no longer pile on top of each other when you zoom in. Where short cables crowd together, a name that would cover another is left out, and selecting a city shows the names of all its cables. + +## [2.2.0] — 2026-10-31 + +- DDoS attacks are realistic now: most are small, the big ones are rare, and their size no longer grows with your network, so a big network is no longer hit by floods larger than the internet's record. Attacks go after one customer (gamers and hosting attract the most) or one city's subscribers, last one to three days, and On-call sees about one a month (#242). +- A flood now arrives on every port the internet reaches you on, so more POPs and more exits spread it thinner, and a port it fills slows every customer on it. Flowspec and scrubbing behind a full port can no longer empty it (#242). +- RTBH now blackholes only the customer under attack, upstream at your transits, most exchanges and about half your private peers: everyone else is saved and the target goes dark until you withdraw it. The IX blackhole button is part of RTBH now, and RouteScript's `blackhole ddos` does the same. +- Find any city with the new 🔍 button in the top bar, or press / on a keyboard (#218). Type a city, a country (in your language or in English) or an exchange, and the map jumps there. +- Cities on the map now show how big they are: zoomed out, bigger cities are bigger dots and megacities glow; zoomed in, a city's skyline grows from a hut to a megacity's towers. When cities crowd together, the smaller ones step back to a dot until you zoom in, so the map stays readable, and exchanges you haven't joined are quieter tags. +- An engaged scrubbing center now pulls the whole flood onto its own ingress and cleans up to its size, so your ports stay clear and only the target suffers if the center is too small. On-demand scrubbing takes half the flood on its first day instead of nothing for two days. +- Each router holds a limited number of Flowspec rules, shown in its POP: every attack takes one rule on each router it enters (a carpet bomb takes four), and when they run out, junk passes that router unfiltered. Bigger routers hold more. +- The NOC's attack card reads like the flood's path: who is hit, which ports are full, what Flowspec and scrubbing do, the result and the one thing to do now. Optional Auto-RTBH and auto-engaged scrubbing switches sit in the NOC, full ports pulse on the map, and Sandbox can send a test flood. +- Flood Season starts at customer level 4, so a 10T scrubbing center is within reach for the terabit floods; a flood you blackhole to save everyone else no longer counts as held. +- The intern's transit order has a new provider choice, Already connected: it only grows the transit you already buy at each POP, the smallest port first, and never signs a new provider, so several upstreams grow together and no customer's "no Cogentle" gets a surprise (#227). +- The intern's PNI order now counts the traffic the PNI list shows at each POP, so it no longer orders a PNI where a network's own cache boxes already serve most of its traffic (#244). +## [2.1.0] — 2026-10-31 + +- Your backbone now runs a technology you choose: plain IGP, LDP/MPLS, RSVP-TE, SR-MPLS or SRv6. Each step up costs plenty and uses less router CPU: label switching makes traffic that only passes through a POP cheaper for its router, and Auto-TE and RouteScript now need RSVP-TE or higher. Routers only run what they support, so a POP with an older router stays outside the backbone, and mixing vendors at the very top of what their routers can do brings interop failures. Networks that already have Auto-TE keep it exactly as it is. +- An upgraded backbone brings new customers: L3VPNs for enterprises from LDP/MPLS, flex-algo low-latency links from SR-MPLS and network slices from SRv6. +- A seat on a consortium cable can be lit with the optics you have: add regen sites in the landing stations along the cable. Before, a seat bought at level 2 or 3 stayed dark until long-haul transponders arrived at level 4. +- List spare capacity with a capacity broker as a standing listing: pick how many alien waves (or your spare pair) to sell, and the broker sells them off over time as carriers on that route want capacity. Each route's market is sized by the eyeballs at both ends, and a busy route sells in days while a road to nowhere sells maybe once, so renting out long empty fibers is no longer a money machine (#203). +- Two new routers for RSVP-TE backbones: the refurbished Brocadabra MLX-16 with 400G ports, and the Extremely Networks SLX 9740 with 1.6T ports. +- From RSVP-TE up, fast reroute has backup paths ready, so customers lose only half as much happiness while a link is cut. +- An interop lab in the NOC tests your vendors against each other first and cuts interop incidents by 60%. +- Four new badges for your backbone: Label switcher, Bleeding edge, Single-vendor shop and Vendor zoo. +- The chaos monkey's notice in the NOC no longer has an Open button that did nothing; the monkey's own card is right above it (#226). +- The puzzle list counts each section's own stars: architect runs show theirs next to their title, and the pack total now sits right above the packs, the stars that unlock the next one (#231). +- The intern's notes now name the exchanges it peered at: a city's first exchange showed as the city, so "Apfelwein-IX, London" really meant Apfelwein-IX and LYNX (#228). +- Cancelling an IRU, giving up your own fiber or decommissioning a POP now puts the optics on its fibers back on the spares shelf, instead of throwing them away (#229). +- Big networks freeze for less on every game day and every click: working out where traffic goes skips exits whose route is already full, so a game day takes about 40% less time (#210). Traffic goes exactly where it went before. +- Premium submarine terminals and Optical engineering can no longer be bought on a cable where they would change nothing (#198). The button now says so, and an upgrade that only helps together with the other one stays available. +- A wave size that is sold out on a route can no longer be reached by upgrading a smaller wave on it (#201). The upgrade button says how long it is sold out, just like when buying. +- Choosing Both for a PNI with one member now really splits it: the second member arrives in the other building when the augment lands, instead of joining the first (#219). +- The Open button next to your intern's weekly shift report in the NOC now opens the Standing orders sheet, where the whole week is laid out (#226). Before, it did nothing. + +## [2.0.0] — 2026-10-30 + +**Series of Tubes 2.0: one game, four doors.** Some of you wanted a calmer game, some a harder one, some a quick puzzle over coffee and some a playground where nothing can go wrong. So now every network starts behind a door, and the rules you pick stay with that network for good. Your saved games carry on exactly as they were. + +**Normal** comes in three flavours. Change Freeze is the calm one: a third of the outages, no DDoS floods, and deliveries in days instead of months. On-call is the game you know. BGP at 3 a.m. is for people whose pager is a personality: more outages, longer ones, more attacks, and fiery badges to prove you survived. In your first month you also pick a charter: a global backbone, or a low-latency boutique racing the speed of light. + +**Sandbox** is a real sandbox now: everything unlocked from day one, money that never runs out, and a chaos dial from nothing ever breaks to spicy. + +**Puzzles** are small networks that carry real traffic, routed exactly like the big game. Deliver every flow for the first star, stay on budget for the second, and survive any single cut for the third. When your build earns a star, the chaos monkey runs round the map snipping every trench and cable to prove it. A new puzzle arrives every Sunday morning, the same for everyone. + +**Architect runs** grow one network brief by brief. New sites sign up, some become mission-critical, a city closes, traffic outgrows its tubes, and the chaos monkey reviews every brief before the next customer signs. Three handmade runs to start, and a fresh one every Sunday with its HQ somewhere new. + +**Scenarios** are themed crises against the clock: a cut cable, a peering spat, a flood week, a race for low latency. A new one comes out every Sunday too. + +And in On-call and BGP at 3 a.m., a **chaos monkey** sometimes moves into your network for a few months and snips tubes on purpose, the ones without a backup path first. Outlast it without a customer noticing and it pays; throw it a banana if you have had enough. + +**Also new:** Tier 1 works like the real thing, so peering with the big club brings their customers along. A NOC intern carries out your standing orders. Customers call when your network can serve them, not only when your level says so. You can buy a seat on a consortium subsea cable, see at a glance whether a PNI is worth it, keep several networks and play two side by side, and every router model has its own face. + +### One game, four doors + +- A new start screen with four doors: Puzzles, Sandbox, Normal, and Scenarios & weekly. Every network now picks its rules when it starts, and they stay locked for that network; your saved games carry on exactly as before. +- Normal comes in three flavours. Change Freeze has a third of the outages and no DDoS floods, delivers PNIs, cross-connects and builds in days instead of months (#151), and skips hardware shortages, sold-out routes and de-peering at exchanges. On-call is the classic game. BGP at 3 a.m. brings almost twice the outages, lasting half as long again, and twice the DDoS. The HUD and the share card show which one you picked. +- Sandbox is a real sandbox now (#188): everything is unlocked from day one, your own subsea cable included, money never runs out, deliveries are quick, and you pick how much chaos you want, from none to spicy. +- Pick a charter in your first month of a Normal game: Global backbone (the game as you know it, and the default) or Low-latency boutique (#187). The boutique gets more trading firms, pays them 40% more and has its own win, Speed of Light: beat the fastest leased latency on three finance routes with your own glass while two latency customers pay you. It comes with a badge and shows on your share card. +- Badges now come in variants: games under the Change Freeze rules earn frosted Freeze-dried badges, and games under BGP at 3 a.m. earn fiery ones worth bragging about. Earning a badge under harder rules than before upgrades it in your collection on this device, and the badge list counts how many of each kind you have. On-call games earn the standard badges; Sandbox and puzzles earn none. +- Keep several networks on one device, and play two of them side by side in two browser windows. The title screen lists your networks, newest first, with their day, tier, cash and when you last played; tap one to continue it, or use ⋯ to export or delete it. Starting a scenario, the weekly challenge or a new network, or importing a save, now adds a network instead of replacing the one you have, and you can rename a network from the menu. Each window remembers its own network when you reload it. If a network is already open in another window, you can switch to it or take it over, and the other window steps aside instead of both saving over each other. Your existing save carries on as your first network. +- A tidier start screen: language first, then your network's name, the doors, three compact difficulty buttons with the chosen one explained below, and one drop-down for your home city with the five suggested homes at the top. +- Pick your own AS number next to your network's name when you start (#135). Leave it empty and the game picks one, and the round green arrow in the name box suggests another name. + +### Puzzles + +- Puzzles: small networks that carry real traffic, routed exactly like the main game (#190). Each puzzle has flows to deliver (eyeballs pulling from a content origin, circuits between two cities with a latency cap, best-effort traffic that may drop), and the map shows every link's load as it fills. Earn up to three stars: everything delivered, under budget, and still delivered when any single trench or cable is cut. Build with the real tools: link sizes from 10G to 800G, parallel links in the same trench or on a diverse route (also from the link panel), routers with real ports and limits, routing metrics, standby, lowest-latency paths for circuits, and the redundancy check. The whole world is open: any city can get a POP if it helps. Parallel links show their count and sizes, and selecting a city lights up every path it has. Eighteen puzzles in five packs, each teaching one idea: Fat Pipes, Router Rodeo, Traffic Cops, N-1 Club and Grand Tour. No clock, no bills, nothing breaks, and your main game is never touched. +- A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle with its own traffic, such as an ocean crossing, a ring, a latency sprint, island hopping or a detour around a busy hub, with its own name and a budget tuned so three stars take a smart design. The Puzzles door says "New this Sunday!" until you have played it, the list counts down to the next one, and your streak and share line use the week's name. A new puzzle week starts on Sunday at 06:00 Berlin time; offline, the game still has a weekly puzzle of its own. +- Every puzzle now has the chaos monkey: when your build earns a new star, it runs round the map snipping each trench and cable in turn, and the cities that lose traffic say how much. Let it loose again whenever you like, or skip straight to the stars. +- In puzzles, the map now shows whether the tubes between two cities share one trench or take separate paths, at any zoom: one trench is drawn as a bundle with a "2× one trench" tag, separate paths bow apart with a "2 paths" tag. +- When a new release changes prices so that this week's or a coming week's puzzle no longer adds up, that puzzle gets a fair new budget, and only its stars start again. Weeks that are over keep theirs. + +### Architect runs + +- Architect runs, under Puzzles: grow one network brief by brief, from a single tube to a ring that shrugs off any cut. Your build carries over between briefs, mission-critical sites must survive any single trench or cable cut with room on the detour, and a chaos monkey runs round the map snipping tubes before the next customer signs. Three runs to start: Euro Run, Coast to Coast and Pacific Rim. +- A new Architect run every week: every Sunday a fresh HQ somewhere in the world and six or seven briefs, each built around the network you already have, with its own stars. Sites can outgrow their tubes, so some briefs are about making room. Later briefs stay a surprise in every Architect run: their cities only appear when they come. + +### Scenarios + +- A new weekly scenario every Sunday morning too, the same for everyone: a themed crisis such as a cut cable, a peering spat, a big event, a flood week, island hopping, a race for low latency, a push across a continent or a shoestring budget, in about a year of game days. It sits at the top of Scenarios & weekly with a countdown and a "New this Sunday!" badge, has its own goal and progress card, a par to beat, a weekly streak and a result line to share. Offline, the classic weekly challenge stands in. +- Scenario tuning: every handmade scenario now asks for what its story is about, with shorter clocks where it was won in a tenth of the time. Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only when your network joins them up; Fibre to the Basement also wants 500 Gbps served; in Anchors Away nobody sells transit in Tallinn and ships really do drag their anchors over the Baltic links, while the Great Firewall's losses no longer break your 99.5% streak; in the Cogentle Spat, Goggle wants a lot more of your traffic before it peers; Flood Season's terabit floods count when your scrubbing or Flowspec took them; Stepping Stones and Mid-Atlantic Accent start with 5M, enough to light the whole 1.6T chain. Gangnam Style Peering is now really about sender pays: Seoul transit carries a fee on every Gbps, the three incumbents only peer over a paid PNI, and Korean users notice every millisecond, so you win by hauling cheap Tokyo transit while keeping Seoul fast and in profit. + +### The chaos monkey + +- A chaos monkey now and then moves into your network in On-call and BGP at 3 a.m., and snips a tube every couple of weeks for 120 to 240 days, tubes with no backup path first. Its snips replace the usual random outages while it is here; get through the visit without a customer noticing for a resilience bonus and a new badge, or throw it a banana to send it home early. The "Met the Backhoe" badge is now "Met the Chaos Monkey", earned on its first visit; badges you already have stay yours. + +### Build your network your way + +- Customers now call when your network can already serve them, not only when your level says so (#187). A fast path between two finance cities brings trading firms, lit dark fiber brings AI interconnects, two diverse paths in one country bring sovereign clouds and broadband in a big city brings cloud gaming, each at its smallest size and with a note on what they spotted; your level still makes them bigger and more frequent. +- Routers, line systems and optics one level above yours can be had early as a vendor demo unit (#187). Ask the vendor, wait about two weeks, then pay 60% over list until your level catches up; and you can dig your own dark fiber from level 2 as a pioneer, at 60% more than the level 3 price. +- Take a seat on a new consortium subsea cable (#173). Capacity conferences offer them, and now and then a consortium calls from level 2: pay your share of the build, wait for the ship, then own one, two or four fiber pairs and light them with your own optics, your way onto your own subsea glass before Tier 1. A cut on that cable cuts your pairs too. +- Hire a NOC intern and give them standing orders: from customer level 2, Kevin from the night shift, Anycast Annie or Tracy Route runs your rules once a game day and pays exactly what your own clicks would. Keep transit above a multiple of its peak, add or swap routers above a load, take free caches, peer at every IX and PNI with the big networks every week, sign ready customers and decline tiny ones, rush repairs, light more fiber and retire small parallel waves. Each order has a pause switch, its own settings, a monthly budget and per-POP exceptions, never breaks a customer's or a bank's transit requirement, and shows what it adds to your monthly bill. The Ops sheet opens with the intern's mood and a weekly shift report, which is also the one notice a week the intern leaves in the NOC (#98, #100, #102, #181, #185, #192, #177). +- The intern only signs a customer after a trial run shows the network can carry them without hurting anyone else, and rushes every repair that has a price, while the budget lasts (#185). The bulk peering and PNI batches live in the Ops sheet, next to the orders that repeat them (#181, #192). +- Open a new city from a template in one tap: POP, broadband, transit, an IX port and the redundancy kit, priced up front, with your standing orders taking it from there (#98, #192). +- Utilities join route servers and request eligible peers across every joined IX, install missing PoP redundancy hardware and balance caches between sites, and request a cache from each eligible provider at each site. A POP's Infra tab shows the redundancy kit as one line with its price, above the rows it fills in. +- Order PNIs with one network or every network at all shared POPs from the Ops sheet: choose a port size, review the total cost, and add missing connections or upgrade smaller ones in one go. Each network keeps its own smallest PNI size and delivery time. +- Set the number of each optic model directly on land and subsea fiber links. Apply a whole change at once, with its total price shown before buying; removed optics return to the spares shelf. +- Every router model has its own picture: open one of your POPs and its router sits next to the city's name. + +### Peering and Tier 1 + +- Tier 1 now works like the real thing: peer with the Tier 1 club and their customers come along for free (#85). A PNI or an exchange session reaches the networks you peer with and everyone who buys transit from them, so you no longer chase every tiny ISP for the win; only networks that buy transit from nobody, like the content giants and the big incumbents, still need peering of their own. Small networks and more real eyeball ISPs now buy transit from real-world upstreams, a peer's customers are tried after your direct peers and before transit (so peering widely still pays), the traceroute shows the hand-off, and the Road to Tier 1 card counts who already comes along. Games already won stay won. +- The peering inbox is gone: your peering policy now answers every peering request for you. Open accepts everyone, Selective accepts small networks on the exchange and newcomers with an up-to-date PeeringDB and quietly declines the rest, and Closed declines them all; once a week the NOC log sums it up, like "Peering desk: 7 new sessions at DE-KICKS and HAMS-IX, 3 declined (Selective)". Max-prefix alerts, the button that raised every limit at once, max-prefix outages at exchanges, your peering reputation and the Large Peering Model are gone too. The policy picker sits in the Networks tab, saved games keep their policy, and a game that hired the AI simply stops paying for it. +- Every network in a POP's PNI list now shows how you reach it today and whether a PNI there is worth the cross-connect (#175, #172). A chip says PNI here (with size and load), PNI elsewhere, which exchanges you peer at, whose customer cone carries it, transit only or not reached; a value line shows how much of its traffic leaves from that POP over transit, exchanges or other PNIs, and what a PNI there would save or cost a month. The best candidates get a ⭐ Worth it tag, the list sorts them first, filters to All, Via transit, Worth it or Already PNI, and groups networks by type, with idle groups folded. The same chip shows in the Networks tab and in the bulk PNI preview. +- Only Spätzle-IX now asks for 50% reach instead of 45%, since peering with the Tier 1 club brings their customers along. Two Tier 1 PNIs and the exchange are no longer quite enough (#114). +- Every country on the map now has at least two homegrown eyeball networks. Sixty-three real consumer ISPs and mobile operators join, from Angola and Bangladesh to Iceland, Japan and Zimbabwe, each with its real AS number and a pun name. They buy transit from the big carriers, so peering with the Tier 1 club reaches them too, and saved games get the usual courtesy route to them for their first 60 days. +- Palau's and the Marshall Islands' main networks now show their real AS numbers instead of ones borrowed from networks elsewhere. + +### Prices, routing and money + +- Prices now follow how connected each city really is, based on public peering and routing data. Every city on the map now has it, from Düsseldorf and Riga to Malé, the Caribbean and the Russian Arctic. Transit costs up to 1.8× more in cities where few networks are present, a POP costs 1.25× to 1.5× where there is little or no carrier-neutral data center, and countries with thousands of networks, like Brazil and the US, bring more ISP customers. Big hubs such as Frankfurt, Amsterdam, New York and São Paulo keep their prices. +- Every city now knows its country. Long-distance waves cost double only where they cross a border inside Africa, as they always meant to; a few northern routes, such as Kristiansand to Esbjerg and Anchorage to Halifax, lose a surcharge they picked up by mistake. +- Transit bills no longer change when you click something later in the day. After each day, the 95th percentile counted that day twice and dropped the oldest day, so building or changing anything could nudge your transit bill (and the bank's view of it) until the next day came round. +- Links can now use a custom routing metric, set either as a multiplier or as an exact cost. Pick Custom under Routing metric to fine-tune where your traffic goes; it explains how a link's cost is worked out and what each preset comes to on that link. +- Check a selected link’s redundancy against current demand: see disconnected endpoints, additional service loss and full fallback links without changing the live network. + +### Attacks + +- Attacks are more varied: sizes and lengths change from one attack to the next, and several can hit at once, each with its own controls in the NOC. Hosting game servers or cloud gaming makes attacks more frequent, as it does in real life (#153). +- Hosting game servers or cloud gaming brings RackNet and TeamSpooked attacks. Both bypass Flowspec and require dedicated mitigation (#153). +- Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation (#153). +- Game server and cloud gaming customers now carry a “Gaming attracts attacks” note on their offers and customer lists, so you can see the DDoS risk before signing them (#153). +- Each live attack in the NOC now shows incoming bandwidth, upstream scrubbing, edge filtering, scrubbing-center use and any traffic still leaking through (#153). +- DDoS bandwidth now adds up: upstream scrubbing, edge filters and scrubbing centers work in sequence. The NOC uses the same figures as traffic routing, including floods that cannot reach a remote center (#153). +- Live attacks now show how much traffic Flowspec actually drops. Routers without TCAM no longer claim to filter attacks, and Flowspec drops are counted separately from other edge filters (#153). +- Live attacks now show one scrubbing detour from the attacked city to its nearest active scrubbing center, using the links' one-way latency (#153). +- The link traffic breakdown now shows the correct source city for scrubbing traffic. Cities using the same center no longer overwrite each other's labels (#153). +- Flood Season keeps sending ever larger attacks when you keep playing after winning or running out of time. Finishing the challenge no longer switches the floods off (#153). +- Flood Season escalates again: ordinary floods mixed with terabit monsters, all growing through the year, and floods go for the POPs that serve customers, so empty POPs no longer hold them for free. + +### Smoother and safer + +- Big networks load faster: on a phone, the map of a late-game network now appears about a second and a half sooner. +- The Networks list shows 100 networks at a time, with a button for the rest, so it opens quickly now that every country has its own networks. +- When your browser's storage is full, the warning now lists your other networks by size so you can export or delete one to make room. Closing the tab in the middle of a puzzle no longer loses recent progress on the network you set aside. +- The China licence follows quick lead times: about 5 days instead of 45 under Change Freeze and in Sandbox. +- Imported saves can no longer change a network's rules or slip HTML into a Flood Season attacker's name. + ## [1.37.0] — 2026-10-28 - Series of Tubes now speaks German. The game follows your browser's language the first time, and you can switch to German under Settings or on the title screen. Networking terms like Peering and Transit stay in English, the way network engineers say them. @@ -114,7 +475,7 @@ All notable changes to this project are documented here. The project follows - Come chat with other players in the new Series of Tubes Signal group. It's linked from the title screen, the menu and How to play: share screenshots, report bugs and argue about peering policy. - RouteScript speaks more BGP. `prefer transit` and `avoid transit` set which upstream goes first, like local-pref, `prepend transit PROVIDER 1-3` moves part of an upstream's traffic away, the way AS-path prepending nudges the rest of the internet, and `protect customers` routes business traffic first when links are congested, so home users take the hit instead of your SLAs. A new Optimize button drafts a script from live traffic and points out networks you could reach over an IX or a PNI instead of transit. - Twelve more Latin American cities: Montevideo, Asunción, Córdoba, La Paz, Quito, Medellín, Caracas, Guatemala City, San José, Querétaro, Monterrey and Guadalajara. Moviestar, Liberty Latte America, Antelope and Tiger Mobile join them, and Salvador and Montevideo get cable landings. -- Seven new cables around Africa (ACE of Spades, SAT-3-Legged Stool, MainOne-Track Mind, Mint Tea West Africa, Set SAIL, Sea-Comedy Hour and Dare-Devil-1), and the existing ones now stop in the new cities. Set SAIL and SACS-y Cable link Brazil to Cameroon and Angola, and Sea-Comedy Hour links Djibouti to Mumbai. Liquid Lunch Networks, Sea-Comedy Networks, Angle-a Cables, Djibouti Calling, Empty-N, Air-Tell Africa, Ethio-Tele-Calm and Atlas Shrugged Telecom join the networks. +- Seven new cables around Africa (ACE of Spades, SAT-3-Legged Stool, MainOne-Track Mind, Mint Tea West Africa, Set SAIL, Sea-Comedy Hour and Dare-Devil-1), and the existing ones now stop in the new cities. Set SAIL and SACS-y Cable link Brazil to Cameroon and Angola, and Sea-Comedy Hour links Djibouti to Mumbai. Liquid Lunch Networks, Sea-Comedy Networks, Angle-a Cables, Djibouti Calling, Empty-N, Air-Tell Africa, Ethio-Tele-Calm and Atlas Hold-the-Line Telecom join the networks. - Hamburg and Munich join the map, with the Moin-IX and the Brezn-IX. Stuttgart and Frankfurt are back where they belong on the map, with Stuttgart between Frankfurt and Zurich instead of halfway to Prague. - Swapping router models now sells the old ones on eBuy for 30% of their price, and removing a router does too (#82). A POP takes one swap a day, so a double click no longer buys two upgrades, and optics and waves now say which port speed they need instead of naming one model. - Fiber between nearby cities bends gently again instead of looping wide around the neighbourhood, so dense regions like Toronto, Ottawa and Montreal stay readable. diff --git a/CLAUDE.md b/CLAUDE.md index bf2ab35..439c4a1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,7 +5,8 @@ https://seriesoftub.es, hosted on GitHub Pages. The game is one static page with Its source is many small files in `src/` (`src/styles/*.css`, `src/game/**/*.js`, the shell `src/index.html`); the build pastes them together, in path order, into a single `index.html`, the same one-file page players have always loaded. Static files (dictionaries, icons, service worker) -live in `site/`. +live in `site/`. `src/agent/` (the facade the MCP server plays through) goes into the development page only, +never into the page players get, and nothing in `src/game/` may use it (`docs/adr/0004-dev-only-code.md`). Read these before larger changes: @@ -13,12 +14,14 @@ Read these before larger changes: - `docs/adr/`: decisions that are settled (GitHub Pages only; one page assembled at build). - `.claude/skills/`: step-by-step procedures (`edit-the-game`, `github-pages`, release, translations, tests, performance). +- `.claude/skills/gameplay-rules/`: the game's design rules (W1, N3, F2…), each enforced by + `tests/gameplay-rules.test.js`; run it before changing cities, networks, cables, modes or balance. ## Commands ```bash npm ci # once: installs jsdom for the tests -npm run dev # play while developing: http://localhost:8080, reloads on save +npm run dev # play while developing: http://localhost:8080, reloads on save (--host to share) npm test # node:test + jsdom, every tests/*.test.js, must stay green node scripts/i18n-check.js # must report "0 missing, 0 unused, 0 broken" (and sorted dictionaries) node scripts/i18n-add.js FILE.json # add/change/remove translations (see `add-strings`) @@ -26,6 +29,7 @@ npm run build # builds _site/ for GitHub Pages (assembles src/, s npm run serve # build and serve the production site locally npm run perf -- --base-ref origin/main # big-network benchmark vs main (see `performance`) npm run perf -- --base-ref origin/main --browser # the same, also in real Chromium (desktop and phone) +npm run mcp # the game as a local MCP server for AI clients, stdio or --http (docs/MCP.md) ``` ## Hard rules diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 77ad90b..9021e8f 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -29,7 +29,7 @@ project, online or at a conference bar after NANOG. - **Own your mistakes.** We all fat-finger a config now and then. Apologise, fix it, move on. - **Keep the jokes kind.** This game runs on puns. The target of a joke is a network, - a cable or a backhoe, never a person or a group of people. + a cable or a router, never a person or a group of people. ## What we don't accept diff --git a/README.md b/README.md index 83dfe55..ec085fa 100644 --- a/README.md +++ b/README.md @@ -52,10 +52,11 @@ and remembers the one you pick under Settings or on the title screen. ```sh npm ci -npm run dev # development server: assembles src/ on every request, reloads on save +npm run dev # development server on localhost (--host to share): assembles src/ on every request, reloads on save npm test # headless tests: boot, geography, a year of play, every incident, every panel npm run build # writes the site for GitHub Pages to _site/, with version and date stamped in npm run i18n:check # lists text missing from (or stale in) the translations +npm run mcp # the game as an MCP server, so an AI client can play and debug it, headless or in your tab (docs/MCP.md) ``` ## Community diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..1ce5130 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,28 @@ +# The MCP server and the development server in one image (docs/MCP.md, "In a container"). docker.yml builds it and +# publishes it to GHCR for releases only; nothing here is ever deployed to GitHub Pages (docs/adr/0001-github-pages-only.md). +# The base is pinned by digest and kept current by Dependabot (.github/dependabot.yml); CI tests on the same Node major. +FROM node:24-slim@sha256:01d566e8d94d8c619591d78652babfccd3c6992a3dffa9ed5ab39e11cf6c70e9 + +WORKDIR /series-of-tubes + +# Dependencies first, exactly as locked, so a change to the code reuses this layer. Every dependency is a dev one (the +# game has none), and the servers need them all. No install scripts run. +COPY package.json package-lock.json ./ +RUN npm ci --no-audit --no-fund --ignore-scripts && npm cache clean --force + +# Only what the servers read: the game's source and static files, the scripts, and the harness the MCP server plays +# through. Owned by root and read-only to the server, which runs as node. +COPY src ./src +COPY site ./site +COPY scripts ./scripts +COPY tests/harness.js ./tests/harness.js +COPY --chmod=0755 docker/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh + +# --save-dir /saves needs somewhere the server may write: a volume mounted here takes this ownership. +RUN mkdir /saves && chown node:node /saves +VOLUME /saves + +USER node +ENV NPM_CONFIG_UPDATE_NOTIFIER=false +EXPOSE 8080 7777 +ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] diff --git a/docker/docker-entrypoint.sh b/docker/docker-entrypoint.sh new file mode 100644 index 0000000..355af5a --- /dev/null +++ b/docker/docker-entrypoint.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Starts the container's servers (docker/Dockerfile, docs/MCP.md "In a container"). +# MCP_MODE=browser (default): the development server on :8080, with the relay a player's tab dials, and the MCP server +# on :7777 driving that tab. +# MCP_MODE=headless: only the MCP server, with a game of its own. +# Everything after the image name goes to scripts/mcp.js (node scripts/mcp.js --help lists the options). +set -uo pipefail +cd /series-of-tubes + +mode=${MCP_MODE:-browser} +case "$mode" in + browser|headless) ;; + *) echo "[entrypoint] MCP_MODE must be browser or headless, not '$mode'" >&2; exit 1 ;; +esac + +extra=("$@") +has() { local a; for a in "${extra[@]}"; do [ "$a" = "$1" ] && return 0; done; return 1; } + +# A container must listen beyond loopback to be reachable at all; --http in the arguments overrides it. +http=(--http 0.0.0.0:7777) +has --http && http=() + +# Listening beyond loopback, the MCP server would take orders from anyone who reaches the port (its Host check stops +# browsers, not other clients), so it gets a token. None given (SOT_MCP_TOKEN or --token-file): this run makes one and +# prints it. MCP_NO_TOKEN=1 turns that off, for a port published to 127.0.0.1 only. +if [ -z "${SOT_MCP_TOKEN:-}" ] && ! has --token-file && [ "${MCP_NO_TOKEN:-}" != 1 ]; then + SOT_MCP_TOKEN=$(node -e "process.stdout.write(require('node:crypto').randomBytes(24).toString('base64url'))") + export SOT_MCP_TOKEN + echo "[entrypoint] No SOT_MCP_TOKEN given: this run's token is $SOT_MCP_TOKEN" >&2 + echo "[entrypoint] claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp --header \"Authorization: Bearer $SOT_MCP_TOKEN\"" >&2 +fi + +pids=() +start() { "$@" & pids+=("$!"); } +shutdown() { + trap '' TERM INT + kill -TERM "${pids[@]}" 2>/dev/null || true + wait "${pids[@]}" 2>/dev/null || true + exit "${1:-0}" +} +trap shutdown TERM INT + +# node directly, not npm run: one process less, and signals reach the server. +if [ "$mode" = browser ]; then + start node scripts/dev.js --host 0.0.0.0 --port 8080 + start node scripts/mcp.js --browser "${http[@]}" "${extra[@]}" +else + start node scripts/mcp.js "${http[@]}" "${extra[@]}" +fi + +# One server stopping stops the container, with its status, so a restart policy can bring both back. +status=0 +wait -n || status=$? +echo "[entrypoint] a server exited with status $status; stopping the container" >&2 +shutdown "$status" diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b3eb5ec..4731c99 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -11,8 +11,13 @@ src/ the game page, in pieces i18n/en.js the English for every label → inlined at the top of the page's '; +const MP = process.argv.includes('--mp') ? require('./lib/mp').createMp({ dir: path.join(ROOT, 'mp-data'), createPerHour: 1000, joinPerHour: 1000, log: (s) => console.error(s) }) : null; const clients = new Set(); function page() { - const { html, map } = assemble(); + const { html, map } = assemble({ dev: true }); // Errors report a line of the assembled page; the console also says which file under src/ that is. - const hint = ``; - return html.replace('', `${hint}${RELOAD}`); + const hint = ``; + return (MP ? html.replace("/*__MP_API__*/''", () => "'/api/mp'") : html).replace('', `${hint}${RELOAD}`); } -http.createServer((req, res) => { +const server = http.createServer((req, res) => { const url = new URL(req.url, 'http://localhost'); + if (MP && MP.handle(req, res)) return; if (url.pathname === '/__dev') { res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' }); res.write(': hi\n\n'); @@ -45,10 +58,26 @@ http.createServer((req, res) => { res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' }); fs.createReadStream(file).pipe(res); } catch (e) { + // The stack goes to the terminal running the server, never into the response. + console.error(e); res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' }); - res.end(String(e && e.stack || e)); + res.end('Could not build the page: see the terminal running npm run dev.'); } -}).listen(PORT, () => console.log(`Series of Tubes (dev): http://localhost:${PORT}/ — edits in src/ and site/ reload the page`)); +}); +const relay = createRelay({ server }); +server.on('error', (e) => { console.error(`error: could not listen on ${HOST}:${PORT}: ${e.message}`); process.exit(1); }); +server.listen(PORT, HOST, () => { + // The banner reports the socket's real address, not the flag it was asked for. + const ad = server.address(), at = `${ad.family === 'IPv6' ? `[${ad.address}]` : ad.address}:${ad.port}`; + const local = /^(127\.|::1$|localhost$)/.test(ad.address); + console.log(`Series of Tubes (dev): http://${at}/ — edits in src/ and site/ reload the page`); + console.error(`[series-of-tubes] agent relay on ws://${at}${relay.path} (no token)${local ? '' : `: bound to ${ad.address}, so anything that can reach this address can drive a game whose player turned agent mode on`}`); + console.error('[series-of-tubes] to let an agent play: Settings → Agent API in the game, then node scripts/mcp.js --browser'); + if (MP) console.error(`[series-of-tubes] multiplayer on: API at http://${at}/api/mp, sessions in ${path.relative(ROOT, MP.dir) || MP.dir}/`); +}); +const shutdown = () => { relay.close(); process.exit(0); }; +process.on('SIGINT', shutdown); +process.on('SIGTERM', shutdown); let timer = null; for (const dir of ['src', 'site']) { diff --git a/scripts/gpu-bench.js b/scripts/gpu-bench.js new file mode 100644 index 0000000..59ed482 --- /dev/null +++ b/scripts/gpu-bench.js @@ -0,0 +1,76 @@ +#!/usr/bin/env node +// The map's speed on your own graphics card, 2D against WebGL, in the browser you play in: +// +// npm run bench:gpu -- --save path/to/save.json (an exported save, or a plain one; default: the perf fixture) +// +// then open the printed address in Chrome, Edge or Firefox and press Start. Headless benchmarks (npm run perf) draw the +// canvas in software, so they cannot say what a GPU does; this one runs where the GPU is. Each scenario plays a few +// seconds with the 2D map and with the WebGL tubes, the table shows in the page, and the server prints it here when the +// run ends. Options: --port N (8090), --secs N per scenario (6), --host 0.0.0.0 to open it from a phone on your network, +// --out FILE to also write the table there. Under WSL, the Windows browser reaches http://localhost:PORT as it is. +// In the address: ?only=gl or ?only=2d (one renderer), ?scen=x1-mid,pan (some scenarios), ?dpr=2 (a 4K screen's +// pixels on a smaller one), ?auto (start at once). The game's clock keeps running: incidents do not pause it. +const fs = require('node:fs'); +const os = require('node:os'); +const http = require('node:http'); +const path = require('node:path'); +const { assemble, ROOT } = require('./lib/page'); +const { lit } = require('./lib/js-literal'); + +const args = process.argv.slice(2); +const opt = (k, d) => { const i = args.indexOf('--' + k); return i >= 0 ? args[i + 1] : d; }; +const PORT = +opt('port', 8090), HOST = opt('host', 'localhost'), SECS = +opt('secs', 6), OUT = opt('out', null); +const SAVE = path.resolve(opt('save', path.join(ROOT, 'tests', 'fixtures', 'big-network.json'))); +const SITE = path.join(ROOT, 'site'); +const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css', '.json': 'application/json', + '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.webmanifest': 'application/manifest+json' }; + +// An exported save is {app, version, S}; a plain one is S itself. +const save = (() => { const d = JSON.parse(fs.readFileSync(SAVE, 'utf8')); return JSON.stringify({ S: d && d.S && d.S.pops ? d.S : d }); })(); +const client = fs.readFileSync(path.join(__dirname, 'lib', 'gpu-bench-client.js'), 'utf8'); +const page = () => assemble().html.replace('', ``); + +/* Only the page this server hands out may talk to it. Any other site open in the same browser could otherwise + POST results (printed to this terminal, written to --out) or, through DNS rebinding, read the save. So the Host + header must name this server, and a POST must come from its own origin. */ +const HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', HOST.includes(':') ? `[${HOST}]` : HOST]); +if (HOST === '0.0.0.0') for (const l of Object.values(os.networkInterfaces()).flat()) if (l && l.family === 'IPv4') HOSTS.add(l.address); +const hostOk = (h) => { const m = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(h || ''); return !!m && HOSTS.has(m[1].toLowerCase()) && (m[2] ? +m[2] : 80) === PORT; }; +const MAX_BODY = 2 * 1048576; +// What the page sends is printed and written as text: no terminal escape sequences or other control characters. +const plain = (s) => String(s ?? '').replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u2028\u2029]/g, ''); + +http.createServer((req, res) => { + const url = new URL(req.url, 'http://localhost'); + try { + if (!hostOk(req.headers.host)) { res.writeHead(421); return res.end(); } + if (url.pathname === '/' || url.pathname === '/index.html') { res.writeHead(200, { 'content-type': TYPES['.html'], 'cache-control': 'no-store' }); return res.end(page()); } + if (url.pathname === '/__bench/save.json') { res.writeHead(200, { 'content-type': TYPES['.json'], 'cache-control': 'no-store' }); return res.end(save); } + if (url.pathname === '/__bench/results' && req.method === 'POST') { + if (req.headers.origin !== `http://${req.headers.host}`) { res.writeHead(403); return res.end(); } + let body = '', size = 0, over = false; + req.on('data', (c) => { size += c.length; if (size > MAX_BODY) { over = true; req.destroy(); return; } body += c; }); + req.on('end', () => { + if (over) return; + try { const r = JSON.parse(body), md = plain(r && r.md); console.log('\n' + md + '\n'); if (OUT) { fs.writeFileSync(OUT, md + '\n\n```json\n' + plain(JSON.stringify(r, null, 1)) + '\n```\n'); console.log(`(also written to ${OUT})`); } } catch (e) { console.error('bad results:', e.message); } + res.writeHead(204); res.end(); }); + return; + } + // The service worker would cache this page over the real one: none here. + if (url.pathname === '/sw.js') { res.writeHead(404); return res.end(); } + const file = path.join(SITE, path.normalize(decodeURIComponent(url.pathname)).replace(/^([/\\]|\.\.)+/, '')); + if (!file.startsWith(SITE + path.sep) || !fs.statSync(file, { throwIfNoEntry: false })?.isFile()) { res.writeHead(404); return res.end(); } + res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' }); + fs.createReadStream(file).pipe(res); + } catch (e) { + // A malformed address (decodeURIComponent) or a missing file: the details stay in this terminal. + console.error('bench server:', e && e.message || e); + res.writeHead(e instanceof URIError ? 400 : 500); res.end(); + } +}).listen(PORT, HOST, () => { + const s = JSON.parse(save).S; + console.log(`GPU benchmark: ${path.basename(SAVE)} (${Object.keys(s.pops || {}).length} POPs, ${(s.links || []).length} links), ${SECS}s per scenario`); + console.log(`Open http://localhost:${PORT}/ in your browser, press Start and keep the tab in front.`); + if (HOST === '0.0.0.0') for (const l of Object.values(os.networkInterfaces()).flat()) if (l && l.family === 'IPv4' && !l.internal) console.log(` from another device: http://${l.address}:${PORT}/`); + console.log('Ctrl+C to stop.'); +}); diff --git a/scripts/i18n-add.js b/scripts/i18n-add.js index 27468e5..027b3db 100644 --- a/scripts/i18n-add.js +++ b/scripts/i18n-add.js @@ -36,7 +36,7 @@ if (args[0] === '--rename') { for (const f of listFiles(src)) { if (f === 'i18n/en.js') continue; const p = path.join(src, f), t = fs.readFileSync(p, 'utf8'); - const u = t.replace(new RegExp(String.raw`(['"\x60])${from.replace(/\./g, '\\.')}\1`, 'g'), (m, q) => { n++; return q + to + q; }); + const u = t.replace(new RegExp(String.raw`(['"\x60])${from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\1`, 'g'), (m, q) => { n++; return q + to + q; }); if (u !== t) fs.writeFileSync(p, u); } console.log(`renamed ${from} → ${to} in every dictionary and ${n} place(s) in src/`); diff --git a/scripts/i18n-check.js b/scripts/i18n-check.js index 8d8e657..5e5a456 100644 --- a/scripts/i18n-check.js +++ b/scripts/i18n-check.js @@ -16,13 +16,26 @@ const D = require('./lib/dict'); const { CALL } = require('./legacy/labels'); const SITE = path.join(__dirname, '..', 'site'); -const page = () => require('./lib/page').assemble().html; +// The development page of a multiplayer build: it has every label, the agent's (src/agent/) and the server-play +// client's (src/game/98-server-play/, only in MP builds) too. src: another source tree (tests). +const page = (src) => require('./lib/page').assemble({ src, dev: true, mp: true }).html; const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/; +// The bodies of the page's bare ', i += 8); + if (end < 0) break; + out.push(html.slice(i, end)); i = end; + } + return out; +} + // The labels the game uses, with problems in how they are used. function sourceLabels(html) { const labels = new Set(), problems = []; - const scripts = [...html.matchAll(/ + @@ -102,6 +111,7 @@ +
Date
Y1 · Jan 1
+
@@ -125,6 +136,7 @@ +
@@ -143,6 +155,7 @@
+
@@ -162,6 +175,7 @@ 'use strict'; + diff --git a/src/styles/00-base.css b/src/styles/00-base.css index eba8a90..c13c729 100644 --- a/src/styles/00-base.css +++ b/src/styles/00-base.css @@ -1,7 +1,9 @@ -/* Layout: full-bleed cartoon world map on canvas; sticker-style panels float above it (HUD top, goals left, inspector right / bottom sheet on phones). Single committed bright look. */ +/* Layout: full-bleed cartoon world map on canvas; sticker-style panels float above it (HUD top, goals left, inspector right / bottom sheet on phones). + Two looks, light and dark (05-theme.css): --ink is the stickers' dark outline (and text on bright fills) in both, + --text the text on the panels. */ :root{ --sea:#57C4E5; --sea2:#3AA6CF; --wave:#9BE2F2; --land:#9BDA6C; --land2:#7FC455; --sand:#F8E6A8; - --ink:#1E2640; --ink2:#55608A; --paper:#FFFFFF; --soft:#EEF5FB; --line:#D5DEEC; + --ink:#1E2640; --ink2:#55608A; --text:#1E2640; --paper:#FFFFFF; --soft:#EEF5FB; --line:#D5DEEC; --me:#FF4F9A; --sun:#FFD23F; --ok:#22C47A; --warn:#FFAA1F; --bad:#FF4D5E; --t1:#7B61FF; --t2:#2F8CFF; --cdn:#FF8A3D; --eye:#16A866; --display:'Baloo 2','Trebuchet MS',system-ui,sans-serif; @@ -14,9 +16,11 @@ body{margin:0} .sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0} .ver{font-size:11.5px;color:var(--ink2);margin-top:10px} .ver a{color:inherit} -body{background:var(--sea);color:var(--ink);font-family:var(--body);overflow:hidden;font-size:14px;-webkit-font-smoothing:antialiased} +body{background:var(--sea);color:var(--text);font-family:var(--body);overflow:hidden;font-size:14px;-webkit-font-smoothing:antialiased} #map{position:fixed;inset:0;width:100%;height:100%;touch-action:none;display:block;cursor:grab} #map.linking{cursor:crosshair} +/* The WebGL tubes and the 2D overlay above them (58-webgl-links.js): pictures only, the map underneath takes the pointer. */ +#mapgl,#mapfx{position:fixed;inset:0;width:100%;height:100%;pointer-events:none} .num{font-variant-numeric:tabular-nums} h2,h3,h4{font-family:var(--display);margin:0;text-wrap:balance;line-height:1.1} button{font:inherit;color:inherit} diff --git a/src/styles/05-theme.css b/src/styles/05-theme.css new file mode 100644 index 0000000..05df6de --- /dev/null +++ b/src/styles/05-theme.css @@ -0,0 +1,24 @@ +/* Dark (#80): , set by the page's from Settings › Theme (93-ui/15-theme.js). The panels take + the night colours of the NOC window: dark paper, light text, the stickers' outlines darker still. Light tints (a goal + to work on, a toast, a pick) are written where they are used as var(--tint-…, light colour): only this look sets them. + Text on bright fills (yellow buttons, warning tags) stays dark ink in both looks. Red text is var(--tx-red,var(--bad)): + --bad stays the fill under white letters, and as text on these cards it falls below AA. */ +:root[data-theme="dark"]{ + color-scheme:dark; + --sea:#0E2A44; --ink:#070B16; --ink2:#A9B7D8; --text:#E9EFFB; --paper:#1A2340; --soft:#232E50; --line:#364470; --eye:#2BC987; + --tint-y:#3B3418; --tint-g:#173B2C; --tint-r:#45212B; --tint-p:#43213D; --tint-b:#17324F; --tint-v:#2C2752; --tint-o:#42301A; + --tint-n:#252F4C; --tint-nl:var(--line); --tx-red:#FF8E9B; --tx-amber:#FFB65C; --tx-blue:#7FD3F5; + scrollbar-color:#4A5B8E transparent; +} +/* The green of good news is lighter as text on dark paper; a tag keeps the deeper green under its white letters. */ +:root[data-theme="dark"] .tag.eye{background:#16A866} +/* A ghost button on dark paper: a shade lighter, so it still reads as a button. */ +:root[data-theme="dark"] .b.ghost,:root[data-theme="dark"] .x{background:var(--soft)} +/* The dropdowns' arrow is a picture: drawn again in the light text colour. */ +:root[data-theme="dark"] select.pick{background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='M1 1l5 5 5-5' fill='none' stroke='%23E9EFFB' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E")} +/* Badge variants: the frost and the fire, at night. */ +:root[data-theme="dark"] .bdg.on.v-freeze{background:linear-gradient(160deg,#15344C,#0F4562);box-shadow:0 2px 0 #5BC0EB,inset 0 0 0 2px var(--paper)} +:root[data-theme="dark"] .bdg.on.v-bgp{background:linear-gradient(160deg,#3E2A16,#55280F)} +:root[data-theme="dark"] .bdg.v-bgp .bv,:root[data-theme="dark"] .bdg.on.v-bgp .bv{color:#FF8A5C} +:root[data-theme="dark"] .bdg.v-freeze .bv{color:#7FD3F5} +:root[data-theme="dark"] .legend .lg:hover{background:rgba(233,239,251,.08)} diff --git a/src/styles/10-hud.css b/src/styles/10-hud.css index ffb4977..ff7d700 100644 --- a/src/styles/10-hud.css +++ b/src/styles/10-hud.css @@ -9,14 +9,14 @@ .brand .val{font-size:20px} .brand .lbl{color:#FFE0EE} .tube{width:30px;height:30px;flex:none} -.up{color:var(--ok)} .down{color:var(--bad)} +.up{color:var(--ok)} .down{color:var(--tx-red,var(--bad))} .note{align-items:flex-start}.note .ndot{width:9px;height:9px;border-radius:50%;margin-top:6px;flex:none;background:var(--ink2);border:2px solid var(--ink)} .note.bad .ndot{background:var(--bad)}.note.good .ndot{background:var(--ok)}.note.goal .ndot{background:#FFD23F} .note .nbody{display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden} #hNoc{position:relative}#hNoc .badge{position:absolute;top:-8px;right:-8px;background:var(--me);color:#fff;border:2.5px solid var(--ink);border-radius:10px;font:900 11px Nunito,sans-serif;padding:0 6px;line-height:16px} .speed{flex-direction:row;align-items:center;gap:4px;padding:4px 6px} .speed button{border:2.5px solid var(--ink);background:var(--paper);border-radius:9px;min-width:34px;height:32px;font-family:var(--display);font-weight:800;cursor:pointer;font-size:13px} -.speed button.on{background:var(--sun)} +.speed button.on{background:var(--sun);color:var(--ink)} .spacer{flex:1} .noc{cursor:pointer;border:3px solid var(--ink)} .hotk{display:inline-flex;align-items:center;justify-content:center;min-width:24px;height:24px;padding:0 4px;border-radius:12px;border:2px solid var(--ink,#1E2640);font:900 11px Nunito,sans-serif;margin-right:8px;color:#fff;background:#FF4D5E} @@ -24,8 +24,10 @@ .noc.hot{background:var(--bad);color:#fff;animation:throb 1s ease-in-out infinite} .noc.hot .lbl{color:#FFE1E4} #hCust .cnt{display:inline-block;min-width:18px;padding:0 5px;border-radius:9px;background:var(--bad);color:#fff;font-size:11px;line-height:18px;text-align:center;vertical-align:3px;margin-left:2px} -#hCust.hot{background:#FFE1E4} +#hCust.hot{background:var(--tint-r,#FFE1E4)} @keyframes throb{50%{transform:scale(1.05)}} .minibar{height:6px;border-radius:4px;background:var(--line);overflow:hidden;margin-top:2px;width:100%} .minibar i{display:block;height:100%;background:var(--ok)} +/* Find a city: a square chip with just the magnifier. */ +#hud .chip.find{justify-content:center;align-items:center;padding:0;width:44px;min-width:44px;font-size:19px;cursor:pointer} diff --git a/src/styles/20-drawers.css b/src/styles/20-drawers.css index cf5509c..d8532f8 100644 --- a/src/styles/20-drawers.css +++ b/src/styles/20-drawers.css @@ -2,10 +2,15 @@ #left{position:fixed;top:calc(env(safe-area-inset-top,0px) + 76px);left:max(12px,env(safe-area-inset-left,0px));width:300px;max-height:calc(100% - 96px - env(safe-area-inset-top,0px) - env(safe-area-inset-bottom,0px));display:flex;flex-direction:column;z-index:4} #panel{position:fixed;top:calc(env(safe-area-inset-top,0px) + 76px);right:max(12px,env(safe-area-inset-right,0px));width:370px;max-height:calc(100% - 96px - env(safe-area-inset-top,0px) - env(safe-area-inset-bottom,0px));display:flex;flex-direction:column;z-index:4} .scroll{overflow:auto;padding:12px 14px 14px;overscroll-behavior:contain} +/* Labels stay on one line and give way (with an ellipsis) before the bar overflows the panel; the counts sit on + the tab's corner so they cost no width. */ .tabs{display:flex;gap:4px;padding:8px 8px 0;border-bottom:3px solid var(--ink);flex:none} -.tabs button{border:2.5px solid var(--ink);border-bottom:none;border-radius:11px 11px 0 0;background:var(--soft);padding:4px 10px 3px;font-family:var(--display);font-weight:800;cursor:pointer;font-size:13.5px;position:relative;top:3px} -.tabs button.on{background:var(--paper);padding-bottom:6px} -.tabs .cnt{display:inline-block;background:var(--me);color:#fff;border-radius:9px;padding:0 6px;font-size:11px;margin-left:4px} +#leftTabs{padding-top:11px} +.tabs button{border:2.5px solid var(--ink);border-bottom:none;border-radius:11px 11px 0 0;background:var(--soft);padding:4px 10px 3px;font-family:var(--display);font-weight:800;cursor:pointer;font-size:13.5px;position:relative;top:3px;flex:0 1 auto;min-width:0;display:flex;align-items:center} +.tabs .tl{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0} +.tabs button.on{background:var(--paper);padding-bottom:6px;flex-shrink:0} +.tabs .cnt{position:absolute;top:-10px;right:-6px;z-index:1;background:var(--me);color:#fff;border:1.5px solid var(--ink);border-radius:9px;padding:0 5px;font-size:10.5px;line-height:15px;white-space:nowrap} +.tabs .cnt.dot{top:-5px;right:-4px;width:11px;height:11px} .tabs .cnt.red{background:var(--bad)} #leftToggle{display:none} @@ -15,8 +20,8 @@ .x{margin-left:auto;border:2.5px solid var(--ink);background:var(--paper);border-radius:10px;width:32px;height:32px;font-size:20px;line-height:1;cursor:pointer;font-weight:900;flex:none} .facts{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px} .fact{background:var(--soft);border:2px solid var(--ink);border-radius:9px;padding:1px 8px;font-size:12px;font-weight:700} -.fact.bad{background:#FFE3E3}.latwarn{background:#FFF1F1;border:2px solid #FF5A5F;border-radius:10px;padding:8px 10px;margin:6px 0;font-size:13px;line-height:1.4} -.fact.ixf{background:#FFF3C4} +.fact.bad{background:var(--tint-r,#FFE3E3)}.latwarn{background:var(--tint-r,#FFF1F1);border:2px solid #FF5A5F;border-radius:10px;padding:8px 10px;margin:6px 0;font-size:13px;line-height:1.4} +.fact.ixf{background:var(--tint-y,#FFF3C4)} .fact.mine{background:var(--me);color:#fff} .fact.down{background:var(--bad);color:#fff} section{padding:10px 0;border-bottom:2px dashed var(--line)} @@ -32,25 +37,36 @@ section h3{font-size:17px;margin-bottom:6px;display:flex;align-items:center;gap: .row .nm{font-weight:800;font-size:13.5px;line-height:1.2} .row .meta{font-size:11.5px;color:var(--ink2);line-height:1.3} .btns{display:flex;flex-wrap:wrap;gap:5px;margin-top:5px} -.why{font-size:11px;color:#B23A48;font-weight:700;margin-top:3px;line-height:1.3} +.why{font-size:11px;color:var(--tx-red,#B23A48);font-weight:700;margin-top:3px;line-height:1.3} -.b{font-family:var(--display);font-weight:800;border:2.5px solid var(--ink);border-radius:11px;background:var(--sun);box-shadow:0 3px 0 var(--ink);padding:4px 11px 3px;cursor:pointer;font-size:14px;line-height:1.2;white-space:nowrap;transition:transform .06s} +.b{font-family:var(--display);font-weight:800;border:2.5px solid var(--ink);border-radius:11px;background:var(--sun);box-shadow:0 3px 0 var(--ink);padding:4px 11px 3px;cursor:pointer;font-size:14px;line-height:1.2;white-space:nowrap;transition:transform .06s;color:var(--ink)} .b:hover{filter:brightness(1.05)} .b:active{transform:translateY(2px);box-shadow:0 1px 0 var(--ink)} .b:disabled{opacity:.42;cursor:not-allowed;transform:none;box-shadow:0 3px 0 var(--ink)} -.b.ghost{background:var(--paper)} +.b.ghost{background:var(--paper);color:var(--text)} .b.pink{background:var(--me);color:#fff} .b.red{background:var(--bad);color:#fff} .b.green{background:var(--ok);color:#fff} .b.sm{font-size:12px;padding:2px 8px 1px;border-radius:9px;box-shadow:0 2px 0 var(--ink)} .b.big{font-size:18px;padding:7px 18px 5px} +/* A city name in a heading that opens the city (link panels, #196): reads as the heading, underlined like a link. */ +.b.clink,.b.clink:active{font:inherit;color:inherit;background:none;border:0;box-shadow:none;transform:none;padding:2px 0;border-radius:0;white-space:normal;text-align:left;text-decoration:underline;text-decoration-thickness:2px;text-underline-offset:4px;text-decoration-color:var(--me)} .b small{font-family:var(--body);font-weight:800;font-size:10.5px;opacity:.85;margin-left:3px} .logo{width:30px;height:30px;border-radius:50%;background:var(--c);border:2.5px solid var(--ink);display:grid;place-items:center;color:#fff;font-family:var(--display);font-weight:800;font-size:11px;flex:none;letter-spacing:-.02em} -.tag{display:inline-block;border:1.8px solid var(--ink);border-radius:7px;padding:0 5px;font-size:10px;font-weight:900;letter-spacing:.03em;text-transform:uppercase;vertical-align:1px;color:#fff;background:var(--ink2)} +.tag{display:inline-block;border:1.8px solid var(--ink);border-radius:7px;padding:0 5px;font-size:10px;font-weight:900;letter-spacing:.03em;text-transform:uppercase;vertical-align:1px;color:#fff;background:#55608A} .tag.t1{background:var(--t1)} .tag.t2{background:var(--t2)} .tag.cdn{background:var(--cdn)} .tag.eye{background:var(--eye)} .tag.open{background:var(--ok)} .tag.selective{background:var(--warn);color:var(--ink)} .tag.restrictive{background:var(--bad)} .tag.paid{background:var(--me)} -.tag.st{background:var(--paper);color:var(--ink)} +.tag.st{background:var(--paper);color:var(--text)} +/* PNI list (#175): one status chip per network, a one-line value, folded groups. Chips wrap on narrow screens. */ +.tag.worth{background:var(--warn);color:var(--ink)} +.pchips{display:flex;flex-wrap:wrap;gap:4px;margin:3px 0} +.pchip{display:inline-block;max-width:100%;border:1.5px solid var(--ink);border-radius:999px;padding:0 7px;font-size:11px;font-weight:800;line-height:1.5;background:var(--paper);color:var(--text);overflow-wrap:anywhere} +.pchip.pk-here,.pchip.pk-else{background:var(--ok);color:#fff} +.pchip.pk-ix{background:var(--t2);color:#fff} +.pchip.pk-none{background:var(--bad);color:#fff} +.pval{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:100%} +.pgrp{margin:8px 0 2px}.pgrp .b{width:100%;text-align:left} .tag.st.on{background:var(--ink);color:#fff} .bar{height:11px;border:2px solid var(--ink);border-radius:7px;background:var(--paper);overflow:hidden;margin:3px 0} .stack{display:flex;height:16px;border:2px solid var(--ink);border-radius:8px;overflow:hidden;margin:4px 0 6px;background:var(--paper)} @@ -65,12 +81,14 @@ section h3{font-size:17px;margin-bottom:6px;display:flex;align-items:center;gap: .goal .ck{width:22px;height:22px;border:2.5px solid var(--ink);border-radius:7px;flex:none;display:grid;place-items:center;font-weight:900;background:var(--paper);font-size:13px} .goal.done .ck{background:var(--ok);color:#fff} .goal.done .gt{text-decoration:line-through;color:var(--ink2)} -.goal.cur{background:#FFF6CF;margin:0 -14px;padding:9px 14px;border-top:2px solid var(--ink);border-bottom:2px solid var(--ink)} +.goal.cur{background:var(--tint-y,#FFF6CF);margin:0 -14px;padding:9px 14px;border-top:2px solid var(--ink);border-bottom:2px solid var(--ink)} .goal .gt{font-weight:900;font-size:13.5px} .goal .gd{font-size:12px;color:var(--ink2);line-height:1.4;margin-top:2px} .goal .gr{font-size:11px;font-weight:900;color:var(--eye);margin-top:2px} .empty{color:var(--ink2);font-size:12.5px;line-height:1.45;padding:6px 0} -.inc{border:2.5px solid var(--ink);border-radius:12px;padding:8px 10px;margin-bottom:8px;background:#FFF0F1} +.inc{border:2.5px solid var(--ink);border-radius:12px;padding:8px 10px;margin-bottom:8px;background:var(--tint-r,#FFF0F1)} .inc .nm{font-weight:900} .inc .meta{font-size:12px;color:var(--ink2);margin-top:2px;line-height:1.35} +/* The NOC tab only says whether something is broken, never how many notifications wait (2.0). */ +.cnt.dot{min-width:0;width:9px;height:9px;padding:0;border-radius:50%;vertical-align:middle} diff --git a/src/styles/30-toasts.css b/src/styles/30-toasts.css index 47db06f..c82aa74 100644 --- a/src/styles/30-toasts.css +++ b/src/styles/30-toasts.css @@ -1,10 +1,16 @@ /* toasts */ #toasts{position:fixed;left:50%;transform:translateX(-50%);bottom:calc(env(safe-area-inset-bottom,0px) + 14px);display:flex;flex-direction:column-reverse;gap:8px;z-index:8;width:min(460px,calc(100% - 32px));pointer-events:none} .toast{pointer-events:none;background:var(--paper);border:3px solid var(--ink);border-radius:14px;box-shadow:3px 3px 0 var(--ink);padding:9px 12px;display:flex;gap:10px;align-items:center;animation:pop .25s cubic-bezier(.3,1.6,.6,1)} -.toast.good{background:#DFFBEA} .toast.bad{background:#FFE1E4} .toast.goal{background:#FFF3C4} +.toast.good{background:var(--tint-g,#DFFBEA)} .toast.bad{background:var(--tint-r,#FFE1E4)} .toast.goal{background:var(--tint-y,#FFF3C4)} .toast .b{pointer-events:auto} .seg{display:flex;flex-wrap:wrap;gap:6px} .seg .b{white-space:normal;text-align:left} +/* A segmented control: one framed row of equal tabs, the active one filled like the HUD's speed buttons (Pie Control). */ +.segc{display:flex;gap:3px;padding:3px;margin:6px 0 10px;border:3px solid var(--ink);border-radius:14px;background:var(--soft);box-shadow:3px 3px 0 var(--ink)} +.segc button{flex:1 1 0;min-width:0;min-height:40px;padding:3px 2px;border:2.5px solid transparent;border-radius:10px;background:none;color:var(--text);font-family:var(--display);font-weight:800;font-size:min(13.5px,3.6vw);line-height:1.1;cursor:pointer;overflow-wrap:anywhere;hyphens:auto} +.segc button:hover{background:var(--paper)} +.segc button.on{background:var(--sun);border-color:var(--ink);color:var(--ink)} +.segc button:focus-visible{outline:3px solid var(--me);outline-offset:1px} .toast .tx{flex:1;font-size:13px;line-height:1.35} .toast .tx b{font-family:var(--display);font-size:14.5px} @keyframes pop{from{transform:scale(.8) translateY(10px);opacity:0}} diff --git a/src/styles/35-optic-counts.css b/src/styles/35-optic-counts.css new file mode 100644 index 0000000..6690821 --- /dev/null +++ b/src/styles/35-optic-counts.css @@ -0,0 +1,4 @@ +.optic-count{display:flex;flex-wrap:wrap;align-items:end;gap:8px;margin-top:8px} +.optic-count label{display:flex;flex-direction:column;gap:3px;font-size:12px;font-weight:800} +.optic-count input.t{width:88px;font-size:16px;min-height:44px} +.optic-count .b{min-height:44px} diff --git a/src/styles/36-net-filter.css b/src/styles/36-net-filter.css new file mode 100644 index 0000000..2bae154 --- /dev/null +++ b/src/styles/36-net-filter.css @@ -0,0 +1,5 @@ +/* Find a network at a POP (#199) and the POP standards rows (#315). */ +.netf{display:flex;flex-direction:column;gap:6px;margin:0 0 10px} +.netf input.t{font-size:16px;padding:6px 10px;min-height:44px} +.netf .btns{margin:0} +.ptier .row .btns{margin-top:4px} diff --git a/src/styles/36-ops.css b/src/styles/36-ops.css new file mode 100644 index 0000000..e0efcd3 --- /dev/null +++ b/src/styles/36-ops.css @@ -0,0 +1,38 @@ +/* Standing orders: the intern's card in the NOC and the Ops sheet */ +.ops-card{border:2px solid #8E5CF7;background:var(--tint-v,#F7F2FF);border-radius:12px;padding:8px 10px;margin:8px 0} +.ops-card .nm{font-weight:800} +.ops-o{border:2px solid var(--line);border-radius:12px;padding:8px 10px;margin:8px 0;background:var(--paper)} +.ops-o.on{border-color:var(--ok)} +.ops-h{display:flex;align-items:center;gap:8px} +.ops-h .grow{flex:1;min-width:0} +.ops-h .nm{font-weight:800;font-size:13.5px;line-height:1.2} +.ops-h .b{min-height:36px;flex:none} +.ops-i{font-size:22px;line-height:1;flex:none} +.ops-p{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px} +.ops-p .b{white-space:normal;text-align:left;min-height:36px} +/* A setting is a list to pick from: two to a row on a phone, the list as wide as its column. */ +.ops-sel{display:flex;flex-direction:column;gap:2px;flex:1 1 140px;min-width:0;font:800 12px Nunito,sans-serif;color:var(--ink2)} +.ops-sel select{width:100%;min-height:36px;font:700 14px Nunito,sans-serif;color:var(--text);background:var(--paper);padding:4px 6px;border:2px solid var(--ink);border-radius:8px} +/* A setting the build standard owns: a whole row, what it says, and the way to its sheet (under it on a narrow phone). */ +.ops-from{flex:1 1 100%;display:flex;flex-wrap:wrap;align-items:center;gap:2px 8px;min-width:0;font:800 12px Nunito,sans-serif;color:var(--ink2)} +.ops-from>span{flex:1 1 100%} +.ops-from b{flex:1 1 160px;min-width:0;font:700 14px Nunito,sans-serif;color:var(--text);overflow-wrap:anywhere} +.ops-from .b{flex:none;min-height:36px} +.ops-log{white-space:pre-wrap;font-size:11.5px;max-height:160px;overflow:auto} +.ops-good{font-size:12.5px;font-weight:800;color:#6B3FD4;margin-top:2px;line-height:1.3} +.ops-mood{margin:6px 0 0;font-style:italic;font-size:13px;color:var(--ink2)} +.ops-rep{border-left:3px solid #8E5CF7;background:var(--tint-v,#F7F2FF);border-radius:0 8px 8px 0;padding:6px 8px;margin:6px 0;font-size:13px;line-height:1.35;overflow-wrap:anywhere} +.ops-rep .eyebrow{margin-bottom:2px} +/* Pie Control's Company tab ends with the Founder's feed: a quiet section, older posts folded away. */ +.pie-feed{border-top:2px solid var(--line);margin-top:12px;padding-top:4px} +.pie-feed h3{font-size:15px;margin:8px 0 4px} +.pie-feed summary{cursor:pointer;font-weight:800;font-size:13px;color:var(--ink2);padding:8px 0;min-height:24px} +.pie-jit{margin:6px 0 2px;overflow-wrap:anywhere} +.pie-jit-bar{margin-bottom:6px} +/* Government money in the bank: the same boxes as the loans next to it. */ +.bank-gov>.meta{font-size:13px;color:var(--ink2);margin:2px 0 6px;line-height:1.35} +.bank-gov .ops-o{border:2.5px solid var(--ink);border-radius:14px;padding:10px 12px;margin-top:10px} +.bank-gov .ops-o .nm{font-weight:800;font-family:var(--display);font-size:16px} +.bank-gov .ops-o .meta{font-size:12.5px;color:var(--ink2);line-height:1.35} +.bank-gov .fact{display:inline-block;margin-top:2px} +.bank-gov .ops-o p.meta{margin:4px 0} diff --git a/src/styles/37-router-art.css b/src/styles/37-router-art.css new file mode 100644 index 0000000..f78ef52 --- /dev/null +++ b/src/styles/37-router-art.css @@ -0,0 +1,7 @@ +/* Router pictures (src/game/10-catalog/25-router-art.js): your POP's model in the city panel's header, left of the + name, on a small map-green stage that looks the same in both themes. */ +.rgpic{flex:0 0 auto;display:block;width:58px;height:46px;border:2px solid #1E2640;border-radius:10px;background:radial-gradient(circle at 50% 125%,#94D168 0 55%,#A8DE7C 56%);overflow:hidden} +.rgpic.big{width:96px;height:77px;border-width:3px;border-radius:14px} +.rgpic .rgart{display:block;width:100%;height:100%} +.ph .phpic{align-self:center} +@media (max-width:420px){.rgpic.big{width:76px;height:61px}} diff --git a/src/styles/38-pie-globe.css b/src/styles/38-pie-globe.css new file mode 100644 index 0000000..3f692f5 --- /dev/null +++ b/src/styles/38-pie-globe.css @@ -0,0 +1,23 @@ +/* Pie Control globe (96-map/89-pie-globe.js): square, as wide as the panel, never wider than the screen allows. */ +.pglobe{position:relative;width:100%;max-width:420px;margin:6px auto;aspect-ratio:1/1} +.pglobe .pgcv{display:block;width:100%;height:100%;touch-action:none;cursor:grab;border-radius:16px} +.pglobe .pgnight{position:absolute;top:6px;right:6px;min-width:36px;min-height:36px} +@media (max-width:420px){.pglobe{max-width:min(100%,62vh)}} +/* Pie Control's Traffic tab (93-ui/86-pie-traffic.js): rows a thumb can hit, nothing wider than the sheet. */ +.pft-head{font-weight:900;font-size:15px;margin:4px 0 8px;overflow-wrap:anywhere} +.pft-h{font-size:15px;margin:12px 0 4px} +.pft-cr,.pft-d{margin:6px 0} +.pft-cr .kv span,.pft-d .kv span{min-width:0;overflow-wrap:anywhere} +.pft-list{display:flex;flex-direction:column;gap:6px} +.pft-row{display:flex;align-items:center;gap:8px;width:100%;min-height:44px;padding:6px 10px;border:2px solid var(--line);border-radius:12px;background:var(--paper);color:var(--text);font:inherit;text-align:left;cursor:pointer;box-sizing:border-box} +.pft-row.on{border-color:var(--me);box-shadow:0 0 0 2px var(--me) inset} +.pft-ic{font-size:20px;flex:none} +.pft-m{flex:1;min-width:0;display:flex;flex-direction:column} +.pft-m b,.pft-m small,.pft-n small{overflow-wrap:anywhere} +.pft-m small,.pft-n small{font-size:12px;color:var(--ink2)} +.pft-n{flex:none;display:flex;flex-direction:column;align-items:flex-end;text-align:right;max-width:40%} +.pft-ck{list-style:none;margin:4px 0 0;padding:0} +.pft-ck li{display:flex;gap:8px;align-items:flex-start;min-height:32px;margin:4px 0} +.pft-ck li span:last-child{display:flex;flex-direction:column;min-width:0} +.pft-ck small{font-size:12px;color:var(--ink2);overflow-wrap:anywhere} +.pft-st{color:var(--tx-red,var(--bad));font-weight:800} diff --git a/src/styles/39-pie-spats.css b/src/styles/39-pie-spats.css new file mode 100644 index 0000000..607fb45 --- /dev/null +++ b/src/styles/39-pie-spats.css @@ -0,0 +1,5 @@ +/* Pie in the Sky spats (85-incidents/65-pie-spats.js): two answers, stacked full width so long labels wrap at 360 px. */ +.pspat-c{display:flex;flex-direction:column;gap:8px;margin-top:10px} +.pspat-c .b{width:100%;min-height:44px;white-space:normal;text-align:left;line-height:1.3} +.pspat-l{margin-top:6px} +.pspat-l .kv{align-items:center;gap:6px} diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index 4e1845f..c8edcf7 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -2,23 +2,34 @@ .seg.site{margin-top:4px;align-items:center} .seg.site .meta{margin-right:4px} .badges{display:grid;grid-template-columns:repeat(auto-fill,minmax(118px,1fr));gap:6px} -.bdg{border:2px solid #C9CEDD;border-radius:12px;padding:6px 7px;background:#F3F4F8;opacity:.6;display:flex;flex-direction:column;gap:1px;min-width:0} +.bdg{border:2px solid var(--tint-nl,#C9CEDD);border-radius:12px;padding:6px 7px;background:var(--tint-n,#F3F4F8);opacity:.6;display:flex;flex-direction:column;gap:1px;min-width:0} .bdg .bi{font-size:20px;filter:grayscale(1)} -.bdg .bt{font:800 12.5px/1.2 "Baloo 2",sans-serif;color:var(--ink)} +.bdg .bt{font:800 12.5px/1.2 "Baloo 2",sans-serif;color:var(--text)} .bdg .br{font:900 10px Nunito,sans-serif;color:var(--rc);text-transform:uppercase;letter-spacing:.04em} -.bdg .bd{font-size:11px;color:#5A6280;line-height:1.25} +.bdg .bd{font-size:11px;color:var(--ink2);line-height:1.25} .bdg.ever{opacity:.85;border-style:dashed;border-color:var(--rc)} -.bdg.on{opacity:1;border-color:var(--rc);background:#fff;box-shadow:0 2px 0 var(--rc)} +.bdg.on{opacity:1;border-color:var(--rc);background:var(--paper);box-shadow:0 2px 0 var(--rc)} .bdg.on .bi,.bdg.ever .bi{filter:none} -.scn{display:flex;gap:10px;align-items:center;border:2px solid #DDE1EC;border-radius:12px;padding:8px 10px;margin-top:8px} -.scn.wk{border-color:var(--me);background:#FFF0F6} +.bdg .bv{font:900 10px Nunito,sans-serif;letter-spacing:.02em} +.bdg.on.v-freeze{background:linear-gradient(160deg,#F2FBFF,#D6F1FC);border-color:#5BC0EB;box-shadow:0 2px 0 #5BC0EB,inset 0 0 0 2px #fff} +.bdg.v-freeze .bv{color:#2A8DB8} +.bdg.on.v-bgp{background:linear-gradient(160deg,#FFF6E8,#FFD9B8);border-color:#FF5A1F;box-shadow:0 2px 0 #C8102E,0 0 8px rgba(255,90,31,.45)} +.bdg.v-bgp .bv{color:#C8102E} +.bdg.ever.v-freeze{border-color:#5BC0EB}.bdg.ever.v-bgp{border-color:#FF5A1F} +.bshelf{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 8px} +.bsh{font:800 12px Nunito,sans-serif;border:2px solid var(--tint-nl,#C9CEDD);border-radius:999px;padding:2px 9px;background:var(--paper);white-space:nowrap} +.bsh.v-freeze{border-color:#5BC0EB}.bsh.v-oncall{border-color:#FFD23F}.bsh.v-bgp{border-color:#FF5A1F} +.bsh.cur{box-shadow:0 2px 0 var(--ink)} +.bvt.v-freeze{color:#2A8DB8;font-weight:900}.bvt.v-bgp{color:#FF5A1F;font-weight:900} +.scn{display:flex;gap:10px;align-items:center;border:2px solid var(--tint-nl,#DDE1EC);border-radius:12px;padding:8px 10px;margin-top:8px} +.scn.wk{border-color:var(--me);background:var(--tint-p,#FFF0F6)} .scn .nm{font-weight:900} .term{background:#1E2640;color:#7CFFB2;font:600 12px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;padding:10px 12px;border-radius:10px;overflow-x:auto;white-space:pre;margin:8px 0} .trsel{display:flex;flex-wrap:wrap;gap:8px;align-items:flex-end;margin-top:8px} .trsel label{display:flex;flex-direction:column;font:800 12px Nunito,sans-serif;gap:2px} .trsel select{font:700 14px Nunito,sans-serif;padding:4px 6px;border:2px solid var(--ink);border-radius:8px;max-width:240px} -.fact.trb{cursor:pointer;font:inherit;border:2px solid var(--ink);background:#fff} -#coach{position:fixed;left:50%;transform:translateX(-50%);top:calc(env(safe-area-inset-top,0px) + 74px);z-index:16;width:min(520px,calc(100% - 24px));background:#fff;border:3px solid var(--ink);border-radius:14px;box-shadow:0 4px 0 var(--ink);padding:8px 10px;display:flex;gap:8px;align-items:center} +.fact.trb{cursor:pointer;font:inherit;border:2px solid var(--ink);background:var(--paper)} +#coach{position:fixed;left:50%;transform:translateX(-50%);top:calc(env(safe-area-inset-top,0px) + 74px);z-index:16;width:min(520px,calc(100% - 24px));background:var(--paper);border:3px solid var(--ink);border-radius:14px;box-shadow:0 4px 0 var(--ink);padding:8px 10px;display:flex;gap:8px;align-items:center} #coach .ct{flex:1;font-weight:800;font-size:14px;line-height:1.35} #coach .cs{display:block;font:900 10px Nunito,sans-serif;color:var(--me);text-transform:uppercase;letter-spacing:.05em} .coach-glow{animation:coachglow 1s ease-in-out infinite;position:relative;z-index:2} @@ -32,13 +43,13 @@ .btns.tcta .b{margin:0;display:flex;align-items:center;justify-content:center;text-align:center;line-height:1.15;white-space:normal;hyphens:auto;-webkit-hyphens:auto;min-height:40px;padding:4px 6px;font-size:14px} .btns.tcta .b.big{grid-column:1/-1;font-size:18px;padding:7px 18px 5px} /* Dropdowns that look like the game's buttons. 16px text: iOS zooms into anything smaller when it is tapped. */ -select.pick{-webkit-appearance:none;appearance:none;font:800 16px var(--display);color:var(--ink);background:var(--soft) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='M1 1l5 5 5-5' fill='none' stroke='%231E2640' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") no-repeat right 12px center;border:3px solid var(--ink);border-radius:12px;padding:6px 36px 6px 12px;min-height:44px;cursor:pointer;box-shadow:0 3px 0 var(--ink)} +select.pick{-webkit-appearance:none;appearance:none;font:800 16px var(--display);color:var(--text);background:var(--soft) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='M1 1l5 5 5-5' fill='none' stroke='%231E2640' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") no-repeat right 12px center;border:3px solid var(--ink);border-radius:12px;padding:6px 36px 6px 12px;min-height:44px;cursor:pointer;box-shadow:0 3px 0 var(--ink)} select.pick:focus-visible{outline:3px solid #FF4F9A;outline-offset:2px} label.f+select.pick{width:100%} .thb{font:inherit;font-weight:900;background:none;border:0;padding:0;cursor:pointer;color:inherit} -.ttop{margin:4px 0;padding:4px 8px;border-left:3px solid #FF8A3D;background:#FFF6EC;border-radius:6px} -.ibx{border:2px solid var(--line,#DDE3EE);border-radius:12px;padding:8px 10px;margin:8px 0;background:#fff}.ibx .nm{font-weight:800}.ibx.mp{border-color:#FF5A5F;background:#FFF1F1}.ibx.ai{border-color:#8E5CF7;background:#F7F2FF}.ibx .term{font-size:11.5px;white-space:pre-wrap;max-height:180px;overflow:auto}.ibx .cnt{display:inline-block;min-width:18px;padding:0 5px;border-radius:9px;background:var(--me);color:#fff;font-size:11px;text-align:center}.ibx .cnt.red{background:#FF5A5F} -.aibtn{background:linear-gradient(90deg,#8E5CF7,#E84FA8);color:#fff}.aisay{background:#F3ECFF;border:2px solid #8E5CF7;border-radius:10px;padding:8px 10px;color:var(--ink)} +.ttop{margin:4px 0;padding:4px 8px;border-left:3px solid #FF8A3D;background:var(--tint-o,#FFF6EC);border-radius:6px} +.ibx{border:2px solid var(--line,#DDE3EE);border-radius:12px;padding:8px 10px;margin:8px 0;background:var(--paper)}.ibx .nm{font-weight:800} +.aibtn{background:linear-gradient(90deg,#8E5CF7,#E84FA8);color:#fff}.aisay{background:var(--tint-v,#F3ECFF);border:2px solid #8E5CF7;border-radius:10px;padding:8px 10px;color:var(--text)} .tehelp h3{margin:14px 0 4px}.tehelp ul{margin:4px 0;padding-left:18px}.tehelp li{margin:4px 0;font-size:13.5px;line-height:1.4}.tehelp dt{margin-top:8px}.tehelp dd{margin:2px 0 0;font-size:13px;line-height:1.4;color:var(--ink2)}.tehelp code{font:600 12.5px ui-monospace,Menlo,Consolas,monospace;background:#1E2640;color:#E6F0FF;border-radius:6px;padding:1px 6px;word-break:break-word} .terec{display:flex;align-items:center;gap:10px;justify-content:space-between;border-top:2px dashed var(--line,#DDE3EE);padding:8px 0}.terec .btn{flex:none} .tecode{width:100%;box-sizing:border-box;font:600 13px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;background:#1E2640;color:#E6F0FF;border:3px solid var(--ink);border-radius:10px;padding:10px;margin-top:8px;resize:vertical;tab-size:2} @@ -56,6 +67,9 @@ label.f+select.pick{width:100%} #update .b{pointer-events:auto} .notes{margin:10px 0 0;padding-left:20px;line-height:1.5} .notes li{margin:4px 0} +.story{margin:10px 0 0;line-height:1.5} +.story p{margin:0 0 10px} +.story b{font-weight:900} #bankBox{position:fixed;inset:0;background:rgba(30,38,64,.35);z-index:16;overflow:auto;padding:calc(env(safe-area-inset-top,0px) + 12px) max(12px,env(safe-area-inset-right,0px)) 16px max(12px,env(safe-area-inset-left,0px))} #bankCard{max-width:760px;margin:0 auto;padding:16px 18px 18px;background:var(--paper)} .menubtn{cursor:pointer;text-align:left;font:inherit;border-color:var(--ink)} @@ -65,7 +79,7 @@ label.f+select.pick{width:100%} .loan{border:2.5px solid var(--ink);border-radius:14px;padding:10px 12px;margin-top:10px;display:flex;gap:10px;align-items:flex-start} .loan .grow{flex:1;min-width:0} .loan .terms{display:flex;flex-wrap:wrap;gap:6px;margin:6px 0} -.grade{font-family:var(--display);font-weight:800;font-size:30px;line-height:1;border:3px solid var(--ink);border-radius:12px;padding:4px 10px;background:var(--sun)} +.grade{font-family:var(--display);font-weight:800;font-size:30px;line-height:1;border:3px solid var(--ink);border-radius:12px;padding:4px 10px;background:var(--sun);color:var(--ink)} #dash{position:fixed;inset:0;background:rgba(30,38,64,.35);z-index:15;overflow:auto;padding:calc(env(safe-area-inset-top,0px) + 12px) max(12px,env(safe-area-inset-right,0px)) 16px max(12px,env(safe-area-inset-left,0px))} #dashCard{max-width:980px;margin:0 auto;padding:16px 18px 18px;background:var(--paper)} .dgrid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;margin:10px 0} @@ -86,6 +100,8 @@ label.f+select.pick{width:100%} .tbl td.r,.tbl th.r{text-align:right} .mix{display:flex;height:10px;width:100px;border:1.5px solid var(--ink);border-radius:5px;overflow:hidden;background:var(--paper)} .mix i{display:block;height:100%} +/* The NOC's traffic table has a row per network: classes, not inline styles, keep its hundreds of rows cheap to parse. */ +.nmc{display:inline-flex;align-items:center;gap:6px}.dlost{color:var(--tx-red,var(--bad))}.b.pall{display:block;margin-top:5px} .tscroll{overflow-x:auto} #modal{position:fixed;inset:0;background:rgba(30,38,64,.45);display:grid;place-items:center;z-index:20;padding:16px max(16px,env(safe-area-inset-right,0px)) 16px max(16px,env(safe-area-inset-left,0px))} #modal .card{width:min(560px,100%);max-height:calc(100% - 20px);overflow:auto;padding:20px 22px} @@ -94,18 +110,38 @@ label.f+select.pick{width:100%} .title-art h1 span{color:var(--me)} .tagline{color:var(--ink2);font-size:14.5px;line-height:1.45;margin:10px 0 14px} label.f{display:block;font-weight:900;font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:var(--ink2);margin:12px 0 5px} -input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radius:12px;padding:8px 12px;font-family:var(--display);font-weight:800;font-size:18px;background:var(--soft)} +input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radius:12px;padding:8px 12px;font-family:var(--display);font-weight:800;font-size:18px;background:var(--soft);color:var(--text);-webkit-text-fill-color:var(--text)} .network-name{display:flex;flex-wrap:wrap;align-items:center;gap:8px} -.network-name input.t{flex:1 1 240px;width:auto;min-width:0} -.plug{display:flex;gap:12px;align-items:center;border:3px solid var(--ink);border-radius:14px;padding:10px 12px;margin:10px 0 4px;background:var(--soft);box-shadow:0 3px 0 var(--ink);color:var(--ink);text-decoration:none} -.plug:hover{background:#FFF6D6}.plug .pi{font-size:30px;line-height:1}.plug b{font-family:var(--display);font-size:16px}.plug .meta{display:block;margin-top:2px}.plug .go{margin-left:auto;font-weight:900;white-space:nowrap} +.network-name{flex-wrap:nowrap}.nmwrap{position:relative;flex:1 1 auto;min-width:0}.nmwrap input.t{width:100%;padding-right:44px;font-size:16px} +.reroll{position:absolute;right:6px;top:50%;transform:translateY(-50%);width:32px;height:32px;border-radius:50%;border:2px solid var(--ink);background:#22C47A;color:#fff;font:900 18px/1 var(--display);cursor:pointer;padding:0;display:flex;align-items:center;justify-content:center}.reroll:active{transform:translateY(-50%) rotate(-90deg)} +.asnwrap{display:flex;align-items:center;gap:4px;flex:0 0 auto;font:800 14px var(--display);color:var(--ink2)}.asnwrap input.t{width:92px;font-size:15px;padding:8px 6px}.asnwrap input.t::placeholder{color:var(--ink2);opacity:.7}.asnwrap input.t.bad{border-color:#E03A3A;background:var(--tint-r,#FFE8E8)} +.metric-in{display:flex;gap:6px;align-items:center;margin-top:6px}.metric-in input.t{flex:1 1 120px;width:auto;min-width:0;font-size:16px;padding:4px 10px} +.plug{display:flex;gap:12px;align-items:center;border:3px solid var(--ink);border-radius:14px;padding:10px 12px;margin:10px 0 4px;background:var(--soft);box-shadow:0 3px 0 var(--ink);color:var(--text);text-decoration:none} +.plug:hover{background:var(--tint-y,#FFF6D6)}.plug .pi{font-size:30px;line-height:1}.plug b{font-family:var(--display);font-size:16px}.plug .meta{display:block;margin-top:2px}.plug .go{margin-left:auto;font-weight:900;white-space:nowrap} .starts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.starts .start:last-child:nth-child(odd){grid-column:1/-1} .start{border:3px solid var(--ink);border-radius:14px;padding:8px 10px;background:var(--paper);cursor:pointer;text-align:left;box-shadow:0 3px 0 var(--ink)} .starts.one{grid-template-columns:1fr} -.start.on{background:#FFE3F0;border-color:var(--me);box-shadow:0 3px 0 var(--me)} +.start.on{background:var(--tint-p,#FFE3F0);border-color:var(--me);box-shadow:0 3px 0 var(--me)} .start b{font-family:var(--display);font-size:17px;display:block} .start span{font-size:12px;color:var(--ink2);line-height:1.3;display:block} /* Home cities: compact tiles stacked in one column, the dropdown for any other city last. */ +/* Title screen doors (modes), Normal's presets and Sandbox's chaos: chunky sticker tiles, one tap each. */ +.doors{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px} +.door,.preset,.chs{position:relative;border:3px solid var(--ink);border-radius:16px;background:var(--paper);box-shadow:0 4px 0 var(--ink);cursor:pointer;text-align:left;padding:9px 11px 8px;display:flex;flex-direction:column;gap:1px;min-width:0;transition:transform .08s ease,box-shadow .08s ease} +.door:active,.preset:active,.chs:active{transform:translateY(3px);box-shadow:0 1px 0 var(--ink)} +.door i,.preset i,.chs i{font-style:normal;font-size:26px;line-height:1.1} +.door b,.preset b,.chs b{font-family:var(--display);font-size:18px;line-height:1.1} +.door span,.preset span,.chs span{font-size:12.5px;color:var(--ink2);line-height:1.3} +.door.on,.preset.on,.chs.on{background:var(--tint-p,#FFE3F0);border-color:var(--me);box-shadow:0 4px 0 var(--me)} +.door.on::after,.preset.on::after,.chs.on::after{content:"✓";position:absolute;top:6px;right:9px;font:900 15px var(--display);color:var(--me)} +.door[data-door=puzzle],.door[data-door=scn]{background:var(--soft)} +.presets{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px} +.preset small{font-size:11px;color:var(--ink2);line-height:1.3;margin-top:4px;border-top:2px dashed var(--line);padding-top:4px} +.preset[data-preset=bgp].on{background:var(--tint-o,#FFE9D6);border-color:#FF6A2B;box-shadow:0 4px 0 #FF6A2B}.preset[data-preset=bgp].on::after{color:#FF6A2B} +.preset[data-preset=freeze].on{background:var(--tint-b,#E2F5FF);border-color:var(--sea2);box-shadow:0 4px 0 var(--sea2)}.preset[data-preset=freeze].on::after{color:var(--sea2)} +.chaos{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px} +.chs{padding:7px 8px 6px}.chs i{font-size:20px}.chs b{font-size:15px}.chs span{font-size:11px} +.lockn{margin:8px 0 0} .starts.homes{display:flex;flex-direction:column;gap:6px} .homes .start{display:flex;flex-wrap:wrap;align-items:baseline;column-gap:10px;row-gap:2px;padding:6px 12px;box-shadow:0 2px 0 var(--ink)} .homes .start.on{box-shadow:0 2px 0 var(--me)} @@ -116,12 +152,85 @@ input.t{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radi .setline select.pick{min-height:36px;padding:4px 30px 4px 10px;border-width:2px;border-radius:10px;box-shadow:0 2px 0 var(--ink);background-position:right 9px center} .tiers{display:grid;gap:7px;margin-top:10px} .tierbtn{display:flex;align-items:center;gap:10px;border:3px solid var(--ink);border-radius:13px;padding:8px 12px;background:var(--paper);cursor:pointer;box-shadow:0 3px 0 var(--ink);text-align:left} -.tierbtn:hover{background:#FFF6CF} +.tierbtn:hover{background:var(--tint-y,#FFF6CF)} .tierbtn:disabled{opacity:.4;cursor:not-allowed} .tierbtn .sz{font-family:var(--display);font-weight:800;font-size:22px;width:70px} .tierbtn .grow{flex:1} .tierbtn .pr{font-family:var(--display);font-weight:800;font-size:18px} +/* A name too long for .sz (an optic on the Express tab) goes on its own line above the reason. */ +.tierbtn .onm{display:block;font-family:var(--display);font-weight:800;font-size:17px;line-height:1.15;margin-bottom:2px}.tierbtn .onm~.meta{display:block} .gl dt{font-family:var(--display);font-weight:800;font-size:16px;margin-top:10px} .gl dd{margin:2px 0 0;color:var(--ink2);line-height:1.45;font-size:13px} .kbd{display:inline-block;border:2px solid var(--ink);border-radius:6px;padding:0 5px;font-weight:900;font-size:11px;background:var(--soft)} +.keylist{display:grid;grid-template-columns:auto 1fr;gap:10px 16px;align-items:center;margin:14px 0 0} +.keylist dt{margin:0;white-space:nowrap}.keylist dd{margin:0;color:var(--ink2);font-size:14px} +.keylist .kbd{font-size:13px;padding:1px 7px;min-width:12px;text-align:center} +.keylist .keytab{display:inline-block;margin:6px 10px 0 0;white-space:nowrap} +/* "Your networks" on the title screen: one big tap target per network, a small ⋯ for export and delete. */ +.slots{display:flex;flex-direction:column;gap:7px;margin-bottom:6px;max-height:min(46vh,330px);overflow:auto;padding:2px 2px 5px} +.slot{display:flex;align-items:stretch;border:3px solid var(--ink);border-radius:16px;background:var(--paper);box-shadow:0 4px 0 var(--ink);flex:none;transition:transform .08s ease,box-shadow .08s ease} +.slot:active{transform:translateY(3px);box-shadow:0 1px 0 var(--ink)} +.slot.top{background:var(--tint-p,#FFE3F0);border-color:var(--me);box-shadow:0 4px 0 var(--me)} +.slot.busy{background:var(--soft);border-style:dashed} +.slot.broken{opacity:.75;border-style:dashed} +.slot-go{flex:1;min-width:0;display:flex;align-items:center;gap:10px;background:none;border:0;padding:8px 6px 8px 11px;font:inherit;color:inherit;text-align:left;cursor:pointer;min-height:52px} +.slot-go>i{font-style:normal;font-size:26px;line-height:1;flex:none} +.slot .sn{flex:1;min-width:0;display:flex;flex-direction:column} +.slot .sn b{font-family:var(--display);font-size:18px;line-height:1.1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.slot .sn small,.slot .sm small{font-size:12px;color:var(--ink2);line-height:1.3;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +.slot .tag{align-self:flex-start;font:900 10px var(--body);text-transform:uppercase;letter-spacing:.05em;color:var(--me);line-height:1.2} +.slot.busy .tag{color:var(--ink2)} +.slot .sm{flex:none;display:flex;flex-direction:column;align-items:flex-end;text-align:right} +.slot .sm em{font:800 15px var(--display);font-style:normal} +.slot-more{flex:none;width:44px;border:0;border-left:2px dashed var(--line);background:none;font:900 22px var(--display);color:var(--text);cursor:pointer;border-radius:0 13px 13px 0} +.slot-more:hover,.slot-go:hover{background:rgba(255,79,154,.06)} +.slot-go:focus-visible,.slot-more:focus-visible{outline:3px solid #FF4F9A;outline-offset:-3px} +.ibx.space{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.ibx.space .btns{margin:0} +h2 .rn{font-size:18px;vertical-align:middle;padding:2px 4px} +/* Title: language first, compact presets, one drawer for the home city (2.0) */ +.tlang{display:flex;justify-content:flex-end;margin:-4px 0 4px}.tlang .pick{width:auto;max-width:60%} +.presets .preset{flex-direction:row;align-items:center;gap:6px;padding:6px 10px 5px}.presets .preset i{font-size:20px}.presets .preset b{font-size:15px} +.presets .preset.on::after{display:none}#presetWhat{margin:6px 0 0} +.homepick{width:100%} +.tcont .b{white-space:normal;max-width:100%;overflow-wrap:anywhere;line-height:1.15} +#modalCard{overflow-x:hidden} +.menu-tiles{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin-top:10px} +.mtile{border:3px solid var(--ink);border-radius:14px;background:var(--paper);box-shadow:0 3px 0 var(--ink);padding:8px 4px 7px;display:flex;flex-direction:column;align-items:center;gap:2px;cursor:pointer;font:800 13px/1.15 var(--display);color:var(--text);text-align:center;min-height:68px;justify-content:center} +.mtile i{font-style:normal;font-size:22px;line-height:1}.mtile:active{transform:translateY(2px);box-shadow:0 1px 0 var(--ink)} +.menu-links{margin:12px 0 0;text-align:center;line-height:2;color:var(--ink2)} +.menu-links .lnk{background:none;border:0;padding:4px 2px;font-weight:700;font-size:14px;font-family:inherit;color:var(--ink2);text-decoration:underline;text-underline-offset:3px;cursor:pointer} +.menu-plugs{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-top:12px} +.mplug{border:2px solid var(--line);border-radius:12px;padding:8px 10px;font-weight:700;font-size:13px;line-height:1.25;color:var(--text);text-decoration:none;background:var(--soft);display:flex;align-items:center} +/* Find a city: big tap targets, the first result (what Enter picks) highlighted. */ +.findlist{margin-top:8px} +.findrow{width:100%;text-align:left;background:none;border:0;border-top:1px solid var(--line);font:inherit;color:var(--text);min-height:48px;padding:6px 8px;cursor:pointer;border-radius:0} +.findrow .nm,.findrow .meta{display:block} +.findrow.on{background:var(--soft);border-radius:10px} +.findrow:hover{background:var(--soft)} +/* The charter picker (36-specialist.js): three big choices, one tap each, nothing else to close it with. */ +.chpick h2{margin:2px 0 4px}.chpick .tagline{margin:0 0 6px} +.chopt{display:flex;align-items:flex-start;gap:12px;width:100%;margin-top:8px;border:3px solid var(--ink);border-radius:14px;padding:10px 12px;background:var(--paper);box-shadow:0 3px 0 var(--ink);font:inherit;color:var(--text);text-align:left;cursor:pointer} +.chopt:hover,.chopt:focus-visible{background:var(--soft)}.chopt:active{transform:translateY(2px);box-shadow:0 1px 0 var(--ink)} +.chi{font-size:28px;line-height:1.1;flex:none}.cht{display:flex;flex-direction:column;gap:2px;min-width:0} +.cht b{font:800 17px/1.2 var(--display)}.cht span{font-size:13px;line-height:1.35;color:var(--ink2)} +@media (max-width:760px){.chopt{padding:9px 10px;gap:10px}.chi{font-size:24px}.cht span{font-size:12.5px}} +/* A phone on its side: the three side by side, so nothing scrolls. */ +@media (orientation:landscape) and (max-height:500px){.chpick h2{font-size:21px !important}.chpick .tagline{display:none} + .chopts{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}.chopt{flex-direction:column;gap:2px;margin-top:6px;padding:8px 10px}.chi{font-size:22px}.cht span{font-size:12px;line-height:1.3}} +/* The capacity market (Lambda Bazaar): a product's bar is what is sold (green) of what the route wants (the line), with + your minimum as a pink tick. */ +.cmset{border-top:1.5px dashed var(--line);padding:8px 0 4px} +.cmset .nm{display:flex;align-items:center;gap:8px;flex-wrap:wrap} +.cmset .seg{margin:4px 0 6px} +.cmp{margin:6px 0 4px} +.cmbar{position:relative;height:9px;border-radius:5px;background:var(--soft);border:1.5px solid var(--line);margin-top:3px;overflow:visible} +.cmbar i{position:absolute;left:0;top:0;bottom:0;background:var(--eye);border-radius:4px} +.cmbar b{position:absolute;top:-4px;bottom:-4px;width:3px;margin-left:-1.5px;background:var(--ink);border-radius:2px} +.cmbar u{position:absolute;top:-5px;bottom:-5px;width:0;margin-left:-1px;border-left:3px dotted var(--me)} +.cmroute{align-items:flex-start} +.tag.cmhot{background:var(--tint-o,#FFE1D6);color:var(--tx-amber,#B43A12)} +.tag.cmcool{background:var(--tint-b,#DDF1FB);color:var(--tx-blue,#1E6A8C)} +/* Moving a network to another device (#263): a pasted link is long, so it wraps anywhere. Its text is --text, as in + input.t: --ink stays dark on the dark theme's --soft. */ +textarea.xfer-in{width:100%;box-sizing:border-box;border:3px solid var(--ink);border-radius:12px;padding:8px 10px;font:13px/1.35 ui-monospace,monospace;background:var(--soft);color:var(--text);-webkit-text-fill-color:var(--text);resize:vertical;word-break:break-all} diff --git a/src/styles/41-multiplayer.css b/src/styles/41-multiplayer.css new file mode 100644 index 0000000..2552670 --- /dev/null +++ b/src/styles/41-multiplayer.css @@ -0,0 +1,36 @@ +/* Multiplayer (only in a copy built with MP_API): the title row, the start/join sheet, the session panel, the HUD chip. */ +.mpdoor-row{margin-top:8px}.mpdoor{width:100%;background:var(--soft)} +.mpbox{border:2px dashed var(--line);border-radius:14px;padding:4px 12px 10px;margin-top:12px} +.mpbox h3,.mp-panel h3{font-family:var(--display);font-size:18px;margin:10px 0 4px} +.mpjoin,.mpchat{display:flex;gap:8px;align-items:center} +.mpjoin input.t,.mpchat input.t{flex:1 1 auto;min-width:0;width:auto} +#mpCode{text-transform:uppercase;letter-spacing:.12em;font-size:18px} +.mpchat input.t{font-size:16px;padding:6px 10px} +.mpcode{display:flex;align-items:center;gap:10px;border:3px solid var(--ink);border-radius:14px;padding:8px 12px;background:var(--soft);margin-top:10px} +.mpcode small{display:block;font-size:10.5px;font-weight:900;letter-spacing:.09em;text-transform:uppercase;color:var(--ink2)} +.mpcode b{font-family:var(--display);font-size:28px;letter-spacing:.08em;line-height:1.1} +.mpboard,.mpfeed{display:flex;flex-direction:column;gap:4px} +.mpfeed{max-height:220px;overflow:auto;margin-top:6px} +.mprow{display:flex;align-items:center;gap:8px;border:2px solid var(--line);border-radius:12px;padding:6px 10px;min-width:0} +.mprow.me{border-color:var(--me);background:var(--tint-p,#FFF2F8)} +.mprow .grow,.mpf .grow{min-width:0;overflow-wrap:anywhere} +.mprow b{font-family:var(--display);font-size:15px} +.mprk{font:900 15px var(--display);width:20px;text-align:center;flex:0 0 auto} +.mpdot{display:inline-block;width:12px;height:12px;border-radius:50%;border:2px solid var(--ink);flex:0 0 auto} +.mpseen,.mpf small{color:var(--ink2);font-size:11px;white-space:nowrap;flex:0 0 auto} +.mpf{display:flex;align-items:baseline;gap:8px;font-size:13px;line-height:1.35} +.mpf .mpdot{width:9px;height:9px;border-width:1.5px} +.mpf.t1first{font-weight:800} +.mpmove{margin-top:12px}.mpmove summary{cursor:pointer;font-weight:800} +.mpmove input.t{font-size:12px;font-family:monospace;padding:6px 8px} +#hud .mpchip{border-width:3px} +/* No room for the chip on a phone (it is hide-sm), nor on a tablet whose top bar still wraps at fitHud's last step: + where you stand shows as a badge on the menu button, which also opens the session. */ +#hud .menubtn{position:relative} +.mpbadge{display:none;position:absolute;top:-8px;right:-8px;background:var(--paper);color:var(--text);border:2.5px solid var(--ink);border-radius:10px;font:900 11px Nunito,sans-serif;padding:0 5px;line-height:16px;pointer-events:none} +#hud.fit3 .mpchip{display:none !important} +#hud.fit3 .mpbadge{display:block} +@media (max-width:760px){ + .mpcode b{font-size:24px} + .mpbadge{display:block} +} diff --git a/src/styles/42-chart-tooltips.css b/src/styles/42-chart-tooltips.css new file mode 100644 index 0000000..99b2712 --- /dev/null +++ b/src/styles/42-chart-tooltips.css @@ -0,0 +1,17 @@ +.legend .lg{font:inherit;color:inherit;background:none;border:0;padding:2px 4px;margin:-2px -4px;border-radius:6px;cursor:pointer} +.legend .lg:hover{background:rgba(30,38,64,.08)} +.legend .lg.off{opacity:.45;text-decoration:line-through} +.chart[data-ch]{touch-action:pan-y;cursor:crosshair} +.chtip{position:fixed;z-index:60;pointer-events:none;background:var(--ink);color:#fff;border-radius:8px;padding:6px 9px;font-size:11.5px;font-weight:700;box-shadow:0 4px 14px rgba(0,0,0,.3);min-width:130px} +.chtip[hidden],.chcur[hidden]{display:none} +.chtip div{display:flex;align-items:center;gap:6px;margin-top:2px} +.chtip div span{margin-left:auto;padding-left:10px;font-variant-numeric:tabular-nums} +.chtip i{width:9px;height:9px;border-radius:3px;border:1px solid #fff} +.chtip .tot{border-top:1px solid rgba(255,255,255,.35);margin-top:4px;padding-top:3px} +.chcur{position:fixed;z-index:59;pointer-events:none;width:0;border-left:1px dashed var(--text)} +/* The charts' grid and axis labels follow the theme (their attributes give the light look's colours). */ +.chart line{stroke:var(--line)}.chart text{fill:var(--ink2)} +.mix[data-mix]{cursor:help} +.nw-chart[data-ch]{touch-action:pan-y;cursor:crosshair} +.noc-window .chtip{border:1px solid #3A4A78} +.noc-window .chcur{border-left-color:#E8EEFA} diff --git a/src/styles/43-server-play.css b/src/styles/43-server-play.css new file mode 100644 index 0000000..3d85c0b --- /dev/null +++ b/src/styles/43-server-play.css @@ -0,0 +1,3 @@ +/* ================= SERVER-RUN PLAY (multiplayer builds only) ================= + The look of src/game/98-server-play/: only in a page built with MP_API (scripts/lib/page.js leaves it out of every + other page). */ diff --git a/src/styles/45-noc-window.css b/src/styles/45-noc-window.css new file mode 100644 index 0000000..03d3330 --- /dev/null +++ b/src/styles/45-noc-window.css @@ -0,0 +1,95 @@ +/* The NOC window (?noc=): a dark wallboard for a second display, and the dashboard's own tabs under Details. */ +body.noc-window{background:#0B1224;overflow:auto} +#nocBoard{color:#E8EEFA} +body.noc-window>*:not(#nocBoard):not(#dash):not(#toasts):not(.chtip):not(.chcur):not(script){display:none !important} +body.noc-window #dash{position:static;background:none;overflow:visible;padding:0 12px 16px} +body.noc-window #toasts{z-index:20} +body.noc-window [data-act="dashClose"]{display:none} + +#nocBar{display:flex;flex-wrap:wrap;align-items:center;gap:6px 14px;padding:10px 16px;background:#0F1830;border-bottom:1px solid #2A3658;position:sticky;top:0;z-index:5} +.nb-id{min-width:0;margin-right:auto} +.nb-as{display:block;font-size:11px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;color:#9FB0D3;overflow-wrap:anywhere} +.nb-title{font-family:var(--display);font-weight:800;font-size:22px;line-height:1.1} +.nb-pill{font-family:var(--display);font-weight:800;font-size:14px;padding:4px 12px;border-radius:99px;color:#07101F;background:#2DD4A7;white-space:nowrap} +.nb-pill.warn{background:#FFB547} +.nb-pill.bad{background:#FF5C6C} +.nb-now{font-family:var(--display);font-weight:800;font-size:17px;font-variant-numeric:tabular-nums;white-space:nowrap} +.nb-now span{color:#9FB0D3;font-weight:700;margin-left:10px} +.nb-why{flex-basis:100%;order:9;color:#FFD08A;font-weight:700;font-size:13px} +.nb-tabs{display:flex;gap:4px} +.nb-tabs button{background:none;border:1px solid #2A3658;color:#C9D5EE;border-radius:9px;padding:5px 11px;font-weight:800;font-size:12.5px;cursor:pointer} +.nb-tabs button.on{background:#E8EEFA;color:#0B1224;border-color:#E8EEFA} + +#nocWall{display:grid;grid-template-columns:minmax(0,1.55fr) minmax(0,1fr);gap:10px;padding:10px 12px 16px} +.nw-tiles{grid-column:1/-1;display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:10px} +.nw-col{display:flex;flex-direction:column;gap:10px;min-width:0} +.nw-low{grid-column:1/-1;display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px} +.nw-tile,.nw-panel{background:#121B33;border:1px solid #2A3658;border-radius:14px;min-width:0} +.nw-tile{padding:8px 12px;position:relative;overflow:hidden} +.nw-l{font-size:10.5px;font-weight:900;letter-spacing:.07em;text-transform:uppercase;color:#9FB0D3} +.nw-v{font-family:var(--display);font-weight:800;font-size:25px;line-height:1.15;white-space:nowrap} +.nw-tile.bad .nw-v{color:#FF5C6C} +.nw-tile.warn .nw-v{color:#FFB547} +.nw-s{font-size:11.5px;font-weight:700;color:#9FB0D3} +.nw-spark{display:block;width:100%;height:22px;margin-top:3px} +.nw-panel{padding:10px 12px} +.nw-h{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:4px 12px;margin-bottom:6px} +.nw-h h3{font-size:15px;color:#E8EEFA} +.nw-legend{display:flex;flex-wrap:wrap;gap:3px 10px;font-size:11.5px;font-weight:700;color:#C9D5EE} +.nw-legend i{display:inline-block;width:9px;height:9px;border-radius:3px;margin-right:4px} +.nw-legend i.dash{width:12px;height:0;border-top:2px dashed #E8EEFA;border-radius:0;vertical-align:middle} +.nw-empty{color:#9FB0D3;font-weight:700;margin:14px 0} +.nw-quiet{color:#2DD4A7;font-weight:800;margin:10px 0} + +.nw-world{position:relative;width:100%;border-radius:10px;background:#0A1A33;overflow:hidden} +.nw-world svg{position:absolute;inset:0;width:100%;height:100%;display:block} +.nw-land path{fill:#233459;stroke:#34497A;stroke-width:1.5;stroke-linejoin:round} +#nwOver{position:absolute;inset:0} +.nw-link{fill:none;stroke-linecap:round;opacity:.85} +.nw-link.down{stroke-dasharray:10 10} +.nw-flow{fill:none;stroke:#fff;stroke-linecap:round;stroke-dasharray:3 34;opacity:.75;pointer-events:none} +.nw-dot{stroke:#0A1A33;stroke-width:3} +.nw-hit{fill:transparent} +.nw-pop{cursor:pointer} +.nw-sel{fill:none;stroke:#fff;stroke-width:3} +.nw-ring{fill:none;stroke-width:4} +.nw-lab{font-family:var(--body);font-weight:800;font-size:28px;fill:#fff;paint-order:stroke;stroke:#0A1A33;stroke-width:7px;stroke-linejoin:round;pointer-events:none} +@media (prefers-reduced-motion:no-preference){ + body.noc-window:not(.noc-still) .nw-flow{animation:nwFlow 1.6s linear infinite} + body.noc-window:not(.noc-still) .nw-ring{animation:nwPing 1.4s ease-out infinite;transform-box:fill-box;transform-origin:center} +} +@keyframes nwFlow{to{stroke-dashoffset:-37}} +@keyframes nwPing{from{transform:scale(.7);opacity:1}to{transform:scale(2.2);opacity:0}} + +.nw-chart{display:block;width:100%;height:auto} +.nw-grid{stroke:#2A3658;stroke-width:1} +.nw-ax{font-size:13px;font-weight:700;fill:#9FB0D3} +.nw-al{border-left:4px solid #FFB547;padding:4px 8px;margin-bottom:6px;background:#19233F;border-radius:0 8px 8px 0;font-size:13px} +.nw-al.bad{border-left-color:#FF5C6C} +.nw-alarms{max-height:min(44vh,430px);overflow:auto} +.nw-pick select{background:#0F1830;color:#E8EEFA;border:1px solid #2A3658;border-radius:8px;padding:4px 6px;font-weight:700;font-size:12.5px;max-width:170px} +.nw-port{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:2px 8px;align-items:center;padding:7px 0;border-top:1px solid #222E4E} +.nw-k{font-size:10px;font-weight:900;color:#07101F;padding:2px 6px;border-radius:6px;white-space:nowrap} +.nw-pm{min-width:0} +.nw-pt{font-size:13px;overflow-wrap:anywhere} +.nw-bar{height:7px;border-radius:9px;background:#26324F;overflow:hidden;margin:3px 0} +.nw-bar i{display:block;height:100%;border-radius:9px} +.nw-pc{font-family:var(--display);font-size:16px;min-width:42px;text-align:right} +.nw-btns{grid-column:1/-1;display:flex;flex-wrap:wrap;gap:4px;--ink:#1E2640;--paper:#fff;--soft:#EEF5FB;--text:#1E2640;color:#1E2640} +.nw-btns .meta{color:#9FB0D3} +.nw-row{display:flex;align-items:center;gap:8px;padding:4px 0} +.nw-row .nw-pm{flex:1} + +@media (max-width:1000px){ + #nocWall{grid-template-columns:minmax(0,1fr)} + .nw-low{grid-template-columns:minmax(0,1fr)} + .nw-tiles{grid-template-columns:repeat(3,minmax(0,1fr))} +} +@media (max-width:520px){ + .nw-tiles{grid-template-columns:repeat(2,minmax(0,1fr))} + .nw-v{font-size:21px} + .nw-lab{display:none} + #nocBar{padding:8px 10px} + #nocWall{padding:8px} + .nb-now span{margin-left:6px} +} diff --git a/src/styles/50-tablet.css b/src/styles/50-tablet.css index 3d86fd1..9efb1c2 100644 --- a/src/styles/50-tablet.css +++ b/src/styles/50-tablet.css @@ -2,6 +2,8 @@ bigger touch targets so the map keeps some room in the middle. */ @media (min-width:761px) and (max-width:1200px){ #left{width:272px} + #leftTabs{gap:3px;padding-left:6px;padding-right:6px} + #leftTabs button{padding-left:6px;padding-right:6px;font-size:12.5px} #panel{width:336px} #left.closed{display:none} #leftToggle{display:flex;position:fixed;left:max(12px,env(safe-area-inset-left,0px));bottom:calc(env(safe-area-inset-bottom,0px) + 14px);z-index:4} @@ -36,3 +38,8 @@ .chip{padding:2px 7px} } +/* Narrow tablets: a slim find chip and slimmer speed buttons keep the HUD on one row. */ +@media (min-width:761px) and (max-width:860px){ + #hud .chip.find{width:32px;min-width:32px;font-size:15px} + .speed button{min-width:23px;padding-left:2px;padding-right:2px} +} diff --git a/src/styles/60-phone.css b/src/styles/60-phone.css index f761b4c..9cfe4ce 100644 --- a/src/styles/60-phone.css +++ b/src/styles/60-phone.css @@ -3,15 +3,15 @@ (play, speed, goals, deals, NOC, networks), and bottom sheets you drag up, down or away. */ html,body{overscroll-behavior:none} .dtabs{position:sticky;top:-12px;z-index:3;display:flex;gap:6px;overflow-x:auto;margin:10px -4px 4px;padding:8px 4px;background:var(--paper);border-bottom:2.5px solid var(--ink);scrollbar-width:none} -.dtabs button{flex:0 0 auto;font:800 13px Nunito,sans-serif;border:2.5px solid var(--ink);border-radius:999px;background:#fff;padding:5px 12px;cursor:pointer;color:var(--ink)} +.dtabs button{flex:0 0 auto;font:800 13px Nunito,sans-serif;border:2.5px solid var(--ink);border-radius:999px;background:var(--paper);padding:5px 12px;cursor:pointer;color:var(--text)} .dtabs button.on{background:var(--pink,#FF4F9A);color:#fff} .dtabs .cnt{display:inline-block;margin-left:5px;min-width:16px;padding:0 4px;border-radius:8px;background:var(--bad);color:#fff;font-size:10.5px;line-height:16px;text-align:center} -.pcard{border:2.5px solid var(--ink);border-radius:14px;padding:8px 10px;margin:0 0 10px;background:#FFF6CF} +.pcard{border:2.5px solid var(--ink);border-radius:14px;padding:8px 10px;margin:0 0 10px;background:var(--tint-y,#FFF6CF)} .pcard .pt{font-weight:900;font-size:15px;margin:1px 0 2px}.pcard .kv{margin-top:5px}.pcard .bar{margin-top:2px} -.pcard.lv{background:#EAF6FF} -.pitch{list-style:none;padding:0;margin:10px 0}.pitch li{margin:7px 0;line-height:1.38;font-size:14px}.pitch li.warn{background:#FFF4D6;border:2px solid var(--ink);border-radius:10px;padding:6px 8px} +.pcard.lv{background:var(--tint-b,#EAF6FF)} +.pitch{list-style:none;padding:0;margin:10px 0}.pitch li{margin:7px 0;line-height:1.38;font-size:14px}.pitch li.warn{background:var(--tint-y,#FFF4D6);border:2px solid var(--ink);border-radius:10px;padding:6px 8px} .isteps{padding-left:22px;margin:8px 0 4px}.isteps li{margin:5px 0;line-height:1.38;font-size:14px}.isteps svg{vertical-align:-3px} -.icard{margin:8px 0 10px;border:2.5px solid var(--ink);border-radius:14px;padding:8px 10px;background:#FFF4D6} +.icard{margin:8px 0 10px;border:2.5px solid var(--ink);border-radius:14px;padding:8px 10px;background:var(--tint-y,#FFF4D6)} /* iPhone home-screen app with a viewport shorter than the screen: the page box takes the real screen height and becomes the containing block for everything fixed, so bottom-anchored UI reaches the bottom. */ html.iosfix,html.iosfix body{height:var(--app-h)} @@ -29,12 +29,13 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar #leftToggle{display:none !important} #tabbar{display:flex;position:fixed;left:0;right:0;bottom:0;z-index:9;height:var(--tabbar);padding:6px max(6px,env(safe-area-inset-right,0px)) env(safe-area-inset-bottom,0px) max(6px,env(safe-area-inset-left,0px));background:var(--paper);border-top:3px solid var(--ink);box-sizing:border-box;gap:2px;align-items:stretch} #tabbar button{flex:1 1 0;min-width:0;border:0;background:transparent;border-radius:12px;font:inherit;font-weight:900;font-size:10.5px;color:var(--ink2);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1px;padding:2px 0;position:relative} - #tabbar button .ic{font-size:19px;line-height:1.05;color:var(--ink)} - #tabbar button.on{background:var(--soft);color:var(--ink)} + #tabbar button .ic{font-size:19px;line-height:1.05;color:var(--text)} + #tabbar button.on{background:var(--soft);color:var(--text)} #tabbar button.play .ic{font-size:21px} - #tabbar button.play.paused{background:#FFE3F0} + #tabbar button.play.paused{background:var(--tint-p,#FFE3F0)} #tabbar .cnt{position:absolute;top:2px;right:calc(50% - 22px);min-width:16px;height:16px;padding:0 4px;border-radius:8px;background:var(--me);color:#fff;font-size:10px;line-height:16px;box-sizing:border-box} #tabbar .cnt.red{background:var(--bad)} + #tabbar .cnt.dot{min-width:0;width:10px;height:10px;padding:0;top:6px;right:calc(50% - 16px)} #left,#panel{top:auto !important;left:0 !important;right:0 !important;width:auto !important;bottom:var(--tabbar) !important;max-height:min(62%,calc(100% - var(--tabbar) - 70px)) !important;border-radius:20px 20px 0 0 !important;border-bottom:0 !important;box-shadow:0 -3px 0 var(--ink) !important;transition:max-height .22s ease,transform .22s ease;z-index:7} #left.full,#panel.full{max-height:calc(100% - var(--tabbar) - 56px - env(safe-area-inset-top,0px)) !important} #left.closed{display:none} @@ -54,9 +55,16 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar #coach{top:auto !important;bottom:calc(var(--tabbar) + 8px);width:calc(100% - 16px);padding:7px 10px;font-size:13px} body.sheet-open #coach{bottom:calc(var(--tabbar) + 8px + min(62vh,520px))} #modal{align-items:end;padding:0} + #modal.link-check{bottom:var(--tabbar)} #modal .cta{position:sticky;bottom:calc(-16px - env(safe-area-inset-bottom,0px));z-index:1;background:var(--paper);margin:12px -16px 0 !important;padding:10px 16px calc(10px + env(safe-area-inset-bottom,0px));border-top:2px solid var(--line)} .title-art h1{font-size:34px}.title-art svg{width:54px;height:54px} .tagline{font-size:13.5px;margin:8px 0 10px} + .slots{max-height:38vh}.slot-go{padding:7px 4px 7px 9px;gap:8px}.slot-go>i{font-size:22px}.slot .sn b{font-size:16px}.slot .sm em{font-size:13.5px}.slot .sn small,.slot .sm small{font-size:11.5px} + .door{padding:7px 9px 6px}.door i{font-size:22px}.door b{font-size:16px}.door span{font-size:11.5px} + .presets{grid-template-columns:repeat(2,minmax(0,1fr));gap:6px} + .presets .preset{flex-direction:column;align-items:center;text-align:center;padding:6px 4px;gap:0} + .presets .preset i{font-size:20px}.presets .preset b{font-size:13.5px} + .chaos{grid-template-columns:repeat(2,minmax(0,1fr))} #modal .card{box-sizing:border-box;width:100%;max-height:calc(100% - env(safe-area-inset-top,0px) - 24px);border-radius:22px 22px 0 0;padding:16px 16px calc(16px + env(safe-area-inset-bottom,0px));border-bottom:0} #dash{padding:calc(env(safe-area-inset-top,0px) + 6px) 0 0} #dash>.card{border-radius:20px 20px 0 0;min-height:100%} @@ -71,11 +79,13 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar #left,#panel{left:auto !important;right:0 !important;width:min(440px,58%) !important;top:calc(env(safe-area-inset-top,0px) + 50px) !important;max-height:none !important;border-radius:20px 0 0 0 !important;border-right:0 !important} #left.full,#panel.full{width:min(640px,80%) !important} #tabbar button .ic{font-size:16px} + .doors{grid-template-columns:repeat(4,minmax(0,1fr))}.chaos{grid-template-columns:repeat(4,minmax(0,1fr))} + .presets{grid-template-columns:repeat(4,minmax(0,1fr))}.preset{display:flex} body.sheet-open #coach{bottom:calc(var(--tabbar) + 8px);left:8px;transform:none;width:calc(42% - 16px)} } /* Installed as an app: no browser chrome, so leave room for the notch and the home indicator. */ @media (display-mode: standalone){ - body{background:#57C4E5} + body{background:var(--sea)} } /* Whatever the language, the HUD stays on one row: fitHud() drops chips until it fits. */ #hud.fit1 .hide-md2,#hud.fit2 .hide-md{display:none !important} @@ -109,3 +119,5 @@ button,.chip,.b,a{touch-action:manipulation;-webkit-tap-highlight-color:transpar } @media (prefers-reduced-motion:reduce){:root:not(.anim-force) *{animation:none !important;transition:none !important}} :root.no-anim *{animation:none !important;transition:none !important} +/* The narrowest phones: a slimmer find chip so the date still fits. */ +@media (max-width:340px){#hud .chip.find{width:34px;min-width:34px;font-size:15px}#hud .menubtn .caret{display:none}} diff --git a/src/styles/70-puzzles.css b/src/styles/70-puzzles.css new file mode 100644 index 0000000..930475b --- /dev/null +++ b/src/styles/70-puzzles.css @@ -0,0 +1,113 @@ +/* Puzzles (#190): one card for the goal, the stars and the budget; on phones a bottom sheet you can shrink. */ +body.pz #hud .chip:not(.brand):not(.speed),body.pz #hud .speed button:not(#muteBtn),body.pz #leftToggle,body.pz #left{display:none !important} +#pzBox{position:fixed;top:calc(env(safe-area-inset-top,0px) + 76px);left:max(12px,env(safe-area-inset-left,0px));width:300px;max-height:calc(100% - 96px - env(safe-area-inset-top,0px));overflow:auto;z-index:4;padding:10px 14px 12px;box-sizing:border-box} +#pzBox .pzh{display:flex;align-items:center;gap:8px}#pzBox h3{font-size:19px} +.pzj{margin:4px 0 6px;font-size:12.5px;color:var(--ink2);line-height:1.35} +.pzs{display:flex;gap:6px;margin:6px 0}.pzs span{flex:1;display:flex;flex-direction:column;align-items:center;border:2.5px solid var(--ink);border-radius:11px;padding:3px 0;font-size:20px;filter:grayscale(1);opacity:.45;transition:transform .25s,opacity .25s} +.pzs span small{font:900 10px var(--body);text-transform:uppercase;letter-spacing:.05em}.pzs span.on{filter:none;opacity:1;background:var(--tint-y,#FFF3C4);transform:scale(1.05)} +.pzck{display:flex;flex-wrap:wrap;gap:5px;margin:6px 0}.pzc{font-weight:900;font-size:12px;border:2px solid var(--ink);border-radius:999px;padding:1px 8px;background:var(--paper)} +.pzc i{font-style:normal} +.pzc.s1{background:var(--tint-p,#FFE3F0)}.pzc.s2{background:var(--ok);color:#fff} +.pzsrc{font-size:12px;font-weight:800;color:var(--ink2);margin:4px 0} +.pzfl{margin:4px 0 6px}.pzf{margin:4px 0;padding:3px 6px;border:2px solid var(--line);border-radius:10px}.pzf.ok{border-color:var(--ok)} +.pzf .kv{font-size:12px;gap:6px}.pzf .bar{margin:2px 0}.pzf .meta .bad{color:var(--tx-red,var(--bad));font-weight:900}.pzf .seg.pzrt{margin-top:3px} +.pzpair{border-top:2px dashed var(--line);padding-top:4px;margin-top:4px}.pzhave{font-size:13px;font-weight:800;margin:6px 0;padding:4px 8px;border-radius:10px;background:var(--tint-y,#FFF4D6)} +.pznote{font-weight:800;font-size:13.5px;margin:8px 0;padding:8px 10px;border:2.5px solid var(--ink);border-radius:12px;background:var(--tint-y,#FFF3C4)} +.row.on{background:var(--tint-p,#FFE3F0);border-radius:10px} +.pztw{font-size:12.5px;font-weight:800;color:var(--tx-red,var(--bad));margin:3px 0}.pztw.ok{color:var(--eye)}.pztw.rule{color:var(--ink2)} +.pzbud{margin:6px 0}.pzbud .kv{font-size:12.5px} +.pzn1{font-size:12.5px;font-weight:800;margin:6px 0;padding:4px 8px;border:2px solid var(--line);border-radius:10px;color:var(--ink2)} +.pzn1.on{border-color:var(--ok);background:var(--tint-g,#DFFBEA);color:var(--text);animation:pzglow 1.6s ease-in-out infinite}.pzn1.bad{border-color:var(--warn);background:var(--tint-y,#FFF4D6);color:var(--text)} +@keyframes pzglow{50%{box-shadow:0 0 0 4px rgba(34,196,122,.25)}} +#pzBox .btns{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px} +#pzBox .grab{display:none} +/* The status bar: name, stars, money and the one thing to fix next stay put while the rest scrolls. */ +#pzBox .pztop{position:sticky;top:-10px;z-index:2;background:var(--paper);margin:-10px -14px 0;padding:10px 14px 4px} +#pzBox .pzh .b.sm{min-width:34px;padding:3px 8px;font-size:16px}#pzBox .pzh .grow{flex:1 1 auto;min-width:0}#pzBox .pzs span small{white-space:nowrap} +/* The three goals, one per star: ⭐ met, 👉 the one to work on (with what to do and Show me), a number while it waits. */ +.pzgoals{margin:2px 0 4px}.pzgoal{padding:3px 2px} +.pzgl{display:flex;align-items:center;gap:8px;font-size:14px}.pzgl b{flex:1;min-width:0;font-weight:800} +.pzgi{width:24px;flex:none;text-align:center;font-size:16px}.pzgi i{font-style:normal;display:inline-block;width:20px;height:20px;border:2px solid var(--line);border-radius:50%;font:900 11px/16px var(--body);color:var(--ink2);box-sizing:border-box} +.pzgv{font-size:12.5px;font-weight:800;color:var(--ink2);white-space:nowrap} +.pzgoal.done b{font-weight:700;color:var(--ink2)}.pzgoal:not(.done):not(.cur){opacity:.6} +.pzgoal.cur{background:var(--tint-y,#FFF4D6);border:2px solid var(--warn);border-radius:12px;padding:6px 8px;margin:3px 0} +.pzgh{font-size:13px;line-height:1.4;margin:3px 0 1px 32px}#pzBox .pzgh .pzshow{margin:2px 0 0 2px;padding:2px 10px;min-height:0;vertical-align:middle} +.pzchips{display:flex;flex-wrap:wrap;gap:5px;margin:4px 0}.pzchip{font-size:12px;font-weight:800;border:2px solid var(--ok);border-radius:999px;padding:1px 9px;background:var(--paper);white-space:nowrap}.pzchip b{font-weight:900} +.pzprog{margin:6px 0 4px}.pzpack{font-size:17px;margin:14px 0 2px}.pzst{font-size:12px;letter-spacing:-1px;white-space:nowrap} +.scn.lock{opacity:.5} +.pzres{position:relative}.pzstars{display:flex;justify-content:center;gap:10px;margin:10px 0 2px} +.pzbig{font-size:46px;filter:grayscale(1);opacity:.3}.pzbig.on{filter:none;opacity:1} +.pzleft{text-align:center;font-weight:900;font-size:13px;margin:2px 0 0;color:var(--ink2)} +.btns.pzdone .pznext{flex:1 1 100%;font-size:22px;padding:10px 18px 8px;animation:pznudge 1.8s ease-in-out 1.6s infinite} +@keyframes pznudge{50%{transform:translateY(-2px);box-shadow:0 5px 0 var(--ink)}} +@media (prefers-reduced-motion:reduce){.btns.pzdone .pznext{animation:none}} +.pzbig.pop{animation:pzpop .5s cubic-bezier(.3,1.6,.5,1) var(--d) both} +@keyframes pzpop{0%{transform:scale(0) rotate(-40deg);opacity:0}100%{transform:scale(1) rotate(0);opacity:1}} +.pzconf{position:absolute;inset:-16px;pointer-events:none;overflow:hidden;z-index:2} +.pzconf i{position:absolute;top:-12px;left:var(--x);width:8px;height:12px;background:var(--c);border:1.5px solid var(--ink);border-radius:2px;animation:pzfall var(--t) ease-in var(--dl) both} +@keyframes pzfall{0%{transform:translateY(0) rotate(0);opacity:1}100%{transform:translateY(420px) rotate(var(--r));opacity:0}} +@media (max-width:760px),(max-height:500px) and (pointer:coarse){ + body.pz #panel{bottom:0 !important} + .pzbig{font-size:40px} +} +/* Phones (97-puzzles-phone.js): nothing scrolls. A bar pinned at the top holds the puzzle's state and the next thing to + do; a city or a link opens a card at the bottom, split into tabs that each fit. --pzdock is the bar's height. */ +@media (max-width:760px),(max-height:500px) and (pointer:coarse){ + body.pz #hud{display:none} + #pzBox.dock{top:calc(env(safe-area-inset-top,0px) + 6px);bottom:auto;left:max(6px,env(safe-area-inset-left,0px));right:max(6px,env(safe-area-inset-right,0px));width:auto;max-height:none;overflow:visible;border-radius:16px;border:3px solid var(--ink);box-shadow:3px 3px 0 var(--ink);padding:6px 8px 7px} + body.pz.sheet-open #pzBox.dock{display:block} + body.pz.sheet-open #pzBox.dock .pzd-goal,body.pz.sheet-open #pzBox.dock .pzd-chips{display:none} + .pzd-bar{display:flex;align-items:center;gap:6px;min-width:0} + .pzd-nm{flex:1 1 auto;min-width:0;font:800 15px/1.2 var(--display);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} + .pzd-stars{display:flex;gap:2px;flex:none} + .pzd-st{display:inline-grid;place-items:center;width:22px;height:22px;border:2px solid var(--line);border-radius:50%;font:900 11px var(--body);color:var(--ink2);box-sizing:border-box} + .pzd-st.on{border:0;font-size:17px}.pzd-st.cur{border-color:var(--warn);background:var(--tint-y,#FFF4D6);color:var(--text)} + .pzd-bud{flex:none;font-weight:900;font-size:12.5px;font-variant-numeric:tabular-nums;white-space:nowrap}.pzd-bud.bad{color:var(--tx-red,var(--bad))} + #pzBox.dock .pzd-bar .b.sm{min-width:36px;min-height:36px;padding:2px 8px;font-size:16px} + .pzd-goal{display:flex;align-items:center;gap:8px;margin-top:6px;padding:5px 8px;background:var(--tint-y,#FFF4D6);border:2px solid var(--warn);border-radius:12px} + .pzd-goal.done{background:var(--tint-g,#DFFBEA);border-color:var(--ok)}.pzd-goal.bad{background:var(--tint-r,#FFE6E9);border-color:var(--bad)} + #pzBox.dock .arsteps{margin:6px 0 4px}#pzBox.dock .arsteps i{height:6px}#pzBox.dock .arbrief{font-size:13px;margin:0 0 2px} + #pzBox.dock .arsites{display:contents}#pzBox.dock .arsite{font-size:12px;padding:2px 8px} + body.pz.sheet-open #pzBox.dock .arbrief,body.pz.sheet-open #pzBox.dock .arsteps{display:none} + .pzd-goal{flex-wrap:wrap}.pzd-gi{flex:none;font-size:16px}.pzd-gt{flex:1 1 170px;min-width:0;font-size:13px;line-height:1.3}.pzd-gt b{font-weight:800} + .pzd-ga{flex:none;display:flex;flex-direction:column;gap:4px}#pzBox.dock .pzd-ga{margin-left:auto}#pzBox.dock .pzd-ga .b{min-height:32px;padding:2px 10px;font-size:13px;white-space:nowrap} + .pzd-chips{display:flex;flex-wrap:wrap;gap:4px;margin-top:6px} + .pzd-chip{font:800 12px/1.2 var(--body);color:var(--text);background:var(--paper);border:2px solid var(--line);border-radius:999px;padding:3px 8px;white-space:nowrap;max-width:100%;overflow:hidden;text-overflow:ellipsis;cursor:pointer} + .pzd-chip b{font-weight:900;font-variant-numeric:tabular-nums}.pzd-chip .bad{color:var(--tx-red,var(--bad))} + .pzd-chip.ok{border-color:var(--ok);background:var(--tint-g,#DFFBEA)}.pzd-chip.part{border-color:var(--warn);background:var(--tint-y,#FFF4D6)}.pzd-chip.none{border-color:var(--bad);background:var(--tint-r,#FFE6E9)} + .pzd-chip.rule{cursor:default;color:var(--ink2)} + /* The card: as tall as its tab, under the bar at most; tabs keep each part short enough to need no scrolling. */ + body.pz #panel{max-height:calc(100% - var(--pzdock,60px) - 18px - env(safe-area-inset-top,0px)) !important} + body.pz #panel>.grab{display:none} + body.pz #panel .pzd-ph{padding:10px 12px 6px;align-items:center}body.pz #panel .pzd-ph .grow{min-width:0} + body.pz #panel .pzd-ph h2{font-size:20px;line-height:1.15}body.pz #panel .pzd-ph h2 small{font:700 12px var(--body);color:var(--ink2);white-space:normal} + body.pz #panel .pzd-ph .eyebrow .mine{color:var(--me)} + .pzd-body{padding:0 14px calc(10px + env(safe-area-inset-bottom,0px))} + .pzd-tabs{display:flex;gap:4px;margin:6px 0 8px;border-bottom:2px solid var(--line)} + .pzd-tabs button{flex:1;font:800 13px var(--body);color:var(--ink2);background:none;border:0;border-bottom:3px solid transparent;margin-bottom:-2px;padding:6px 2px;min-height:36px} + .pzd-tabs button.on{color:var(--text);border-bottom-color:var(--me)} + .pzd-row{display:flex;align-items:center;gap:8px;padding:4px 0;border-bottom:1.5px dashed var(--line);font-size:13px}.pzd-row .grow{min-width:0}.pzd-row.on{background:var(--tint-p,#FFE3F0);border-radius:8px} + .pzd-to{flex-wrap:wrap}.pzd-foot{justify-content:flex-end} + .pzd-models{display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:5px;margin-top:6px} + .pzd-model{display:flex;flex-direction:column;align-items:flex-start;gap:0;text-align:left;font:inherit;color:var(--text);background:var(--paper);border:2px solid var(--ink);border-radius:10px;padding:3px 7px;min-width:0;cursor:pointer} + .pzd-mh{display:flex;gap:6px;width:100%;align-items:baseline}.pzd-mh b{flex:1 1 auto;min-width:0;font-size:12.5px;font-weight:900;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.pzd-mh span{flex:none;font-weight:900;font-size:12.5px} + .pzd-model small{font-size:11px;color:var(--ink2);line-height:1.25;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} + .pzd-model.on{background:var(--tint-p,#FFE3F0);border-color:var(--me)}.pzd-model:disabled:not(.on){opacity:.45;border-color:var(--line)} + .pzd-rt{margin:6px 0 0}.pzd-rt .b{min-height:34px} + .pzd-tiers{display:grid;grid-template-columns:1fr 1fr;gap:6px}.pzd-tiers .b{margin:0;display:flex;flex-direction:column;align-items:center;gap:0;white-space:normal;line-height:1.15;padding:4px 6px}.pzd-tiers .b small{font-size:11px} + /* What a routing metric does, and the redundancy check's question, are on the desktop card; here the buttons speak. */ + .pzd-routing section{margin:0}.pzd-routing h3{font-size:15px;margin:4px 0}.pzd-routing .note,.pzd-routing .lead{display:none}.pzd-routing .btns{margin:4px 0 8px} + body.pz #hint{bottom:calc(env(safe-area-inset-bottom,0px) + 12px) !important} + body.pz #toasts{top:calc(env(safe-area-inset-top,0px) + var(--pzdock,60px) + 14px) !important;bottom:auto !important} +} +@media (orientation:landscape) and (max-height:500px) and (pointer:coarse),(orientation:landscape) and (max-width:760px) and (max-height:500px){ + #pzBox.dock{right:auto;width:min(380px,46%)} + body.pz #toasts{top:auto !important;bottom:12px !important;left:8px !important;transform:none !important;width:calc(46% - 16px) !important} + /* The bar sits on the left here, so the card on the right can have the whole height. */ + body.pz #panel{top:calc(env(safe-area-inset-top,0px) + 6px) !important;max-height:calc(100% - 6px - env(safe-area-inset-top,0px)) !important} +} +/* The weekly puzzle: a badge on the Puzzles door and in the list while this week's puzzle is unplayed. */ +.pznew{display:inline-block;font:900 10.5px/1.2 var(--body);font-style:normal;text-transform:uppercase;letter-spacing:.04em;background:var(--me);color:#fff;border:2px solid var(--ink);border-radius:999px;padding:1px 7px;white-space:nowrap;vertical-align:1px} +.door .pznew{position:absolute;top:-9px;right:8px;transform:rotate(4deg);animation:pznew 2.4s ease-in-out infinite} +@keyframes pznew{50%{transform:rotate(-3deg) scale(1.08)}} +.scn.wk{flex-wrap:wrap}.scn.wk .grow{min-width:0;flex:1 1 200px}.pzcd{font-weight:800;color:var(--text)} diff --git a/src/styles/71-architect.css b/src/styles/71-architect.css new file mode 100644 index 0000000..dab5131 --- /dev/null +++ b/src/styles/71-architect.css @@ -0,0 +1,27 @@ +/* Architect runs (prototype): the brief, its sites, the review line */ +.arsteps{display:flex;gap:4px;margin:4px 0 6px}.arsteps i{flex:1;height:7px;border:2px solid var(--ink);border-radius:99px;background:var(--paper)} +.arsteps i.done{background:var(--ok)}.arsteps i.on{background:#FFD23F} +.arbrief{margin:2px 0 8px;font-size:14.5px;font-weight:800;line-height:1.35} +.arsites{display:flex;flex-wrap:wrap;gap:5px;margin:4px 0 6px} +.arsite{font-weight:900;font-size:12px;border:2px solid var(--line);border-radius:999px;padding:1px 8px;background:var(--paper);color:var(--ink2)} +.arsite.ok{border-color:var(--ok);color:var(--text)}.arsite.gold{border-color:#E5484D;background:var(--tint-r,#FFE8E8)} +.arline{font-size:12.5px;font-weight:800;margin:3px 0;color:var(--ink2)}.arline.ok{color:var(--text)}.arline.bad{color:var(--tx-red,var(--bad))} +.arshape{font-size:12.5px;font-weight:900;margin:4px 0} +.arrev{font-size:12.5px;font-weight:800;margin:6px 0;padding:5px 8px;border:2px solid var(--line);border-radius:10px;color:var(--ink2)} +.arrev.on{border-color:#FF8A3D;background:var(--tint-o,#FFF0E3);color:var(--text)}.arrev.ok{border-color:var(--ok);background:var(--tint-g,#DFFBEA);color:var(--text)} +.arrev.bad{border-color:var(--bad);background:var(--tint-r,#FFE6E9);color:var(--text)} +#pzBox .arbtns .b.big{flex:1 1 100%} +.artubes{display:flex;justify-content:space-between;align-items:center;font-size:12.5px;font-weight:800;margin:4px 0}.artubes b{font-size:15px;letter-spacing:2px;color:var(--me)} +.artubes em{font-style:normal;font-size:11.5px;letter-spacing:0;color:var(--tx-amber,#B86A00)}.artubes.over b{color:var(--tx-amber,#B86A00)} +/* Laptops and up: a bigger card, easier to read at a glance */ +@media (min-width:761px) and (min-height:501px){ + #pzBox.ar{width:390px;padding:14px 18px 16px} + #pzBox.ar h3{font-size:23px}#pzBox.ar .eyebrow{font-size:12px} + #pzBox.ar .arsteps i{height:9px} + #pzBox.ar .arbrief{font-size:17.5px;margin:4px 0 10px} + #pzBox.ar .arsite{font-size:14px;padding:2px 10px} + #pzBox.ar .arline,#pzBox.ar .arrev,#pzBox.ar .artubes,#pzBox.ar .pzbud .kv{font-size:14px} + #pzBox.ar .artubes b{font-size:19px}#pzBox.ar .pzbud .bar{height:12px} + #pzBox.ar .arbtns .b.sm{font-size:13px;padding:5px 11px} +} +.arsite small{font-weight:800;opacity:.75}.arsite.thin{border-color:var(--bad);background:var(--tint-r,#FFE6E9);color:var(--text)} diff --git a/tests/act-args-builtins.test.js b/tests/act-args-builtins.test.js new file mode 100644 index 0000000..399c7b0 --- /dev/null +++ b/tests/act-args-builtins.test.js @@ -0,0 +1,44 @@ +// A click's args name things the game looks up by key: S.pops[city], S.myIx[city]. A city that is '__proto__' or +// 'constructor', or any other name Object.prototype has ('toString': S.pops.toString is a function, so it reads as a +// POP), from an MCP agent or a request to a server-run network, must find nothing there, never a prototype or a +// built-in's statics: every action that takes one, with each such name in each usual arg, alone and next to the args +// that get an action that far (a kind, a quoted price), leaves the page's built-ins as they were, spends nothing on +// them, and writes no entry under that name anywhere in the game (S.popTiers.at.toString). +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const BAD = ['__proto__', 'constructor', 'prototype', 'toString', 'hasOwnProperty', 'valueOf']; +// The other args an action may need before it looks the name up: ptSave a kind, ptApply a kind and a price. +const WITH = { k: 'micro', cost: 0 }; +const ARGS = ['city', 'id', 'net', 'k', 'c', 'v', 'a', 'b', 'to', 'from', 'link', 's', 'z']; + +test('no action reaches a built-in through an arg that names one', (t) => { + // The development page: API_CMD is every action an agent may send (the MCP facade), the sent ones of a server's page. + const { ev, errors, dom } = load({ agent: true }); + t.after(() => dom.window.close()); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e12;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;"); + for (const c of ['fra', 'ams', 'lon', 'par']) ev(`ACT.buildPop({city:'${c}'})`); + ev("ACT.launchBB({city:'fra'});closeModal();UI.confirm=null;compute();"); + // What the built-ins hold now: anything an action adds to them is found by name. + ev(`window.__fp=()=>{const o={};for(const [n,x] of [['Object',Object],['Object.prototype',Object.prototype],['Array',Array],['Array.prototype',Array.prototype],['Function.prototype',Function.prototype],['String.prototype',String.prototype]])o[n]=Object.getOwnPropertyNames(x).sort().join(','); + const e=[];for(const k in {})e.push(k);for(const k in [])e.push('[]'+k);o.enum=e.join(',');return o;};window.__fp0=__fp(); + window.__clean=()=>{for(const [n,x] of [['Object',Object],['Object.prototype',Object.prototype],['Array',Array],['Array.prototype',Array.prototype],['Function.prototype',Function.prototype],['String.prototype',String.prototype]]){const had=new Set(__fp0[n].split(','));for(const k of Object.getOwnPropertyNames(x))if(!had.has(k))delete x[k];}}; + window.__junk=(v)=>{const out=[],walk=(o,p,d)=>{if(!o||typeof o!=='object'||d>4)return;if(Object.prototype.hasOwnProperty.call(o,v)){out.push(p+'.'+v);delete o[v];}for(const k of Object.keys(o))walk(o[k],p+'.'+k,d+1);};walk(S,'S',0);return out;};`); + const acts = JSON.parse(ev('JSON.stringify(Object.keys(API_CMD).filter(k=>typeof ACT[k]==="function"&&!/^pz[A-Z]/.test(k)))')); + const hits = []; + for (const act of acts) { + for (const name of ARGS) { + for (const v of BAD) for (const extra of [{}, WITH]) { + const args = { ...extra, [name]: v }; + const r = JSON.parse(ev(`(()=>{const c0=S.cash;let err=null;try{ACT[${JSON.stringify(act)}](${JSON.stringify(args)});}catch(e){err=String(e&&e.message||e);} + try{closeModal();}catch(e){}UI.confirm=null;const f=__fp(),d=Object.keys(f).filter(k=>f[k]!==__fp0[k]);if(d.length)__clean();return JSON.stringify({d,spent:c0-S.cash,err,junk:__junk(${JSON.stringify(v)})});})()`)); + if (r.d.length) hits.push(`${act}(${JSON.stringify(args)}) changed ${r.d.join(', ')}${r.spent > 0 ? ` and spent ${r.spent}` : ''}`); + if (r.junk.length) hits.push(`${act}(${JSON.stringify(args)}) wrote ${r.junk.join(', ')}`); + } + } + } + t.diagnostic(`${acts.length} actions × ${ARGS.length} args × ${BAD.length} names × 2`); + assert.deepEqual(hits, []); + assert.deepEqual(errors, []); +}); diff --git a/tests/address-space.test.js b/tests/address-space.test.js new file mode 100644 index 0000000..f6e34d8 --- /dev/null +++ b/tests/address-space.test.js @@ -0,0 +1,532 @@ +// IPv4 address space (#150, src/game/60-features/33-address-space.js): business customers need public blocks, broadband +// homes share addresses behind CGNAT when they do not fit, blocks are bought, sold, leased in and leased out, and the +// whole thing is a rule (ip4): On-call and BGP at 3 a.m. only, scenarios when they opt in. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +// Frankfurt on On-call, plenty of cash, nothing breaking, level 9 so every kind of customer can turn up. +const BASE = "ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall');S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=9;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.offers=[];S.biz=[];" + + "ACT.launchBB({city:'fra'});S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:3});compute()"; +function game(t, opts) { + const h = load(opts); + t.after(() => h.dom.window.close()); + h.ev(BASE); + return h; +} +const J = (ev, x) => JSON.parse(ev(`JSON.stringify(${x})`)); +const homes = (ev, g) => ev(`S.pops.fra.bb.d=${g};compute()`); +const biz = (ev, b) => ev(`S.biz.push(${lit({ id: b.id || 'b' + Math.random().toString(36).slice(2), city: 'fra', city2: null, reqs: [], name: 'X', type: 'host', bw: 10, rate: 60, mood: 100, since: 0, ...b })});compute()`); + +test('what each customer needs: a block by kind and size, nothing for circuits, fiber, downstream ISPs or orbit', (t) => { + const { ev, errors } = game(t); + const need = (type, bw) => ev(`ip4Need({type:${lit(type)},bw:${bw}})`); + assert.equal(need('dia', 1), 8, 'a small DIA port gets a /29'); + assert.equal(need('dia', 10), 32); + assert.equal(need('game', 5), 16); + assert.equal(need('host', 10), 64); + assert.equal(need('host', 80), 512, 'a big hosting company a /23'); + assert.equal(need('cgame', 3200), 2048); + assert.equal(need('metav', 6400), 2048); + assert.equal(need('host', 1e6), 4096, 'capped at a /20'); + for (const k of ['l2vpn', 'hyper', 'wwave', 'dfpair', 'isp', 'edu', 'provedor', 'event', 'pizza', 'flywifi']) assert.equal(need(k, 100), 0, k); + assert.equal(ev('ip4Cidr(8)'), '/29'); + assert.equal(ev('ip4Cidr(512)'), '/23'); + // Every IPv4 kind is a real kind of customer that pays by the Gbps. + assert.deepEqual(J(ev, 'Object.keys(IP4_BIZ).filter(k=>!BIZ_T[k]||!(BIZ_T[k].rate>0)||BIZ_T[k].l2||BIZ_T[k].fiber||BIZ_T[k].orbit)'), []); + assert.deepEqual(errors, []); +}); + +test('consumption: business first, homes take the rest, and the ones that do not fit go behind CGNAT', (t) => { + const { ev, errors } = game(t); + // A new network: one /21 from the RIR, held two years before it can move. + assert.deepEqual(J(ev, 'S.ip4.b.map(b=>[b.len,b.k,b.d])'), [[21, 'rir', 0]]); + assert.equal(ev('S.ip4.nat'), 16); + homes(ev, 50); + let u = J(ev, 'ip4Use()'); + assert.deepEqual([u.T, u.B, u.H, u.cg, u.over, u.free], [2048, 0, 500, 0, 0, 2048 - 32], '500 homes all public; a new customer could push them all behind CGNAT'); + assert.equal(ev('R.cost.ip4'), undefined, 'nothing to pay while everyone has an address'); + biz(ev, { type: 'host', bw: 80 }); // a /23 + homes(ev, 150); + u = J(ev, 'ip4Use()'); + // 1,536 left for 1,500 homes: all public. 1,600 homes: (1600-1536)*16/15 rounded up go behind CGNAT. + assert.deepEqual([u.B, u.cg], [512, 0]); + homes(ev, 160); + u = J(ev, 'ip4Use()'); + assert.equal(u.cg, Math.ceil((1600 - 1536) * 16 / 15)); + assert.ok(u.H - u.cg + Math.ceil(u.cg / 16) <= 1536, 'public homes plus the CGNAT pool fit the space'); + const c = J(ev, 'ip4Bill(R.rev.eyeballs)'); + assert.ok(c.box > 0 && c.refund > 0, 'CGNAT boxes and refunds cost money'); + assert.equal(ev('R.cost.ip4'), Math.round(c.box + c.refund)); + assert.ok(Math.abs(c.refund - ev('R.rev.eyeballs') * (u.cg / u.H) * 0.015) < 1e-6, 'refunds: 1.5% of the CGNAT share of what homes pay at 1:16'); + // A wider ratio frees addresses and annoys more gamers. + const free16 = u.free; + ev("ACT.ip4Nat({v:'64'})"); + assert.equal(ev('S.ip4.nat'), 64); + assert.ok(J(ev, 'ip4Use()').free > free16); + assert.ok(J(ev, 'ip4Bill(R.rev.eyeballs)').refund > c.refund); + ev("ACT.ip4Nat({v:'16'})"); + // Business customers squeeze the homes: past the ratio, homes are squeezed out (port exhaustion) and it shows. + biz(ev, { type: 'host', bw: 80, id: 'h2' }); + biz(ev, { type: 'host', bw: 1e6, id: 'h3' }); + u = J(ev, 'ip4Use()'); + assert.equal(u.cg, u.H); + assert.ok(u.over > 0 && u.free < 0); + assert.ok(J(ev, 'ip4Bill(R.rev.eyeballs)').refund >= ev('R.rev.eyeballs*ip4Use().over') * 0.15, 'squeezed homes want real money back'); + // Narrowing the ratio is refused when the signed customers would not fit. + ev("ACT.ip4Nat({v:'8'})"); + assert.equal(ev('S.ip4.nat'), 16); + assert.deepEqual(errors, []); +}); + +test('an offer that needs more IPv4 than is free cannot be signed, and says why; a block fixes it', (t) => { + const { ev, dom, errors } = game(t); + homes(ev, 50); + ev(`S.offers.push({id:'big',city:'fra',name:'Pixel Palace',type:'cgame',bw:3200,rate:45,reqs:[],exp:S.day+30},{id:'small',city:'fra',name:'Tiny DIA',type:'dia',bw:1,rate:600,reqs:[],exp:S.day+30})`); + assert.equal(ev("ip4Fits(S.offers[0])"), false, 'a /21 does not fit the starting /21 with homes on it'); + assert.equal(ev("ip4Fits(S.offers[1])"), true); + // The deals list and the city panel say why, with a way to the address space. + ev("UI.left='deals';UI.leftOpen=true;renderLeft();selectCity('fra');UI.tab='cust';renderPanel()"); + const left = dom.window.document.getElementById('leftBody').textContent; + assert.match(left, /Needs a \/21 of IPv4 \(2,048 addresses\); only 2,016 free\./); + assert.ok(dom.window.document.querySelector('#leftBody [data-act="ip4Open"]'), 'a button to the address space'); + ev("ACT.accept({id:'big'})"); + assert.equal(ev("S.offers.some(o=>o.id==='big')"), true, 'not signed'); + assert.equal(ev('S.biz.length'), 0); + assert.match(dom.window.document.getElementById('toasts').textContent, /Pixel Palace needs a \/21 of IPv4/); + ev("ACT.accept({id:'small'})"); + assert.equal(ev('S.biz.length'), 1, 'a small one fits'); + // Buy a /21 and the big one signs. + const cash = ev('S.cash'); + ev("ACT.ip4Buy({len:21})"); + assert.equal(ev('S.cash'), cash - ev('ip4Cost(21)')); + assert.equal(ev('ip4Cost(21)'), Math.round(2048 * 38 * (1 - 0.015 * 3) / 100) * 100, 'about $38 an address, a little less for a bigger block'); + ev("ACT.accept({id:'big'})"); + assert.equal(ev('S.biz.length'), 2); + assert.equal(J(ev, 'ip4Use()').B, 8 + 2048); + // The bank opens at the section. + ev("ACT.ip4Open()"); + assert.equal(dom.window.document.getElementById('bankBox').hidden, false); + assert.ok(dom.window.document.getElementById('bankIp4')); + assert.deepEqual(errors, []); +}); + +test('the sales desk and the CEO do not sign what does not fit', (t) => { + const { ev, errors } = game(t); + homes(ev, 50); + ev("ACT.salesHire({id:'shark'});closeModal();S.slAuto.on=true"); + ev("S.offers.push({id:'big',city:'fra',name:'Big One',type:'metav',bw:6400,rate:35,reqs:[],exp:S.day+30})"); + ev('slAutoDay(S.day)'); + assert.equal(ev("S.offers.some(o=>o.id==='big')"), true, 'the shark leaves it'); + ev("ACT.salesFire({});ACT.salesFire({});closeModal();ACT.salesHire({id:'ceo'});closeModal()"); + assert.equal(ev("salesOverride(S.offers.find(o=>o.id==='big'))"), false, 'no handshake on addresses you do not have'); + assert.equal(ev("(()=>{const t=SALES_GOLF.find(x=>(BIZ_T[x].lv||1)<=lvl()&&ip4Fits({type:x,bw:BIZ_T[x].opts[BIZ_T[x].opts.length-1]}));return t;})()"), 'gpu', 'the golf deal is the biggest that fits (a /23 for an AI data center, not a /21 for cloud gaming)'); + assert.deepEqual(errors, []); +}); + +test('buying, leasing in, leasing out and selling move the right money', (t) => { + const { ev, dom, errors } = game(t); + homes(ev, 20); + const rev0 = ev('R.revMo'), cost0 = ev('R.costMo'); + ev("ACT.ip4Lease({len:22})"); + const lin = ev("S.ip4.b.find(b=>b.k==='in').mo"); + assert.equal(lin, 512, 'a /22 leases for $0.50 an address a month'); + assert.equal(ev('R.costMo'), cost0 + lin); + assert.equal(ev('ip4Use().T'), 3072); + ev("ACT.ip4Buy({len:24})"); + const bought = ev("S.ip4.b.find(b=>b.k==='buy').id"); + ev(`ACT.ip4Out({id:${lit(bought)}})`); + assert.equal(ev(`S.ip4.b.find(b=>b.id===${lit(bought)}).mo`), Math.round(256 * 0.4)); + assert.equal(ev('R.revMo'), rev0 + Math.round(256 * 0.4), 'leased out: income every month'); + assert.equal(ev('R.rev.ip4'), Math.round(256 * 0.4)); + // A leased-out block cannot be sold; take it back first. A fresh block cannot move for two years. + ev(`ACT.ip4Sell({id:${lit(bought)}})`); + assert.equal(ev(`S.ip4.b.some(b=>b.id===${lit(bought)})`), true); + ev(`ACT.ip4Back({id:${lit(bought)}})`); + assert.equal(ev('R.rev.ip4'), undefined); + ev(`ACT.ip4Sell({id:${lit(bought)}})`); + assert.match(dom.window.document.getElementById('toasts').textContent, /won't transfer that block again/); + ev('S.day+=730'); + const cash = ev('S.cash'); + ev(`ACT.ip4Sell({id:${lit(bought)}})`); + assert.equal(ev(`S.ip4.b.some(b=>b.id===${lit(bought)})`), true, 'the first click only asks'); + ev(`ACT.ip4Sell({id:${lit(bought)}})`); + assert.equal(ev(`S.ip4.b.some(b=>b.id===${lit(bought)})`), false); + assert.equal(ev('S.cash'), cash + ev('ip4Value(24)')); + assert.ok(ev('ip4Value(24)') < ev('ip4Cost(24)'), 'the broker keeps a cut'); + // Hand the leased block back: the fee stops. + ev("ACT.ip4Return({id:S.ip4.b.find(b=>b.k==='in').id})"); + assert.equal(ev("S.ip4.b.some(b=>b.k==='in')"), false); + assert.equal(ev('R.cost.ip4'), undefined); + // Space in use cannot be given away: with customers on every address, leasing out or selling the /21 is refused. + biz(ev, { type: 'host', bw: 80 }); + biz(ev, { type: 'host', bw: 40, id: 'h2' }); + const rir = ev("S.ip4.b.find(b=>b.k==='rir').id"); + ev(`ACT.ip4Out({id:${lit(rir)}})`); + assert.equal(ev(`!!S.ip4.b.find(b=>b.id===${lit(rir)}).out`), false); + assert.match(dom.window.document.getElementById('toasts').textContent, /Your customers need those addresses/); + assert.deepEqual(errors, []); +}); + +test('investors on a revenue share take their cut of IPv4 lease income, not of a sale', (t) => { + const { ev, dom, errors } = game(t); + homes(ev, 20); + ev("S.loanOffers.push({id:'v1',bank:'vult',amount:500000,exp:S.day+20,covs:['blitz'],share:0.1});ACT.takeLoan({id:'v1'})"); + const base = () => ev('R.rev.eyeballs+R.rev.business+R.rev.ix+(R.rev.orbit||0)'); + const rs0 = ev('R.cost.revshare'); + assert.ok(rs0 > 0 && Math.abs(rs0 - 0.1 * base()) < 1e-6, 'the vultures take 10% of what homes pay'); + ev('ACT.ip4Buy({len:20})'); + const id = ev("S.ip4.b.find(b=>b.k==='buy').id"); + ev(`ACT.ip4Out({id:${lit(id)}})`); + const lout = ev('R.rev.ip4'); + assert.equal(lout, ev('ip4OutMo(20)')); + assert.ok(Math.abs(ev('R.cost.revshare') - 0.1 * (base() + lout)) < 1e-6, 'and 10% of the lease too'); + assert.ok(Math.abs(ev('R.cost.revshare') - 0.1 * (ev('R.revMo') - ev('R.rev.grant||0') - ev('R.rev.gov||0'))) < 1, 'of everything but government money'); + // A bank's big loan with a revenue share takes its share of the lease while it runs, and stops once repaid. + ev("S.loans.push({id:'b1',bank:'db',start:S.day,amount:2e6,got:2e6,bal:2e6,apr:0.1,apr0:0.1,pay:1,left:12,term:12,share:0.05,covs:[],base:{sub:0}});compute()"); + assert.ok(Math.abs(ev('R.cost.revshare') - 0.15 * (base() + lout)) < 1e-6); + ev("S.loans.find(l=>l.id==='b1').bal=0;compute()"); + assert.ok(Math.abs(ev('R.cost.revshare') - 0.1 * (base() + lout)) < 1e-6); + // Taking the block back ends the cut; selling it is a one-off that is all yours, like a fiber pair's up-front price. + ev(`ACT.ip4Back({id:${lit(id)}})`); + assert.equal(ev('R.rev.ip4'), undefined); + assert.ok(Math.abs(ev('R.cost.revshare') - rs0) < 1e-6); + ev('S.day+=730;compute()'); + const rs1 = ev('R.cost.revshare'), cash = ev('S.cash'); + ev(`ACT.ip4Sell({id:${lit(id)}});ACT.ip4Sell({id:${lit(id)}})`); + assert.equal(ev(`S.ip4.b.some(b=>b.id===${lit(id)})`), false); + assert.equal(ev('S.cash'), cash + ev('ip4Value(20)')); + assert.ok(Math.abs(ev('R.cost.revshare') - rs1) < 1e-6); + // The dashboard's Investor revenue share row shows the new amount. + ev("ACT.ip4Buy({len:20});ACT.ip4Out({id:S.ip4.b.filter(b=>b.k==='buy').pop().id});UI.dtab='overview';renderDash()"); + assert.ok(ev('R.cost.revshare') > rs1, 'a new lease is shared again'); + assert.ok(dom.window.document.getElementById('dash').textContent.includes(ev('fmt$(R.cost.revshare)'))); + assert.deepEqual(errors, []); +}); + +test('a list of blocks stops where a save keeps them: buying and leasing past it is refused, and a full save loads whole', (t) => { + const { ev, dom, errors } = load({ agent: true }); + t.after(() => dom.window.close()); + ev(BASE); + homes(ev, 20); + // The market's default size, clicked over and over (or an agent in a loop): bought and leased /24s. + ev('for(let i=0;i<150;i++)ACT.ip4Buy({len:24});for(let i=0;i<150;i++)ACT.ip4Lease({len:24})'); + assert.equal(ev('S.ip4.b.length'), ev('IP4_BLK'), 'stops at the most a save keeps'); + assert.equal(ev('IP4_BLK'), 256); + assert.match(dom.window.document.getElementById('toasts').textContent, /You hold 256 IPv4 blocks/); + const cash = ev('S.cash'), T = ev('ip4Use().T'), mo = ev('R.cost.ip4'); + ev('ACT.ip4Buy({len:16});ACT.ip4Lease({len:16})'); + assert.deepEqual([ev('S.ip4.b.length'), ev('S.cash'), ev('ip4Use().T')], [256, cash, T], 'refused: no money spent, nothing added'); + // The bank says so and greys the market out; an agent's quote says why. + ev('ACT.ip4Open()'); + const sec = dom.window.document.querySelector('#bankCard .bank-ip4'); + assert.match(sec.textContent, /the most one network can keep track of/); + assert.equal(sec.querySelector('[data-act="ip4Buy"]').disabled, true); + assert.equal(sec.querySelector('[data-act="ip4Lease"]').disabled, true); + assert.match(J(ev, 'API_CMD.ip4Buy.quote({len:24}).blocked')[0], /256 IPv4 blocks/); + assert.match(J(ev, 'API_CMD.ip4Lease.quote({len:24}).blocked')[0], /256 IPv4 blocks/); + // Saved and loaded: every block, every lease, the same space and bill. + const before = ev('JSON.stringify(S.ip4)'); + ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + assert.equal(ev('JSON.stringify(S.ip4)'), before); + assert.deepEqual([ev('ip4Use().T'), ev('R.cost.ip4')], [T, mo]); + // Handing one back makes room for a bigger block. + ev("ACT.ip4Return({id:S.ip4.b.find(b=>b.k==='in').id});ACT.ip4Buy({len:16})"); + assert.deepEqual([ev('S.ip4.b.length'), ev('S.ip4.b[255].len')], [256, 16]); + assert.deepEqual(errors, []); +}); + +test('a customer renewing bigger stays at its size when the bigger block is not free, and says why', (t) => { + const { ev, dom, errors } = game(t); + homes(ev, 0); + // Eight 40G hosts (a /24 each) fill the /21; the ninth is refused at the door. + for (let i = 0; i < 9; i++) ev(`S.offers.push({id:'o${i}',city:'fra',name:'Host ${i}',type:'host',bw:40,rate:60,reqs:[],exp:S.day+30});ACT.accept({id:'o${i}'})`); + assert.equal(ev('S.biz.length'), 8); + assert.equal(J(ev, 'ip4Use()').free, 0); + // The next term of host 0 on a day its own rolls say: stay, and grow (to 80G, a /23). + const renew = () => J(ev, `(()=>{const b=S.biz[0];for(const x of S.biz)if(x!==b)x.te=1e6; + for(let k=Math.max(S.day,b.te)+1;k=(0.04+0.08*Math.min(1,clComp(b)/6))*salesLeaveMul(b)){S.day=k;document.getElementById('toasts').innerHTML='';clDay(k);compute(); + return {bw:b.bw,te:b.te,in:S.biz.includes(b),free:ip4Use().free,toasts:document.getElementById('toasts').textContent};}}return null;})()`); + let r = renew(); + assert.ok(r, 'a growing renewal turns up'); + assert.deepEqual([r.bw, r.in, r.free], [40, true, 0], 'renewed at the size it has: nobody runs on addresses you do not have'); + assert.ok(r.te > ev('S.day'), 'a new term'); + assert.match(r.toasts, /Host 0 \(Frankfurt\) wanted to grow to 80(\.0)? Gbps, but you had no IPv4 addresses free for it\./); + assert.match(r.toasts, /renewed/); + // The acquisition that would stay bigger goes through the same door. + assert.equal(ev('(()=>{const out={v4:[]};return clGrow(S.biz[0],out)===false&&out.v4.length===1&&S.biz[0].bw===40;})()'), true); + // A block bought, the next growing renewal grows. + ev('ACT.ip4Buy({len:24})'); + r = renew(); + assert.deepEqual([r.bw, r.free], [80, 0]); + assert.match(r.toasts, /renewed and grew to 80(\.0)? Gbps/); + // Without the rule, growth is as it always was. + ev("S.rules=makeRules('freeze');compute()"); + r = renew(); + assert.equal(r.bw, 160); + assert.doesNotMatch(r.toasts, /IPv4/); + assert.deepEqual(errors, []); +}); + +test('the address space says what its numbers mean: free counts homes behind CGNAT, blocks in use say why they stay', (t) => { + const { ev, dom, errors } = game(t); + ev('S.day=800'); + homes(ev, 50); + ev('ACT.ip4Open()'); + const sec = () => dom.window.document.querySelector('#bankCard .bank-ip4'); + assert.match(sec().textContent, /Free for new customers \(homes move behind CGNAT first\)2,016/); + // The /21 is out of its holding period, but 500 homes use it: greyed out, and the row says why. + let row = sec().querySelector('[data-act="ip4Out"]').closest('.row'); + assert.equal(row.querySelector('[data-act="ip4Out"]').disabled, true); + assert.equal(row.querySelector('[data-act="ip4Sell"]').disabled, true); + assert.match(row.querySelector('.why').textContent, /Your customers need those addresses/); + // A leased-in /24 the customers need too: Give it back is greyed, with the reason. + ev("ACT.ip4Lease({len:24})"); + biz(ev, { type: 'host', bw: 80, id: 'h1' }); + biz(ev, { type: 'host', bw: 80, id: 'h2' }); + biz(ev, { type: 'host', bw: 80, id: 'h3' }); + biz(ev, { type: 'host', bw: 80, id: 'h4' }); + assert.equal(J(ev, 'ip4Use()').free, 224, 'fewer free than the /24 holds'); + ev('UI._bh=null;renderBank()'); + row = sec().querySelector('[data-act="ip4Return"]').closest('.row'); + assert.equal(row.querySelector('[data-act="ip4Return"]').disabled, true); + assert.match(row.querySelector('.why').textContent, /Your customers need those addresses/); + // With room to spare, no reason is shown and the buttons work. + ev("S.biz=[];compute();ACT.ip4Buy({len:24});UI._bh=null;renderBank()"); + row = [...sec().querySelectorAll('[data-act="ip4Out"]')].pop().closest('.row'); + assert.equal(row.querySelector('[data-act="ip4Out"]').disabled, false); + assert.equal(row.querySelector('.why'), null); + assert.deepEqual(errors, []); +}); + +test('the AS box on the dashboard lists the blocks you announce, not a made-up count', (t) => { + const { ev, dom, errors } = game(t); + const asBox = () => { ev("ACT.dash({});ACT.dashTab({k:'infra'})"); const k = [...dom.window.document.querySelectorAll('#dashCard .kv')].map(e => e.textContent).find(x => /IPv6/.test(x)); ev('ACT.dashClose()'); return k; }; + assert.match(asBox(), /1 × \/21 IPv4, 1 × \/32 IPv6/, 'the starting allocation'); + ev("ACT.ip4Lease({len:22});ACT.ip4Buy({len:24})"); + assert.match(asBox(), /1 × \/21, 1 × \/22, 1 × \/24 IPv4/, 'bought and leased-in blocks are announced too'); + ev("S.rules=makeRules('freeze');compute()"); + assert.match(asBox(), /1 × \/22 IPv4/, 'without the rule it stays as it always was'); + assert.deepEqual(errors, []); +}); + +test('the market price drifts gently with the day, and holds still without the market rule', (t) => { + const { ev, errors } = game(t); + assert.equal(ev('ip4Px(0)'), 38); + assert.equal(ev('ip4Px(180)'), 38, 'flat for half a year'); + const px = [400, 900, 1500, 2200].map((d) => ev(`ip4Px(${d})`)); + assert.ok(px.every((p) => p > 30 && p < 50), 'realistic: $30 to $50 an address: ' + px); + assert.ok(Math.abs(ev('ip4Px(546)') - ev('ip4Px(545)')) < 0.1, 'a gentle trend, not a jump'); + assert.ok(ev('ip4Cost(16)') / 65536 < ev('ip4Cost(24)') / 256, 'bigger blocks a little cheaper per address'); + ev("S.rules=makeRules('oncall',{market:false})"); + assert.equal(ev('ip4Px(1500)'), 38); + assert.deepEqual(errors, []); +}); + +test('the day says it once when homes go behind CGNAT, and when even CGNAT cannot fit them', (t) => { + const { ev, dom, errors } = game(t); + const said = () => dom.window.document.getElementById('toasts').textContent; + // A handful of homes over the edge (under a percent of them) is not news yet. + homes(ev, 205.3); + ev('ip4Day(S.day)'); + const few = J(ev, 'ip4Use()'); + assert.ok(few.cg > 0 && few.cg < few.H / 100, JSON.stringify(few)); + assert.equal(ev('S.ip4.w'), 0); + assert.doesNotMatch(said(), /IPv4/); + homes(ev, 250); + ev('ip4Day(S.day)'); + assert.match(said(), /Your IPv4 is full\.\s*19% of your homes now share addresses behind CGNAT/); + assert.equal(ev('S.ip4.w'), 1); + ev("document.getElementById('toasts').innerHTML='';ip4Day(S.day)"); + assert.equal(said(), '', 'only once'); + // Homes hovering at the limit hear it once: dipping just under does not rearm it, real room again does. + homes(ev, 204); + ev('ip4Day(S.day)'); + assert.deepEqual([J(ev, 'ip4Use()').cg, ev('S.ip4.w')], [0, 1]); + homes(ev, 250); + ev('ip4Day(S.day)'); + assert.equal(said(), '', 'not again while hovering'); + homes(ev, 150); + ev('ip4Day(S.day)'); + assert.equal(ev('S.ip4.w'), 0, 'room to spare: it rearms'); + homes(ev, 250); + ev('ip4Day(S.day)'); + assert.match(said(), /Your IPv4 is full/); + ev("document.getElementById('toasts').innerHTML=''"); + biz(ev, { type: 'host', bw: 1e6 }); + ev('ip4Day(S.day)'); + assert.match(dom.window.document.getElementById('toasts').textContent, /Out of IPv4/); + assert.equal(ev('S.ip4.w'), 3); + ev("S.biz=[];S.pops.fra.bb.d=10;compute();ip4Day(S.day)"); + assert.equal(ev('S.ip4.w'), 0, 'fixed: the warnings rearm'); + assert.deepEqual(errors, []); +}); + +// The notices came with an Address space button, but their line in the NOC's notifications had no Open: the log did not +// know the button (openOf), so it fell back to the text, which names no POP. Open now goes where the button went. +test('an address-space notice in the notifications opens the bank at its Address space, and the NOC window may ask for it', (t) => { + const { ev, dom, errors } = game(t); + const doc = dom.window.document; + // Where the bank scrolls to: the Address space's own button scrolls it into view. + ev("S.log=[];window.__into=[];(()=>{const s=Element.prototype.scrollIntoView;Element.prototype.scrollIntoView=function(){__into.push(this.id);if(s)return s.apply(this,arguments);};})()"); + homes(ev, 250); + ev('ip4Day(S.day)'); + assert.match(ev('S.log[0].t'), /Your IPv4 is full/); + assert.deepEqual(J(ev, 'S.log[0].o'), { a: 'ip4' }); + ev("closeModal();ACT.leftTab({t:'noc'})"); + const b = doc.querySelector(`#leftBody [data-act=logOpen][data-args='${lit({ id: ev('S.log[0].id') })}']`); + assert.ok(b, 'the notice has an Open button'); + b.click(); + assert.equal(doc.getElementById('bankBox').hidden, false, 'the bank is open'); + assert.ok(doc.getElementById('bankIp4')); + assert.deepEqual(J(ev, '__into'), ['bankIp4'], 'at its Address space'); + // A renewal that could not grow carries the same button. + biz(ev, { id: 'h1', name: 'Hoster' }); + ev("ACT.bankClose();S.log=[];ip4News([[S.biz.find(b=>b.id==='h1'),20]])"); + assert.deepEqual(J(ev, 'S.log[0].o'), { a: 'ip4' }); + // Kept in the save; with IPv4 off (a save from a gentler preset) it still opens the bank. + ev("S=migrate(JSON.parse(JSON.stringify(S)));"); + assert.deepEqual(J(ev, 'S.log[0].o'), { a: 'ip4' }); + ev("ACT.bankClose();S.rules.ip4=false;__into.length=0;ACT.logOpen({id:S.log[0].id})"); + assert.equal(ev('ip4On()'), false); + assert.equal(doc.getElementById('bankBox').hidden, false); + assert.deepEqual(J(ev, '__into'), []); + // The NOC window's clicks run in the game only from its list; the address space is on it (#150). + assert.ok(ev("NOC_GO.includes('ip4Open')&&!NOC_LOCAL.includes('ip4Open')")); + assert.deepEqual(errors, []); +}); + +test('rule off means no effect: gentler presets, sandbox, puzzles and scenarios unless they opt in', (t) => { + const { ev, dom, errors } = game(t); + assert.deepEqual(J(ev, "['soft','freeze','oncall','bgp','sandbox','puzzle'].map(p=>makeRules(p).ip4)"), [false, false, null, null, false, false], 'On-call and BGP keep the default (on), written nowhere'); + assert.equal(ev('RULE_DEF.ip4'), true); + ev("S.rules=makeRules('freeze');S.pops.fra.bb.d=500;compute()"); + assert.equal(ev('ip4On()'), false); + ev("S.offers.push({id:'big',city:'fra',name:'Big One',type:'metav',bw:6400,rate:35,reqs:[],exp:S.day+30})"); + assert.equal(ev("ip4Why(S.offers[0])"), ''); + ev("ACT.accept({id:'big'})"); + assert.equal(ev('S.biz.length'), 1, 'signed: IPv4 is plentiful here'); + assert.equal(ev('R.cost.ip4'), undefined); + ev("ACT.ip4Buy({len:24})"); + assert.equal(ev('S.ip4.b.length'), 1, 'the market is closed'); + ev("ACT.bank()"); + assert.equal(dom.window.document.getElementById('bankIp4'), null, 'no address space in the bank'); + ev("ACT.bankClose()"); + // Sandbox and scenarios. + ev("beginGame('Box','fra',{mode:'sandbox'});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev('ip4On()'), false, 'sandbox'); + ev("beginGame('S','fra',{mode:'normal',preset:'oncall',scn:SCN.find(x=>x.city==='fra')||SCN[0]});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev("S.mode"), 'scenario'); + assert.equal(ev('ip4On()'), false, 'scenarios run On-call but stay as they were'); + ev('S.scn.rules.ip4=true'); + assert.equal(ev('ip4On()'), true, 'unless they opt in'); + ev("beginGame('B','fra',{mode:'normal',preset:'bgp'});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev('ip4On()'), true, 'BGP at 3 a.m.'); + assert.deepEqual(errors, []); +}); + +test('old saves: what they already use is registered to them, so nothing changes on load', (t) => { + const { ev, errors } = game(t); + homes(ev, 300); + biz(ev, { type: 'host', bw: 80 }); + biz(ev, { type: 'dia', bw: 10, id: 'd1' }); + biz(ev, { type: 'l2vpn', bw: 10, id: 'l1' }); + // The same network without the rule, for its money. + ev("window.__r=S.rules;S.rules=makeRules('freeze');compute();window.__m=[R.revMo,R.costMo];S.rules=__r"); + ev('S.day=400;delete S.ip4;S=migrate(JSON.parse(JSON.stringify(S)));compute()'); + const u = J(ev, 'ip4Use()'); + assert.equal(u.cg, 0, 'no home behind CGNAT'); + const want = (u.B + u.H) * 1.25; + assert.ok(u.T >= want && u.T - want < 256, 'what they use and a quarter more to grow into, rounded up to whole /24s: ' + JSON.stringify(u)); + assert.ok(J(ev, 'S.ip4.b').every((b) => b.k === 'rir' && b.d === 400 && b.len >= 16 && b.len <= 24)); + assert.deepEqual([ev('R.revMo'), ev('R.costMo')], J(ev, '__m'), 'the same money as before the feature'); + // A tiny old save still gets the /21 a new one starts with. + ev("S.biz=[];S.pops.fra.bb.d=1;delete S.ip4;S=sanitize(JSON.parse(JSON.stringify(S)))"); + assert.deepEqual(J(ev, 'S.ip4.b.map(b=>b.len)'), [21]); + // A big old network: whole /16s. + ev("S.pops.fra.bb.d=20000;delete S.ip4;S=sanitize(JSON.parse(JSON.stringify(S)))"); + const big = J(ev, 'ip4Use()'); + assert.ok(big.T >= 200000 && big.cg === 0 && J(ev, 'S.ip4.b.filter(b=>b.len===16).length') === 3); + assert.deepEqual(errors, []); +}); + +test('the big network loads with its usage granted: routing and money as before', (t) => { + const { ev, dom, errors } = load({ seed: 3 }); + t.after(() => dom.window.close()); + const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute()`); + const on = ev('ip4On()'); + const digest = 'JSON.stringify([R.served,R.revMo,R.costMo,R.cost,R.rev])'; + const a = ev(digest); + ev("window.__r=S.rules;S.rules=Object.assign({},S.rules,{ip4:false});compute()"); + assert.equal(ev(digest), a, 'the grant covers it all (rule ' + (on ? 'on' : 'off') + ')'); + assert.equal(J(ev, 'S.ip4.b.length') > 0, true); + assert.deepEqual(errors, []); +}); + +test('saves: garbage is repaired, and the state round-trips', (t) => { + const { ev, errors } = game(t); + ev("ACT.ip4Lease({len:23});ACT.ip4Nat({v:'32'})"); + const before = ev('JSON.stringify(S.ip4)'); + ev('S=sanitize(JSON.parse(JSON.stringify(S)))'); + assert.equal(ev('JSON.stringify(S.ip4)'), before); + ev(`S.ip4={b:[{id:'a',len:12,k:'rir',d:0},{id:'b',len:24,k:'stolen',d:0},{id:'c',len:24,k:'buy',d:-5,out:'yes',mo:5},{id:'d',len:23,k:'in',d:1e9,mo:-3},null,{id:'e',len:24,k:'rir',d:0,out:true,mo:'x'}],nat:7,w:99};S=sanitize(JSON.parse(JSON.stringify(S)))`); + assert.deepEqual(J(ev, 'S.ip4'), { b: [{ id: 'c', len: 24, k: 'buy', d: 0 }, { id: 'd', len: 23, k: 'in', d: ev('S.day'), mo: 0 }, { id: 'e', len: 24, k: 'rir', d: 0, out: true, mo: 0 }], nat: 16, n64: 128, w: 3 }); + ev("S.ip4='nope';S=sanitize(JSON.parse(JSON.stringify(S)))"); + assert.ok(J(ev, 'S.ip4.b.length') >= 1, 'a broken field is granted afresh'); + assert.deepEqual(errors, []); +}); + +test('the address space works on a phone: one column, wrapping buttons, the dropdowns stacked', (t) => { + const { ev, dom, errors } = game(t); + ev("window.innerWidth=360;window.innerHeight=740;S.pops.fra.bb.d=250;compute();ACT.ip4Lease({len:24});ACT.ip4Open()"); + const sec = dom.window.document.querySelector('#bankCard .bank-ip4'); + assert.ok(sec, 'the section is in the bank'); + assert.equal(sec.querySelectorAll('select').length, 3, 'the CGNAT ratio, the NAT64 ratio and the block size'); + for (const s of sec.querySelectorAll('select')) assert.ok(s.closest('.ops-sel'), 'each dropdown in a stacking label'); + for (const b of sec.querySelectorAll('button')) assert.ok(b.closest('.btns'), 'every button in a wrapping row: ' + b.textContent); + assert.match(sec.textContent, /2,500, \d+% behind CGNAT/); + // The dropdown picks the size the buttons quote. + ev("ACT.ip4Pick({v:'18'})"); + assert.ok(dom.window.document.querySelector('#bankCard [data-act="ip4Buy"]').dataset.args.includes('"len":18')); + assert.deepEqual(errors, []); +}); + +test('no raw labels in the address space, in every language', (t) => { + for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) { + const { ev, dom, errors } = load(lang === 'en' ? {} : { lang }); + ev(BASE); + ev("S.pops.fra.bb.d=300;compute();ACT.ip4Lease({len:24});ACT.ip4Buy({len:24});S.ip4.b[2].out=true;S.ip4.b[2].mo=99;S.biz.push({id:'z',city:'fra',city2:null,reqs:[],name:'Z',type:'host',bw:1e6,rate:1,mood:100,since:0});compute();ip4Day(S.day);ACT.ip4Open()"); + ev("S.offers.push({id:'o',city:'fra',name:'O',type:'host',bw:80,rate:60,reqs:[],exp:S.day+30});UI.left='deals';renderLeft()"); + ev("for(let i=S.ip4.b.length;i 2, lang + ': the full list and the blocks in use say why'); + const txt = dom.window.document.getElementById('bankCard').textContent + dom.window.document.getElementById('leftBody').textContent + dom.window.document.getElementById('toasts').textContent; + assert.doesNotMatch(txt, /\bip4\.[a-z_]+|\{[a-z]+\}|undefined|NaN/, lang); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); + +test('buying what an offer asks for on signing (#241) buys nothing when its IPv4 block does not fit', (t) => { + const { ev, errors } = game(t); + homes(ev, 50); + ev("S.pops.fra.gen=false;S.offers.push({id:'big',city:'fra',name:'Pixel Palace',type:'cgame',bw:3200,rate:45,reqs:['gen'],exp:S.day+30});compute()"); + assert.equal(ev("ip4Fits(S.offers[0])"), false); + assert.equal(ev("reqFix(S.offers[0]).cost"), ev('GEN_COST'), 'the generator is what it lacks'); + assert.equal(ev("reqFixHtml(S.offers[0])"), '', 'no "Buy and sign" button for a deal that cannot be signed'); + const c0 = ev('S.cash'); + ev("ACT.acceptFix({id:'big',cost:GEN_COST})"); + assert.equal(ev('S.cash'), c0, 'nothing spent'); + assert.equal(ev('S.pops.fra.gen'), false, 'no generator bought for it'); + assert.equal(ev('S.biz.length'), 0); + // A block that makes it fit brings the button back, and the click buys and signs. + ev("ACT.ip4Buy({len:21});renderAll()"); + assert.notEqual(ev("reqFixHtml(S.offers[0])"), ''); + ev("ACT.acceptFix({id:'big',cost:GEN_COST})"); + assert.deepEqual([ev('S.pops.fra.gen'), ev('S.biz.length')], [true, 1]); + assert.deepEqual(errors, []); +}); diff --git a/tests/agent-api.test.js b/tests/agent-api.test.js new file mode 100644 index 0000000..d909338 --- /dev/null +++ b/tests/agent-api.test.js @@ -0,0 +1,90 @@ +// The agent facade (src/agent/, window.TUBES) and where it lives: in the development page only. It does nothing until +// a tool calls it, listens to toast() only during a call, and the page players get carries none of it. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { load } = require('./harness'); +const page = require('../scripts/lib/page'); + +// Names the agent files define at the top level: none may appear in the page players get. +const AGENT_NAMES = ['TUBES', 'API_CMD', 'API_DOMAINS', 'API_RELAY', 'apiCall', 'apiDispatch', 'apiSchema', 'apiAgentStart']; + +test('the facade is inert until called, and listens to the game only during a call', () => { + const a = load({ agent: true }); + assert.equal(a.ev('toast.name'), 'toast', 'loading the page leaves toast() alone'); + assert.equal(a.ev('spend.name'), 'spend', 'and spend()'); + assert.equal(a.ev('API_TOASTS.depth'), 0); + assert.deepEqual(JSON.parse(a.ev('JSON.stringify(TUBES.tools)')).sort(), ['act', 'actions', 'advance', 'catalog', 'city', 'classes', 'click', 'clock', 'find', + 'hot_spots', 'network', 'open_link', 'panel', 'peering_check', 'results', 'schema', 'screen', 'since', 'state', 'status', 'traceroute', 'ui'].sort()); + // Before a game there is a contract to read, and nothing else. + assert.ok(a.ev("TUBES.call('schema',{section:'commands'}).buildPop")); + assert.throws(() => a.ev("TUBES.call('status',{})"), /No game is running/); + assert.throws(() => a.ev("TUBES.call('eval',{})"), /No tool "eval"/); + a.ev('ACT.start({});S.cash=1e6;compute()'); + // A call hears what the game says while it runs, and gives toast() back after, also when it fails. + const r = a.ev("TUBES.call('act',{action:'buyTransit',args:{city:'fra',net:'cog',tier:1}})"); + assert.equal(r.outcome, 'applied'); + assert.ok(r.toasts.some((t) => /Cogentle/.test(t)), 'the game\'s own words'); + assert.equal(a.ev('toast.name'), 'toast'); + assert.throws(() => a.ev("TUBES.call('act',{action:'buildPop',args:{city:'atlantis'}})"), /not a cityId/); + assert.equal(a.ev('toast.name+spend.name+API_TOASTS.depth'), 'toastspend0', 'a failing call restores both'); + // A toast outside a call is the game's alone. + a.ev("toast('hello','good')"); + assert.equal(a.ev('API_TOASTS.list.length'), 0); + assert.deepEqual(a.errors, []); +}); + +test('headless and the player\'s tab share one contract; only the tab holds the dice back and names its owner', () => { + const a = load({ agent: true }); + a.ev('ACT.start({});S.nextFail=S.day+30;compute()'); + const here = a.ev("TUBES.call('schema',{})"), there = a.ev("TUBES.call('schema',{},{relay:true})"); + for (const k of ['commands', 'view', 'drafts', 'denied', 'domains', 'results']) assert.deepEqual(here[k], there[k], k); + assert.equal(here.mode.backend, 'headless'); + assert.equal(there.mode.backend, 'browser'); + assert.ok(there.session.startScn.refused && !here.session.startScn.refused, 'starting a scenario is the player\'s in their tab'); + assert.equal(a.ev("TUBES.call('state',{path:'nextFail'})"), a.ev('S.nextFail'), 'headless reads everything'); + assert.equal(a.ev("TUBES.call('state',{path:'nextFail'},{relay:true})"), null, 'the tab holds it back'); + assert.equal(a.ev("'rng' in TUBES.call('state',{},{relay:true})"), false); + assert.equal(a.ev("TUBES.call('state',{path:'cash'},{relay:true})"), a.ev('S.cash')); + assert.deepEqual(a.errors, []); +}); + +test('the page players get has no agent code; the development page has it', () => { + const ship = page.assemble().html, dev = page.assemble({ dev: true }).html; + assert.ok(!ship.includes('@include-dev'), 'the marker line is dropped whole'); + for (const n of AGENT_NAMES) { + assert.ok(!new RegExp(`\\b${n}\\b`).test(ship), `${n} is not in the page players get`); + assert.ok(new RegExp(`\\b${n}\\b`).test(dev), `${n} is in the development page`); + } + // The agent files are pasted in where the marker is, after the game, inside the same script. + const at = dev.indexOf('/* ================= AGENT API: argument domains'); + assert.ok(at > dev.indexOf('/* ================= LOOP ================='), 'after the game'); + assert.ok(at < dev.lastIndexOf(''), 'inside the game\'s script'); + assert.equal(page.shipped().html.match(/\bTUBES\b/), null, 'nor in the shipped page, labels compiled'); + // The players' page is the game alone: no facade, and it boots and plays. + const p = load(); + assert.equal(p.ev('typeof TUBES+typeof apiCall+typeof API_CMD'), 'undefinedundefinedundefined'); + assert.equal(p.ev('JSON.stringify(HOOKS)+UI.clockLocked'), '{}false', 'no hooks, and the clock is the player\'s'); + p.ev("ACT.start({});ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});for(let i=0;i<5;i++)dayTick()"); + assert.ok(p.ev('R.served') > 0); + assert.deepEqual(p.errors, []); +}); + +test('an @include-dev line only expands in the development page', () => { + const src = fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-dev-include-')); + try { + fs.mkdirSync(path.join(src, 'a')); + fs.mkdirSync(path.join(src, 'b')); + fs.writeFileSync(path.join(src, 'a', '10-a.js'), 'const A=1;\n'); + fs.writeFileSync(path.join(src, 'b', '10-b.js'), 'const B=2;\n'); + fs.writeFileSync(path.join(src, 'index.html'), '\n'); + const ship = page.assemble({ src }), dev = page.assemble({ src, dev: true }); + assert.equal(ship.html, '\n'); + assert.equal(dev.html, '\n'); + // Error lines still map to their files in both. + assert.deepEqual(page.locate(dev.map, 3), { file: 'b/10-b.js', line: 1 }); + assert.deepEqual(page.locate(ship.map, 3), { file: 'index.html (shell)', line: 3 }); + } finally { fs.rmSync(src, { recursive: true, force: true }); } +}); diff --git a/tests/agent-relay.test.js b/tests/agent-relay.test.js new file mode 100644 index 0000000..2b04ba8 --- /dev/null +++ b/tests/agent-relay.test.js @@ -0,0 +1,540 @@ +// The agent relay (scripts/agent/relay.js): a WebSocket router between the game page (src/agent/80-relay.js, agent +// mode in Settings) and tool clients. This drives the whole chain with a real page: the harness loads the game +// in jsdom, the page's own client dials the relay (a test opts in with __AGENT_RELAY_TEST__ and points it at the +// relay's port, because under __TUBES_TEST__ nothing dials on its own), and a raw WebSocket tool client, the relay +// client (scripts/lib/relay-client.js) and the MCP server in browser mode (scripts/mcp.js --browser) take turns driving +// it. No token anywhere: whatever can connect to the port may drive the game, by design. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawn } = require('node:child_process'); +const http = require('node:http'); +const WebSocket = require('ws'); +const { load } = require('./harness'); + +const ROOT = path.join(__dirname, '..'); +const { createRelay } = require('../scripts/agent/relay'); +const { createRelaySession } = require('../scripts/lib/relay-client'); +const SERVER = path.join(ROOT, 'scripts', 'mcp.js'); +const { wait, until, freePort, kill } = require('./net'); +const { lit } = require('../scripts/lib/js-literal'); +let PORT; // a free one from the OS, before the first test +test.before(async () => { PORT = await freePort(); }); + +const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-relay-')); + +// The relay in-process, riding a real http.Server (the same createRelay the servers host): no child to leak, and +// 'listening' means the first dial cannot race the bind. +let CUR = null; // the relay started last +function startRelay(port = PORT) { + const srv = http.createServer((req, res) => { res.writeHead(404); res.end(); }); + const relay = createRelay({ server: srv }); + return CUR = { + relay, srv, + listening: () => new Promise((res, rej) => { srv.once('error', rej); srv.listen(port, '127.0.0.1', res); }), + close: () => new Promise((r) => { relay.close(); srv.close(() => r()); }), + }; +} + +// The game page: jsdom via the harness, agent mode on (opts.ms: the clock, 0 for the agent's). The page's own client +// connects to this relay's host:port as the page. The harness origin matches the relay host, so the page's WebSocket +// Origin is same-origin (the relay refuses a foreign one; a Node tool sends none). +function page(opts = {}) { + const a = load({ url: `http://127.0.0.1:${opts.port ?? PORT}/`, seed: opts.seed ?? 5, storage: { 'sot-agent': JSON.stringify({ on: true, ms: opts.ms ?? 60000 }) }, agent: true }); + dial(a, opts.port); + return a; +} +const dial = (a, port = PORT) => a.ev(`window.__AGENT_RELAY_TEST__=true;API_RELAY_HOST='127.0.0.1:'+${port};apiAgentSync()`); +// Waits until the relay holds this page and the page knows how many tools are there (the clock follows that count). +async function joined(a) { + assert.ok(await until(() => { const s = CUR.relay.status(); return s.page && a.ev('API_RELAY.tools') === s.tools; }), 'the page joined the relay'); +} +// Waits until the page has heard the relay's tool count: its clock runs or holds by it. +const heard = async (a, n) => assert.ok(await until(() => a.ev('API_RELAY.tools') === n), `the page sees ${n} tool(s)`); +// Kill the page's dial and retry timer before a test ends, or its backoff keeps the process alive. +const stop = (...ps) => { for (const a of ps) if (a) a.ev("window.__AGENT_RELAY_TEST__=false;apiAgentSet('on',false)"); }; + +// A raw tool client, the way the MCP server speaks to the relay. `headers` fakes a browser's Origin (which Node's ws +// does not send) for the cross-site test. +function toolClient(port = PORT, headers) { + const ws = new WebSocket(`ws://127.0.0.1:${port}/agent`, headers ? { headers } : undefined); + const calls = new Map(); + let seq = 0; + const events = []; + ws.on('message', (d) => { + const m = JSON.parse(String(d)); + if (m.kind === 'presence') { events.push(m); return; } + if (m.kind === 'result' && calls.has(m.id)) { calls.get(m.id)(m); calls.delete(m.id); } + }); + return { + ws, events, + open: () => new Promise((res, rej) => { ws.on('open', res); ws.on('error', rej); }), + auth: (role = 'tool') => ws.send(JSON.stringify({ kind: 'auth', role })), + call: (tool, args) => new Promise((res) => { // a timeout, never a hang + const id = 'c' + (++seq); + const t = setTimeout(() => { calls.delete(id); res({ error: `no answer for ${tool} (the page went silent?)` }); }, 20000); + calls.set(id, (m) => { clearTimeout(t); res(m); }); + ws.send(JSON.stringify({ kind: 'call', id, tool, args: args || {} })); + }), + close: () => { try { ws.close(); } catch {} }, + }; +} +// A tool that has been let in: the relay's first presence message comes right after the role is granted. +async function tool(port = PORT) { const t = toolClient(port); await t.open(); t.auth('tool'); assert.ok(await until(() => t.events.length > 0), 'the relay let the tool in'); return t; } + +async function withRelay(fn) { + const r = startRelay(); + await r.listening(); + try { return await fn(r); } finally { await r.close(); } +} + +// The MCP server over stdio, as a client runs it. +function mcp(argv, onErr) { + const child = spawn(process.execPath, [SERVER, ...argv], { stdio: ['pipe', 'pipe', 'pipe'] }); + let buf = '', id = 0, err = ''; + const waiting = new Map(); + child.stderr.on('data', (d) => { err += d; if (onErr) onErr(String(d)); }); + child.stdout.on('data', (d) => { + buf += d; + let i; + while ((i = buf.indexOf('\n')) >= 0) { + const line = buf.slice(0, i); buf = buf.slice(i + 1); + let m; try { m = JSON.parse(line); } catch { continue; } + if (m.id !== undefined && waiting.has(m.id)) { waiting.get(m.id)(m); waiting.delete(m.id); } + } + }); + const send = (o) => new Promise((res) => { const k = ++id; waiting.set(k, res); child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: k, ...o }) + '\n'); }); + return { + child, send, stderr: () => err, + init: async () => { const r = await send({ method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '0' } } }); + child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n'); return r; }, + call: async (name, args) => (await send({ method: 'tools/call', params: { name, arguments: args || {} } })).result, + json: async (name, args) => JSON.parse((await send({ method: 'tools/call', params: { name, arguments: args || {} } })).result.content[0].text), + kill: () => kill(child), + }; +} + +test('the relay binds loopback, gates on the role, and never needs a token', () => withRelay(async () => { + const silent = toolClient(); + await silent.open(); + assert.equal(await new Promise((res) => silent.ws.on('close', (code) => res(code))), 4003, 'a client that never states a role is closed'); + const bogus = toolClient(); + await bogus.open(); + bogus.auth('hacker'); + assert.equal(await new Promise((res) => bogus.ws.on('close', (code) => res(code))), 4001, 'a role that is neither page nor tool is refused'); + const t = await tool(); + assert.deepEqual(t.events.map((e) => e.page), [false], 'a fresh tool sees no page'); + const r = await t.call('state', { path: 'cash' }); + assert.match(r.error, /no game page connected/i); + t.close(); +})); + +test('a live page answers tool calls through the relay, from a fixed list of tools', () => withRelay(async () => { + const t = await tool(); + const a = page(); + try { + a.ev("ACT.start({});S.cash=500000;compute()"); + assert.ok(await until(() => t.events.some((e) => e.page === true)), 'the tools see the page join'); + await joined(a); + const q = await t.call('act', { action: 'buildPop', args: { city: 'ams' }, dryRun: true }); + assert.equal(q.value.outcome, 'quote'); + assert.equal(q.value.quote.setup, 20000); + assert.equal(a.ev('S.pops.ams'), undefined, 'nothing was dispatched in the page'); + const r = await t.call('act', { action: 'buildPop', args: { city: 'ams' } }); + assert.equal(r.value.outcome, 'applied'); + assert.equal(r.value.charged, 20000); + assert.equal(a.ev('S.pops.ams && S.pops.ams.day'), 0, 'the page really changed'); + assert.equal(r.dayBefore, 0); + assert.equal((await t.call('state', { path: 'cash' })).value, 480000); + assert.equal((await t.call('status')).value.pops.length, 2); + const nope = await t.call('act', { action: 'speed', args: { v: 0 } }); + assert.match(nope.error, /not available here/); + // Unknown tools never reach the facade: its fixed list is the whole vocabulary. + const hack = await t.call('eval', { code: 'S.cash=1e9' }); + assert.match(hack.error, /no tool "eval"/); + assert.equal(a.ev('S.cash'), 480000); + assert.equal(a.ev('API_TOASTS.depth===0&&API_TOASTS.real===null&&toast.name'), 'toast', 'toast() is the game\'s own again after every call'); + } finally { stop(a); t.close(); } +})); + +test('in the player\'s tab the player owns the game, their windows, their settings and the dice', () => withRelay(async () => { + const t = await tool(); + const a = page({ ms: 0 }); + try { + a.ev("ACT.start({});S.cash=1e7;S.nextFail=S.day+40;S.nextEvent=S.day+50;compute()"); + await joined(a); + // The dice stay hidden, whole or by path, and the schema says so. + const st = (await t.call('state')).value; + for (const k of ['rng', 'nextFail', 'nextEvent']) assert.ok(!(k in st), `${k} is held back`); + assert.equal((await t.call('state', { path: 'nextFail' })).value, null); + assert.equal(st.cash, 1e7, 'the board itself is all there'); + const mode = (await t.call('schema', { section: 'mode' })).value; + assert.equal(mode.backend, 'browser'); + assert.equal(mode.clock, 'agent'); + assert.ok(mode.withheld.nextFail); + assert.ok((await t.call('schema', { section: 'state' })).value.rng.withheld); + // Starting, loading or leaving a game is the player's. + for (const [action, args] of [['startScn', { id: a.ev('SCN[0].id') }], ['pzStart', { id: a.ev('PZ[0].id') }], ['startWeekly', {}]]) { + const r = await t.call('act', { action, args }); + assert.match(r.error || '', /the player's/, action); + } + assert.equal(a.ev('S.mode'), 'normal'); + // So are their settings, agent mode's own switch included: it is no game action, so no tool can find or press it. + assert.match((await t.call('act', { action: 'prefSet', args: { v: 'pauseFurious:0' } })).error, /not available here/); + assert.match((await t.call('act', { action: 'agentSet', args: {} })).error, /no action/); + assert.equal(a.ev('API_AGENT_PREFS.on'), true); + // A window the player opened by hand stays theirs: the agent plays behind it, and never closes or replaces it. + a.ev("(()=>{const b=document.createElement('button');b.dataset.act='settings';document.body.appendChild(b);b.click();b.remove();})()"); + assert.equal(a.ev("$('modal').hidden"), false, 'the player has a window open'); + assert.equal(a.ev('API_MODAL.hand'), true, 'marked as theirs'); + const html = a.ev("$('modalCard').innerHTML"); + const sc = (await t.call('screen')).value; + assert.equal(sc.where, 'modal'); + assert.ok(sc.playerWindow, 'the screen says whose it is'); + assert.equal(sc.question, false, 'and that it is no question'); + const b = await t.call('act', { action: 'buildPop', args: { city: 'ams' } }); + assert.equal(b.value.outcome, 'applied', 'the agent plays on behind it'); + const v = await t.call('act', { action: 'opsOpen' }); + assert.equal(v.value.screen.where, 'modal'); + assert.match(v.value.screen.note || '', /shown to you and closed again/, 'its own sheet is shown, then the player\'s window comes back'); + await t.call('act', { action: 'closeModal' }); + assert.equal(a.ev("$('modal').hidden"), false, 'closeModal does not close the player\'s window'); + assert.equal(a.ev("$('modalCard').innerHTML"), html, 'nor change it'); + await t.call('screen', { where: 'modal' }); + const c = await t.call('click', { button: 0 }); + assert.match(c.error || '', /theirs to press/); + assert.match((await t.call('open_link', { from: 'fra', to: 'nyc' })).error || '', /would replace it/); + // Days run behind it (the agent's clock here), and it is still there after. + const adv = await t.call('advance', { days: 3 }); + assert.equal(adv.value.daysRun, 3); + assert.equal(a.ev('S.day'), 3); + assert.equal(a.ev("$('modalCard').innerHTML"), html); + } finally { stop(a); t.close(); } +})); + +test('the agent\'s clock moves only with advance; a running clock only with time, and wait reads it', () => withRelay(async () => { + const t = await tool(); + const a = page({ ms: 0 }); + try { + a.ev("ACT.start({});S.cash=1e7;compute()"); + await joined(a); + assert.equal(a.ev('UI.speed'), 0, 'a tool is connected, but the agent\'s clock stands still'); + a.ev('last=performance.now();for(let i=1;i<=20;i++)frame(last+i*250)'); + assert.equal(a.ev('S.day'), 0, 'the loop runs no days'); + const adv = await t.call('advance', { days: 20 }); + assert.equal(adv.value.daysRun, 20, 'advance runs them, where the player sees them'); + assert.equal(a.ev('S.day'), 20); + assert.match((await t.call('clock')).value.mode, /agent/); + // The player switches to a pace: the clock runs by itself, and advance is refused. + a.ev("apiAgentSet('ms',30000)"); + assert.equal(a.ev('UI.speed'), a.ev('DAY_MS/30000'), 'a pace, and a tool connected: it runs, a day per 30 s'); + assert.match((await t.call('advance', { days: 1 })).error, /use wait/); + const c = (await t.call('clock')).value; + assert.equal(c.mode, 'realtime'); + assert.equal(c.running, true); + // The page's own loop moves days at the pace (the test plays the browser's frames, 2 s of them per day). + a.ev('API_AGENT_PREFS.ms=2000;apiAgentSync()'); + a.ev('last=performance.now()'); + const frames = setInterval(() => a.ev('frame(performance.now())'), 20); + try { + const { createBrowserSession } = require('../scripts/lib/mcp-browser'); + const { TOOLS } = require('../scripts/lib/mcp-game'); + const s = createBrowserSession({ port: PORT }); + const w = await TOOLS.find((x) => x.name === 'wait').run(s, { days: 1, maxSeconds: 10 }); + assert.ok(w.daysRun >= 1, `wait returns once a day has passed (${lit(w)})`); + assert.equal(w.stoppedBecause, null); + await s.close(); + } finally { clearInterval(frames); } + } finally { stop(a); t.close(); } +})); + +test('the page client reconnects after the relay restarts, and stops when the player switches agent mode off', () => withRelay(async (r) => { + const t = await tool(); + const a = page(); + try { + a.ev("ACT.start({});S.cash=500000;compute()"); + assert.ok(await until(() => t.events.some((e) => e.page === true))); + await r.close(); + assert.ok(await until(() => a.ev('!API_RELAY.ws||API_RELAY.ws.readyState!==1')), 'the page saw the relay go'); + a.ev("apiAgentSet('on',false)"); + const r2 = startRelay(); + await r2.listening(); + try { + await wait(1200); // past the first backoff retry: it must not dial + assert.equal(a.ev('API_RELAY.on'), false, 'the client is off'); + assert.equal(r2.relay.status().page, false, 'and never dialled'); + a.ev("apiAgentSet('on',true)"); + await joined(a); + const t2 = await tool(); + assert.ok(t2.events.some((e) => e.page === true), 'the page reconnected after the relay came back'); + assert.equal((await t2.call('state', { path: 'cash' })).value, 500000, 'and answers calls again'); + t2.close(); + } finally { stop(a); await r2.close(); } + } finally { stop(a); t.close(); } +})); + +test('a paced clock holds while no tool is connected, and runs when one arrives', () => withRelay(async () => { + const a = page({ seed: 5 }); + try { + a.ev("ACT.start({});S.nextFail=S.day+99;S.nextEvent=S.day+99;compute()"); + await joined(a); + assert.equal(a.ev('UI.speed'), 0, 'no tool connected: the clock holds'); + assert.equal(a.ev('UI.clockLocked'), true, 'agent mode stays on'); + a.ev('last=performance.now();frame(last);frame(last+250);frame(last+500)'); + assert.equal(a.ev('S.day'), 0, 'no day ran'); + const t = await tool(); + await heard(a, 1); + assert.ok(a.ev('UI.speed') > 0, 'a tool connecting runs it'); + t.close(); + await heard(a, 0); + assert.equal(a.ev('UI.speed'), 0, 'the tool leaving holds it again'); + a.ev('S.uiSpeed=4;gameResume()'); + assert.equal(a.ev('UI.speed'), 0, 'gameResume holds with no tool connected'); + const t2 = await tool(); + await heard(a, 1); + assert.ok(a.ev('UI.speed') > 0, 'and a tool arriving runs it again'); + // An unrelated preference change does not drop the connection or hold the clock. + a.ev('window.__w0=API_RELAY.ws'); + a.ev("ACT.prefSet({v:'pauseFurious:0'})"); + a.ev("apiAgentSet('ms',300000)"); + assert.equal(a.ev('API_RELAY.ws===window.__w0'), true, 'the same socket survived both'); + assert.equal(a.ev('UI.speed'), a.ev('DAY_MS/300000'), 'the clock never held for them, and runs at the new pace'); + t2.close(); + } finally { stop(a); } +})); + +test('a second page replaces the first: one game per relay, the newest tab wins', () => withRelay(async () => { + const a = page({ seed: 5 }); + a.ev("ACT.start({});S.cash=111000;compute()"); + await joined(a); // in that order: two dials at once may land either way + const b = page({ seed: 6 }); + b.ev("ACT.start({});S.cash=222000;compute()"); + assert.ok(await until(() => a.ev('API_RELAY.on') === false), 'the first page yields to the second'); + await joined(b); + const t = await tool(); + try { + assert.equal((await t.call('state', { path: 'cash' })).value, 222000, 'the newest page answers'); + } finally { stop(a, b); t.close(); } +})); + +test('the MCP server drives the player\'s page in browser mode, over stdio', () => withRelay(async () => { + const a = page({ seed: 9, ms: 0 }); + a.ev("ACT.start({});S.cash=1000000;compute()"); + await joined(a); + const m = mcp(['--browser', '--relay-host', 'localhost', '--relay-port', String(PORT)]); + try { + const init = await m.init(); + assert.match(init.result.instructions, /player's own browser tab/); + const list = (await m.send({ method: 'tools/list' })).result.tools.map((x) => x.name); + for (const n of ['status', 'act', 'schema', 'state', 'advance', 'wait', 'screen', 'click']) assert.ok(list.includes(n), n); + for (const n of ['new_game', 'load_save', 'export_save']) assert.ok(!list.includes(n), `${n} is the headless session's`); + const mode = await m.json('schema', { section: 'mode' }); + assert.equal(mode.backend, 'browser'); + assert.equal(mode.transport, 'relay'); + assert.equal(mode.relay, `ws://localhost:${PORT}/agent`, 'the mode says which relay: host, port and path'); + assert.equal(await m.json('state', { path: 'cash' }), 1000000); + const r = await m.json('act', { action: 'buildPop', args: { city: 'ams' } }); + assert.equal(r.outcome, 'applied'); + assert.equal(r.charged, 20000); + assert.equal(a.ev('S.pops.ams && S.pops.ams.day'), 0, "the player's page really changed"); + assert.equal((await m.json('advance', { days: 2 })).daysRun, 2); + assert.ok((await m.json('actions')).includes('buildLink(a,b,tier,cable?,route?,premiumCrossing?)')); + const no = await m.call('act', { action: 'startScn', args: { id: a.ev('SCN[0].id') } }); + assert.equal(no.isError, true); + assert.match(no.content[0].text, /the player's/); + } finally { stop(a); await m.kill(); } +})); + +test('a game page older than the code stops the server rather than mislead', () => withRelay(async () => { + const a = page({ seed: 3 }); + a.ev("ACT.start({});compute()"); + // A stale tab whose commands keep their names but change shape: only a deep compare of the sections catches it. + a.ev('const __c=TUBES.call;TUBES.call=(t,x,c)=>{const v=__c(t,x,c);if(t==="schema"&&!x.section)v.commands.buildPop.args=[{name:"city",required:true}];return v;};'); + await joined(a); + const m = mcp(['--browser', '--relay-port', String(PORT), '--page-wait-ms', '8000']); + try { + const init = await m.init(); + assert.ok(init.result.serverInfo, 'the handshake is answered at once'); + const code = await new Promise((r) => m.child.on('exit', (c2) => r(c2))); + assert.equal(code, 1, 'the server exits with an error'); + assert.match(m.stderr(), /disagrees with the code on disk \(commands\)/); + assert.match(m.stderr(), /reload the page/); + } finally { stop(a); await m.kill(); } +})); + +test('the MCP server answers the handshake at once and waits for the game page', () => withRelay(async () => { + const gone = mcp(['--browser', '--relay-port', String(PORT), '--page-wait-ms', '1200']); + const code = await new Promise((r) => gone.child.on('exit', (c2) => r(c2))); + assert.equal(code, 1, 'exits 1 without a page'); + assert.match(gone.stderr(), /waiting for the game page/); + assert.match(gone.stderr(), /no game page answered/); + assert.match(gone.stderr(), /Settings → Agent API/); + assert.doesNotMatch(gone.stderr(), /TypeError/); + const m = mcp(['--browser', '--relay-port', String(PORT), '--page-wait-ms', '20000']); + let a = null; + try { + const t0 = Date.now(); + await m.init(); + // Far below the page wait (20 s), with room for a slow start of the process on a busy runner. + assert.ok(Date.now() - t0 < 10000, 'initialize does not wait for a browser tab'); + const early = await m.call('status'); + assert.equal(early.isError, true, 'a tool before the page arrives is an error, not a hang'); + await until(() => /waiting for the game page/.test(m.stderr())); + assert.match(m.stderr(), /waiting for the game page/); + a = page({ seed: 4 }); + a.ev("ACT.start({});S.cash=444000;compute()"); + await until(() => /ready/.test(m.stderr())); + assert.match(m.stderr(), /ready/, 'the server proceeded once the page answered'); + assert.equal(await m.json('state', { path: 'cash' }), 444000, 'and drives the late page'); + } finally { stop(a); await m.kill(); } +})); + + +test('dev.js binds loopback and parses --port; the page dials its own host', async () => { + const port = await freePort(); + const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'dev.js'), '--port', String(port)], { stdio: ['ignore', 'ignore', 'pipe'] }); + let serr = ''; + child.stderr.on('data', (d) => { serr += d; }); + let a = null; + try { + const banner = new RegExp(`agent relay on ws://127\\.0\\.0\\.1:${port}/agent`); + await until(() => banner.test(serr)); // dev.js builds the page first: seconds on a busy runner + assert.match(serr, banner, 'dev.js binds loopback and honours --port'); + const t = await tool(port); + assert.ok(t.events.some((e) => e.page === false), 'the relay answers on 127.0.0.1'); + t.close(); + a = load({ url: `http://127.0.0.1:${port}/`, agent: true, storage: { 'sot-agent': JSON.stringify({ on: true }) } }); + assert.equal(a.ev('API_RELAY.on'), false, 'under __TUBES_TEST__ nothing dials on its own'); + a.ev(`window.__AGENT_RELAY_TEST__=true;API_RELAY_HOST='';apiAgentSync()`); + assert.equal(a.ev('API_RELAY.on'), true); + assert.equal(a.ev('apiRelayUrl()'), `ws://127.0.0.1:${port}/agent`, 'its own host and port, the relay path'); + } finally { + stop(a); + await kill(child); + } +}); + +test('calls neither page nor relay can answer resolve as errors, not hangs', async () => { + const r = startRelay(); + await r.listening(); + const pages = []; + try { + const t = await tool(); + const a = page(); + pages.push(a); + a.ev('ACT.start({});S.cash=500000;compute()'); + await joined(a); + // The page dies with a call in flight; it is silenced first, so the call is provably pending when it closes. + a.ev('API_RELAY.ws.onmessage=()=>{}'); + const p = t.call('act', { action: 'buildPop', args: { city: 'ams' } }); + assert.ok(await until(() => r.relay.status().calls === 1), 'the call reached the relay'); + a.ev('API_RELAY.ws.close(1000)'); + assert.match((await p).error || '', /disconnected before answering/i); + stop(a); + t.close(); + // The relay dies under a call in flight: the client answers on its own behalf, at once. + const b = page({ seed: 12 }); + pages.push(b); + b.ev('ACT.start({});S.cash=222000;compute()'); + await joined(b); + b.ev('API_RELAY.ws.onmessage=()=>{}'); + const s = createRelaySession({ host: '127.0.0.1', port: PORT }); + const p2 = s.call('state', { path: 'cash' }); + assert.ok(await until(() => r.relay.status().calls === 1), 'the call reached the relay'); + await r.close(); + assert.match((await p2).refused || '', /connection closed/i); + await s.close(); + } finally { + for (const pg of pages) stop(pg); + await r.close(); + } +}); + +test('a page that hangs on a call answers within --call-ms, not minutes later', () => withRelay(async () => { + const a = page({ seed: 4 }); + try { + a.ev('ACT.start({});compute()'); + await joined(a); + a.ev('API_RELAY.ws.onmessage=()=>{}'); // connected, alive, and never answering + const s = createRelaySession({ host: '127.0.0.1', port: PORT, callMs: 300 }); + const t0 = Date.now(); + const r = await s.call('state', { path: 'cash' }); + assert.match(r.refused || '', /no answer from the game page in 0\.3 s/); + assert.ok(Date.now() - t0 < 10000, 'the configured timeout, not the default (30 s)'); + assert.equal(createRelaySession({}).config.callMs, 30000, 'the default is 30 s'); + await s.close(); + } finally { stop(a); } +})); + +test('the relay refuses a cross-site Origin and takes a same-origin page or a token-less tool', () => withRelay(async () => { + const evil = toolClient(PORT, { Origin: 'http://evil.example' }); + await evil.open(); + assert.equal(await new Promise((res) => evil.ws.on('close', (code) => res(code))), 4004, 'refused before any role is granted'); + // DNS rebinding: evil.example re-pointed at 127.0.0.1 is "same-origin" with itself, but the Host is a name. + const rebound = toolClient(PORT, { Host: `evil.example:${PORT}`, Origin: `http://evil.example:${PORT}` }); + await rebound.open(); + assert.equal(await new Promise((res) => rebound.ws.on('close', (code) => res(code))), 4004, 'a rebound DNS name is refused'); + const named = toolClient(PORT, { Host: `evil.example:${PORT}` }); + await named.open(); + assert.equal(await new Promise((res) => named.ws.on('close', (code) => res(code))), 4004, 'with or without an Origin'); + const same = toolClient(PORT, { Origin: `http://127.0.0.1:${PORT}` }); + await same.open(); + same.auth('page'); + const t = await tool(); + await until(() => same.events.some((e) => e.tools === 1)); + assert.ok(same.events.some((e) => e.tools === 1), 'the same-origin page connects and sees the tool'); + t.close(); same.close(); +})); + +// Spawns a server script and resolves with the address its relay banner reports (server.address()). +function bannerOf(argv) { + const child = spawn(process.execPath, argv, { stdio: ['ignore', 'ignore', 'pipe'] }); + let serr = ''; + return new Promise((res) => { + const done = (v) => { clearTimeout(t); child.kill('SIGKILL'); res(v); }; + const t = setTimeout(() => done({ addr: null, serr }), 30000); // dev.js builds the page first + child.stderr.on('data', (d) => { serr += d; const m = /agent relay on ws:\/\/(\S+)\/agent/.exec(serr); if (m) done({ addr: m[1], serr }); }); + }); +} + +test('dev.js: a bare --host binds loopback, never every interface; binding wider is the operator\'s choice, and said', async () => { + const p1 = await freePort(); + const dev = await bannerOf([path.join(ROOT, 'scripts', 'dev.js'), '--host', '--port', String(p1)]); + assert.equal(dev.addr, `127.0.0.1:${p1}`, `the socket is bound to loopback (${dev.serr})`); + const p2 = await freePort(); + const wide = await bannerOf([path.join(ROOT, 'scripts', 'dev.js'), '--host', '0.0.0.0', '--port', String(p2)]); + assert.equal(wide.addr, `0.0.0.0:${p2}`, 'the banner is the real socket, not the flag echoed back'); + assert.match(wide.serr, /bound to 0\.0\.0\.0, so anything that can reach this address can drive/); +}); + +test('browser mode over HTTP: a client connects to the server, the server to the player\'s page', () => withRelay(async () => { + const a = page({ seed: 11, ms: 0 }); + a.ev("ACT.start({});S.cash=555000;compute()"); + await joined(a); + const child = spawn(process.execPath, [SERVER, '--browser', '--relay-port', String(PORT), '--http', '127.0.0.1:0'], { stdio: ['ignore', 'ignore', 'pipe'] }); + let err = ''; + try { + const port = await new Promise((res, rej) => { + child.stderr.on('data', (d) => { err += d; const m = /on http:\/\/127\.0\.0\.1:(\d+)\/mcp/.exec(err); if (m) res(+m[1]); }); + child.on('exit', () => rej(new Error(err))); + }); + const post = (body) => new Promise((res, rej) => { + const data = JSON.stringify({ jsonrpc: '2.0', id: 1, ...body }); + // A fresh connection each time (agent: false): a kept-alive one can be closed by the server's idle timer just + // as the next request goes out on it, which a slow runner hits now and then (ECONNRESET). + const req = http.request({ agent: false, host: '127.0.0.1', port, path: '/mcp', method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'mcp-protocol-version': '2025-06-18', 'content-length': Buffer.byteLength(data) } }, (r) => { + let t = ''; r.setEncoding('utf8'); r.on('data', (d) => { t += d; }); + r.on('end', () => { const line = t.split('\n').find((l) => l.startsWith('data: ')); res(JSON.parse(line ? line.slice(6) : t)); }); + }); + req.on('error', (e) => rej(new Error(`${e.message}; the server said: ${err}`))); req.end(data); + }); + const init = await post({ method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '1' } } }); + assert.match(init.result.instructions, /player's own browser tab/); + const r = await post({ method: 'tools/call', params: { name: 'state', arguments: { path: 'cash' } } }); + assert.equal(JSON.parse(r.result.content[0].text), 555000, 'the player\'s game, through HTTP and the relay'); + const no = await post({ method: 'tools/call', params: { name: 'new_game', arguments: {} } }); + assert.ok(no.error || (no.result && no.result.isError), 'no new_game in the player\'s tab'); + } finally { stop(a); await kill(child); } +})); diff --git a/tests/agent-settings.test.js b/tests/agent-settings.test.js new file mode 100644 index 0000000..d3c721b --- /dev/null +++ b/tests/agent-settings.test.js @@ -0,0 +1,167 @@ +// Agent mode in the player's tab (src/agent/75-mode.js, 85-ticker.js): its own switch and clock in Settings, kept +// apart from the game's preferences; the gate that keeps it off the public site; the speed the save remembers across +// it; the badge that stands in for the speed buttons; and the clock that keeps running where frames do not. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +const prefs = (ms = 60000, on = true) => ({ 'sot-agent': JSON.stringify({ on, ms }) }); +const agent = (o = {}) => load({ agent: true, storage: prefs(o.ms), ...o }); +// Press one of agent mode's own Settings buttons, as the player does. +const press = (a, v) => a.ev(`(()=>{ACT.settings({});const b=document.querySelector('[data-agent-set="${v}"]');b.click();return true;})()`); + +test('the clock buttons set the pace, or give the clock to the agent, and are remembered', () => { + const a = agent(); + a.ev('ACT.start({});S.cash=1e9;compute()'); + for (const m of [30000, 60000, 120000, 300000]) { + press(a, `ms:${m}`); + assert.equal(a.ev('apiAgentMs()'), m, `the ${m} ms button sets the pace`); + assert.equal(JSON.parse(a.ev(`localStorage.getItem('sot-agent')`)).ms, m, 'in agent mode\'s own storage'); + assert.ok(a.ev(`document.querySelector('[data-agent-set="ms:${m}"]').classList.contains('pink')`), 'and shows as picked'); + } + // 0: the agent's clock. It stands still: no speed, and the loop never runs a day by itself. + press(a, 'ms:0'); + assert.equal(a.ev('apiAgentMs()'), 0); + assert.equal(a.ev('UI.speed'), 0, 'the agent\'s clock stands still'); + a.ev('last=performance.now();for(let i=1;i<=40;i++)frame(last+i*250)'); + assert.equal(a.ev('S.day'), 0, 'no day passes on its own'); + assert.match(a.ev('settingsHtml()'), /The agent moves it/); + // Junk is ignored, never coerced. + a.ev("apiAgentSet('ms','nope');apiAgentSet('ms',true);apiAgentSet('ms',12345);apiAgentSet('nope',1)"); + assert.equal(a.ev('apiAgentMs()'), 0); + // Its buttons are agent mode's own, not game actions: no tool finds them on a screen. + assert.equal(a.ev(`document.querySelectorAll('#modal [data-agent-set][data-act]').length`), 0); + assert.deepEqual(a.errors, []); +}); + +test('the game\'s preferences stay exactly as they are', () => { + const a = agent(); + assert.deepEqual(Object.keys(a.ev('PREF_DEF')).sort(), ['pauseFurious', 'pauseIncident', 'quiet', 'warnUnhappy']); + a.ev("ACT.prefSet({v:'pauseFurious:0'})"); + assert.equal(a.ev('PREFS.pauseFurious'), false); + a.ev("ACT.prefSet({v:'agent:1'})"); + assert.equal(a.ev("'agent' in PREFS"), false, 'prefSet knows nothing of agent mode'); + assert.equal(a.ev(`localStorage.getItem('sot-prefs')`), JSON.stringify({ pauseFurious: false })); + assert.deepEqual(a.errors, []); +}); + +test('agent mode only exists where a relay can be reached', () => { + const a = agent(); + assert.equal(a.ev('API_AGENT_OK'), true); + assert.match(a.ev('settingsHtml()'), /Agent API/, 'the Settings sheet has the section'); + // Plain http to an address: yes, wherever the operator bound the dev server. https (the public site cannot even + // open ws:// from its pages), and DNS names (the relay refuses them): no. + const gate = (p, h) => a.ev(`apiAgentLocal(${lit(p)},${lit(h)})`); + for (const h of ['127.0.0.1', 'localhost', 'tubes.localhost', '10.0.0.4', '192.168.1.5', '203.0.113.7', '[::1]']) assert.equal(gate('http:', h), true, h); + assert.equal(gate('https:', 'seriesoftub.es'), false, 'the public site has no relay behind it'); + assert.equal(gate('http:', 'seriesoftub.es'), false); + assert.equal(gate('http:', 'example.com'), false); + assert.equal(gate('file:', ''), false); + assert.deepEqual(a.errors, []); +}); + +test('on the public site there is no agent mode, even with the preference set by hand', () => { + const a = load({ url: 'https://seriesoftub.es/', agent: true, storage: prefs() }); + a.ev('ACT.start({});S.cash=1e9;compute()'); + assert.equal(a.ev('API_AGENT_OK'), false); + assert.doesNotMatch(a.ev('settingsHtml()'), /Agent API/, 'no section in Settings'); + assert.equal(a.ev('UI.clockLocked'), false, 'the clock is the player\'s'); + assert.equal(a.ev('API_RELAY.on'), false, 'nothing dials'); + a.ev('ACT.speed({v:2})'); + assert.equal(a.ev('UI.speed'), 2, 'the speed buttons work'); + assert.deepEqual(a.errors, []); +}); + +test('agent mode remembers the speed the player left the game at, not the agent\'s', () => { + const a = agent({ storage: prefs(60000, false) }); // agent mode off: the player is playing + a.ev('ACT.start({});S.cash=1e9;ACT.speed({v:2});compute();save(true)'); + assert.equal(a.ev('S.uiSpeed'), 2, 'the save carries the player speed'); + press(a, 'on:1'); + assert.equal(a.ev('UI.clockLocked'), true); + assert.equal(a.ev('UI.speed'), 0, 'no tool is connected, so the clock holds'); + for (const x of ['ACT.speed({v:4})', 'ACT.phonePlay()', 'ACT.phoneSpeed()', "dispatchEvent(new KeyboardEvent('keydown',{code:'Space',key:' '}))"]) { + a.ev(x); + assert.equal(a.ev('UI.speed'), 0, `${x} does nothing while an agent drives`); + } + assert.equal(a.ev('autoPause()'), false, 'nothing pauses a locked clock either'); + a.ev('S.day=5;save(true)'); + assert.equal(a.ev('S.uiSpeed'), 2, 'save() never stores the locked speed in its place'); + a.ev('S.uiSpeed=4;gameResume()'); + assert.equal(a.ev('UI.speed'), 0, 'resuming a game keeps the lock'); + a.ev('S.uiSpeed=2'); + press(a, 'on:0'); + assert.equal(a.ev('UI.clockLocked'), false); + assert.equal(a.ev('UI.speed'), 2, 'switching off restores the speed the player left the game at'); + a.ev('ACT.speed({v:4})'); + assert.equal(a.ev('UI.speed'), 4, 'and the speed buttons are back'); + assert.deepEqual(a.errors, []); +}); + +test('a paced clock runs behind an open window and in a hidden tab, and leaves the rest to the frame', () => { + const a = agent({ ms: 30000 }); + a.ev('ACT.start({});S.cash=1e9;S.nextFail=S.day+999;S.nextEvent=S.day+999;compute()'); + // As if a tool were connected: the pace runs. + a.ev('API_RELAY.on=true;apiRelayPresence(1)'); + assert.equal(a.ev('UI.speed'), a.ev('DAY_MS/30000')); + // Visible, no window: the frame runs the days, the ticker none. + a.ev('API_TICKER.last=0;apiAgentTick(1000);for(let t=1250;t<=31000;t+=250)apiAgentTick(t)'); + assert.equal(a.ev('S.day'), 0, 'the ticker leaves a visible, open map to the frame'); + a.ev('last=0;for(let t=250;t<=30250;t+=250)frame(t)'); + assert.equal(a.ev('S.day'), 1, 'which runs a day in 30 s'); + // A window open: the frame stops, the ticker goes on. + a.ev('ACT.settings({})'); + a.ev('last=40000;for(let t=40250;t<=70000;t+=250)frame(t)'); + assert.equal(a.ev('S.day'), 1, 'no days in the frame behind a window'); + a.ev('API_TICKER.last=0;apiAgentTick(70000);for(let t=70250;t<=100250;t+=250)apiAgentTick(t)'); + assert.equal(a.ev('S.day'), 2, 'the ticker runs the day behind it'); + a.ev('closeModal()'); + // A hidden tab: frames stop altogether, the ticker goes on. + a.ev("Object.defineProperty(document,'visibilityState',{value:'hidden',configurable:true})"); + a.ev('API_TICKER.last=0;apiAgentTick(200000);for(let t=200250;t<=230250;t+=250)apiAgentTick(t)'); + assert.equal(a.ev('S.day'), 3, 'and in a hidden tab'); + // Off: the ticker does nothing at all. + a.ev("apiAgentSet('on',false)"); + a.ev('API_TICKER.last=0;apiAgentTick(300000);for(let t=300250;t<=400000;t+=250)apiAgentTick(t)'); + assert.equal(a.ev('S.day'), 3); + assert.deepEqual(a.errors, []); +}); + +test('phones show the agent pace in the tab bar, where the speed button was', () => { + const a = agent(); + a.ev('ACT.start({});S.cash=1e9;compute();window.innerWidth=360;window.innerHeight=740;renderTabbar()'); + const pace = () => a.ev(`(()=>{const b=document.querySelector('#tabbar button.pace');return b?{dis:b.disabled,ic:b.querySelector('.ic').textContent}:null;})()`); + assert.equal(a.ev('isPhone()'), true); + assert.deepEqual({ ...pace() }, { dis: true, ic: '1 min' }, 'the locked speed button reads the pace'); + assert.equal(a.ev(`document.querySelector('#tabbar button.play').disabled`), true, 'and play/pause is locked'); + assert.equal(a.ev(`document.querySelectorAll('#tabbar [data-act="phonePlay"],#tabbar [data-act="phoneSpeed"]').length`), 0); + a.ev("apiAgentSet('ms',30000);renderTabbar()"); + assert.equal(pace().ic, '30 s', 'and follows the pace the player picks'); + a.ev("apiAgentSet('ms',0);renderTabbar()"); + assert.equal(pace().ic, '🤖', 'the agent\'s clock has a badge of its own'); + // The desktop and tablet HUD badge says the same, in place of the speed buttons. + a.ev('renderHUD()'); + assert.equal(a.ev("$('spPace').hidden"), false); + assert.equal(a.ev("$('sp1').hidden"), true); + assert.equal(a.ev("$('spPace').textContent"), 'Agent\'s clock'); + a.ev("apiAgentSet('ms',30000);renderHUD()"); + assert.match(a.ev("$('spPace').textContent"), /30 s per simulated day/); + // Agent mode off: the ordinary buttons are back, and the badge goes. + a.ev("apiAgentSet('on',false);renderTabbar();renderHUD()"); + assert.equal(pace(), null); + assert.match(a.ev(`document.querySelector('#tabbar [data-act="phoneSpeed"] .ic').textContent`), /×$/); + assert.equal(a.ev("$('spPace').hidden"), true); + assert.equal(a.ev("$('sp1').hidden"), false); + assert.deepEqual(a.errors, []); +}); + +test('the Settings sheet\'s agent section is complete in every language, on a phone too', () => { + for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) { + const a = load({ agent: true, storage: prefs(), ...(lang === 'en' ? {} : { lang }) }); + a.ev('ACT.start({});window.innerWidth=360;window.innerHeight=740;ACT.settings({})'); + const html = a.ev("$('modalCard').innerHTML"); + assert.ok(html.includes('data-agent-set="ms:0"') && html.includes('data-agent-set="ms:300000"'), `${lang}: every clock button is there`); + assert.doesNotMatch(a.ev("$('modalCard').textContent"), /settings\./, `${lang}: no label shows untranslated`); + assert.deepEqual(a.errors, [], lang); + } +}); diff --git a/tests/alien-wave-rent.test.js b/tests/alien-wave-rent.test.js new file mode 100644 index 0000000..92b68e1 --- /dev/null +++ b/tests/alien-wave-rent.test.js @@ -0,0 +1,81 @@ +// #203: renting out alien waves was a money machine. A wave is now priced against what the fiber itself costs, and gets +// cheaper as a route fills; extra crews cut a build to half its planned time at most; a typed order cannot end a link +// in a city the map does not show. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const fiber = (ev, id, a, b, km) => ev(`S.links.push({id:'${id}',a:'${a}',b:'${b}',kind:'df',own:true,sys:'cl',ch:[],km:${km},ready:0,day:0,cut:0,mo:1,trench:'own:${id}',pairs:1})`); +const sell = (ev, id) => ev(`(()=>{const l=S.links.find(x=>x.id==='${id}'),r=wwRate(l,1);S.biz.push({id:uid(),type:'wwave',link:l.id,slots:1,rate:r,city:l.a,city2:l.b,name:'n'+S.biz.length,bw:1,mood:80,since:0,reqs:[]});return r})()`); + +test('#203 an alien wave rents for a share of the fiber, and each one sold on a route makes the next cheaper', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;S.biz=[];S.offers=[];for(const c of ['lon','nyc'])if(!S.pops[c])ACT.buildPop({city:c})"); + fiber(ev, 'f', 'lon', 'nyc', 5570); + const F = ev('dfLeaseMo(5570)+ampCount(5570)*AMP_MO'), M = ev("brMarket('lon','nyc')"); + const rates = []; + for (let i = 0; i < M; i++) rates.push(sell(ev, 'f')); + assert.ok(rates[0] <= 0.3 * F + 1, `the first wave costs at most 30% of the fiber: ${rates[0]} vs ${F}`); + for (let i = 1; i < rates.length; i++) assert.ok(rates[i] <= rates[i - 1], 'never dearer than the one before'); + assert.ok(rates.at(-1) < rates[0] * 0.45, 'the last waves of a full route go cheap'); + const full = rates.reduce((a, b) => a + b, 0); + assert.ok(full / F > 2 && full / F < 8, `a full route earns a few times its lease, not dozens: ${(full / F).toFixed(1)}×`); + // The old price: one wave cost about as much as the whole fiber, and a full route earned ~29× its lease. + assert.ok(full < ev(`Math.round(waveMo(5570,false,2)*0.55)*${M}`) / 3); + // A random offer and a broker sale on the same route follow the same price. + fiber(ev, 'g', 'lon', 'nyc', 5570); + ev("S.biz=[]"); + assert.equal(ev("(()=>{let n=0;const o=fiberOffer('wwave',S.links.find(l=>l.id==='g'),()=>'x');return o.rate===wwRate(S.links.find(l=>l.id==='g'),o.slots)})()"), true); + assert.deepEqual(errors, []); +}); + +test('#203 extra crews cut a build to half its planned time, no further', () => { + const { ev, errors, dom } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;for(const c of ['fra','waw'])if(!S.pops[c])ACT.buildPop({city:c})"); + const km = Math.round(ev("kmBetween('fra','waw')")), days = ev(`dfBuildDays(${km})`); + ev(`S.links.push({id:'b',a:'fra',b:'waw',kind:'df',own:true,sys:'roadm',ch:[],km:${km},ready:S.day+${days},day:S.day,cut:0,mo:1,trench:'own:b',pairs:1});after();UI.sel={type:'link',id:'b'};renderPanel()`); + const start = ev('S.day'); + assert.match(ev("document.getElementById('panelBody').textContent"), new RegExp(`All the crews: done in ${Math.ceil(days / 2)} days`)); + const cash = ev('S.cash'); + ev("ACT.crews({id:'b',all:1})"); + assert.equal(ev("S.links.find(l=>l.id==='b').ready"), start + Math.ceil(days / 2), 'half the planned build'); + assert.ok(ev('S.cash') < cash); + const c2 = ev('S.cash'); + ev("ACT.crews({id:'b'});ACT.crews({id:'b',all:1})"); + assert.equal(ev('S.cash'), c2, 'no more crews to buy'); + ev('renderPanel()'); + const crews = [...dom.window.document.querySelectorAll('#panelBody [data-act=crews]')]; + assert.ok(crews.length && crews.every((b) => b.disabled)); + assert.match(ev("document.getElementById('panelBody').textContent"), /half its planned time/); + // Phone: the panel still renders with the note. + ev("window.innerWidth=360;renderAll()"); + assert.deepEqual(errors, []); +}); + +test('#203 a dark fiber, cable or wave cannot be ordered to a city the map does not show', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6"); + ev("ACT.buildPop({city:'sao'})"); + const home = 'sao', off = ev("(()=>{const c=CITIES.find(c=>c.off&&!cityOn(c.id)&&dfAllowed('sao',c.id));return c?c.id:null})()"); + assert.ok(off, 'there is a hidden city to try'); + const pops = ev('Object.keys(S.pops).length'); + ev(`UI.pending={a:'${home}',b:'${off}'};UI.dfSrc='lease';UI.dfSys='lite';ACT.orderDf()`); + ev(`UI.pending={a:'${home}',b:'${off}'};ACT.buildLink({tier:0})`); + assert.equal(ev('Object.keys(S.pops).length'), pops, 'no POP appears there'); + assert.equal(ev(`S.links.some(l=>l.b==='${off}'||l.a==='${off}')`), false); + assert.deepEqual(errors, []); +}); + +test('#203 a dark fiber lease costs more, and a lease already signed keeps its price', () => { + const { ev, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;for(const c of ['fra','ams'])if(!S.pops[c])ACT.buildPop({city:c})"); + assert.equal(ev('dfLeaseMo(1000)'), 2100); + ev("UI.pending={a:'fra',b:'ams'};UI.dfSrc='lease';UI.dfSys='lite';ACT.orderDf()"); + const km = ev("S.links.find(l=>l.kind==='df').km"); + assert.equal(ev("S.links.find(l=>l.kind==='df').mo"), Math.round(600 + km * 1.5)); + // An old save's lease, signed at the old price, keeps it. + const old = Math.round(400 + km); + ev(`S.links.find(l=>l.kind==='df').mo=${old};S=migrate(JSON.parse(JSON.stringify(S)))`); + assert.equal(ev("S.links.find(l=>l.kind==='df').mo"), old); + assert.deepEqual(errors, []); +}); diff --git a/tests/any-home-city.test.js b/tests/any-home-city.test.js index 9044b9c..3166c02 100644 --- a/tests/any-home-city.test.js +++ b/tests/any-home-city.test.js @@ -1,33 +1,32 @@ const test = require('node:test'); const assert = require('node:assert/strict'); const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); -const choose = (ev, v) => ev(`(()=>{const s=document.getElementById('homeSel');s.value=${JSON.stringify(v)};s.dispatchEvent(new Event('change',{bubbles:true}));})()`); -const onTiles = ev => JSON.parse(ev("JSON.stringify([...document.querySelectorAll('.starts .start.on')].map(b=>b.dataset.city||'own'))")); - -test('the title screen offers five homes and a sixth tile for any city, grouped by continent', () => { +const choose = (ev, v) => ev(`(()=>{const s=document.getElementById('homeSel');s.value=${lit(v)};s.dispatchEvent(new Event('change',{bubbles:true}));})()`); +test('the title screen has one drawer for the home city: the five suggested first, then every city by continent', () => { const { ev, errors } = load(); assert.equal(ev('S'), null, 'before any game exists'); - assert.equal(ev("document.querySelectorAll('.starts .start').length"), 6); - const opts = JSON.parse(ev("JSON.stringify([...document.querySelectorAll('#homeSel option')].map(o=>o.value).filter(Boolean))")); + const opts = JSON.parse(ev("JSON.stringify([...document.querySelectorAll('#homeSel option')].map(o=>o.value))")); + assert.deepEqual(opts.slice(0, 5), ['fra', 'nyc', 'sin', 'sao', 'syd'], 'the suggested homes come first'); + assert.equal(new Set(opts).size, opts.length, 'no city twice'); assert.ok(opts.length > 150, `lots of cities (${opts.length})`); assert.ok(opts.every(c => ev(`homeOk('${c}')`)), 'only cities that work as a home'); assert.ok(!opts.some(c => ev(`!!CITY['${c}'].cn||!!CITY['${c}'].off`)), 'no hidden or Chinese cities'); assert.ok(!opts.includes('stg'), 'no city without transit to buy'); - assert.ok(ev("document.querySelectorAll('#homeSel optgroup').length") >= 5, 'grouped by continent'); + assert.ok(ev("document.querySelectorAll('#homeSel optgroup').length") >= 6, 'suggested plus continents'); + assert.equal(ev("document.getElementById('homeSel').value"), 'fra'); + assert.equal(ev("document.querySelectorAll('.starts .start').length"), 0, 'no tiles any more'); assert.deepEqual(errors, []); }); -test('picking any city starts the network there, and the tiles follow the choice', () => { +test('picking any city starts the network there, and the line under the drawer follows the choice', () => { const { ev, errors } = load(); choose(ev, 'lis'); assert.equal(ev('UI.startCity'), 'lis'); - assert.deepEqual(onTiles(ev), ['own'], 'the sixth tile lights up'); assert.equal(ev("document.getElementById('homeWhat').textContent"), 'Lisbon · ' + ev("REG[CITY.lis.reg]"), 'and names the city in full'); - ev("document.querySelector('.start[data-city=nyc]').click()"); - assert.deepEqual(onTiles(ev), ['nyc'], 'a suggested tile takes over again'); - assert.equal(ev("document.getElementById('homeSel').value"), '', 'and the dropdown resets'); - assert.match(ev("document.getElementById('homeWhat').textContent"), /more cities/); + choose(ev, 'nyc'); + assert.equal(ev("document.getElementById('homeWhat').textContent"), ev("tr('title.huge_eyeball_market_pricey')"), 'a suggested home says what it is like'); choose(ev, 'akl'); ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()"); assert.equal(ev('S.home'), 'akl'); @@ -45,12 +44,15 @@ test('a home that cannot work is refused, and the game falls back to Frankfurt', assert.deepEqual(errors, []); }); -test('the sixth tile works on a phone and in every language', () => { +test('the title screen works on a phone in every language: language first, the name on top, compact presets', () => { for (const lang of ['en', 'it', 'pt', 'fr', 'es', 'de']) { const { ev, errors } = load(lang === 'en' ? {} : { lang }); ev('window.innerWidth=360;showTitle()'); - assert.equal(ev("document.querySelector('label.start.own b').textContent"), ev("tr('title.anywhere_else')"), lang); - if (lang !== 'en') assert.notEqual(ev("tr('title.anywhere_else')"), 'Anywhere else', `${lang}: translated`); + const order = ev("(()=>{const c=document.getElementById('modalCard');const at=s=>[...c.querySelectorAll('*')].indexOf(c.querySelector(s));return [at('#langTitle'),at('.title-art'),at('#nmIn'),at('.doors'),at('#homeSel')].join(',')})()").split(',').map(Number); + assert.ok(order.every((v, i) => v >= 0 && (i === 0 || v > order[i - 1])), `${lang}: language, title, name, doors, home (${order})`); + assert.equal(ev("document.querySelectorAll('#modalCard .preset small,#modalCard .preset span').length"), 0, `${lang}: presets are just icon and name`); + assert.ok(ev("document.getElementById('presetWhat').textContent.length") > 10, `${lang}: the chosen preset explained below`); + if (lang !== 'en') assert.notEqual(ev("tr('title.suggested')"), 'Suggested', `${lang}: translated`); assert.deepEqual(errors, []); } }); diff --git a/tests/architect.test.js b/tests/architect.test.js new file mode 100644 index 0000000..080758c --- /dev/null +++ b/tests/architect.test.js @@ -0,0 +1,206 @@ +// Architect runs (prototype): one network built brief by brief, reviewed by a chaos monkey. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +// Reference builds, brief by brief: [a, b, route] lays a tube (a diverse trench when the pair has one), ['@rm', city] +// closes a POP. Each must pass every brief within budget and land at par. +const REF = { + euro: [[['ams', 'fra', 'land']], [['ams', 'par', 'land'], ['ams', 'lon', 'nshuttle']], [['par', 'fra', 'land']], + [['ams', 'zrh', 'land'], ['par', 'zrh', 'land']], [['lon', 'par', 'pasdc'], ['ams', 'lon', 'concerto']], [['@rm', 'fra'], ['ams', 'dus', 'land'], ['ams', 'dus', 'land']]], + usa: [[['ash', 'nyc', 'land']], [['ash', 'chi', 'land']], [['nyc', 'chi', 'land']], [], [['chi', 'dal', 'land'], ['dal', 'sjc', 'land']], [['chi', 'sjc', 'land']]], + pacific: [[['tok', 'hkg', 'adc']], [['hkg', 'sin', 'land']], [['tok', 'hkg', 'apg']], [['hkg', 'sin', 'sjc2']], [['sin', 'syd', 'indigo']]], +}; +const lay = (ev, a, b, via, div = 1) => ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:${div}});ACT.pzLink({tier:AR_TIER});closeModal()`); +const review = (ev) => { ev('arShowStart();arShowSkip()'); return ev('S.ar.passed===pzSig()'); }; + +test('architect runs: every reference passes each brief, on plan and within budget', () => { + const { ev, errors } = load(); + assert.deepEqual(JSON.parse(ev('JSON.stringify(AR_RUNS.map(r=>r.id))')).sort(), Object.keys(REF).sort()); + for (const [id, plan] of Object.entries(REF)) { + ev(`ACT.pzArStart({id:'${id}'})`); + assert.equal(ev('arOn()&&!!S.pops[S.ar.hq]'), true, `${id}: starts with a POP at HQ`); + plan.forEach((steps, i) => { + for (const s of steps) if (s[0] === '@rm') ev(`ACT.pzRmPop({city:'${s[1]}'})`); else lay(ev, ...s); + assert.equal(review(ev), true, `${id} brief ${i + 1}: ${ev('arEval().why')} ${ev('JSON.stringify(UI.arFail)')}`); + assert.deepEqual(JSON.parse(ev('JSON.stringify([UI.mk.mood,UI.mk.sprayAt])')), ['cheer', null], `${id}: a skipped review that passes still ends in a cheer`); + if (i < plan.length - 1) { ev('ACT.pzArNext()'); assert.equal(ev('UI.mk'), null, `${id}: the monkey leaves with the next brief`); } + }); + assert.equal(ev('arOver()'), 0, `${id}: never over a brief's tubes`); + assert.equal(ev('arSpend()<=arRun().budget'), true, `${id}: within budget`); + assert.ok(ev('arSpend()>arRun().budget*0.95'), `${id}: the budget sits just above the reference`); + ev('ACT.pzArNext()'); + assert.equal(ev('JSON.parse(localStorage.getItem(AR_KEY)).runs[S.ar.id].st'), 3, `${id}: three stars stored`); + } + assert.deepEqual(errors, []); +}); + +test('architect runs: the chaos monkey finds a shared trench, edits clear the cut, old builds are paid for', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'euro'})"); + assert.equal(ev("arHide('lis')&&arHide('bru')"), true, 'cities outside the run are hidden'); + assert.equal(ev("arHide('dus')"), true, 'a city a later brief adds stays hidden until then'); + // Later briefs stay a surprise: nothing on the map or a city card says where the run goes next. + assert.equal(ev("typeof arTags"), 'undefined'); + ev("UI.sel={type:'city',id:'fra'};renderPanel()"); + assert.doesNotMatch(ev("document.getElementById('panelBody')?.textContent||''"), /brief \d|Coming up/i); + ev('ACT.pzArAll()'); + assert.equal(ev("arHide('lis')"), false, 'and shown on request'); + ev('ACT.pzArAll()'); + lay(ev, 'ams', 'fra', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ams', 'par', 'land'); lay(ev, 'ams', 'lon', 'nshuttle'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ams', 'fra', 'land', 0); // the same trench: looks redundant, is not + assert.equal(review(ev), false); + assert.deepEqual(JSON.parse(ev('JSON.stringify(UI.arFail.gold)')), ['fra']); + assert.ok(ev('S.links.some(l=>l.cut)'), 'the failing cut stays on the map'); + ev('ACT.pzUndo()'); + assert.equal(ev('!UI.arFail&&!S.links.some(l=>l.cut)'), true, 'an edit clears it'); + const sunk = ev('S.ar.sunk'); + ev("ACT.pzRmLink({id:S.links.find(l=>l.br===0).id})"); + assert.ok(ev('S.ar.sunk') > sunk, 'removing an earlier brief\'s tube refunds nothing'); + ev('ACT.pzReset()'); + assert.equal(ev('S.ar.sunk'), sunk, 'reset goes back to the start of the brief'); + // Two diverse trenches would make both gold, but the plan has one tube: the ring is the answer. + lay(ev, 'ams', 'fra', 'land'); lay(ev, 'ams', 'par', 'land'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(arTubes())')), { u: 2, max: 1, over: 1 }); + ev('ACT.pzReset()'); + lay(ev, 'par', 'fra', 'land'); + assert.equal(ev('arTubes().over'), 0); + assert.equal(review(ev), true); + assert.deepEqual(errors, []); +}); + +test('architect runs: a latency brief needs the fast path, and normal puzzles are untouched', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'usa'})"); + lay(ev, 'ash', 'nyc', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ash', 'chi', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ash', 'nyc', 'land'); assert.equal(review(ev), true, 'a diverse trench makes New York gold'); ev('ACT.pzArNext()'); + assert.equal(ev('arEval().lat.ok'), false, 'via Ashburn is too slow'); + lay(ev, 'nyc', 'chi', 'land'); + assert.equal(ev('arEval().lat.ok&&arEval().ready'), true); + ev("ACT.pzStart({id:'hello'})"); + assert.equal(ev('!S.ar&&pzKind("lon")==="goal"&&!arHide("par")'), true); + assert.deepEqual(errors, []); +}); + +test('architect runs: Play on the title screen\'s puzzle list starts a run', () => { + const { ev, errors } = load(); + ev('ACT.puzzleMenu()'); + assert.equal(ev('S'), null, 'no game loaded yet'); + ev("document.querySelector('#modal [data-act=pzArStart]').click()"); + assert.equal(ev('arOn()&&S.ar.id'), 'euro'); + assert.deepEqual(errors, []); +}); + +test('architect runs: a ring goal needs one cycle through its cities', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'euro'})"); + lay(ev, 'ams', 'fra', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ams', 'par', 'land'); lay(ev, 'ams', 'lon', 'nshuttle'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'par', 'fra', 'land'); review(ev); ev('ACT.pzArNext()'); + lay(ev, 'ams', 'zrh', 'land'); lay(ev, 'par', 'zrh', 'land'); review(ev); ev('ACT.pzArNext()'); + assert.equal(ev("arRingOk(['ams','par','lon'])"), false, 'London hangs off Amsterdam: no ring'); + assert.match(ev('arEval().why'), /ring/i); + lay(ev, 'lon', 'par', 'pasdc'); + assert.equal(ev("arRingOk(['ams','par','lon'])&&arEval().ready"), true); + assert.deepEqual(errors, []); +}); + +test('architect runs: the detour needs room, and a roomy but pricey build misses the budget star', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'euro'})"); + const head = [[['ams', 'fra', 'land']], [['ams', 'par', 'land'], ['ams', 'lon', 'nshuttle']], [['par', 'fra', 'land']]]; + const run = (plan) => plan.forEach((steps, i) => { + for (const s of steps) if (s[0] === '@rm') ev(`ACT.pzRmPop({city:'${s[1]}'})`); else lay(ev, ...s); + assert.equal(review(ev), true, `brief ${i + 1}: ${ev('arEval().why')} ${ev('JSON.stringify(UI.arFail)')}`); + ev('ACT.pzArNext()'); + }); + run(head); + // Zürich hung off Frankfurt: connected both ways, but a cut on Amsterdam-Frankfurt sends Frankfurt and Zürich through + // Paris, and that tube is too thin for all three. + lay(ev, 'fra', 'zrh', 'land'); lay(ev, 'par', 'zrh', 'land'); + assert.equal(review(ev), false); + assert.ok(JSON.parse(ev('JSON.stringify(UI.arFail.short)')).length > 0, 'someone still connected runs short'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(UI.arFail.gold)')), [], 'nobody gold is cut off'); + ev('ACT.pzReset()'); + lay(ev, 'ams', 'zrh', 'land'); lay(ev, 'par', 'zrh', 'land'); + assert.equal(review(ev), true, 'Zürich straight to HQ spreads the detours'); + ev('ACT.pzArNext()'); + // Paris doubles: a second Amsterdam-Paris trench gives room, at a price. + lay(ev, 'lon', 'par', 'pasdc'); lay(ev, 'ams', 'par', 'land'); + assert.equal(review(ev), true); ev('ACT.pzArNext()'); + ev("ACT.pzRmPop({city:'fra'})"); lay(ev, 'ams', 'dus', 'land'); lay(ev, 'dus', 'zrh', 'land'); + assert.equal(review(ev), true); + assert.equal(ev('arOver()'), 0); + assert.ok(ev('arSpend()') > ev('arRun().budget')); + assert.equal(ev('arStars(arSpend())'), 2, 'on plan, over budget: two stars'); + assert.deepEqual(errors, []); +}); + +test('architect runs: a bigger tube brings a bigger router, and changing an old tube is a new lease', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'euro'})"); + lay(ev, 'ams', 'fra', 'land'); review(ev); ev('ACT.pzArNext()'); + assert.equal(ev("S.pops.ams.rgen||0"), 0, 'the free router takes 100G'); + const sunk = ev('S.ar.sunk'); + ev("ACT.pzTier({id:S.links[0].id,tier:2})"); + assert.ok(ev("RG[S.pops.ams.rgen].maxLT>=2&&RG[S.pops.fra.rgen].maxLT>=2"), '400G needs a bigger router at both ends'); + assert.ok(ev('S.ar.sunk') > sunk, 'the old 100G lease is paid for'); + ev('ACT.pzUndo()'); + assert.equal(ev("(S.pops.ams.rgen||0)===0&&S.ar.sunk===" + sunk), true, 'undo puts it all back'); + assert.deepEqual(errors, []); +}); + +test('architect runs: the map tells two tubes in one trench from two separate paths', () => { + const { ev, errors } = load(); + ev("ACT.pzArStart({id:'euro'});ACT.pzArAll();S.cash=1e9"); + lay(ev, 'ams', 'fra', 'land', 1); lay(ev, 'ams', 'fra', 'land', 0); + lay(ev, 'ams', 'par', 'land', 1); lay(ev, 'ams', 'par', 'land', 1); + assert.equal(ev("arPaths(S.links.find(l=>l.b==='fra'||l.a==='fra'))"), 1, 'same trench: one path'); + assert.equal(ev("arPaths(S.links.find(l=>l.b==='par'||l.a==='par'))"), 2, 'diverse: two paths'); + ev("cam.x=CITY.ams.x;cam.y=CITY.ams.y;cam.z=2.4;drawFrame(performance.now())"); + assert.deepEqual(JSON.parse(ev("JSON.stringify(AR_PILLS.map(p=>p[2]).sort())")), ['2× one trench', '✓ 2 paths']); + assert.deepEqual(errors, []); +}); + +test('#231 the puzzle list counts each section\'s own stars: runs above, packs next to the packs', () => { + const { ev, errors } = load(); + // 2 stars on a pack puzzle, 2 on Euro Run, 3 on another run + ev("localStorage.setItem(PZ_KEY,JSON.stringify({set:PZ_SET,noted:1,s:{[PZ[0].id]:{st:2}}}));localStorage.setItem(AR_KEY,JSON.stringify({runs:{[AR_RUNS[0].id]:{st:2},[AR_RUNS[1].id]:{st:3}}}))"); + ev('ACT.puzzleMenu()'); + const heads = JSON.parse(ev("JSON.stringify([...document.querySelectorAll('#modal h3.pzpack')].map(h=>h.textContent))")); + assert.match(heads[0], new RegExp(`Architect runs ⭐ 5/${3 * ev('AR_RUNS.length')}`), heads[0]); + // the packs' total sits right above the first pack, after the runs and the weekly puzzle, and says what it counts + const order = ev(`(()=>{const m=document.querySelector('#modal'),box=m.querySelector('.pzprog'),run=m.querySelector('[data-act=pzArStart]'),pack=[...m.querySelectorAll('h3.pzpack')].find(h=>!h.textContent.includes('🏗️')); + return [!!(run.compareDocumentPosition(box)&Node.DOCUMENT_POSITION_FOLLOWING),!!(box.compareDocumentPosition(pack)&Node.DOCUMENT_POSITION_FOLLOWING),box.textContent].join('|')})()`); + const [afterRuns, beforePacks, box] = order.split('|'); + assert.equal(afterRuns, 'true', 'below the architect runs'); + assert.equal(beforePacks, 'true', 'above the first pack'); + assert.match(box, new RegExp(`Stars from the packs⭐ 2 / ${3 * ev('PZ.length')}`), box); + assert.deepEqual(errors, []); +}); + +test('#282 Euro Run on the game\'s own defaults: new tubes and diverse tubes take the cheapest route, so the plain plan earns three stars', () => { + const { ev, errors } = load(); + // Each new tube takes the route the window offers; each second tube comes from the tube's own "diverse" button. + const neu = (a, b) => ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzLink({tier:AR_TIER});closeModal()`); + const div = (a, b) => ev(`(()=>{const l=S.links.find(x=>edgeKey(x)===edgeKey({a:'${a}',b:'${b}'}));ACT.pzAddPar({id:l.id,div:1});ACT.pzLink({tier:AR_TIER});closeModal()})()`); + ev("ACT.pzArStart({id:'euro'})"); + const briefs = [() => neu('ams', 'fra'), () => { neu('ams', 'par'); neu('ams', 'lon'); }, () => neu('par', 'fra'), () => { neu('ams', 'zrh'); neu('par', 'zrh'); }, + () => { neu('lon', 'par'); div('ams', 'lon'); }, () => { ev("ACT.pzRmPop({city:'fra'})"); neu('ams', 'dus'); div('ams', 'dus'); }]; + briefs.forEach((f, i) => { + f(); + assert.equal(review(ev), true, `brief ${i + 1}: ${ev('arEval().why')}`); + if (i === 4) { + const cost = (v) => ev(`pzLinkCost(pzRoutes('ams','lon').find(x=>x.via==='${v}'),AR_TIER,true)`); + const used = ev("S.links.filter(l=>edgeKey(l)===edgeKey({a:'ams',b:'lon'})).map(l=>l.cable).sort().join()"); + const other = used.split(',').find((v) => v !== 'nshuttle'); + for (const v of ['uly', 'circe', 'concerto']) assert.ok(cost(other) <= cost(v), `the diverse London tube is the cheapest other cable, not ${other}`); + } + if (i < briefs.length - 1) ev('ACT.pzArNext()'); + }); + assert.equal(ev('arOver()'), 0); + assert.equal(ev('arSpend()<=arRun().budget'), true, `within budget: ${ev('arSpend()')} of ${ev('arRun().budget')}`); + assert.deepEqual(errors, []); +}); diff --git a/tests/au-north.test.js b/tests/au-north.test.js new file mode 100644 index 0000000..6d5cdaa --- /dev/null +++ b/tests/au-north.test.js @@ -0,0 +1,42 @@ +// #255: northern Australia. Port Hedland lands the cable up to Darwin and the one out to Singapore, Townsville is North +// Queensland's data centre, Alice Springs sits in the middle with no sea at all. In the wet season (November to April) +// a cut on land in the tropical north takes twice as long to reach. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const J = (ev, code) => JSON.parse(ev(`JSON.stringify(${code})`)); + +test('#255 Port Hedland, Townsville and Alice Springs are on the map and playable', () => { + const { ev, errors } = load(); + for (const c of ['phe', 'tsv', 'asp']) { + const x = J(ev, `(({cc,land,reg,au})=>({cc,land,reg,au}))(CITY.${c})`); + assert.deepEqual(x, { cc: 'AU', land: 'oc', reg: 'OC', au: true }, c); + assert.ok(ev(`homeOk('${c}')`), `${c} can be a home city`); + assert.ok(ev(`NETS.some(n=>n.id==='tsy'&&n.pops.includes('${c}')&&sellsAt(n,'${c}'))`), `${c}: Telstraya sells transit there`); + } + const cabs = (c) => J(ev, `CABLE_PAIRS.filter(p=>p.a==='${c}'||p.b==='${c}').map(p=>p.a==='${c}'?p.b:p.a).sort()`); + assert.deepEqual(cabs('phe'), ['drw', 'sin'], 'Port Hedland: up the coast to Darwin, out to Singapore'); + assert.deepEqual(cabs('asp'), [], 'Alice Springs has no sea'); + assert.deepEqual(cabs('tsv'), [], 'Townsville is reached over land'); + assert.equal(ev("CAB.nwcs.name"), 'No Worries Cable System'); + assert.deepEqual(errors, []); +}); + +test('#255 the wet season doubles the time to reach a cut in the tropical north, and only there', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;S.nextFail=S.nextEvent=1e9;"); + const cut = (a, b, month) => { + ev(`S.day=dayOf(cal(S.day).y,${month},15);S.inc=[];S.links=[{id:'l',a:'${a}',b:'${b}',kind:'wave',sub:false,tier:0,km:kmBetween('${a}','${b}'),cut:0,mo:1000}];compute();`); + ev("Math.random=(()=>{let s=7;return()=>{s=(s*16807)%2147483647;return s/2147483647;};})();fireFailure('cut')"); + const i = J(ev, "S.inc.find(i=>i.type==='cut')"); + return { days: i.until - ev('S.day'), msg: i.msg }; + }; + const wet = cut('tsv', 'bne', 0), dry = cut('tsv', 'bne', 6), south = cut('syd', 'mel', 0); + assert.equal(wet.days, dry.days * 2, 'January takes twice as long as July in Townsville'); + assert.match(wet.msg, /wet season washed out the track/); + assert.doesNotMatch(dry.msg, /wet season/); + assert.equal(south.days, dry.days, 'Sydney–Melbourne has no wet season'); + assert.equal(ev("CITY.drw.wet&&CITY.phe.wet&&!CITY.asp.wet"), true, 'Darwin is tropical too; Alice Springs is desert'); + assert.deepEqual(errors, []); +}); diff --git a/tests/automation.test.js b/tests/automation.test.js new file mode 100644 index 0000000..4cca19f --- /dev/null +++ b/tests/automation.test.js @@ -0,0 +1,223 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +// #185's engines: the repair one is the NOC intern's standing order, the sales one belongs to the sales desk +// (39-sales-auto.js). Here the engineer, who signs only what the trial says the network can serve, as #185 did. +function setup(ev) { + ev("ACT.start({});S.cash=1e8;S.offers=[];S.biz=[];S.nextFail=S.nextEvent=1e6;for(const g of GOALS)S.done[g.id]=0;S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:1});S.lvl=2;S.ops.intern='kevin';S.ops.floor=0;S.rules=makeRules('freeze');ACT.salesHire({id:'eng'});compute()"); +} +const shift = ev => ev('slAutoDay(S.day);opsDay(S.day)'); +function offer(ev, id, extra = {}) { + ev(`S.offers.push(${lit({ id, city: 'fra', name: id, type: 'dia', bw: 1, rate: 600, reqs: [], exp: 30, ...extra })})`); +} + +test('the sales desk signs ready offers once a day, and switching it off stops it', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'first'); + shift(ev); + assert.equal(ev('S.biz.length'), 0, 'off by default'); + ev('ACT.salesAuto()'); + shift(ev); + assert.equal(ev('S.biz[0].id'), 'first'); + ev('ACT.salesAuto()'); + offer(ev, 'off'); + ev('dayTick()'); + assert.equal(ev('S.biz.length'), 1, 'switched off, it signs nothing'); + assert.ok(ev("S.offers.some(o=>o.id==='off')")); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('the trial includes new bandwidth and later offers cannot overbook earlier accepted sales', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'one', { bw: 60 }); + offer(ev, 'two', { bw: 60 }); + const state = ev('JSON.stringify(S)'); + ev('window.beforeState=S;window.beforeResult=R;window.beforeHot=UI.hotMap'); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + assert.equal(ev('JSON.stringify(S)'), state); + assert.equal(ev('S===beforeState&&R===beforeResult&&UI.hotMap===beforeHot'), true); + ev('S.slAuto.on=true;slAutoDay(S.day)'); + assert.equal(ev('S.biz.length'), 1); + assert.equal(ev('S.offers[0].id'), 'two'); + assert.ok(ev('bizSf(S.biz[0])') >= 0.95); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('the sales desk checks actual circuits, latency and NNI capacity', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;compute()"); + offer(ev, 'circuit', { type: 'hft', city2: 'ams', bw: 10, latMax: 50, reqs: ['lat'] }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'POPs alone are not a circuit'); + ev("S.links.push({id:'path',a:'fra',b:'ams',kind:'wave',tier:1,km:450,sub:false,cut:0,mo:1});compute()"); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + ev('S.offers[0].latMax=0.1'); + assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'latency budget must pass'); + ev("S.offers=[];window.fabric=FABS.find(f=>f.cities.includes('fra')).id;ACT.buyNni({city:'fra',prov:fabric,tier:0})"); + const prov = ev('fabric'); + const bandwidth = ev('NNI[0].g * 0.75'); + offer(ev, 'fabric-one', { type: 'fabip', prov, bw: bandwidth, reqs: ['nni'] }); + offer(ev, 'fabric-two', { type: 'fabip', prov, bw: bandwidth, reqs: ['nni'] }); + // Transit has enough headroom, so the second rejection is the shared NNI port. + ev("S.transit[0].tier=4;compute();S.slAuto.on=true;slAutoDay(S.day)"); + assert.equal(ev('S.biz.length'), 1); + assert.equal(ev('S.offers[0].id'), 'fabric-two'); + assert.ok(ev("nniUsed('fra',fabric)<=NNI[0].g")); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('new circuits do not take service away from healthy signed customers', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;S.links.push({id:'path',a:'fra',b:'ams',kind:'wave',tier:1,km:450,sub:false,cut:0,mo:1});S.transit[0].city='ams';compute()"); + offer(ev, 'existing', { bw: 80 }); + ev("ACT.accept({id:'existing'})"); + offer(ev, 'new-circuit', { type: 'l2vpn', city2: 'ams', bw: 50 }); + assert.equal(ev('bizWhy(S.biz[0]).length'), 0); + assert.equal(ev('!!autoOffer(S.offers[0])'), false); + assert.ok(ev('bizSf(S.biz[0])') >= 0.95, 'failed preview leaves the old routing result intact'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('fiber sales check live equipment and free spectrum, and repeated carrier orders still merge', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev("ACT.buildPop({city:'ams'});S.pops.ams.rgen=3;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',own:true,sys:'lite',ch:Array(14).fill('zr4'),km:450,sub:false,ready:0,cut:0,mo:1}];S.biz=[{id:'old',name:'Same Carrier',type:'wwave',city:'fra',city2:'ams',link:'fiber',bw:1,rate:1000,slots:1,reqs:[],mood:100,since:0}];compute()"); + offer(ev, 'full', { type: 'wwave', city2: 'ams', link: 'fiber', slots: 2 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false); + ev("S.offers[0].slots=1;S.offers[0].name='Same Carrier';S.links[0].eqDown=10;compute()"); + assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'a broken amplifier prevents a wave sale'); + ev('S.links[0].eqDown=0;compute();S.slAuto.on=true;slAutoDay(S.day)'); + assert.equal(ev('S.biz.length'), 1); + assert.equal(ev('S.biz[0].slots'), 2); + assert.equal(ev('S.biz[0].rate'), 1600); + assert.equal(ev('freeCh(S.links[0])'), 0); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('capacity pair sales need completed infrastructure and reserve it for the accepted contract', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'pairs', { type: 'capfib', city2: 'ams', slots: 2, win: 90 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false); + ev("ACT.buildPop({city:'ams'});S.links=[{id:'own',a:'fra',b:'ams',kind:'df',own:true,sys:'roadm',ch:[],km:450,sub:false,ready:0,cut:0,mo:1}];compute()"); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + ev('S.slAuto.on=true;slAutoDay(S.day)'); + assert.equal(ev('S.biz[0].link'), 'own'); + assert.equal(ev('capPend(S.biz[0])'), true, 'normal delivery handover still happens on a game day'); + offer(ev, 'second-pairs', { type: 'capfib', city2: 'ams', slots: 2, win: 90 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false, 'the same trench cannot be promised twice'); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('future event demand is tested before signing, with booked events reserving headroom', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'event', { type: 'event', bw: 80, rate: 0, start: 10, dur: 3, fee: 5000, exp: 9 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + ev('S.slAuto.on=true;slAutoDay(S.day)'); + assert.equal(ev('S.biz[0].start'), 10, 'the trial does not move the actual event date'); + assert.equal(ev('R.cityDem.fra'), 0); + offer(ev, 'too-large', { bw: 30 }); + assert.equal(ev('!!autoOffer(S.offers[0])'), false); + ev('S.offers[0].bw=10'); + assert.equal(ev('!!autoOffer(S.offers[0])'), true); + assert.equal(ev('S.biz[0].start'), 10); + assert.equal(ev('R.cityDem.fra'), 0); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('failed capacity trials restore game, routing and map state even when compute throws', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'ready'); + ev("window.beforeState=S;window.beforeResult=R;window.beforeHot=UI.hotMap;window.originalCompute=compute;window.compute=()=>{throw new Error('trial failed')}"); + assert.throws(() => ev('autoOffer(S.offers[0])'), /trial failed/); + assert.equal(ev('S===beforeState&&R===beforeResult&&UI.hotMap===beforeHot'), true); + ev('window.compute=originalCompute'); + assert.equal(ev('S.biz.length'), 0); + assert.equal(ev('S.offers.length'), 1); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('the repair order rushes affordable repairs once, skips unaffordable and expired incidents, and obeys its pause', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev(`S.cash=10000;S.links=[{id:'fiber',a:'fra',b:'ams',kind:'df',sys:'lite',ch:['zr4'],km:450,sub:false,ready:0,cut:0,eqDown:10,chFail:{i:0,until:10},mo:1}]; + S.pops.fra.down=8;S.inc=[ + {id:'amp',type:'amp',ref:'fiber',until:10,cost:30000,msg:'Broken amp'}, + {id:'optic',type:'optic',ref:'fiber',until:10,cost:5000,msg:'Broken optic'}, + {id:'slow',type:'crash',ref:'fra',until:8,cost:2000,slow:true,msg:'Slow boot'}, + {id:'orphan',type:'amp',ref:'gone',until:10,cost:299,msg:'Removed equipment'}, + {id:'expired',type:'amp',ref:'fiber',until:0,cost:1000,msg:'Expired'}, + {id:'ddos',type:'ddos',ref:'fra',until:10,cost:1000,msg:'Attack'}]; + S.ops.on.repair=true;opsDay(S.day)`); + assert.equal(ev('S.cash'), 3000); + assert.equal(ev("S.inc.some(i=>i.id==='optic')"), false); + assert.equal(ev('S.links[0].chFail'), null); + assert.equal(ev("S.inc.find(i=>i.id==='slow').rushed"), true); + assert.equal(ev("S.inc.find(i=>i.id==='slow').until"), 1); + assert.equal(ev("S.inc.find(i=>i.id==='slow').cost"), 0); + assert.equal(ev('S.pops.fra.down'), 1); + ev('opsDay(S.day)'); + assert.equal(ev('S.cash'), 3000, 'no duplicate rush payment'); + ev('S.cash=40000;opsDay(S.day)'); + assert.equal(ev('S.cash'), 10000); + assert.equal(ev('S.links[0].eqDown'), 0); + assert.equal(ev("S.inc.some(i=>i.id==='amp')"), false); + ev("ACT.opsToggle({k:'repair'});S.inc.push({id:'new',type:'amp',ref:'fiber',until:10,cost:1000,msg:'New failure'});opsDay(S.day)"); + assert.equal(ev('S.cash'), 10000); + assert.equal(ev("S.inc.some(i=>i.id==='new')"), true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('the sales desk leaves unready and expired offers alone without failure notifications', () => { + const { ev, dom, errors } = load(); + setup(ev); + offer(ev, 'generator', { reqs: ['gen'] }); + offer(ev, 'missing-pop', { city: 'ams' }); + offer(ev, 'scrub', { type: 'scrub' }); + offer(ev, 'expired', { exp: 0 }); + offer(ev, 'ipv6', { reqs: ['ipv6'] }); + const log = ev('S.log.length'); + ev('S.slAuto.on=true;slAutoDay(S.day)'); + assert.equal(ev('S.biz.length'), 0); + assert.equal(ev('S.offers.length'), 5); + assert.equal(ev('S.log.length'), log, 'no failed manual-action toasts and no notice when nothing got done'); + ev('S.pops.fra.gen=true;compute();slAutoDay(S.day)'); + assert.equal(ev('S.biz.length'), 1); + assert.equal(ev('S.biz[0].id'), 'generator'); + // Manual acceptance keeps its existing sign-now, provision-later behavior. + ev("ACT.accept({id:'scrub'})"); + assert.equal(ev("S.biz.some(b=>b.id==='scrub')"), true); + assert.deepEqual(errors, []); + dom.window.close(); +}); + +test('#185\'s auto-repair toggle in old saves becomes the repair order; its auto-accept, which never ran without an intern, goes', () => { + const { ev, dom, errors } = load(); + setup(ev); + ev("delete S.ops;delete S.slAuto;S.autoSales=true;S.autoRepair=true;S=migrate(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('S.ops.on.repair'), true); + assert.equal(ev("'sales' in S.ops.on"), false, 'the intern has no sales order any more'); + assert.equal(ev('S.slAuto.on'), false, 'nothing signs on its own that did not before'); + assert.equal(ev("'autoSales' in S||'autoRepair' in S"), false); + assert.equal(ev('S.ops.intern'), null, 'no intern until you hire one, so nothing runs yet'); + ev("delete S.ops;S.autoSales='true';S.autoRepair=1;S=migrate(S)"); + assert.equal(ev('S.ops.on.repair'), false); + assert.deepEqual(errors, []); + dom.window.close(); +}); diff --git a/tests/backbone-core.test.js b/tests/backbone-core.test.js new file mode 100644 index 0000000..6f38984 --- /dev/null +++ b/tests/backbone-core.test.js @@ -0,0 +1,260 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +const start = "ACT.start({});S.cash=1e9;S.lvl=13;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0"; +const g = n => `RG.findIndex(r=>r.n===${lit(n)})`; + +test('every router is classed by the highest backbone it runs', () => { + const { ev, errors } = load(); + const want = { + 0: ['Rusty Router 9000', 'Edge Lord 400', 'Sonic the Whitebox 32'], + 1: ['Mikrowtik CCR', 'Mikrowtik CCR 3.2T'], + 2: ['Chonk 800', 'Brocadabra MLX-16', 'Extremely Networks SLX 9740'], + 3: ['Absolute Unit 1.6T', 'Arrrhipster 7280R', 'Arrrhipster 7800R', 'Arrrhipster 7800R5'], + 4: ['Absolute Unit 3.2T', 'Disco 8K', 'Disco 8K Ultra', 'Knockia 7750', 'Knockia 7950 XRS', 'Sonic the Whitebox 64', 'The Router at the End of the Universe'], + }; + for (const [lv, names] of Object.entries(want)) for (const n of names) assert.equal(ev(`RG[${g(n)}].cr`), +lv, n); + assert.equal(ev('RG.length'), Object.values(want).flat().length, 'every model is classed'); + assert.equal(ev("RG.filter(r=>r.v==='arrrhipster').some(r=>r.cr>=4)"), false, 'no Arrrhipster runs SRv6'); + assert.equal(ev("RG.filter(r=>r.v==='disco'||r.v==='knockia').every(r=>r.cr===4)"), true, 'every Disco and Knockia does'); + // Everything below its top, except the whitebox that does SRv6 natively and no MPLS at all. + assert.equal(ev(`[0,1,2,3,4].map(L=>rgCore(${g('Disco 8K')},L)).join()`), 'true,true,true,true,true'); + assert.equal(ev(`[0,1,2,3,4].map(L=>rgCore(${g('Sonic the Whitebox 64')},L)).join()`), 'true,false,false,false,true'); + assert.equal(ev(`[0,1,2].map(L=>rgCore(${g('Mikrowtik CCR')},L)).join()`), 'true,true,false'); + // The two new ones go at the end, so saved POPs keep their models. + assert.equal(ev(g('Brocadabra MLX-16')), ev('RG.length') - 2); + assert.equal(ev("RG[RG_TOP].n"), 'The Router at the End of the Universe'); + assert.equal(ev("RG_ART.length"), ev("RG.length"), 'a picture for each'); + assert.equal(ev("mainRG(1)"), ev(g('Edge Lord 400')), 'the default upgrade path is unchanged'); + assert.equal(ev(`PZ_RG.includes(${g('Brocadabra MLX-16')})`), false, 'puzzles keep their router list'); + assert.deepEqual(errors, []); +}); + +test('a new network runs plain IGP: no Auto-TE until the backbone is upgraded, one step at a time', () => { + const { ev, dom, errors } = load(); + ev(start); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.core)')), { lv: 0, run: 0 }); + ev('ACT.buyTE()'); + assert.equal(ev('!!S.te'), false, 'no Auto-TE on plain IGP'); + // The backbone lives in the NOC's routing window; the refusal is a toast. + ev('ACT.routingOpen()'); + assert.match(dom.window.document.getElementById('modal').textContent, /Backbone/); + assert.match(dom.window.document.getElementById('toasts').textContent, /Auto-TE needs an RSVP-TE/); + const cash = ev('S.cash'); + ev('ACT.coreUp()'); + assert.equal(ev('S.core.lv'), 1); + assert.equal(cash - ev('S.cash'), ev('CORE_COST[1]')); + ev('ACT.buyTE()'); + assert.equal(ev('!!S.te'), false, 'LDP has no TE either'); + ev('ACT.coreUp()'); + assert.equal(ev('S.core.run'), 2); + ev('ACT.buyTE()'); + assert.equal(ev('!!S.te'), true, 'RSVP-TE unlocks Auto-TE'); + assert.equal(ev('JSON.stringify(S.te)'), ev('JSON.stringify(migrate(JSON.parse(JSON.stringify(packSave(S)))).te)'), 'Auto-TE as a reload makes it'); + // Customer levels gate each step. + ev('S.lvl=3;ACT.coreUp()'); + assert.equal(ev('S.core.lv'), 2, 'SR-MPLS needs customer level 5'); + assert.deepEqual(errors, []); +}); + +test('running a lower level is free, and Auto-TE and RouteScript pause below RSVP-TE', () => { + const { ev, errors } = load(); + ev(start + ";ACT.coreUp();ACT.coreUp();ACT.coreUp();ACT.buyTE();S.te.script='spill at 80%'"); + assert.equal(ev('S.core.lv'), 3); + assert.ok(ev('!!teRules()'), 'RouteScript runs on SR-MPLS'); + const cash = ev('S.cash'); + ev('ACT.coreSet({v:1})'); + assert.equal(ev('S.core.run'), 1); + assert.equal(ev('S.cash'), cash, 'free'); + assert.equal(ev('teRules()'), null, 'paused on LDP'); + ev('compute()'); + assert.equal(ev('R.teMoved'), 0); + ev('ACT.coreSet({v:3})'); + assert.ok(ev('!!teRules()'), 'back on, script and all'); + ev('ACT.coreSet({v:4})'); + assert.equal(ev('S.core.run'), 3, 'cannot run what was never bought'); + assert.deepEqual(errors, []); +}); + +test('the core costs router CPU, less the higher it goes; POPs whose router cannot run it stay outside', () => { + const { ev, errors } = load(); + ev(start + `;ACT.buildPop({city:'ams'});S.pops.fra.rgen=${g('Disco 8K')}`); + const cap = c => ev(`nodeCap('${c}')`); + const base = cap('fra'); + const at = []; + for (let L = 1; L <= 4; L++) { ev('ACT.coreUp()'); at.push(cap('fra') / base); } + assert.deepEqual(at.map(x => +x.toFixed(2)), [0.9, 0.92, 0.95, 0.97], 'LDP costs the most CPU, SRv6 the least'); + assert.equal(ev("inCore('ams')"), false, 'a Rusty Router cannot run SRv6'); + assert.equal(cap('ams'), ev('RG[0].cap'), 'and pays no CPU for it'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(coreOut())')), ['ams']); + assert.deepEqual(errors, []); +}); + +test('label switching: traffic passing through a POP costs its router less from LDP up', () => { + const pass = lv => { + const { ev, errors } = load(); + ev(start + ";ACT.buildPop({city:'ams'});ACT.buildPop({city:'bru'});ACT.launchBB({city:'ams'});S.pops.ams.bb.d=150"); + ev(`for(const c in S.pops)S.pops[c].rgen=${g('Mikrowtik CCR')};S.pops.bru.rgen=${g('Chonk 800')};`); + ev("const L=(a,b,t)=>{openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();};L('ams','bru',1);L('bru','fra',1);ACT.buyTransit({city:'fra',net:'cog',tier:1})"); + for (let i = 0; i < lv; i++) ev('ACT.coreUp()'); + ev('compute()'); + assert.deepEqual(errors, []); + return { load: ev("R.nodeLoad.bru||0"), served: ev('R.served') }; + }; + const ip = pass(0), ldp = pass(1); + assert.ok(ip.served > 50 && Math.abs(ldp.served - ip.served) < 1, 'same traffic either way'); + assert.ok(ldp.load < ip.load * 0.7, `Brussels only passes it on: lighter with labels (${ldp.load.toFixed(1)} vs ${ip.load.toFixed(1)})`); +}); + +test('interop failures: only with mixed vendors at the top of what some router can do', () => { + const { ev, errors } = load(); + ev(start + `;ACT.buildPop({city:'ams'});S.pops.fra.rgen=${g('Disco 8K')};S.pops.ams.rgen=${g('Knockia 7750')};`); + ev("const L=(a,b,t)=>{openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();};L('fra','ams',1)"); + for (let i = 0; i < 4; i++) ev('ACT.coreUp()'); + assert.ok(ev('coreIopRisk()') > 0, 'Disco and Knockia at SRv6, the top for both'); + ev('ACT.coreSet({v:3})'); + assert.equal(ev('coreIopRisk()'), 0, 'one step below: they get along'); + ev('ACT.coreSet({v:4})'); + ev(`S.pops.ams.rgen=${g('Disco 8K Ultra')}`); + assert.equal(ev('coreIopRisk()'), 0, 'one vendor never fights itself'); + ev(`S.pops.ams.rgen=${g('Knockia 7750')};ACT.coreSet({v:2})`); + assert.equal(ev('coreIopRisk()'), 0, 'RSVP-TE is below both'); + ev(`S.pops.fra.rgen=${g('Chonk 800')}`); + assert.ok(ev('coreIopRisk()') > 0, 'a Chonk 800 at RSVP-TE is at its top'); + assert.ok(ev('coreIopRisk()') < ev('CORE_IOP[4]'), 'and RSVP-TE squabbles less than SRv6'); + ev("fireFailure('interop')"); + const inc = "S.inc.find(i=>i.type==='interop')"; + assert.ok(ev(`!!${inc}`), 'an interop incident'); + assert.equal(ev(`linkDown(S.links.find(l=>l.id===${inc}.ref))`), true, 'the link between the vendors is down'); + assert.equal(ev("incTitle('interop')"), 'Vendor interop failure'); + assert.deepEqual(errors, []); +}); + +test('a new game never gets interop incidents or CPU costs: the classic game is unchanged', () => { + const { ev, errors } = load(); + ev(start + `;ACT.buildPop({city:'ams'});S.pops.ams.rgen=${g('Knockia 7750')};S.pops.fra.rgen=${g('Disco 8K')}`); + assert.equal(ev('coreIopRisk()'), 0); + assert.equal(ev("nodeCap('ams')"), ev(`RG[${g('Knockia 7750')}].cap`)); + assert.deepEqual(errors, []); +}); + +test('saves: an old save with Auto-TE keeps it on the old rules, scenarios ignore the core, garbage is repaired', () => { + const { ev, errors } = load(); + ev(start + ";ACT.coreUp();ACT.coreUp();ACT.buyTE()"); + ev("const s=JSON.parse(JSON.stringify(S));delete s.core;window.__t=migrate(s)"); + assert.deepEqual(JSON.parse(ev('JSON.stringify(__t.core)')), { lv: 2, run: 2, legacy: true }, 'Auto-TE bought before backbones: legacy RSVP-TE'); + ev("S=__t;compute()"); + assert.equal(ev('coreOn()'), false, 'the old rules'); + assert.equal(ev('coreTE()'), true, 'Auto-TE keeps running'); + ev('ACT.coreSet({v:2})'); + assert.equal(ev('coreOn()'), true, 'changing the backbone switches to the new rules'); + ev("const s=JSON.parse(JSON.stringify(S));delete s.core;delete s.te;window.__t=migrate(s)"); + assert.deepEqual(JSON.parse(ev('JSON.stringify(__t.core)')), { lv: 0, run: 0 }, 'no Auto-TE: plain IGP'); + ev("const s=JSON.parse(JSON.stringify(S));s.core={lv:9,run:-3,legacy:'yes'};window.__t=migrate(s)"); + assert.deepEqual(JSON.parse(ev('JSON.stringify(__t.core)')), { lv: 4, run: 0 }); + ev("S.scn={id:'x',rules:{},days:9};S.core={lv:0,run:0}"); + assert.equal(ev('coreOn()'), false, 'scenarios set TE up themselves'); + assert.deepEqual(errors, []); +}); + +test('the backbone panel and the router panels, on a phone too', () => { + for (const w of [1280, 360]) { + const { ev, dom, errors } = load(); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()"); + ev(`window.innerWidth=${w};` + start.replace('ACT.start({});', '') + `;ACT.buildPop({city:'ams'});S.pops.fra.rgen=${g('Disco 8K')};ACT.coreUp();ACT.coreUp();ACT.leftTab({t:'noc'});ACT.routingOpen();renderAll()`); + const txt = dom.window.document.body.textContent; + assert.match(txt, /RSVP-TE\/MPLS/, `${w}px`); + assert.match(txt, /outside the backbone/, 'Amsterdam is left out'); + assert.match(txt, /Upgrade to SR-MPLS/); + ev("UI.sel={type:'city',id:'fra'};UI.tab='links';UI.models=true;renderPanel()"); + const p = dom.window.document.getElementById('panelBody').textContent; + assert.match(p, /Disco · backbone up to SRv6/); + assert.match(p, /Brocadabra · backbone up to RSVP-TE\/MPLS/); + assert.match(p, /Whitebox · backbone up to SRv6 · no MPLS, SRv6 only/); + assert.deepEqual(errors, []); + } +}); + +test('an upgraded backbone brings its own customers: L3VPN from LDP, flex-algo from SR-MPLS, slices from SRv6', () => { + const { ev, errors } = load(); + ev(start + ";for(const c of ['ams','lon','par'])ACT.buildPop({city:c});for(const c in S.pops)S.pops[c].rgen=" + g('Disco 8K')); + const offered = () => ev("coreProducts(Object.keys(S.pops)).join()"); + assert.equal(offered(), '', 'plain IGP: none of them'); + ev('ACT.coreUp()'); + assert.equal(offered(), 'l3vpn,l3vpn'); + ev('ACT.coreUp();ACT.coreUp()'); + assert.equal(offered(), 'l3vpn,l3vpn,flex,flex'); + ev('ACT.coreUp()'); + assert.equal(offered(), 'l3vpn,l3vpn,flex,flex,slice,slice'); + ev('ACT.coreSet({v:0})'); + assert.equal(offered(), '', 'running plain IGP again: no new offers'); + // Each kind spawns a real offer that can be signed. + ev('ACT.coreSet({v:4})'); + for (const t of ['l3vpn', 'flex', 'slice']) { + ev(`S.offers=[];Math.random=(()=>{let s=7;return()=>(s=(s*9301+49297)%233280)/233280;})();for(let i=0;i<60&&!S.offers.some(o=>o.type==='${t}');i++){const p=coreProducts;coreProducts=()=>['${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}','${t}'];spawnOffer();coreProducts=p;}`); + assert.ok(ev(`S.offers.some(o=>o.type==='${t}')`), `a ${t} offer`); + assert.ok(ev(`S.offers.find(o=>o.type==='${t}').rate`) > 0, `${t} pays`); + assert.equal(typeof ev(`bTerms(S.offers.find(o=>o.type==='${t}'))`), 'string'); + } + // A legacy save or a scenario never sees them. + ev("S.core.legacy=true"); + assert.equal(offered(), ''); + assert.deepEqual(errors, []); +}); + +test('fast reroute: from RSVP-TE up, customers lose half as much happiness while a link is cut', () => { + const hit = run => { + const { ev, errors } = load(); + ev(start + `;ACT.buildPop({city:'ams'});S.pops.fra.rgen=S.pops.ams.rgen=${g('Disco 8K')};for(let i=0;i<${run};i++)ACT.coreUp();`); + ev("const L=(a,b,t)=>{openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();};L('fra','ams',1);S.links[0].ready=0"); + ev("S.biz.push({id:'b1',type:'dia',city:'ams',name:'X',bw:1,rate:600,mood:80,since:-99});S.links[0].cut=3;bizSf=()=>0.5;dayTick()"); + assert.deepEqual(errors, []); + return 80 - ev("S.biz.find(b=>b.id==='b1').mood"); + }; + const plain = hit(0), frr = hit(2); + assert.ok(plain > 0, 'a cut hurts'); + assert.ok(Math.abs(frr - plain / 2) < 0.01, `half as much with FRR (${plain} vs ${frr})`); + assert.ok(Math.abs(hit(1) - plain) < 0.01, 'LDP has no fast reroute'); +}); + +test('an interop lab cuts interop incidents, is bought once, and survives a save', () => { + const { ev, errors } = load(); + ev(start + `;ACT.buildPop({city:'ams'});S.pops.fra.rgen=${g('Disco 8K')};S.pops.ams.rgen=${g('Knockia 7750')};`); + ev("const L=(a,b,t)=>{openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();};L('fra','ams',1)"); + ev('ACT.coreLab()'); + assert.equal(ev('!!S.core.lab'), false, 'nothing to test on plain IGP'); + for (let i = 0; i < 4; i++) ev('ACT.coreUp()'); + const before = ev('coreIopRisk()'), cash = ev('S.cash'); + ev('ACT.coreLab()'); + assert.equal(ev('S.cash'), cash - ev('CORE_LAB')); + assert.ok(Math.abs(ev('coreIopRisk()') - before * 0.4) < 1e-9, '60% fewer'); + ev('ACT.coreLab()'); + assert.equal(ev('S.cash'), cash - ev('CORE_LAB'), 'bought once'); + ev("S=sanitize(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('S.core.lab'), true); + ev("S.core.lab='yes';S=sanitize(JSON.parse(JSON.stringify(S)))"); + assert.equal(ev('S.core.lab'), undefined, 'garbage is dropped'); + assert.deepEqual(errors, []); +}); + +test('badges for the backbone: label switcher, bleeding edge, single-vendor shop, vendor zoo', () => { + const { ev, errors } = load(); + const ok = id => ev(`BADGES.find(b=>b.id==='${id}').ok()`); + ev(start + ";for(const c of ['ams','lon','par','bru','mad','mil','sto'])ACT.buildPop({city:c});for(const c in S.pops)S.pops[c].rgen=" + g('Disco 8K')); + assert.equal(ev('Object.keys(S.pops).length'), 8); + for (const id of ['label', 'bleed', 'mono', 'zoo']) assert.equal(ok(id), false, id); + ev('ACT.coreUp()'); + assert.equal(ok('label'), true); + ev('ACT.coreUp();ACT.coreUp()'); + assert.equal(ok('mono'), true, 'eight POPs of one vendor on SR-MPLS'); + ev('ACT.coreUp()'); + assert.equal(ok('bleed'), true); + ev(`S.pops.ams.rgen=${g('Knockia 7750')};S.pops.lon.rgen=${g('Absolute Unit 3.2T')};S.pops.par.rgen=${g('Sonic the Whitebox 64')}`); + assert.equal(ok('mono'), false); + assert.equal(ok('zoo'), true, 'Disco, Knockia, Junipurr and Whitebox'); + ev('ACT.coreSet({v:0})'); + assert.equal(ok('zoo'), false, 'not on plain IGP'); + assert.deepEqual(errors, []); +}); diff --git a/tests/badge-cape-horn.test.js b/tests/badge-cape-horn.test.js new file mode 100644 index 0000000..ca899f8 --- /dev/null +++ b/tests/badge-cape-horn.test.js @@ -0,0 +1,32 @@ +// #272: "The Long Way Round" asks for a link round Cape Horn. Your own subsea cable from Buenos Aires to Santiago +// goes round the Horn too, not only a wave leased on the old ring. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const horn = (ev) => ev("BADGES.find(b=>b.id==='horn').ok()"); +const start = (ev) => ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=5e9;S.lvl=4;S.won=true;for(const g of GOALS)S.done[g.id]=0;ACT.buildPop({city:'bue'});ACT.launchBB({city:'bue'})"); + +test('#272 your own subsea cable from Buenos Aires to Santiago earns The Long Way Round', () => { + const { ev, errors } = load(); + start(ev); + assert.equal(horn(ev), false, 'no link round the Horn yet'); + assert.equal(ev("ownCabWhy('bue','scl')"), '', 'a cable can be laid Buenos Aires–Santiago'); + ev("UI.lmode='df';UI.dfSrc='lease';openLinkModal('bue','scl');ACT.ownCab();ACT.orderCable()"); + assert.ok(ev("S.links.some(l=>l.own&&l.sub&&!l.cable&&[l.a,l.b].includes('scl'))"), 'the cable is ordered'); + assert.equal(horn(ev), true, 'it goes round Cape Horn'); + ev('checkBadges()'); + assert.notEqual(ev("S.ach.horn"), undefined, 'and the badge is earned'); + assert.deepEqual(errors, []); +}); + +test('#272 a wave on the old ring still earns it, a cable that stays north of the Horn does not', () => { + const { ev, errors } = load(); + start(ev); + ev("S.links.push({id:'w1',a:'bue',b:'scl',kind:'wave',tier:1,km:5000,sub:true,cable:'sam1',mo:1,mult:1,trench:'cab:sam1',cut:0,day:0})"); + assert.equal(horn(ev), true, 'a wave on the ring round the Horn'); + ev("S.links=S.links.filter(l=>l.id!=='w1')"); + ev("S.links.push({id:'c1',a:'bue',b:'rio',kind:'df',own:true,sub:true,seaPath:[[-58.4,-34.6],[-50,-30],[-43.2,-22.9]],km:2000,cable:null,ch:[],mo:1,trench:'own:c1',cut:0,day:0,ready:0})"); + assert.equal(horn(ev), false, 'Buenos Aires–Rio never gets near the Horn'); + assert.deepEqual(errors, []); +}); diff --git a/tests/badges-variants.test.js b/tests/badges-variants.test.js new file mode 100644 index 0000000..d30a78d --- /dev/null +++ b/tests/badges-variants.test.js @@ -0,0 +1,172 @@ +// Badge variants by ruleset preset (2.0): On-call earns the standard badge, Change Freeze a frosted one and BGP at +// 3 a.m. a fiery one; Sandbox and puzzles earn none. A harder preset upgrades a badge you already have. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +// The preset is read from S.rules.preset until the ruleset feature lands with rulePreset(). +const start = (ev, preset) => { + ev("localStorage.removeItem('sot-badges');ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})"); + if (preset) ev(`S.rules={preset:'${preset}'}`); + ev("S.ach={};S.achP={};compute()"); +}; +const earnHello = (ev) => ev("S.pni.push({id:'x',net:'nfx',city:'fra',tier:0});compute();checkBadges()"); +const hof = (ev) => JSON.parse(ev("localStorage.getItem('sot-badges')||'{}'")); + +test('every save without a preset plays On-call and earns the standard badge', () => { + const { ev, errors } = load(); + start(ev); + assert.equal(ev('badgeVar()'), 'oncall'); + earnHello(ev); + assert.ok(ev('S.ach.hello!==undefined')); + assert.equal(ev('S.achP.hello'), 'oncall'); + assert.deepEqual(hof(ev).hello.vs && Object.keys(hof(ev).hello.vs), ['oncall']); + assert.equal(hof(ev).hello.v, 'oncall'); + assert.deepEqual(errors, []); +}); + +test('Change Freeze earns frosted badges and BGP at 3 a.m. fiery ones, shown in the toast and the list', () => { + for (const [p, name, cls] of [['freeze', /Freeze-dried/, 'v-freeze'], ['bgp', /Forged at 3 a\.m\./, 'v-bgp']]) { + const { ev, dom, errors } = load(); + start(ev, p); + ev("window.__t=[];const _t=toast;toast=(h,...a)=>{window.__t.push(h);return _t(h,...a);}"); + earnHello(ev); + assert.equal(ev('S.achP.hello'), p); + assert.match(ev("window.__t.join(' ')"), name, `${p}: the toast names the variant`); + ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft()"); + const card = dom.window.document.querySelector(`#leftBody .bdg.on.${cls}`); + assert.ok(card, `${p}: the badge list shows the variant`); + assert.match(card.textContent, name); + assert.equal(hof(ev).hello.v, p, 'remembered on this device'); + assert.deepEqual(errors, []); + } +}); + +test('Sandbox and puzzles earn no badges', () => { + for (const p of ['sandbox', 'puzzle']) { + const { ev, errors } = load(); + start(ev, p); + earnHello(ev); + assert.equal(ev('badgeVar()'), null); + assert.equal(ev('Object.keys(S.ach).length'), 0, p); + assert.deepEqual(errors, []); + } + const { ev, errors } = load(); + start(ev); + ev("S.mode='sandbox'"); + earnHello(ev); + assert.equal(ev('Object.keys(S.ach).length'), 0, 'the old sandbox mode too'); + assert.deepEqual(errors, []); +}); + +test('a harder preset upgrades a badge, an easier one never downgrades it', () => { + const { ev, errors } = load(); + start(ev, 'freeze'); + earnHello(ev); + const day = ev('S.ach.hello'); + ev("window.__t=[];const _t=toast;toast=(h,...a)=>{window.__t.push(h);return _t(h,...a);}"); + ev("S.rules.preset='oncall';checkBadges()"); + assert.equal(ev('S.achP.hello'), 'oncall', 'On-call beats Change Freeze'); + assert.match(ev("window.__t.join(' ')"), /Badge upgraded/); + ev("S.day+=10;S.rules.preset='bgp';checkBadges()"); + assert.equal(ev('S.achP.hello'), 'bgp'); + assert.equal(ev('S.ach.hello'), day, 'the day it was first earned stays'); + ev("window.__t=[];S.rules.preset='freeze';checkBadges()"); + assert.equal(ev('S.achP.hello'), 'bgp', 'never downgraded'); + assert.equal(ev("window.__t.length"), 0, 'and no toast'); + const h = hof(ev).hello; + assert.deepEqual(Object.keys(h.vs).sort(), ['bgp', 'freeze', 'oncall'], 'the collection holds every variant earned'); + assert.equal(h.v, 'bgp', 'the shelf shows the best one'); + assert.deepEqual(errors, []); +}); + +test('the collection counts badges per variant on this device, and fits a phone', () => { + const { ev, dom, errors } = load(); + ev('window.innerWidth=360'); + start(ev, 'bgp'); + earnHello(ev); + ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft()"); + const shelf = dom.window.document.querySelector('#leftBody .bshelf'); + assert.ok(shelf); + const total = ev('BADGES.length'); + assert.match(shelf.textContent, new RegExp(`Forged at 3 a\\.m\\. 1/${total}`)); + assert.match(shelf.textContent, new RegExp(`Freeze-dried 0/${total}`)); + assert.ok(dom.window.document.querySelector('#leftBody .bsh.v-bgp.cur'), 'the variant this game earns is marked'); + assert.match(dom.window.document.getElementById('leftBody').textContent, /forged in fire/); + assert.deepEqual(JSON.parse(ev('JSON.stringify(badgeShelf(hof()))')), { freeze: 0, oncall: 0, bgp: 1 }); + assert.deepEqual(errors, []); +}); + +test('old saves and old halls of fame keep loading, as standard badges', () => { + const { ev, errors } = load(); + start(ev); + // a 1.x save: S.ach holds days, no S.achP; a 1.x hall of fame: {d, n} per badge + ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2025-01-02',n:'Old'},t1:{d:'2025-03-04',n:'Old'},junk:5}))"); + ev("const o=JSON.parse(JSON.stringify(S));o.ach={hello:12,t1:'400'};delete o.achP;S=migrate(o)"); + assert.equal(ev('S.achP.hello'), 'oncall'); + assert.equal(ev('S.ach.t1'), 400, 'days are numbers'); + assert.deepEqual(JSON.parse(ev("JSON.stringify(Object.keys(S.achP).sort())")), ['hello', 't1']); + const h = JSON.parse(ev('JSON.stringify(hof())')); + assert.equal(h.hello.v, 'oncall'); + assert.equal(h.hello.vs.oncall, '2025-01-02'); + assert.equal(h.junk, undefined, 'broken entries are dropped'); + // a hand-edited variant is not trusted + ev("const o=JSON.parse(JSON.stringify(S));o.achP={hello:'lava',t1:'bgp'};S=migrate(o)"); + assert.equal(ev('S.achP.hello'), 'oncall'); + assert.equal(ev('S.achP.t1'), 'bgp'); + ev("localStorage.setItem('sot-badges','[1,2]')"); + assert.equal(ev('JSON.stringify(hof())'), '{}'); + ev("UI.left='goals';UI.leftOpen=true;renderLeft()"); + // new games start with an empty variant map + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev('JSON.stringify(S.achP)'), '{}'); + assert.deepEqual(errors, []); +}); + +test('the share card rings the variant badges', () => { + const { ev, errors } = load(); + start(ev, 'bgp'); + earnHello(ev); + // count the strokes the card draws with a variant badge and with the same badge in its standard look + const calls = () => ev("(()=>{const cv=shareCanvas();return cv.getContext('2d').calls.n;})()"); + const fiery = calls(); + ev("S.achP.hello='oncall'"); + const plain = calls(); + assert.ok(fiery > plain, `the ring and the tally are drawn (${fiery} > ${plain} calls)`); + assert.deepEqual(errors, []); +}); + +test('a variant named after an Object prototype key is not a variant', () => { + const { ev, errors } = load(); + start(ev); + for (const k of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) { + ev(`const o=JSON.parse(JSON.stringify(S));o.ach={hello:3};o.achP={hello:${lit(k)}};S=migrate(o)`); + assert.equal(ev('S.achP.hello'), 'oncall', k); + assert.equal(ev(`bvar(${lit(k)}).k`), 'oncall', `bvar(${k})`); + ev(`S.rules={preset:${lit(k)}}`); + assert.equal(ev('badgeVar()'), 'oncall', `badgeVar() under preset ${k}`); + } + ev("S.rules={preset:'oncall'};S.achP.hello='constructor';shareCanvas()"); + assert.deepEqual(errors, []); +}); + +test('"Badge upgraded" means the collection on this device got a better variant', () => { + const { ev, errors } = load(); + const spy = () => ev("window.__t=[];if(!window.__sp){window.__sp=1;const _t=toast;toast=(h,...a)=>{window.__t.push(h);return _t(h,...a);};}"); + // a new game, but this device already holds the frosted badge: the standard one upgrades it + start(ev, 'oncall'); + ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2026-01-01',n:'Old',vs:{freeze:'2026-01-01'}}}))"); + spy(); earnHello(ev); + assert.match(ev("window.__t.join(' ')"), /Badge upgraded/); + assert.equal(hof(ev).hello.v, 'oncall'); + // another new game, the device already holds the fiery one: earning the frosted one is a plain unlock + start(ev, 'freeze'); + ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2026-01-01',n:'Old',vs:{bgp:'2026-01-01'}}}))"); + spy(); earnHello(ev); + const t = ev("window.__t.join(' ')"); + assert.match(t, /Badge unlocked/); + assert.doesNotMatch(t, /Badge upgraded/); + assert.equal(hof(ev).hello.v, 'bgp', 'the best variant stays on the shelf'); + assert.deepEqual(errors, []); +}); diff --git a/tests/best-effort.test.js b/tests/best-effort.test.js new file mode 100644 index 0000000..03698a9 --- /dev/null +++ b/tests/best-effort.test.js @@ -0,0 +1,160 @@ +// Best Effort (☕): the gentlest Normal preset. Change Freeze's quiet (rare outages, no DDoS, no chaos monkey, quick +// builds, no market) plus no cable ships, no conferences, patient customers, a rescue loan instead of game over and +// quiet notifications by default. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const start = (ev, preset) => ev(`beginGame('Soft Serve','mrs',{mode:'normal',preset:'${preset}'});if(UI.pendGame)ACT.pitchSkip();closeModal();S.cash=1e8;for(const g of GOALS)S.done[g.id]=0`); +const J = (ev, code) => JSON.parse(ev(`JSON.stringify(${code})`)); + +test('Best Effort is a Normal preset with its own rules, kept through save and load', () => { + const { ev, errors } = load(); + start(ev, 'soft'); + assert.equal(ev('rulePreset()'), 'soft'); + assert.deepEqual(J(ev, "['chaos','lead','market','sea','confs','broke','moods','pnis'].map(rule)"), ['calm', 'quick', false, 'timer', false, 'rescue', 'patient', 'instant']); + assert.equal(ev('ddosOff()'), true, 'no DDoS'); + assert.equal(ev('mkElig()'), false, 'no chaos monkey'); + ev("S.rules.confs=true;S.rules.sea='ships';const t=JSON.stringify(packSave(S));S=migrate(JSON.parse(t))"); + assert.deepEqual(J(ev, "[rulePreset(),rule('confs'),rule('sea')]"), ['soft', false, 'timer'], 'an edited save gets its preset back'); + // Every other preset keeps the classic game's ships, conferences, game over and moods. + for (const p of ['freeze', 'oncall', 'bgp']) { + start(ev, p); + assert.deepEqual(J(ev, "['sea','confs','broke','moods','pnis'].map(rule)"), ['ships', true, 'lose', 'normal', 'wait'], p); + } + assert.deepEqual(errors, []); +}); + +test('Best Effort: a subsea cut mends on its own clock, with no cable ship', () => { + for (const [p, ships] of [['soft', false], ['freeze', true]]) { + const { ev, errors } = load(); + start(ev, p); + ev("ACT.buildPop({city:'bcn'});S.links=[{id:'med',a:'bcn',b:'mrs',kind:'wave',sub:true,tier:0,km:365,cable:'medusa',cut:0,mo:1000}];S.inc=[];S.fleet={};compute();fireFailure('cut')"); + const i = J(ev, "S.inc.find(i=>i.type==='cut')"); + assert.ok(i, p); + assert.equal(i.ship != null || !!i.seaq, ships, `${p}: a ship sails out only with ships`); + assert.equal(Object.keys(J(ev, 'S.fleet')).length > 0, ships, p); + if (!ships) { + assert.ok(i.until > ev('S.day') && i.until - ev('S.day') <= 17, 'mends in 10 to 17 days, like a cut on land'); + for (let k = 0; k < 18; k++) ev('dayTick()'); + assert.equal(ev("S.inc.some(i=>i.type==='cut')"), false, 'and is mended'); + } + assert.deepEqual(errors, [], p); + } +}); + +test('Best Effort: no conference season', () => { + const { ev, errors } = load(); + start(ev, 'soft'); + assert.deepEqual(J(ev, 'upcomingConfs(400)'), []); + for (let k = 0; k < 400; k++) ev('S.nextFail=S.nextEvent=1e9;dayTick()'); + assert.equal(ev('!!S.conf||!!(S.stats.confs)'), false); + assert.equal(ev('confSection()'), ''); + assert.equal(ev("S.log.some(e=>/NANOG|APRICOT|PTC/.test(JSON.stringify(e)))"), false, 'no invitations'); + start(ev, 'freeze'); + assert.ok(J(ev, 'upcomingConfs(400)').length > 0, 'Change Freeze still has them'); + assert.deepEqual(errors, []); +}); + +test('Best Effort: customers sour half as fast', () => { + const drop = {}; + for (const p of ['soft', 'freeze']) { + const { ev, errors } = load(); + start(ev, p); + ev("ACT.launchBB({city:'mrs'});ACT.buyTransit({city:'mrs',net:'cog',tier:1});S.biz=[{id:'b',name:'B',type:'dia',city:'mrs',bw:1,rate:100,mood:80,since:0}];S.day=100;compute()"); + // Every path down: the customer gets nothing for a day. + ev("S.transit.forEach(t=>t.down=S.day+5);S.nextFail=S.nextEvent=1e9;dayTick()"); + drop[p] = 80 - ev("S.biz[0].mood"); + assert.deepEqual(errors, [], p); + } + assert.ok(drop.freeze > 0); + assert.ok(Math.abs(drop.soft - drop.freeze / 2) < 1e-9, `half: ${drop.soft} vs ${drop.freeze}`); +}); + +test('Best Effort: deep in the red, a rescue loan instead of game over', () => { + const { ev, errors } = load(); + start(ev, 'soft'); + ev("ACT.launchBB({city:'mrs'});compute();S.cash=-250000;S.nextFail=S.nextEvent=1e9;dayTick()"); + assert.equal(ev('!!S.lost'), false); + assert.ok(ev('S.cash') > 0, 'back in the black'); + const l = J(ev, "S.loans.find(l=>l.bank==='gov')"); + assert.ok(l && l.covs.length === 0 && l.term === 60 && l.pay > 0, 'a five-year state loan, no conditions'); + assert.match(ev("document.getElementById('toasts').textContent"), /Ministry of Tubes stepped in/); + start(ev, 'freeze'); + ev("ACT.launchBB({city:'mrs'});compute();S.cash=-250000;S.nextFail=S.nextEvent=1e9;dayTick()"); + assert.equal(ev('!!S.lost'), true, 'the other presets still end the game'); + assert.deepEqual(errors, []); +}); + +test('quiet notifications: on by default in Best Effort, a setting everywhere, and the NOC log keeps everything', () => { + const { ev, dom, errors } = load(); + const shown = () => ev("document.getElementById('toasts').textContent"); + ev("localStorage.removeItem('sot-prefs');PREFS={}"); + start(ev, 'soft'); + assert.equal(ev('quietOn()'), true); + ev("document.getElementById('toasts').innerHTML='';UI.tick=true;toast('Quiet news','good');toast('Bad news','bad');toast('A milestone','goal');UI.tick=false"); + assert.doesNotMatch(shown(), /Quiet news/, 'good news from the day stays in the log'); + assert.match(shown(), /Bad news/); + assert.match(shown(), /A milestone/); + assert.equal(ev("S.log.some(e=>/Quiet news/.test(JSON.stringify(e)))"), true, 'the NOC log has it'); + ev("toast('You clicked','good')"); + assert.match(shown(), /You clicked/, 'what a click says still shows'); + start(ev, 'oncall'); + assert.equal(ev('quietOn()'), false, 'off elsewhere by default'); + // The setting, at 360 px. + dom.window.innerWidth = 360; + ev('UI.setOpen=true;openModal(settingsHtml())'); + const doc = dom.window.document; + assert.match(doc.getElementById('modalCard').textContent, /Quiet notifications/); + doc.querySelector('#modalCard [data-act="prefSet"][data-args*="quiet:1"]').click(); + assert.equal(ev('quietOn()'), true, 'chosen on, on in every mode'); + start(ev, 'soft'); + ev("ACT.prefSet({v:'quiet:0'})"); + assert.equal(ev('quietOn()'), false, 'chosen off, off even in Best Effort'); + assert.deepEqual(errors, []); +}); + +test('the title screen offers Best Effort first, and it earns Freeze-dried badges', () => { + const { ev, dom, errors } = load(); + const doc = dom.window.document; + ev('window.innerWidth=360;showTitle()'); + const ps = [...doc.querySelectorAll('#modal .preset')].map((b) => b.dataset.preset); + assert.deepEqual(ps, ['soft', 'freeze', 'oncall', 'bgp']); + doc.querySelector('.preset[data-preset=soft]').click(); + assert.match(doc.getElementById('presetWhat').textContent, /No SLA, no pager/); + ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip()"); + assert.equal(ev('rulePreset()'), 'soft'); + assert.match(ev("document.getElementById('hAsn').textContent"), /Best Effort/); + assert.equal(ev('badgeVar()'), 'freeze'); + assert.deepEqual(errors, []); +}); + +test('Best Effort: PNIs and their augments are up the moment they are ordered', () => { + const { ev, errors } = load(); + ev("beginGame('Soft Serve','fra',{mode:'normal',preset:'soft'});if(UI.pendGame)ACT.pitchSkip();closeModal();S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;S.nextFail=S.nextEvent=1e9;ACT.launchBB({city:'fra'});for(const c in S.pops)S.pops[c].rgen=3;compute()"); + assert.equal(ev("pniEta('nfx')"), 'Up the moment you order it'); + ev("document.getElementById('toasts').innerHTML='';R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:1})"); + assert.equal(ev('pniOn(S.pni[0])'), true, 'a PNI with a big network, up at once'); + assert.match(ev("document.getElementById('toasts').textContent"), /PNI with NetChill is up/); + ev('compute()'); + assert.ok(ev('R.usePni[S.pni[0].id]') > 0, 'and carrying traffic'); + ev("R.demTo.nfx=1e4;ACT.pni({city:'fra',net:'nfx',tier:2})"); + assert.deepEqual(J(ev, '[S.pni[0].tier,S.pni[0].up===undefined]'), [2, true], 'an upgrade, at once'); + ev('ACT.lagP({id:S.pni[0].id,d:1})'); + assert.deepEqual(J(ev, '[S.pni[0].n,S.pni[0].up===undefined]'), [2, true], 'a LAG member, at once'); + // Change Freeze still waits, if only days. + start(ev, 'freeze'); + ev("S.cash=1e9;S.lvl=6;ACT.launchBB({city:'mrs'});for(const c in S.pops)S.pops[c].rgen=3;compute();R.demTo.nfx=1e4;ACT.pni({city:'mrs',net:'nfx',tier:1})"); + assert.ok(ev('S.pni[0].ready') > ev('S.day')); + assert.deepEqual(errors, []); +}); + +test('no "attracts attacks" warning where nobody attacks', () => { + const { ev, errors } = load(); + const risk = () => ev("bRisk({type:Object.keys(BIZ_T).find(k=>BIZ_T[k].gaming)})"); + start(ev, 'soft'); + assert.equal(risk(), ''); + start(ev, 'oncall'); + assert.match(risk(), /Gaming attracts attacks/); + assert.deepEqual(errors, []); +}); diff --git a/tests/big-numbers.test.js b/tests/big-numbers.test.js new file mode 100644 index 0000000..2fbe509 --- /dev/null +++ b/tests/big-numbers.test.js @@ -0,0 +1,24 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +test('money and bandwidth keep a readable unit past a billion dollars and a petabit', () => { + const { ev, errors } = load(); + const f = x => ev(x); + assert.equal(f('fmt$(1.5e6)'), '$1.50M'); + assert.equal(f('fmt$(250e6)'), '$250.0M'); + assert.equal(f('fmt$(999.97e6)'), '$1.00B'); + assert.equal(f('fmt$(1.2e9)'), '$1.20B'); + assert.equal(f('fmt$(-12.5e9)'), '-$12.5B'); + assert.equal(f('fmt$(120e9)'), '$120.0B'); + assert.equal(f('fmtG(2500)'), '2.50 Tbps'); + assert.equal(f('fmtG(999000)'), '999.0 Tbps'); + assert.equal(f('fmtG(999990)'), '1.00 Pbps'); + assert.equal(f('fmtG(12e6)'), '12.0 Pbps'); + // The map's fiber labels and the NOC graph axes use the short form. + assert.equal(f('fmtCap(334000)'), '334T'); + assert.equal(f('fmtCap(1024000)'), '1P'); + assert.equal(f('fmtCap(3152700)'), '3.2P'); + assert.equal(f('fmtCap(400)'), '400G'); + assert.deepEqual(errors, []); +}); diff --git a/tests/bilbao-landing.test.js b/tests/bilbao-landing.test.js new file mode 100644 index 0000000..cd046d3 --- /dev/null +++ b/tests/bilbao-landing.test.js @@ -0,0 +1,78 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +const start = "ACT.start({});S.cash=1e9;S.nextFail=1e9;S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0"; + +test('Bilbao is on the map, on land and ready to take a POP; it has no exchange of its own', () => { + const { ev, errors } = load(); + ev(start); + assert.equal(ev("CITY.bio.name"), 'Bilbao'); + assert.equal(ev("CITY.bio.cc"), 'ES'); + assert.equal(ev("CITY.bio.land"), 'eu'); + assert.equal(ev("onLand(CITY.bio.x,CITY.bio.y)"), true); + assert.equal(ev("!!CITY.bio.ix"), false, 'the exchange is in Madrid'); + assert.ok(ev("kmBetween('bio','mad')") > 250 && ev("kmBetween('bio','mad')") < 450); + assert.equal(ev("isSub('bio','mad')"), false, 'reached overland from Madrid'); + assert.equal(ev("typeof CITY.sdr"), 'undefined', 'no Santander'); + ev("ACT.buildPop({city:'mad'});ACT.buildPop({city:'bio'})"); + assert.equal(ev("!!S.pops.bio"), true); + assert.deepEqual(errors, []); +}); + +test('the transatlantic cables that come ashore on the Biscay coast land at Bilbao', () => { + const { ev, errors } = load(); + ev("ACT.start({})"); + const lands = id => JSON.parse(ev(`JSON.stringify(CABLES.find(c=>c.id==='${id}').pairs.map(p=>p.slice(0,2)))`)); + assert.deepEqual(lands('marea'), [['ash', 'bio']]); + assert.deepEqual(lands('grace'), [['nyc', 'lon'], ['nyc', 'bio']]); + assert.ok(lands('sol').some(p => p.join() === 'pdl,bio')); + for (const [id, a, b] of [['marea', 'ash', 'bio'], ['grace', 'nyc', 'bio'], ['sol', 'pdl', 'bio']]) { + assert.equal(ev(`cablesFor('${a}','${b}').map(c=>c.cid).includes('${id}')`), true, `${id} lands at Bilbao`); + } + for (const id of ['marea', 'grace', 'sol']) { + assert.equal(ev(`CABLE_PAIRS.some(p=>p.cid==='${id}'&&(p.a==='mad'||p.b==='mad'))`), false, `${id} no longer ends at Madrid`); + } + assert.deepEqual(errors, []); +}); + +test('transit and peers in Bilbao: the big carriers, Drizzle Electric and Tangerine Telecom; old saves still load', () => { + const { ev, errors } = load(); + ev(start); + for (const n of ['lvl', 'cog', 'skl', 'drz', 'tng']) assert.equal(ev(`NET.${n}.pops.includes('bio')`), true, `${n} is in Bilbao`); + assert.equal(ev("CITY_PDB.bio.join()"), '1,8,1341', 'PeeringDB: one facility, eight networks'); + ev("ACT.buildPop({city:'bio'})"); + for (const n of ['drz', 'tng']) { + ev(`ACT.buyTransit({city:'bio',net:'${n}',tier:1})`); + assert.equal(ev(`S.transit.some(t=>t.city==='bio'&&t.net==='${n}')`), true, `${n} sells transit in Bilbao`); + } + // A save from before: a Marea link between Ashburn and Madrid. + ev("ACT.buildPop({city:'ash'});ACT.buildPop({city:'mad'})"); + const save = JSON.parse(ev("JSON.stringify(Object.assign(JSON.parse(JSON.stringify(S)),{links:[{id:'old1',a:'ash',b:'mad',kind:'wave',tier:2,km:6500,mo:100,cut:0,sub:true,cable:'marea',ready:0}]}))")); + const out = JSON.parse(ev(`JSON.stringify(sanitize(JSON.parse(${lit(JSON.stringify(save))})).links.map(l=>[l.a,l.b,l.cable]))`)); + assert.deepEqual(out, [['ash', 'mad', null]], 'the link survives as a plain subsea link'); + for (const z of [0.35, 1.4, 6]) ev(`cam.z=${z};draw(performance.now())`); + assert.deepEqual(errors, []); +}); + +test('Marea leaves the American coast at Virginia Beach, not New Jersey, so its line does not cross the northeast', () => { + const { ev, errors } = load(); + ev(start); + const pts = JSON.parse(ev("JSON.stringify(CABLES.find(c=>c.id==='marea').pairs[0][2])")); + assert.deepEqual(pts[0], [-75.7, 36.85], 'the first waypoint is off Virginia Beach'); + assert.ok(pts.every(([lo, la]) => ev(`(()=>{const p=proj(${lo},${la});return !onLand(p[0],p[1])})()`)), 'every waypoint is at sea'); + assert.deepEqual(errors, []); +}); + +test('Columbus III-and-a-half comes ashore in the south, near Cadiz, not on the Biscay coast', () => { + const { ev, errors } = load(); + ev(start); + const pair = JSON.parse(ev("JSON.stringify(CABLES.find(c=>c.id==='col3').pairs.find(p=>p[0]==='mia'&&p[1]==='mad'))")); + assert.ok(pair, 'Miami to Madrid, as before, so old saves keep their Columbus links'); + const last = pair[2][pair[2].length - 1]; + assert.ok(last[1] < 37 && last[0] > -7 && last[0] < -5.5, `it lands on the Gulf of Cadiz (${last})`); + assert.equal(ev("cablesFor('mia','bio').some(c=>c.cid==='col3')"), false, 'not at Bilbao'); + assert.ok(pair[2].every(([lo, la]) => ev(`(()=>{const p=proj(${lo},${la});return !onLand(p[0],p[1])})()`)), 'every waypoint is at sea'); + assert.deepEqual(errors, []); +}); diff --git a/tests/border-closed-links.test.js b/tests/border-closed-links.test.js new file mode 100644 index 0000000..f084d0a --- /dev/null +++ b/tests/border-closed-links.test.js @@ -0,0 +1,53 @@ +// #329: a link a political event takes down (the Gulf spat, Russia's sovereign internet drill) is drawn broken on +// the map, so its panel must say why and for how long, and the link modal must warn before you lease one. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const start = "ACT.start({});S.cash=1e9;S.lvl=13;S.nextFail=S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;"; +const panel = ev => ev("document.getElementById('panel').textContent"); + +test('#329 a link down for the Gulf spat says so in its panel, with the days left', () => { + const { ev, errors } = load(); + ev(start + "ACT.launchBB({city:'doh'});S.pops.auh={day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:3};compute()"); + ev("S.links.push({id:'w1',a:'doh',b:'auh',kind:'wave',tier:0,km:300,sub:false,mo:1,cut:0,day:0})"); + const id = 'w1'; + ev('S.ev.gulf=S.day+40;compute()'); + assert.equal(ev(`linkDown(S.links.find(l=>l.id==='${id}'))`), true, 'the spat takes it down'); + ev(`selectLink('${id}')`); + assert.match(panel(ev), /Border closed/); + assert.match(panel(ev), /Qatar/); + assert.match(panel(ev), /Back in 40 days/); + // Leasing another one now warns that it stays dark. + ev("openLinkModal('doh','auh')"); + assert.match(ev("document.getElementById('modalCard').textContent"), /stay dark/); + assert.match(ev("dfModalBody('doh','auh',300,0)"), /stay dark/, 'dark fiber warns too'); + // On a phone the panel is a bottom sheet with the same note. + ev(`closeModal();window.innerWidth=390;selectLink('${id}')`); + assert.match(panel(ev), /Border closed/); + ev('window.innerWidth=1280'); + // After the spat, nothing about it. + ev('S.ev.gulf=0;compute();closeModal()'); + ev(`selectLink('${id}')`); + assert.doesNotMatch(panel(ev), /Border closed/); + ev("openLinkModal('doh','auh')"); + assert.doesNotMatch(ev("document.getElementById('modalCard').textContent"), /stay dark/); + assert.deepEqual(errors, []); +}); + +test('#329 dark fiber and virtual circuits into Qatar explain the spat too, and Russia\'s drill is named', () => { + const { ev, errors } = load(); + ev(start + "ACT.launchBB({city:'doh'});S.pops.auh={day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:3};compute()"); + ev("S.links.push({id:'dfx',a:'doh',b:'auh',kind:'df',own:false,sys:'lite',ch:[],km:300,sub:false,mo:1,ready:0,cut:0,day:0});S.ev.gulf=S.day+10"); + ev("selectLink('dfx')"); + assert.match(panel(ev), /Border closed/); + ev("S.links.push({id:'vx1',a:'doh',b:'auh',kind:'vxc',prov:Object.keys(FAB)[0],vt:0,km:300,sub:false,mo:1,cut:0,day:0})"); + ev("selectLink('vx1')"); + assert.match(panel(ev), /Border closed/); + assert.match(panel(ev), /Qatar/); + ev("S.links.push({id:'ru1',a:'mos',b:'hel',kind:'wave',tier:0,km:900,sub:false,mo:1,cut:0,day:0});S.ev.gulf=0;S.ev.runet=S.day+1"); + ev("selectLink('ru1')"); + assert.match(panel(ev), /Border closed/); + assert.match(panel(ev), /Russia/); + assert.deepEqual(errors, []); +}); diff --git a/tests/borders-overland.test.js b/tests/borders-overland.test.js new file mode 100644 index 0000000..d8b740f --- /dev/null +++ b/tests/borders-overland.test.js @@ -0,0 +1,63 @@ +// Fiber over land inside one country: cities on land with no road in (Russia's Arctic and Kamchatka, Alaska, Greenland's +// towns) can be dug to from the rest of their own country, and only their own. North and South Korea, like Kyiv and +// Moscow, get no circuit between them at all. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const start = "ACT.start({});S.cash=1e9;S.lvl=13;S.nextFail=S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;"; + +test('cities of one country on one piece of land can build terrestrial fiber between them', () => { + const { ev, errors } = load(); + ev(start); + for (const [a, b, why] of [['pvs', 'dyr', 'Pevek–Anadyr, both Chukotka'], ['pvs', 'mos', 'Pevek–Moscow, across Russia'], ['pkc', 'vvo', 'Kamchatka–Vladivostok'], + ['jnu', 'sea', 'Juneau–Seattle, both US'], ['brw', 'ome', "Alaska's Arctic coast"], ['nuk', 'sis', "Greenland's towns, one island"]]) { + assert.equal(ev(`isSub('${a}','${b}')`), false, `${why}: over land`); + assert.equal(ev(`dfAllowed('${a}','${b}')`), true, `${why}: dark fiber can be built`); + assert.equal(ev(`landMult('${a}','${b}')`) < 45, true, `${why}: not priced as a crossing between continents`); + } + ev("UI.lmode='wave';openLinkModal('pvs','dyr')"); + assert.match(ev("document.getElementById('modalCard').textContent"), /Terrestrial/); + assert.deepEqual(errors, []); +}); + +test('only inside the country: islands and other countries stay across the sea', () => { + const { ev, errors } = load(); + ev(start); + for (const [a, b, why] of [['jnu', 'van', 'Juneau–Vancouver: a border'], ['yfb', 'mtl', 'Iqaluit is on Baffin Island'], ['pkc', 'uus', 'Sakhalin is an island'], + ['ome', 'vvo', 'Nome–Vladivostok: two countries'], ['hnl', 'sea', 'Hawaii']]) { + assert.equal(ev(`isSub('${a}','${b}')`), true, why); + } + assert.equal(ev("landMult('ist','esb')") < 45, true, 'Istanbul–Ankara is one country, not two continents'); + assert.deepEqual(errors, []); +}); + +test('no circuit of any kind between North and South Korea, and still none between Kyiv and Moscow', () => { + const { ev, errors } = load(); + ev(start + "ACT.launchBB({city:'icn'});S.pops.fnj={day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:3};compute()"); + for (const [a, b, msg] of [['icn', 'fnj', /North and South Korea/], ['fnj', 'icn', /North and South Korea/], ['kyv', 'mos', /Kyiv and Moscow/]]) { + ev(`UI.pending=null;openLinkModal('${a}','${b}')`); + assert.match(ev("document.getElementById('modalCard').textContent"), msg); + assert.equal(ev('UI.pending'), null, 'nothing to order'); + assert.equal(ev(`dfAllowed('${a}','${b}')`), false); + } + // Even an action called directly (an agent, a stale window) builds nothing. + const n = ev('S.links.length'); + ev("UI.pending={a:'icn',b:'fnj'};ACT.buildLink({tier:0});UI.pending={a:'icn',b:'fnj'};UI.dfSrc='build';ACT.orderDf();UI.pending={a:'icn',b:'fnj'};ACT.orderCable()"); + assert.equal(ev('S.links.length'), n); + // Seoul and Pyongyang are still on one landmass, but a latency customer cannot count on a link between them. + assert.ok(ev("latFloor('icn','fnj')") > ev("latMaxOf('icn','fnj')")); + assert.deepEqual(errors, []); +}); + +test('nothing leaves South Korea over land: every way out is a subsea cable', () => { + const { ev, errors } = load(); + ev(start); + for (const c of ['pek', 'sha', 'vvo', 'fnj']) assert.equal(ev(`isSub('icn','${c}')`), true, `Seoul–${c}: by sea only`); + assert.equal(ev("CITIES.filter(c=>c.cc!=='KR'&&!isSub('icn',c.id)).length"), 0, 'no city anywhere is overland from Seoul'); + assert.equal(ev("dfAllowed('icn','pek')"), false, 'no terrestrial dark fiber to Beijing'); + assert.equal(ev("isSub('pek','fnj')"), false, 'the rest of the peninsula still borders China'); + ev("UI.via=null;UI.lmode='wave';openLinkModal('icn','tok')"); + assert.match(ev("document.getElementById('modalCard').textContent"), /Subsea/); + assert.deepEqual(errors, []); +}); diff --git a/tests/bstd-ipv6-only.test.js b/tests/bstd-ipv6-only.test.js new file mode 100644 index 0000000..7767b96 --- /dev/null +++ b/tests/bstd-ipv6-only.test.js @@ -0,0 +1,209 @@ +// The build standard's "Broadband: IPv6-only" row (96-pop-standard.js, the swap itself in 34-ipv6-only.js): every +// broadband city still on dual stack starts its home-router swap, the most dual-stack homes first, priced as the city +// panel prices it (the whole swap, paid as the routers go in), from the sheet's button or the intern's standing order, +// within the order's budget and the cash floor. Only while IPv4 is scarce (rule ip4). +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +// On-call (IPv4 is scarce), plenty of cash, nothing breaking. Broadband in Amsterdam (3,000 homes), Frankfurt (1,300) and +// Paris (500): their swaps cost $12k, $5.2k and $2k. +const BASE = "ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall');S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=9;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.offers=[];S.biz=[];" + + "ACT.launchBB({city:'fra'});S.pops.fra.rgen=3;ACT.buyTransit({city:'fra',net:'lvl',tier:3});for(const c of ['ams','par']){ACT.buildPop({city:c});ACT.launchBB({city:c});}" + + "S.pops.fra.bb.d=130;S.pops.ams.bb.d=300;S.pops.par.bb.d=50;compute()"; +function game(t, opts) { + const h = load(opts); + t.after(() => h.dom.window.close()); + h.ev(BASE); + return h; +} +const J = (ev, x) => JSON.parse(ev(`JSON.stringify(${x})`)); +const std = (ev, d) => ev(`S.popStd=${lit(d)}`); +const v6 = (ev, plan = 'bstdPlan(false)') => J(ev, `${plan}.filter(j=>j.k==='v6').map(j=>[j.c,j.cost])`); +const swapping = ev => J(ev, "['ams','fra','par'].filter(c=>S.pops[c].bb.v6e)"); +const COST = { ams: 12000, fra: 5200, par: 2000 }; + +test('the row: every dual-stack broadband city, the most homes first, at the swap\'s own price and its IPv4 bill', (t) => { + const h = game(t, { agent: true }); + const { ev, errors } = h; + assert.equal(ev('ip4On()'), true); + assert.deepEqual(J(ev, "['ams','fra','par'].map(ip6Cost)"), [COST.ams, COST.fra, COST.par]); + assert.deepEqual(v6(ev), [], 'no standard, no jobs'); + std(ev, { v6: true }); + assert.deepEqual(v6(ev), [['ams', COST.ams], ['fra', COST.fra], ['par', COST.par]], 'Amsterdam first: the most homes behind CGNAT'); + assert.equal(ev('bstdLine(bstd())'), '1 more target'); + // The plan's running costs are the IPv4 bill with every city done, against today's. + const want = ev("(()=>{const eye=(R.rev&&R.rev.eyeballs)||0,m=b=>b.box+b.box64+b.refund,s={ip4:S.ip4,biz:S.biz,pops:{...S.pops}};for(const c of ['ams','fra','par'])s.pops[c]={...S.pops[c],bb:{...S.pops[c].bb,v6:1}};return m(ip4Bill(eye,s))-m(ip4Bill(eye));})()"); + const q = J(ev, 'bstdQuote(false)'); + assert.deepEqual([q.pops, q.n, q.cost], [3, 3, COST.ams + COST.fra + COST.par]); + assert.equal(q.mo, Math.round(want)); + // A city already swapping, one done, one with no homes yet: nothing to do there. + ev("S.pops.ams.bb.v6e=S.day+40;S.pops.par.bb.v6=1;ACT.buildPop({city:'lon'});ACT.launchBB({city:'lon'});S.pops.lon.bb.d=0;compute()"); + assert.deepEqual(v6(ev), [['fra', COST.fra]]); + // A POP the intern is told to leave alone keeps its routers as they are. + ev("ACT.opsHire({id:'annie'});closeModal();S.ops.skip.fra=['std']"); + assert.deepEqual(v6(ev, 'bstdPlan(true)'), []); + assert.deepEqual(v6(ev), [['fra', COST.fra]], 'the button is not the intern'); + // The MCP tools: the target and the quote. + ev("S.popStd=null;apiRun('bstdSet',{k:'v6'})"); + assert.deepEqual(J(ev, 'S.popStd'), { rt: 1, v6: true }); + assert.equal(J(ev, "apiRun('bstdApply',{},{dryRun:true})").quote.setup, COST.fra); + assert.deepEqual(errors, []); +}); + +test('the button starts every swap it can pay in full, on top of what the swaps under way still owe', (t) => { + const { ev, dom, errors } = game(t); + std(ev, { v6: true }); + // Enough for Amsterdam and Paris, not for Frankfurt as well: the busiest first, then whatever still fits. + ev(`S.cash=${COST.ams + COST.fra - 1};ACT.bstdOpen()`); + const btn = dom.window.document.querySelector('#modalCard [data-act="bstdApply"]'); + assert.equal(btn.textContent, `Bring everything up now · ${ev(`fmt$(${COST.ams + COST.fra + COST.par})`)}`); + btn.click(); + assert.deepEqual(swapping(ev), ['ams', 'par']); + assert.equal(ev('S.cash'), COST.ams + COST.fra - 1, 'nothing paid yet: the routers are paid as they go in'); + assert.equal(ev('ip6Owed()'), COST.ams + COST.par); + const said = `2 jobs done for the build standard, ${ev(`fmt$(${COST.ams + COST.par})`)}.`; + assert.ok(dom.window.document.getElementById('toasts').textContent.includes(said), 'the toast counts the swaps whole, as the quote did'); + // Day by day the swaps pay what the button counted, and Frankfurt waits for the money. + ev('for(let i=0;i<60;i++){S.day++;ip4Day(S.day);}compute()'); + assert.deepEqual(J(ev, "['ams','par'].map(c=>S.pops[c].bb.v6)"), [1, 1]); + assert.ok(Math.abs(ev('S.cash') - (COST.fra - 1 - COST.par)) < 1e-6, 'the swaps cost what the button counted: ' + ev('S.cash')); + assert.deepEqual(v6(ev), [['fra', COST.fra]]); + assert.deepEqual(errors, []); +}); + +test("the intern rolls it out within the order's budget and the cash floor, and the shift log names the cities", (t) => { + const { ev, errors } = game(t); + std(ev, { v6: true }); + ev("ACT.opsHire({id:'annie'});closeModal();S.ops.on.std=true;S.ops.floor=0;S.ops.cap.std=OPS_CAPS[0]"); + // A $10k month: Amsterdam's $12k swap never fits it; Frankfurt and Paris do. + const c0 = ev('S.cash'); + ev('opsDay(S.day)'); + assert.deepEqual(swapping(ev), ['fra', 'par']); + assert.equal(ev('S.ops.spent.std'), COST.fra + COST.par, 'the whole swaps count against the month'); + assert.equal(ev('S.cash'), c0, 'and are paid as the routers go in'); + const e = J(ev, 'S.ops.log[0]'); + assert.equal(e.up, undefined, 'nothing paid up front'); + assert.ok(e.r.some(x => x[0] === 'broke'), 'Amsterdam waits for the budget'); + assert.match(ev('opsLine(S.ops.log[0])'), /did 2 jobs for the build standard \(Frankfurt IPv6, Paris IPv6\)/); + assert.equal(ev('S.ops.log[0].r.find(x=>x[0]===\'std\')[2].every(opsWhereOk)'), true, 'the log survives a save'); + // No budget, a $50k floor and $15k above it: Amsterdam starts; Frankfurt does not fit on top of what Amsterdam owes, + // Paris does. + ev("for(const c of ['fra','par']){delete S.pops[c].bb.v6e;delete S.pops[c].bb.v6;}S.ops.cap.std=0;S.ops.floor=50000;S.cash=50000+15000;S.day++;compute();opsDay(S.day)"); + assert.deepEqual(swapping(ev), ['ams', 'par']); + assert.equal(ev('S.cash'), 65000); + // Paid down, the next shift starts Frankfurt. + ev('for(let i=0;i<60;i++){S.day++;ip4Day(S.day);}S.cash=1e6;compute();opsDay(S.day)'); + assert.deepEqual(swapping(ev), ['fra']); + assert.deepEqual(errors, []); +}); + +// Only Amsterdam has homes to swap: one $12k swap. A quiet lite fiber Frankfurt–Paris for the line-system target. +const AMS_ONLY = "S.pops.fra.bb.d=0;S.pops.par.bb.d=0;compute()"; +const FIBER = "S.links.push({id:'q',a:'fra',b:'par',kind:'df',own:false,sys:'lite',ch:[],km:Math.round(kmBetween('fra','par')),sub:false,cable:null,mo:1000,trench:'q',cut:0,day:0,ready:0,spares:false});compute()"; + +test("what a swap still owes stays above the intern's cash floor for every job after it, in every order", (t) => { + const { ev, errors } = game(t); + ev(AMS_ONLY); + ev("ACT.opsHire({id:'annie'});closeModal();for(const k in S.ops.on)S.ops.on[k]=false;S.ops.on.std=true;S.ops.floor=50000;S.ops.cap.std=1e6"); + std(ev, { v6: true }); + ev(`S.cash=50000+${COST.ams}+500;opsDay(S.day)`); + assert.deepEqual(swapping(ev), ['ams']); + assert.equal(ev('ip6Owed()'), COST.ams); + // The next day the standard wants a generator at every POP too. The cash above the floor covers one only with the + // swap's money: it waits. + assert.equal(ev('GEN_COST'), 12000); + std(ev, { v6: true, gen: true }); + ev('S.day++;compute();opsDay(S.day)'); + assert.deepEqual(J(ev, 'Object.keys(S.pops).filter(c=>S.pops[c].gen)'), []); + assert.deepEqual(J(ev, 'S.ops.log[0].r'), [['broke', 1, ['std']]]); + // With no income at all, the swap then pays its routers day by day and never takes the cash under the floor. + const low = ev('(()=>{let m=S.cash;for(let i=0;i<60;i++){S.day++;ip6Day(S.day);m=Math.min(m,S.cash);}return m;})()'); + assert.equal(ev('S.pops.ams.bb.v6'), 1); + assert.ok(low >= 50000 - 1e-6, 'the floor held: ' + low); + // A swap started by hand is owed too, and every order keeps it aside: the routers order here. + ev("S.pops.ams.bb.d=600;delete S.pops.ams.bb.v6;compute();ACT.ip6Go({city:'ams'})"); + assert.equal(ev('!!S.pops.ams.bb.v6e'), true); + const owed = ev('ip6Owed()'); + assert.ok(owed > 0); + assert.deepEqual(J(ev, `(()=>{const r=[];for(const d of [-1,0]){S.cash=50000+1000+${owed}+d;r.push(opsShift().can('routers',1000));}return r;})()`), [false, true]); + assert.deepEqual(errors, []); +}); + +test('the button keeps what a swap it just started owes for the jobs after it in the same click', (t) => { + const { ev, dom, errors } = game(t); + ev(AMS_ONLY); + ev(FIBER); + std(ev, { v6: true, sys: 'roadm' }); + const plan = J(ev, 'bstdPlan(false).map(j=>[j.k,j.w,j.cost])'); + assert.deepEqual(plan.map((j) => j.slice(0, 2)), [['v6', 'ams IPv6'], ['sys', 'fra|par']], 'the swap first, then the fiber'); + const sys = plan[1][2]; + // A dollar short of both: the swap starts, and the fiber waits rather than spend the swap's routers. + ev(`S.cash=${COST.ams + sys - 1};ACT.bstdApply({})`); + assert.deepEqual(swapping(ev), ['ams']); + assert.equal(ev("S.links.find(l=>l.id==='q').sys"), 'lite'); + assert.equal(ev('S.cash'), COST.ams + sys - 1); + assert.ok(dom.window.document.getElementById('toasts').textContent.includes(`One job done for the build standard, ${ev(`fmt$(${COST.ams})`)}. One thing is still below it`), "the toast: the swap, and the fiber still below the standard"); + // A dollar more, and the next tap swaps the fiber with the swap's routers still in hand. + ev('S.cash+=1;ACT.bstdApply({})'); + assert.equal(ev("S.links.find(l=>l.id==='q').sys"), 'roadm'); + assert.equal(ev('S.cash'), COST.ams); + assert.equal(ev('ip6Owed()'), COST.ams); + assert.deepEqual(errors, []); +}); + +test('only while IPv4 is scarce: no row, no jobs and no count in the gentler rules; saves keep the target', (t) => { + const { ev, dom, errors } = game(t); + std(ev, { v6: true }); + ev("S.rules=makeRules('freeze');compute()"); + assert.equal(ev('ip4On()'), false); + assert.deepEqual(v6(ev), []); + assert.equal(ev('bstdLine(bstd())'), 'None'); + ev('ACT.bstdOpen()'); + const sel = [...dom.window.document.querySelectorAll('#modalCard select[data-chg="bstdSet"]')].map(s => JSON.parse(s.dataset.args).k); + assert.ok(sel.length > 0 && !sel.includes('v6'), 'no IPv6-only list'); + assert.doesNotMatch(dom.window.document.getElementById('modalCard').textContent, /IPv6/); + // The target stays in the standard: back on scarce IPv4 it is there again. + ev("closeModal();S.rules=makeRules('oncall');compute()"); + assert.deepEqual(v6(ev).map(x => x[0]), ['ams', 'fra', 'par']); + // Saves: the target round-trips; an old standard has none; junk is no target. + const rt = d => J(ev, `(()=>{const s={popStd:${lit(d)}};popStdSanitize(s);return s.popStd;})()`); + assert.deepEqual(rt({ rt: 1, v6: true }), { rt: 1, v6: true }); + assert.deepEqual(rt({ g: 1, rt: 2 }), { g: 1, rt: 2 }); + assert.equal(rt({ rt: 1, v6: 'yes' }), null); + assert.deepEqual(J(ev, 'migrate(JSON.parse(JSON.stringify(S))).popStd'), { rt: 1, v6: true }); + assert.deepEqual(errors, []); +}); + +test('the sheet at 360 px, portrait and landscape, in every language: the row, its note and what is below it', () => { + for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) { + const { ev, dom, errors } = load(lang === 'en' ? {} : { lang }); + ev(BASE); + const doc = dom.window.document; + for (const [w, hgt] of [[360, 740], [740, 360]]) { + ev(`window.innerWidth=${w};window.innerHeight=${hgt};S.popStd=null;closeModal();ACT.bstdOpen()`); + assert.equal(ev('isPhone()'), true, lang); + const sel = () => [...doc.querySelectorAll('#modalCard select[data-chg="bstdSet"]')].find(s => JSON.parse(s.dataset.args).k === 'v6'); + let s = sel(); + assert.ok(s && s.closest('.ops-sel'), lang + ': two to a row with the other POP targets'); + s.value = String(s.options.length - 1); + s.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + assert.equal(ev('bstd().v6'), true, lang); + assert.ok(ev('bstdShown()'), lang); + s = sel(); + assert.equal(s.options[s.selectedIndex].textContent, ev("tr('bstd.every_bb_city')"), lang); + const txt = doc.getElementById('modalCard').textContent; + assert.ok(txt.includes(ev("tr('bstd.v6_note')")), lang + ': the note'); + assert.ok(txt.includes(ev(`fmt$(${COST.ams + COST.fra + COST.par})`)), lang + ': the bill'); + assert.doesNotMatch(txt, /\b(bstd|ops|pop_std|common|ip6)\.[a-z_0-9]+/, lang + ': a raw label'); + assert.doesNotMatch(txt, /\{[a-z]\w*\}|undefined|NaN/, lang); + for (const b of doc.querySelectorAll('#modalCard button.b')) assert.ok(b.closest('.btns') || b.closest('.ops-h'), lang + ': ' + b.textContent); + } + // The city panel's line counts it. + ev("closeModal();selectCity('fra');ACT.tab({t:'links'})"); + assert.ok(doc.getElementById('panelBody').textContent.includes(ev("trn('bstd.n_more_targets',1)")), lang); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); diff --git a/tests/bstd-owner.test.js b/tests/bstd-owner.test.js new file mode 100644 index 0000000..e4612ba --- /dev/null +++ b/tests/bstd-owner.test.js @@ -0,0 +1,276 @@ +// One owner per fiber: the build standard's order (std) and the optical order (optup) take fibers dark with the same +// test (a routing without the fiber, in the route worker in play), share one budget of dark swaps a night, and never both +// work on one fiber in a shift; the decom order leaves a wave the standard just upgraded. Change Freeze, no failures. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +// Frankfurt (broadband, 100G Cogentle transit), Amsterdam and Paris with broadband, everyone on four Chonk 800s, level 7. +const BASE = "Date.now=()=>1.7e12;ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=7;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');" + + "ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});for(const c of ['ams','par','lon'])ACT.buildPop({city:c});" + + "for(const c of ['fra','ams','par','lon']){S.pops[c].rgen=RG.findIndex(r=>r.n==='Chonk 800');S.pops[c].routers=4;}ACT.launchBB({city:'ams'});ACT.launchBB({city:'par'});compute()"; +function game(t, extra = '', opts = {}) { + const h = load(opts); + t.after(() => h.dom.window.close()); + h.ev(BASE); + if (extra) h.ev(extra); + return h; +} +const hire = (ev, id) => ev(`ACT.opsHire({id:'${id}'});S.ops.floor=0;S.ops.cap={std:0,optup:0};S.ops.on.std=true;closeModal()`); +const std = (ev, d) => ev(`S.popStd=bstdPut({...bstd(),...${lit(d)}})`); +// A leased dark fiber, built and lit with these optics; a wave. +const fiber = (ev, a, b, ch, sys = 'lite') => ev(`(()=>{const id=uid();S.links.push({id,a:'${a}',b:'${b}',kind:'df',own:false,sys:'${sys}',ch:${lit(ch)},km:Math.round(kmBetween('${a}','${b}')),sub:false,cable:null,mo:1000,trench:id,cut:0,day:S.day,ready:S.day,spares:false});return id;})()`); +const wave = (ev, a, b, tier) => ev(`(()=>{const id=uid();S.links.push({id,a:'${a}',b:'${b}',kind:'wave',tier:${tier},km:Math.round(kmBetween('${a}','${b}')),cut:0,mo:1,trench:id,day:S.day});return id;})()`); +const L = (ev, id) => JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(id)})||null)`)); +const said = ev => JSON.parse(ev('JSON.stringify((S.ops.log[0]&&S.ops.log[0].d===S.day?S.ops.log[0].r:[]).map(x=>[x[0],x[1]]))')); +// Count the fiber tests that route (opsDarkTrial()), on the page here: tests never use the worker. +const COUNT = "window.__tr=0;const _t=opsDarkTrial;opsDarkTrial=function(){__tr++;return _t.apply(this,arguments);};"; + +test('both orders share one budget of dark swaps a night: one for Annie, two for Kevin, whoever does them', t => { + for (const [id, want] of [['annie', 1], ['kevin', 2]]) { + // Nobody on the far ends: the fibers really are quiet, whenever the shift routes again. + const { ev, errors } = game(t, 'S.pops.ams.bb=null;S.pops.par.bb=null'); + const ids = ['ams', 'par', 'lon'].map(c => fiber(ev, 'fra', c, ['zr4', 'zr4'])); + ev('compute();for(const l of S.links)R.load[l.id]=0'); + hire(ev, id); + std(ev, { sys: 'roadm' }); + ev('S.ops.on.optup=true;opsDay(S.day)'); + assert.equal(ids.filter(x => L(ev, x).sys === 'roadm').length, want, id + ': fibers swapped tonight'); + assert.deepEqual(said(ev), [['std', want]], id + ': the build standard went first, the optical order found no room left'); + // Alone, the optical order has the same budget (the line system from the standard). + ev('S.ops.on.std=false;S.day+=2;compute();for(const l of S.links)R.load[l.id]=0;opsDay(S.day)'); + assert.equal(ids.filter(x => L(ev, x).sys === 'roadm').length, Math.min(3, 2 * want), id); + assert.deepEqual(said(ev), [['optup', Math.min(want, 3 - want)]]); + assert.deepEqual(errors, []); + } +}); + +test('a fiber the build standard worked on tonight is its own: the optical order takes it the next night', t => { + // A full Rainbow-in-a-Box fiber to Amsterdam, running hot, and a big wave beside it for the day it goes dark. + const { ev, errors } = game(t); + const f = fiber(ev, 'fra', 'ams', Array(16).fill('zr4')); + wave(ev, 'fra', 'ams', 3); + const hot = `compute();R.load[${lit(f)}]=1e5;`; + hire(ev, 'annie'); + std(ev, { opt: 'fast' }); + ev(`S.ops.on.optup=true;${hot}opsDay(S.day)`); + assert.deepEqual([L(ev, f).sys, [...new Set(L(ev, f).ch)]], ['lite', ['zr8']], 'the standard swapped its optics; its line system stays tonight'); + assert.deepEqual(said(ev), [['std', 1]], 'the optical order left it alone'); + ev(`S.day++;${hot}opsDay(S.day)`); + assert.equal(L(ev, f).sys, 'roadm', 'the next night, with nothing left for the standard there, the optical order moves it up'); + assert.deepEqual(said(ev), [['optup', 1]]); + assert.deepEqual(errors, []); +}); + +test("the standard's order takes a fiber dark on the optical order's test: a way around, not just a parallel link, and never a little traffic with none", t => { + // Amsterdam's broadband rides Frankfurt–Amsterdam; Paris closes a ring of fibers with room. + const { ev, errors } = game(t); + const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'ams', 'par', ['zr4', 'zr4']), c = fiber(ev, 'par', 'fra', ['zr4', 'zr4']); + ev(COUNT); + hire(ev, 'annie'); + std(ev, { sys: 'roadm' }); + // Busy by the plan's own measure, and nothing parallel: the button waits for it, the intern routes and finds the ring. + const busy = `compute();R.load[${lit(a)}]=capOf(S.links.find(l=>l.id===${lit(a)}))*0.9;`; + ev(busy); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(false).held)')), ['fra|ams'], 'the button: busy, nothing parallel'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(true).held)')), [], 'the intern: a routing decides'); + const served = ev('R.served'); + ev('opsDay(S.day)'); + assert.equal(ev('__tr'), 1, 'one routing without the fiber'); + assert.deepEqual([L(ev, a).sys, L(ev, b).sys, L(ev, c).sys], ['roadm', 'lite', 'lite'], 'the busy one first, one a night'); + ev('compute()'); + assert.ok(ev('R.served') >= served - 1e-6, 'and every gigabit still gets through, round the ring'); + // A little traffic (well under the plan's "quiet") and no way around: the old test let it go dark; this one never. + const g = game(t); + const x = fiber(g.ev, 'fra', 'ams', ['zr4', 'zr4']); + g.ev('compute()'); + assert.ok(g.ev(`R.load[${lit(x)}]`) > 1 && !g.ev(`bstdBusy(S.links.find(l=>l.id===${lit(x)}))`), 'Amsterdam\'s broadband, under 10% of the fiber'); + hire(g.ev, 'kevin'); + std(g.ev, { sys: 'roadm', opt: 'fast' }); + g.ev(COUNT + 'opsDay(S.day)'); + assert.deepEqual([L(g.ev, x).sys, L(g.ev, x).eqDown], ['lite', undefined], 'Amsterdam is never cut off for a day'); + assert.deepEqual(L(g.ev, x).ch, ['zr8', 'zr8'], 'it gets the fastest optics its line system takes'); + assert.equal(g.ev('__tr'), 0, 'known without routing'); + assert.deepEqual(errors, []); + assert.deepEqual(g.errors, []); +}); + +test('with two swaps a night, the second fiber is judged on the routing with the first one dark, not on the loads from before', t => { + // The ring again, Kevin on shift. Once Frankfurt–Amsterdam is dark, Amsterdam's traffic rides Amsterdam–Paris, which + // carried nothing before: its "nothing rides it" is asked again after the shift routes, and is no longer true. + const { ev, errors } = game(t); + const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'ams', 'par', ['zr4', 'zr4']), c = fiber(ev, 'par', 'fra', ['zr4', 'zr4']); + hire(ev, 'kevin'); + std(ev, { sys: 'roadm' }); + ev(`compute();R.load[${lit(a)}]=capOf(S.links.find(l=>l.id===${lit(a)}))*0.9;`); + assert.equal(ev(`R.load[${lit(b)}]||0`), 0, 'Amsterdam–Paris is idle today'); + const served = ev('R.served'); + ev('opsDay(S.day)'); + assert.deepEqual([L(ev, a).sys, L(ev, b).sys, L(ev, c).sys], ['roadm', 'lite', 'lite'], 'Amsterdam keeps one way in'); + ev('compute()'); + assert.ok(ev('R.served') >= served - 1e-6, 'and every gigabit still gets through'); + assert.deepEqual(errors, []); +}); + +test('two busy fibers side by side: one goes dark tonight, its twin carries it, and the twin goes the next night', t => { + // Amsterdam's broadband split over two Frankfurt–Amsterdam fibers, a few gigabits each: busy, though under the + // button's "quiet". Kevin has room for two swaps, but the twin waits rather than fail the test and wait a week. + const { ev, errors } = game(t); + const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']); + hire(ev, 'kevin'); + std(ev, { sys: 'roadm' }); + ev('compute()'); + assert.ok(ev(`R.load[${lit(a)}]`) > 1 && ev(`R.load[${lit(b)}]`) > 1, 'both carry Amsterdam'); + ev('opsDay(S.day)'); + assert.deepEqual([[L(ev, a).sys, L(ev, b).sys].sort(), ev('OPTUP_NO.size')], [['lite', 'roadm'], 0], 'one tonight, and no fiber failed'); + ev('S.day++;compute();opsDay(S.day)'); + assert.deepEqual([L(ev, a).sys, L(ev, b).sys], ['roadm', 'roadm'], 'the twin the next night'); + assert.deepEqual(errors, []); +}); + +test('a fiber that fails the test waits a week, for both orders, and gets the optics its line system takes meanwhile', t => { + // The ring back from Amsterdam is two 10G waves: too thin for Amsterdam's broadband. + const { ev, errors } = game(t); + const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']); + wave(ev, 'ams', 'par', 0); wave(ev, 'par', 'fra', 0); + ev('compute()'); + assert.ok(ev(`R.load[${lit(a)}]`) > 10, 'more than the ring carries'); + ev(COUNT); + hire(ev, 'annie'); + std(ev, { sys: 'roadm', opt: 'fast' }); + ev('S.ops.on.optup=true;opsDay(S.day)'); + assert.equal(ev('__tr'), 1, 'tested once'); + assert.deepEqual([L(ev, a).sys, L(ev, a).ch], ['lite', ['zr4', 'zr4']], 'no swap, and no optics for a line system it did not get'); + assert.equal(ev(`OPTUP_NO.get(${lit(a)})`), ev('S.day+OPTUP_WAIT')); + for (let d = 1; d < 7; d++) ev('S.day++;compute();opsDay(S.day)'); + assert.equal(ev('__tr'), 1, 'not tested again that week, by either order'); + assert.deepEqual([L(ev, a).sys, L(ev, a).ch], ['lite', ['zr8', 'zr8']], 'the fastest optics the old line system takes'); + assert.deepEqual(errors, []); +}); + +test('an express riding the fiber goes dark with it in the test: its traffic has to get around too', t => { + // Frankfurt–Brussels–Paris as an express over two bare ROADM fibers; Paris reaches its transit over it. + const { ev, errors } = game(t, "ACT.buildPop({city:'bru'});S.pops.bru.rgen=S.pops.fra.rgen;S.lvl=8;" + + "window.df=(a,b)=>{const id=uid();S.links.push({id,a,b,kind:'df',own:true,sys:'roadm',ch:[],km:kmBetween(a,b),sub:false,cable:null,mo:100,trench:id,cut:0,day:S.day,ready:S.day,spares:false,pairs:1});return id;};" + + "window.s1=df('fra','bru');window.s2=df('bru','par');compute();ACT.xpBuild({a:'fra',b:'par',via:s1+','+s2,o:'zr4'});window.x=S.links.find(l=>l.kind==='xp').id;compute()"); + const [s1, s2, x] = ['s1', 's2', 'x'].map(k => ev(k)); + assert.ok(ev('R.load[x]') > 1 && !ev('(R.load[s1]||0)+(R.load[s2]||0)'), 'the express carries Paris; the fibers carry nothing of their own'); + ev(COUNT + "window.__xd=[];const _c=compute;compute=function(){if(S.links.find(l=>l.id===s1).eqDown>S.day||S.links.find(l=>l.id===s2).eqDown>S.day)__xd.push(xpDown(S.links.find(l=>l.id===x)));return _c.apply(this,arguments);}"); + hire(ev, 'annie'); + std(ev, { sys: 'cl' }); + const sys = () => [L(ev, s1).sys, L(ev, s2).sys]; + // No way around either fiber: known without routing. + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(true).held)')).sort(), ['bru|par', 'fra|bru']); + ev('opsDay(S.day)'); + assert.deepEqual([sys(), ev('__tr')], [['roadm', 'roadm'], 0]); + // A wave beside the first fiber: it has a way around now, but Paris has none without the express. + wave(ev, 'fra', 'bru', 1); + ev('S.day++;compute();opsDay(S.day)'); + assert.equal(ev('__tr'), 1, 'one routing without the fiber'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(__xd)')), [true], 'the express was dark in it'); + assert.deepEqual(sys(), ['roadm', 'roadm'], 'Paris would be cut off: no swap'); + // A wave to Paris carries it round: the swap goes ahead, with the express dark for the day. + wave(ev, 'fra', 'par', 3); + ev('OPTUP_NO.clear();S.day++;compute();opsDay(S.day)'); + assert.deepEqual(sys().sort(), ['cl', 'roadm'], 'one of them, one a night'); + assert.equal(ev('xpDown(S.links.find(l=>l.id===x))'), true); + ev('compute()'); + assert.ok(ev('R.load[x]||0') === 0 && ev('R.served') > 0); + assert.deepEqual(errors, []); +}); + +test('the decom order never hands back a wave the build standard upgraded that same shift', t => { + const { ev, errors } = game(t); + // A 800G wave and two 100G waves between Frankfurt and Amsterdam, in three trenches. + const big = wave(ev, 'fra', 'ams', 3), w1 = wave(ev, 'fra', 'ams', 1), w2 = wave(ev, 'fra', 'ams', 1); + hire(ev, 'annie'); + ev("S.ops.on.decom=true;S.ops.p.decom={keep:false}"); + std(ev, { wv: 2 }); + // The plan sees a pair that needs all three once the small ones are 400G; the routing after the shift's jobs, which + // decom reads, sees almost nothing on them. + ev(`compute();R.load[${lit(big)}]=700;R.load[${lit(w1)}]=150;R.load[${lit(w2)}]=150`); + assert.equal(ev('bstdQuote(true).n'), 2, 'both small waves go up'); + ev('opsDay(S.day)'); + const tiers = () => JSON.parse(ev("JSON.stringify(S.links.filter(l=>l.kind==='wave').map(l=>l.tier))")); + assert.deepEqual(tiers(), [3, 2, 2], 'both upgraded, both kept today'); + assert.deepEqual(said(ev), [['std', 2]]); + // Tomorrow they are the decom order's to judge again. + ev('S.day++;compute();opsDay(S.day)'); + assert.deepEqual(tiers(), [3]); + assert.deepEqual(said(ev), [['decom', 2]]); + assert.deepEqual(errors, []); +}); + +// In play the test is routed in the route worker. jsdom has no Worker: a second page plays it (rwServe() there), as in +// tests/day-steps.test.js. The day is the day dayTick() plays, and the page itself never routes. +test("in play, the standard's fiber test is routed by the route worker, and the day is the day dayTick() plays", t => { + // The ring of fibers, Amsterdam's and Paris's broadband on it. + const RING = "for(const [a,b] of [['fra','ams'],['ams','par'],['par','fra']]){const id=uid();S.links.push({id,a,b,kind:'df',own:false,sys:'lite',ch:['zr4','zr4'],km:Math.round(kmBetween(a,b)),sub:false,cable:null,mo:1000,trench:id,cut:0,day:S.day,ready:S.day,spares:false});}compute();" + + "ACT.opsHire({id:'annie'});S.ops.floor=0;S.ops.cap={};S.ops.on.std=true;closeModal();S.popStd=bstdPut({...bstd(),sys:'roadm'});__reseed(4242);"; + const open = seed => { const h = load({ seed }); t.after(() => h.dom.window.close()); h.dom.window.structuredClone = globalThis.structuredClone; return h; }; + const ref = open(777), page = open(777), wk = open(1); + for (const h of [ref, page]) { h.ev(BASE); h.ev(RING); } + page.ev('window.__q=[];window.__later=[];RW.budget=0;RW.later=f=>__later.push(f);rwOn=()=>!RW.dead;rwStart=()=>RW.w||(RW.w={postMessage:m=>__q.push(structuredClone(m)),terminate(){__q.length=0;}});'); + page.ev('window.__pc=0;const _c=compute;compute=function(){__pc++;return _c.apply(this,arguments);};'); + wk.ev('window.__out=null;window.postMessage=(m,tr)=>{__out=structuredClone(m,{transfer:tr});};'); + let trials = 0; + const pump = () => { for (;;) { + if (page.ev('__later.length')) { page.ev('__later.shift()()'); continue; } + if (!page.ev('__q.length')) break; + if (page.ev('!!(__q[0].trial&&__q[0].trial.dark)')) trials++; + wk.dom.window.__m = page.ev('__q.shift()'); wk.ev('rwServe(__m)'); page.dom.window.__a = wk.ev('__out'); page.ev('rwDone(__a)'); } }; + ref.ev('dayTick()'); + page.ev('rwDay()'); pump(); + assert.equal(trials, 1, 'the fiber test went to the worker'); + assert.equal(page.ev('__pc'), 0, 'no routing on the page'); + assert.equal(page.ev("S.links.filter(l=>l.sys==='roadm').length"), 1, 'and it passed: the rest of the ring carries its traffic'); + const STATE = 'JSON.stringify({S,served:R.served,load:R.load})'; + assert.equal(page.ev(STATE), ref.ev(STATE), 'the same day as dayTick()'); + assert.deepEqual([...ref.errors, ...page.errors, ...wk.errors], []); +}); + +// In play the shift rests between the standard's jobs (DAY_REST, rwRest()), and the player can tap meanwhile: every job +// is checked again against the game as it is then, not as the plan found it at the start of the shift. +test('the player acts while the shift rests: nothing past the standard, nothing paid twice, nothing claimed, and no snag for a POP gone', t => { + // Every POP on one router. std: the standard; act: what the player does at the first rest after a job of the shift. + const play = (std, act, setup = '') => { + const { ev, errors } = game(t, "for(const c of ['fra','ams','par','lon'])S.pops[c].routers=1;compute()"); + hire(ev, 'annie'); + ev(`S.popStd=${std};${setup};window.__later=[];RW.budget=0;RW.later=f=>__later.push(f)`); + ev('rwDay()'); + let spent = null; + while (ev('__later.length')) { + if (spent === null && ev('S.ops.spent.std>0')) { spent = ev('S.ops.spent.std'); ev(act); } + ev('__later.shift()()'); + } + assert.ok(spent > 0, 'the shift rested after a job'); + return { ev, errors, spent }; + }; + const routers = ev => JSON.parse(ev('JSON.stringify(Object.fromEntries(Object.entries(S.pops).map(([c,p])=>[c,p.routers])))')); + // The button brings every POP up to the standard while the shift rests after its first job. + let { ev, errors, spent } = play('{rt:3}', 'ACT.bstdApply()'); + assert.deepEqual(routers(ev), { fra: 3, ams: 3, par: 3, lon: 3 }, 'three routers each, as the standard says'); + assert.equal(ev('S.ops.spent.std'), spent, 'the shift paid for nothing after the button'); + assert.deepEqual(said(ev), [['std', 1]]); + assert.deepEqual(errors, []); + // The same with a model: the swaps the button did are not the shift's. + ({ ev, errors, spent } = play("{g:RG.findIndex(r=>r.n==='Absolute Unit 1.6T'),rt:2}", 'ACT.bstdApply()', "for(const c in S.pops)S.pops[c].routers=2")); + assert.deepEqual(JSON.parse(ev('JSON.stringify([...new Set(Object.values(S.pops).map(p=>RG[p.rgen].n))])')), ['Absolute Unit 1.6T']); + assert.equal(ev('S.ops.spent.std'), spent); + assert.deepEqual(said(ev), [['std', 1]], 'one swap, not four'); + assert.deepEqual(errors, []); + // A PNI the player orders by hand meanwhile, smaller than the plan's: the shift does not order it again as an upgrade. + const net = "NETS.find(n=>n.pops.includes('fra')&&n.pops.includes('ams')&&pniMin(n.id)===0&&peerOk(n.id,'pni','ams').ok&&peerOk(n.id,'pni','fra').ok).id"; + ({ ev, errors, spent } = play('{rt:2,pni:2}', `pniPlace(pniQuote('ams',${net},0))`, + `S.rules.pnis='instant';window.__net=${net};S.pni.push({id:'P1',city:'fra',net:__net,tier:1,ready:S.day});compute();const _v=pniVal;pniVal=(id,c)=>id===__net&&c==='ams'?{..._v(id,c),worth:true,want:40,tier:1}:_v(id,c)`)); + assert.deepEqual(JSON.parse(ev("JSON.stringify(S.pni.filter(x=>x.city==='ams').map(x=>[x.tier,!!x.up]))")), [[0, false]], 'the player\'s own, as ordered'); + assert.deepEqual(said(ev), [['std', 4]], 'the routers only'); + assert.deepEqual(errors, []); + // Amsterdam decommissioned meanwhile: its jobs are left out, the order runs on, the other POPs get theirs. + ({ ev, errors } = play('{rt:3}', "decommission(['ams'])")); + assert.equal(ev('S.ops.on.std'), true, 'the order is still on'); + assert.deepEqual(said(ev), [['std', 6]], 'no snag'); + assert.deepEqual(routers(ev), { fra: 3, par: 3, lon: 3 }); + assert.deepEqual(errors, []); +}); diff --git a/tests/build-standard.test.js b/tests/build-standard.test.js new file mode 100644 index 0000000..eda6f57 --- /dev/null +++ b/tests/build-standard.test.js @@ -0,0 +1,565 @@ +// The build standard: one target state for every POP, port and fiber, set in its own sheet, applied to new POPs at +// once, brought up by the intern's "Keep to the build standard" order or in one tap, and priced before anything changes. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { load } = require('./harness'); +const { lit } = require('../scripts/lib/js-literal'); + +// Frankfurt (one Edge Lord, broadband, 100G Cogentle transit) and Amsterdam (one router, nothing on it yet), level 7, +// PNIs up the moment they are ordered and Change Freeze (no fat fingers, no dice). +const BASE = "ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=7;S.nextFail=S.nextEvent=1e9;UI.speed=0;S.rules=makeRules('freeze');S.rules.pnis='instant';" + + "ACT.launchBB({city:'fra'});S.pops.fra.rgen=1;ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});compute()"; +const AU = "RG.findIndex(r=>r.n==='Absolute Unit 3.2T')"; +// Kevin by default; a fiber test that counts swaps a night hires Annie (Kevin does two: tests/bstd-owner.test.js). +const hire = (ev, id = 'kevin') => ev(`ACT.opsHire({id:'${id}'});S.ops.floor=0;S.ops.cap.std=0;S.ops.on.std=true;closeModal()`); +const shift = ev => ev('opsDay(S.day)'); +function game(t, extra = '') { + const h = load(); + t.after(() => h.dom.window.close()); + h.ev(BASE); + if (extra) h.ev(extra); + return h; +} +const pop = (ev, c) => JSON.parse(ev(`JSON.stringify(S.pops.${c})`)); +const std = (ev, d) => ev(`S.popStd=${lit(d)}`); +// A leased dark fiber between two POPs, built and lit with these optics. +const fiber = (ev, a, b, ch, sys = 'lite') => ev(`(()=>{const id=uid();S.links.push({id,a:'${a}',b:'${b}',kind:'df',own:false,sys:'${sys}',ch:${lit(ch)},km:Math.round(kmBetween('${a}','${b}')),sub:false,cable:null,mo:1000,trench:id,cut:0,day:S.day,ready:S.day,spares:false});return id;})()`); + +test('the POP part: model, routers, second building and generator, the busiest POP first, at exactly what the plan priced', t => { + const { ev, errors } = game(t); + hire(ev); + std(ev, { g: ev(AU), rt: 2, site2: true, gen: true }); + const q = JSON.parse(ev('JSON.stringify(bstdQuote(true))')), c0 = ev('S.cash'); + assert.equal(q.pops, 2); + shift(ev); + for (const c of ['fra', 'ams']) { + const p = pop(ev, c); + assert.deepEqual([p.rgen, p.routers, !!p.site2, !!p.gen], [ev(AU), 2, true, true], c); + } + assert.equal(c0 - ev('S.cash'), q.cost, 'the shift paid what the plan said'); + // Frankfurt has one router carrying broadband: a second went in first, so the swap rolled through. + assert.equal(ev("S.inc.some(i=>i.type==='maint')"), false, 'no maintenance window'); + assert.match(ev('opsLine(S.ops.log[0])'), /build standard/); + assert.match(ev('opsLine(S.ops.log[0])'), /Frankfurt/); + assert.equal(ev('opsWhereOk(S.ops.log[0].r[0][2][0])'), true, 'the log survives a save'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdPlan(true))')), [], 'nothing left to do'); + // Its monthly books include the building and the generator now. + ev('compute()'); + assert.equal(ev('opsMoNow()') > ev('2*(SITE2_MO+GEN_MO)'), true); + assert.deepEqual(errors, []); +}); + +test('a busy POP with one router never gets a maintenance window; never a step down; the core keeps its routers', t => { + const { ev, errors } = game(t); + hire(ev); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + // A small budget: only the extra router fits this month, so the swap waits for it (and never goes ahead alone). + std(ev, { g: chonk, rt: 1 }); + ev(`S.ops.cap.std=OPS_CAPS.find(c=>c>=routerCost(1,1)&&cx[0]==='broke')"), 'the log says the budget ran out'); + ev('{const m0=monthIdx(S.day);while(monthIdx(S.day)===m0)S.day++;}S.ops.cap.std=0;compute();opsDay(S.day)'); + assert.deepEqual([pop(ev, 'fra').routers, pop(ev, 'fra').rgen], [2, chonk], 'then the swap rolls through'); + assert.equal(ev("S.inc.some(i=>i.type==='maint')"), false); + // A smaller model as the standard: nobody is swapped back. + std(ev, { g: 1, rt: 1 }); + ev('S.day++;compute();opsDay(S.day)'); + assert.equal(pop(ev, 'fra').rgen, chonk); + // A POP in the backbone core is never swapped onto a model that cannot run it (the Whitebox 64 has no label stack for + // RSVP-TE): the best main-line model no bigger than it that can, instead. + const sonic = ev("RG.findIndex(r=>r.n==='Sonic the Whitebox 64')"); + ev(`S.pops.ams.rgen=RG.findIndex(r=>r.n==='Arrrhipster 7280R');S.pops.ams.routers=2`); + std(ev, { g: sonic, rt: 1 }); + assert.equal(ev("bstdModel(S.popStd.g,'ams')"), sonic, 'a plain IGP backbone takes any model'); + ev('S.core={lv:2,run:2}'); + assert.ok(ev("inCore('ams')")); + assert.equal(ev("bstdModel(S.popStd.g,'ams')"), chonk, 'RSVP-TE in the core: the Chonk 800 instead'); + assert.deepEqual(errors, []); +}); + +test('budget, cash floor, per-POP exceptions; without an intern nothing runs and no dice are rolled', t => { + const { ev, errors } = game(t); + std(ev, { rt: 2, gen: true }); + ev('S.ops.on.std=true'); + const r = ev('window.__n=0;window.__r=Math.random;Math.random=()=>{__n++;return __r()};const s=JSON.stringify(S);opsDay(S.day);Math.random=__r;s===JSON.stringify(S)&&__n===0'); + assert.equal(r, true, 'no intern: nothing happens, nothing random'); + hire(ev); + // Amsterdam is excepted: the intern never touches it. + ev("S.ops.skip.ams=['std']"); + // The floor: only what leaves the floor clear. A generator is $12k, a router more. + ev('S.ops.floor=50000;S.cash=50000+GEN_COST+1'); + shift(ev); + assert.deepEqual([pop(ev, 'fra').gen, pop(ev, 'fra').routers], [true, 1], 'the generator fit above the floor, the router did not'); + assert.ok(ev('S.cash') >= 50000, 'never below the floor'); + assert.deepEqual([pop(ev, 'ams').gen, pop(ev, 'ams').routers], [false, 1], 'the excepted POP is untouched'); + assert.equal(ev("bstdQuote(true).pops"), 1, 'the intern\'s own view leaves the exception out'); + assert.equal(ev("bstdQuote(false).pops"), 2, 'the sheet still shows it below the standard'); + // A monthly cap of setup fees. + ev("S.cash=1e8;S.ops.floor=0;S.ops.cap.std=10000;S.day++;opsDay(S.day)"); + assert.equal(pop(ev, 'fra').routers, 1, 'a router is more than the budget'); + assert.deepEqual(errors, []); +}); + +test('the bank that forbids generators gets none; DE-KICKS is skipped; an exchange port where there is one', t => { + const { ev, dom, errors } = game(t); + hire(ev); + ev("S.loans.push({id:'L1',bank:'storm',amount:1e6,covs:['nogen'],apr:0.05,term:24,pay:0,start:S.day,left:24})"); + std(ev, { gen: true, ix: true }); + assert.equal(ev('popStdQuote()'), null, 'a new POP is not quoted a generator either'); + shift(ev); + assert.equal(pop(ev, 'fra').gen, false); + assert.equal(pop(ev, 'ams').gen, false); + assert.equal(ev("COVS.nogen.ok()"), true, 'the covenant holds'); + // Frankfurt's exchange is DE-KICKS: that wants a sales call (a quote window), so the intern leaves it alone. + assert.equal(ev('isDk("fra")'), true); + assert.equal(ev('S.ixp.fra'), undefined); + assert.equal(ev('!!(S.dk&&S.dk.q)'), false, 'no DE-KICKS quote was asked for'); + assert.equal(dom.window.document.getElementById('modal').hidden, true, 'and no window opened'); + assert.equal(ev('S.ixp.ams'), 0, 'Amsterdam gets a 10G port'); + ev('ACT.bstdApply()'); + assert.equal(pop(ev, 'fra').gen, false, 'the button respects the covenant too'); + assert.deepEqual(errors, []); +}); + +test('ports: LAG members up to the standard, split over both buildings; PNIs spread to more cities; never fewer members', t => { + const { ev, errors } = game(t); + hire(ev); + const net = ev("NETS.find(n=>n.pops.includes('fra')&&n.pops.includes('ams')&&pniMin(n.id)===0&&peerOk(n.id,'pni','ams').ok&&peerOk(n.id,'pni','fra').ok).id"); + ev(`S.pops.fra.site2=true;S.pni.push({id:'P1',city:'fra',net:${lit(net)},tier:1,ready:S.day});ACT.buyIx({city:'ams',tier:1});(S.ixn=S.ixn||{}).ams=4;compute()`); + // The PNI list says a second one in Amsterdam is worth it. + ev(`const _v=pniVal;pniVal=(id,c)=>id===${lit(net)}&&c==='ams'?{..._v(id,c),worth:true,want:40,tier:1}:_v(id,c)`); + std(ev, { lag: 2, split: true, pni: 2 }); + shift(ev); + const t0 = JSON.parse(ev('JSON.stringify(S.transit[0])')); + assert.deepEqual([t0.n, t0.site], [2, 'ab'], 'transit: a second member, split over both buildings'); + const p = JSON.parse(ev(`JSON.stringify(S.pni.find(x=>x.id==='P1'))`)); + assert.deepEqual([p.n, p.site], [2, 'ab'], 'the PNI too'); + assert.equal(ev('S.ixn.ams'), 4, 'a bigger LAG stays as it is'); + assert.equal(ev(`S.pni.filter(x=>x.net===${lit(net)}).length`), 2, 'a PNI in a second city'); + assert.ok(ev(`S.pni.some(x=>x.net===${lit(net)}&&x.city==='ams')`)); + assert.equal(ev("S.ixSite&&S.ixSite.ams"), undefined, 'Amsterdam has one building: nothing to split'); + assert.deepEqual(errors, []); +}); + +test('fiber: the line system only on a quiet fiber or with a way around, one a shift; faster optics, old ones on the shelf; bigger waves', t => { + const { ev, errors } = game(t); + hire(ev, 'annie'); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + ev(`ACT.buildPop({city:'par'});for(const c of ['fra','ams','par']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); + const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'fra', 'par', ['zr4']); + ev("compute();for(const l of S.links)R.load[l.id]=0"); + std(ev, { sys: 'roadm', opt: 'fast' }); + const cap0 = ev(`S.links.find(l=>l.id===${lit(a)}).ch.reduce((s,o)=>s+optG(o,S.links.find(l=>l.id===${lit(a)})),0)`); + shift(ev); + const L = id => JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(id)}))`)); + assert.deepEqual([L(a).sys, L(b).sys].sort(), ['lite', 'roadm'], 'one fiber goes dark per shift'); + const up = L(a).sys === 'roadm' ? a : b, other = up === a ? b : a; + assert.equal(L(up).eqDown, ev('S.day+1')); + assert.ok(L(up).ch.every(o => o === 'tp16'), 'its optics are the fastest that reach on the new line system: ' + L(up).ch); + // The other one only waits its turn: no optics in between that its own swap would put on the shelf a day later. + assert.ok(L(other).ch.every(o => o === 'zr4'), 'a quiet fiber waiting its turn keeps its optics: ' + L(other).ch); + assert.equal(ev('S.spares.zr4'), L(up).ch.length, 'the old optics of the swapped fiber went on the shelf'); + assert.equal(ev('S.spares.zr8'), undefined, 'and no stand-in optics were bought'); + // Busy and alone between its cities: it keeps its line system, and gets the fastest optics that one takes. + ev(`S.day+=2;compute();R.load[${lit(other)}]=capOf(S.links.find(l=>l.id===${lit(other)}))*0.9;opsDay(S.day)`); + assert.equal(L(other).sys, 'lite', 'not while it is busy and alone'); + assert.ok(L(other).ch.every(o => o === 'zr8'), 'the fastest the old line system takes: ' + L(other).ch); + assert.equal(ev('S.spares.zr4'), 3, 'all the old optics went on the shelf'); + // A parallel wave with room carries its load: now it can go dark for a day, and gets the bigger optics. + ev(`const o=S.links.find(l=>l.id===${lit(other)});UI.lmode='wave';UI.pending={a:o.a,b:o.b};ACT.buildLink({tier:3});S.day++;compute();R.load[o.id]=capOf(o)*0.9;for(const l of S.links)if(l.kind==='wave')R.load[l.id]=0;opsDay(S.day)`); + assert.equal(L(other).sys, 'roadm'); + assert.ok(L(other).ch.every(o => o === 'tp16'), L(other).ch); + assert.equal(ev('S.spares.zr8'), L(other).ch.length); + const cap1 = ev(`S.links.find(l=>l.id===${lit(a)}).ch.reduce((s,o)=>s+optG(o,S.links.find(l=>l.id===${lit(a)})),0)`); + assert.ok(cap1 > cap0, `capacity went up: ${cap0} → ${cap1}`); + // Waves: a bigger one than the standard stays as it is; a smaller one goes up. + const w = ev("S.links.find(l=>l.kind==='wave').id"); + assert.equal(L(w).tier, 3); + std(ev, { wv: 2 }); + ev('S.day++;compute();opsDay(S.day)'); + assert.equal(L(w).tier, 3, 'an 800G wave is never made smaller'); + std(ev, { wv: 3 }); + ev(`S.links.find(l=>l.id===${lit(w)}).tier=1;S.day++;compute();opsDay(S.day)`); + assert.equal(L(w).tier, 3, 'a 100G wave goes up to 800G'); + assert.deepEqual(errors, []); +}); + +test('quiet fibers take their line system one a shift and buy nothing in between: the intern spends what the quote said', t => { + const { ev, errors } = game(t); + hire(ev, 'annie'); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + ev(`ACT.buildPop({city:'par'});ACT.buildPop({city:'lon'});for(const c of ['fra','ams','par','lon']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); + const ids = ['ams', 'par', 'lon'].map(c => fiber(ev, 'fra', c, ['zr4', 'zr4'])); + const quiet = 'compute();for(const l of S.links)R.load[l.id]=0'; + ev(quiet); + std(ev, { sys: 'roadm', opt: 'fast' }); + const q = JSON.parse(ev('JSON.stringify(bstdQuote(true))')), c0 = ev('S.cash'); + assert.deepEqual([q.links, q.held], [3, []]); + for (let d = 1; d <= 3; d++) { + ev(`${quiet};opsDay(S.day);S.day++`); + const ls = ids.map(id => JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(id)}))`))); + assert.equal(ls.filter(l => l.sys === 'roadm').length, d, 'one more fiber a shift'); + for (const l of ls) assert.deepEqual(l.ch, l.sys === 'roadm' ? ['tp16', 'tp16'] : ['zr4', 'zr4'], 'tp16 on the new line system, the old optics until then'); + assert.equal(ev('S.spares.zr8'), undefined, 'no optics bought only to be shelved a day later'); + } + assert.equal(c0 - ev('S.cash'), q.cost, 'three shifts spent exactly the quote'); + assert.deepEqual(errors, []); +}); + +test('an optics swap is checked at what it costs when it runs: a refused job before it never lets one past the floor or the cap', t => { + const { ev, errors } = game(t); + hire(ev); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + ev(`ACT.buildPop({city:'par'});for(const c of ['fra','ams','par']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); + // Paris's fiber is the hotter one: its zr8s go to tp16 first and onto the shelf, where Amsterdam's swap expects them. + const b = fiber(ev, 'fra', 'par', ['zr8', 'zr8'], 'roadm'), a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']); + const loads = `compute();for(const l of S.links)R.load[l.id]=0;R.load[${lit(b)}]=50;`; + ev(`S.spares={};${loads}`); + std(ev, { opt: 'fast' }); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdPlan(true).map(j=>[j.w,j.cost]))')), [['fra|par', 140000], ['fra|ams', 0]], 'priced as if the first one ran'); + const ch = id => JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(id)}).ch)`)); + // The first is more than the budget: the second is not free then, and the cap and the floor see its real price. + ev(`S.ops.cap.std=10000;S.ops.floor=50000;S.cash=80000;S.ops.spent={};${loads}opsDay(S.day)`); + assert.equal(ev('S.cash'), 80000, 'nothing spent past the cap or the floor'); + assert.deepEqual([ch(a), ch(b)], [['zr4', 'zr4'], ['zr8', 'zr8']]); + assert.ok(ev("S.ops.log[0].r.some(x=>x[0]==='broke')"), 'the log says the money ran out'); + ev(`S.ops.cap.std=0;S.day++;${loads}opsDay(S.day)`); + assert.equal(ev('S.cash'), 80000, 'no cap: the floor alone still holds'); + // Exactly enough above the floor for Amsterdam's own zr8s, bought new: it goes ahead, down to the floor and no further. + ev(`S.cash=50000+2*optCost('zr8');S.day++;${loads}opsDay(S.day)`); + assert.deepEqual(ch(a), ['zr8', 'zr8']); + assert.equal(ev('S.cash'), 50000); + // The button checks the price at the click too: never more than the cash in hand. + std(ev, { opt: 'fast' }); + ev(`S.spares={};S.links.find(l=>l.id===${lit(a)}).ch=['zr4','zr4'];S.cash=30000;${loads}ACT.bstdApply()`); + assert.deepEqual(ch(a), ['zr4', 'zr4'], 'two zr8 at $44k do not fit $30k'); + assert.equal(ev('S.cash'), 30000); + assert.deepEqual(errors, []); +}); + +test('a busy fiber with nothing parallel keeps its line system: the sheet, the button and the MCP quote say what the click buys', t => { + const h = load({ agent: true }); + t.after(() => h.dom.window.close()); + const { ev, errors } = h; + ev(BASE); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + ev(`for(const c of ['fra','ams']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); + const a = fiber(ev, 'fra', 'ams', Array(6).fill('zr4')); + const busy = `compute();R.load[${lit(a)}]=capOf(S.links.find(l=>l.id===${lit(a)}))*0.9;`; + // tp16 on the shelf: the quote must not count on a line-system swap that will not happen today. + ev(`S.spares={tp16:6};${busy}`); + std(ev, { sys: 'roadm', opt: 'fast' }); + const q = JSON.parse(ev('JSON.stringify(bstdQuote(false))')); + assert.deepEqual([q.held, q.links, q.n], [['fra|ams'], 1, 1]); + assert.equal(q.cost, 6 * ev("optCost('zr8')"), 'six zr8 for the line system it keeps'); + ev(`closeModal();${busy}`); + const dry = JSON.parse(ev("JSON.stringify(apiRun('bstdApply',{},{dryRun:true}))")); + assert.equal(dry.quote.setup, q.cost, 'the MCP quote is the same bill'); + assert.match(dry.quote.blocked[0], /^Frankfurt–Amsterdam: its line system waits/); + ev(`${busy}ACT.bstdOpen()`); + const doc = h.dom.window.document; + assert.match(doc.getElementById('modalCard').textContent, /One fiber keeps its line system for now/); + assert.equal(doc.querySelector('#modalCard [data-act="bstdApply"]').textContent, `Bring everything up now · ${ev(`fmt$(${q.cost})`)}`); + const c0 = ev('S.cash'); + ev(`${busy}document.querySelector('#modalCard [data-act="bstdApply"]').click()`); + assert.equal(c0 - ev('S.cash'), q.cost, 'the click spent the quote'); + const l = JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(a)}))`)); + assert.deepEqual([l.sys, l.ch], ['lite', Array(6).fill('zr8')], 'and bought what it listed'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.spares)')), { tp16: 6, zr4: 6 }); + // Two busy fibers that carry each other: one goes dark, the other waits for tomorrow, and the quote knew. + const b = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']); + ev(`S.links.find(l=>l.id===${lit(a)}).ch=['zr4','zr4']`); + const both = `compute();for(const id of [${lit(a)},${lit(b)}])R.load[id]=capOf(S.links.find(l=>l.id===id))*0.4;`; + ev(both); + const q2 = JSON.parse(ev('JSON.stringify(bstdQuote(false))')), c1 = ev('S.cash'); + assert.deepEqual([q2.links, q2.held.length], [2, 1]); + ev(`${both}ACT.bstdApply()`); + assert.equal(c1 - ev('S.cash'), q2.cost); + assert.deepEqual(JSON.parse(ev(`JSON.stringify([${lit(a)},${lit(b)}].map(id=>S.links.find(l=>l.id===id).sys).sort())`)), ['lite', 'roadm'], 'never both dark on the same day'); + assert.deepEqual(errors, []); +}); + +test("a customer's wave keeps its fiber's line system, for the button and the intern; leased pairs and IRUs do not", t => { + const h = load({ agent: true }); + t.after(() => h.dom.window.close()); + const { ev, errors } = h; + ev(BASE); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + ev(`ACT.buildPop({city:'par'});for(const c of ['fra','ams','par']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); + // Two quiet fibers: Amsterdam's carries a carrier's managed 100G wave (Lambda Bazaar), Paris's nothing. + const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']), b = fiber(ev, 'fra', 'par', ['zr4', 'zr4']); + ev(`S.biz.push({id:'mw',name:'Photon Express',city:'fra',city2:'ams',link:${lit(a)},slots:1,g:100,type:'mwave',bw:1,rate:1000,reqs:[],mood:100,since:S.day})`); + const quiet = 'compute();for(const l of S.links)R.load[l.id]=0;'; + ev(quiet); + assert.equal(ev("fiberOk(S.biz.find(b=>b.id==='mw'))"), true); + std(ev, { sys: 'roadm' }); + const q = JSON.parse(ev('JSON.stringify(bstdQuote(false))')); + assert.deepEqual([q.held, q.wv, q.wait, q.links, q.n], [['fra|ams'], ['fra|ams'], [], 2, 1], 'only Paris\'s fiber is on the bill'); + ev(`closeModal();${quiet}`); + const dry = JSON.parse(ev("JSON.stringify(apiRun('bstdApply',{},{dryRun:true}))")); + assert.match(dry.quote.blocked[0], /^Frankfurt–Amsterdam: its line system waits: a customer's wave rides it/); + ev(`${quiet}ACT.bstdOpen()`); + const txt = h.dom.window.document.getElementById('modalCard').textContent; + assert.match(txt, /One fiber keeps its line system: a customer's wave rides it/); + assert.doesNotMatch(txt, /until it is quiet/, 'not the reason a busy fiber waits for'); + ev(`${quiet}document.querySelector('#modalCard [data-act="bstdApply"]').click()`); + const L = id => JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(id)}))`)); + assert.equal(L(b).sys, 'roadm', 'the free fiber is swapped'); + assert.deepEqual([L(a).sys, L(a).eqDown > ev('S.day')], ['lite', false], 'the wave\'s fiber stays lit'); + ev('compute()'); + assert.equal(ev("fiberOk(S.biz.find(b=>b.id==='mw'))"), true, 'and the customer is served'); + // The intern waits on it too: no swap, however quiet. + hire(ev, 'annie'); + ev(`S.day+=2;${quiet}opsDay(S.day)`); + assert.equal(L(a).sys, 'lite'); + // Glass only (an IRU, or a hyperscaler's pairs on your own build) never notices a line-system swap: the intern goes ahead. + for (const type of ['dfpair', 'pairs']) { + ev(`S.links.find(l=>l.id===${lit(a)}).sys='lite';S.links.find(l=>l.id===${lit(a)}).own=true;S.biz=S.biz.filter(b=>b.id!=='mw'&&b.id!=='g');S.biz.push({id:'g',name:'Strand Theft Auto',city:'fra',city2:'ams',link:${lit(a)},type:'${type}',bw:1,rate:1000,reqs:[],mood:100,since:S.day})`); + ev(`S.day+=2;${quiet}`); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(true).held)')), [], type + ': nothing waits'); + ev(`${quiet}opsDay(S.day)`); + assert.deepEqual([L(a).sys, L(a).eqDown > ev('S.day')], ['roadm', true], type + ': the intern swapped it'); + assert.equal(ev("fiberOk(S.biz.find(b=>b.id==='g'))"), true, type + ': and the pair stays up'); + } + assert.deepEqual(errors, []); +}); + +test('optics a new router model takes are on the bill with it, and wait for its swap', t => { + const { ev, errors } = game(t); + // Edge Lords take no zr8: the Absolute Unit does. + ev('S.pops.ams.rgen=1;S.pops.fra.routers=2;S.pops.ams.routers=2'); + const a = fiber(ev, 'fra', 'ams', ['zr4', 'zr4']); + ev('compute()'); + assert.equal(ev("RG[1].cls[j.k,j.w,j.dep?j.dep.length:0]))")); + assert.deepEqual(plan.filter(j => j[0] === 'opt'), [['opt', 'fra|ams', 2]], 'the optics wait for both swaps'); + // The intern: the swaps are over the budget, so the optics are not pulled out and put back. + hire(ev); + ev('S.ops.cap.std=50000;compute();opsDay(S.day)'); + assert.deepEqual(JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(a)}).ch)`)), ['zr4', 'zr4']); + assert.ok(!(ev('S.ops.spent.std') > 0)); + // The button: the swaps and the optics, exactly the quote, and nothing left over. + ev('S.ops.on.std=false;compute()'); + const q = JSON.parse(ev('JSON.stringify(bstdQuote(false))')), c0 = ev('S.cash'); + ev('ACT.bstdApply()'); + assert.equal(c0 - ev('S.cash'), q.cost); + assert.deepEqual(JSON.parse(ev(`JSON.stringify(S.links.find(l=>l.id===${lit(a)}).ch)`)), ['zr8', 'zr8']); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(false))')), { cost: 0, mo: 0, pops: 0, ports: 0, links: 0, n: 0, held: [], wait: [], wv: [] }, 'one tap brought everything up'); + assert.deepEqual(errors, []); +}); + +test('waves the decom order is about to hand back are never upgraded first', t => { + const { ev, errors } = game(t); + hire(ev); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + ev(`for(const c of ['fra','ams']){S.pops[c].rgen=${chonk};S.pops[c].routers=4;}`); + ev("UI.lmode='wave';UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:3});for(let i=0;i<2;i++){UI.pending={a:'fra',b:'ams'};UI.route='diverse';ACT.buildLink({tier:1});}compute()"); + const waves = () => JSON.parse(ev("JSON.stringify(S.links.filter(l=>l.kind==='wave').map(l=>l.tier))")); + assert.deepEqual(waves(), [3, 1, 1]); + std(ev, { wv: 2 }); + assert.equal(ev('bstdQuote(true).n'), 2, 'without decom both small waves go up'); + ev('S.ops.on.decom=true'); + const q = JSON.parse(ev('JSON.stringify(bstdQuote(true))')); + assert.equal(q.n, 1, 'decom keeps one spare in another trench and hands the other back: only the spare goes up'); + const c0 = ev('S.cash'); + ev('S.day++;compute();opsDay(S.day)'); + assert.deepEqual(waves(), [3, 2], 'the spare went up, the other went back'); + assert.equal(c0 - ev('S.cash'), q.cost, 'no month of rent paid on a wave that went back'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(S.ops.log[0].r.map(x=>[x[0],x[1]]))')), [['std', 1], ['decom', 1]]); + assert.deepEqual(errors, []); +}); + +test('a new POP gets the whole POP standard, priced on the button; the template\'s kit never pays for it twice', t => { + const { ev, dom, errors } = game(t); + std(ev, { g: ev(AU), rt: 2, site2: true, gen: true, lag: 2 }); + const q = JSON.parse(ev('JSON.stringify(popStdQuote())')); + assert.deepEqual([q.g, q.rt, q.site2, q.gen], [ev(AU), 2, true, true]); + ev("selectCity('par');renderPanel()"); + assert.match(dom.window.document.getElementById('panelBody').textContent, /Includes your build standard: 2 × Absolute Unit 3\.2T, second building, generator/); + let c0 = ev('S.cash'); + ev("ACT.buildPop({city:'par'})"); + assert.equal(c0 - ev('S.cash'), ev("popCost('par')") + q.cost, 'the button\'s price is what it costs'); + const p = pop(ev, 'par'); + assert.deepEqual([p.rgen, p.routers, p.site2, p.gen], [ev(AU), 2, true, true]); + // The template: broadband, transit, an IX port and the kit, all with the standard. The kit has nothing left to add. + hire(ev); + const tq = JSON.parse(ev("JSON.stringify(opsTplQuote('lon'))")); + assert.equal(tq.kit, false, 'the standard already has the generator, the building and the second router'); + assert.ok(tq.parts.includes('build standard')); + c0 = ev('S.cash'); + ev("ACT.opsNewPop({city:'lon'})"); + assert.equal(c0 - ev('S.cash'), tq.cost, 'the template costs what it quoted'); + assert.equal(pop(ev, 'lon').gen, true); + // Without a generator in the standard, the kit adds just that. + std(ev, { g: ev(AU), rt: 2, site2: true }); + const tq2 = JSON.parse(ev("JSON.stringify(opsTplQuote('mad'))")); + assert.equal(tq2.kit, true); + c0 = ev('S.cash'); + ev("ACT.opsNewPop({city:'mad'})"); + assert.equal(c0 - ev('S.cash'), tq2.cost); + assert.deepEqual([pop(ev, 'mad').gen, pop(ev, 'mad').routers], [true, 2]); + assert.deepEqual(errors, []); +}); + +test('"Bring everything up now" spends what the quote said and does what it listed; the quote changes nothing', t => { + const { ev, errors } = game(t); + ev(`S.pops.fra.routers=2;S.pops.fra.site2=true;ACT.buyIx({city:'ams',tier:0})`); + const chonk = ev("RG.findIndex(r=>r.n==='Chonk 800')"); + ev(`for(const c of ['fra','ams'])S.pops[c].rgen=${chonk}`); + fiber(ev, 'fra', 'ams', ['zr4']); + ev("compute()"); + std(ev, { g: ev(AU), rt: 3, site2: true, gen: true, lag: 2, split: true, ix: true, sys: 'roadm', opt: 'fast' }); + const s0 = ev('JSON.stringify(S)'); + const q = JSON.parse(ev('JSON.stringify(bstdQuote(false))')); + ev('ACT.bstdOpen()'); + assert.equal(ev('JSON.stringify(S)'), s0, 'the quote and the sheet leave the game alone'); + assert.ok(q.n > 0 && q.pops === 2 && q.ports >= 2 && q.links === 1, JSON.stringify(q)); + const c0 = ev('S.cash'); + ev("document.querySelector('#modalCard [data-act=\"bstdApply\"]').click()"); + assert.equal(c0 - ev('S.cash'), q.cost, 'it cost exactly the quote'); + assert.deepEqual(JSON.parse(ev('JSON.stringify(bstdQuote(false))')), { cost: 0, mo: 0, pops: 0, ports: 0, links: 0, n: 0, held: [], wait: [], wv: [] }, 'and everything is up to the standard'); + assert.match(ev("document.getElementById('toasts').textContent"), /jobs done for the build standard/); + assert.match(ev("document.getElementById('modalCard').textContent"), /Everything meets the standard/); + assert.equal(ev('S.ixSite.ams'), 'ab'); + assert.deepEqual(errors, []); +}); + +test('saves: an old {g, rt} standard loads unchanged and still means the same; junk is repaired; none stays none', t => { + const { ev, errors } = game(t); + const back = d => ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.popStd=${d};sanitize(s);return JSON.stringify(s.popStd);})()`); + assert.deepEqual(JSON.parse(back(`{g:${ev(AU)},rt:2}`)), { g: ev(AU), rt: 2 }, 'an old standard is exactly the routers it was'); + assert.equal(back('undefined'), 'null', 'an old save without one'); + assert.equal(back('null'), 'null'); + assert.equal(back("'x'"), 'null'); + assert.deepEqual(JSON.parse(back("{g:'x',rt:'7',site2:'yes',gen:true,lag:3,split:1,ix:true,pni:9,sys:'warp',opt:'fast',wv:99}")), { rt: 7, gen: true, ix: true, opt: 'fast' }, 'each odd value reads as keep'); + assert.equal(back('{g:999}'), 'null', 'nothing left is no standard'); + // The old meaning: a new POP gets those routers, and nothing else is done anywhere unless the order is switched on. + ev(`S=migrate(JSON.parse(JSON.stringify(Object.assign(S,{popStd:{g:${ev(AU)},rt:2}}))));delete S.ops.on.std;S=migrate(JSON.parse(JSON.stringify(S)))`); + assert.equal(ev('S.ops.on.std'), false, 'an old save has the order off'); + ev("ACT.buildPop({city:'par'})"); + assert.deepEqual([pop(ev, 'par').rgen, pop(ev, 'par').routers, !!pop(ev, 'par').site2, !!pop(ev, 'par').gen], [ev(AU), 2, false, false]); + // A model smaller than the basic router (the Mikrowtik has more ports) is still what a new POP gets, as it always was. + const mk = ev("RG.findIndex(r=>r.n==='Mikrowtik CCR')"); + assert.ok(ev(`RG[${mk}].cap { + for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) { + const h = load(lang === 'en' ? {} : { lang }); + const { ev, dom, errors } = h; + ev(BASE); + dom.window.innerWidth = 360; + const doc = dom.window.document; + const leaks = () => { + const txt = doc.getElementById('modalCard').textContent; + assert.doesNotMatch(txt, /\b(bstd|ops|pop_std|common)\.[a-z_]+/, lang + ': a raw label'); + assert.doesNotMatch(txt, /\{[a-z]\w*\}|undefined|NaN/, lang); + }; + ev('ACT.menu()'); + doc.querySelector('#modalCard [data-act="bstdOpen"]').click(); + assert.ok(ev('bstdShown()'), lang + ': from the menu'); + leaks(); + // Every target is a list; pick its last value and the standard follows, the sheet stays open and in focus. (IPv6-only + // broadband is a target only while IPv4 is scarce, not in Change Freeze: tests/bstd-ipv6-only.test.js.) + const keys = JSON.parse(ev('JSON.stringify(BSTD.filter(bstdOn).map(x=>x.k))')); + assert.equal(doc.querySelectorAll('#modalCard select[data-chg="bstdSet"]').length, keys.length); + for (const k of keys) { + const s = [...doc.querySelectorAll('#modalCard select[data-chg="bstdSet"]')].find(x => JSON.parse(x.dataset.args).k === k); + assert.ok(s.closest('.ops-sel'), 'the Ops sheet\'s two-to-a-row lists'); + s.value = String(s.options.length - 1); + s.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + assert.ok(ev('bstdShown()'), lang + ' ' + k); + assert.equal(doc.activeElement && doc.activeElement.dataset.args, JSON.stringify({ k }), 'the keyboard stays on the list'); + assert.notEqual(ev(`bstd()[${lit(k)}]`), ev(`BSTDK[${lit(k)}].d`), lang + ' ' + k); + } + leaks(); + if (lang === 'fr') assert.match(doc.getElementById('modalCard').textContent, /Répartis sur les deux bâtiments/, 'LAG is masculine'); + // The Ops sheet has a way in before anyone is hired too. + ev('ACT.opsOpen()'); + assert.equal(ev('opsHired()'), false); + doc.querySelector('#modalCard [data-act="bstdOpen"]').click(); + assert.ok(ev('bstdShown()'), lang + ': from the Ops sheet with no intern'); + // The intern's switch and budget sit in the sheet once one is hired, and stay there when used. + ev("ACT.opsHire({id:'annie'});closeModal();ACT.bstdOpen()"); + doc.querySelector('#modalCard [data-act="opsToggle"]').click(); + assert.ok(ev('S.ops.on.std') && ev('bstdShown()'), lang); + const cap = doc.querySelector('#modalCard select[data-chg="opsCap"]'); + cap.value = String(cap.options.length - 1); + cap.dispatchEvent(new dom.window.Event('change', { bubbles: true })); + assert.equal(ev("opsCap('std')"), 0, lang); + assert.ok(ev('bstdShown()'), lang); + leaks(); + // From the Ops sheet and the city panel. + ev('ACT.opsOpen()'); + doc.querySelector('#modalCard [data-act="bstdOpen"]').click(); + assert.ok(ev('bstdShown()'), lang + ': from the Ops sheet'); + ev("closeModal();selectCity('fra');ACT.tab({t:'links'})"); + assert.doesNotMatch(doc.getElementById('panelBody').textContent, /\b(bstd|pop_std)\.[a-z_]+/, lang); + doc.querySelector('#panelBody [data-act="bstdOpen"]').click(); + assert.ok(ev('bstdShown()'), lang + ': from the city panel'); + assert.deepEqual(errors, [], lang); + dom.window.close(); + } +}); + +test('puzzles have no standard; the MCP tools see every action', () => { + const { ev, errors } = load(); + ev(BASE); + std(ev, { rt: 2 }); + ev("ACT.puzzleMenu();ACT.pzStart({id:PZ[0].id})"); + assert.ok(ev('pzOn()')); + assert.equal(ev('popStdQuote()'), null); + assert.equal(ev('bstdPlan(false).length'), 0); + ev("ACT.bstdSet({k:'rt'})"); + assert.equal(ev('bstdShown()'), false); + assert.deepEqual(errors, []); +}); + +test('the big network: one shift of the order takes a few milliseconds', t => { + const { ev, errors } = load({ seed: 3 }); + t.after(() => ev('0')); + const SAVE = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8'); + ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute()`); + ev(`S.ops.intern='kevin';S.ops.on.std=true;S.ops.floor=0;S.ops.cap.std=0;S.rules.pnis='instant';S.popStd={g:${AU},rt:2,site2:true,gen:true,lag:2,split:true,ix:true,pni:2,sys:'cl',opt:'fast',wv:4}`); + const plan = ev('(()=>{const t=performance.now();for(let i=0;i<5;i++)bstdPlan(true);return (performance.now()-t)/5;})()'); + const jobs = ev('bstdPlan(true).length'); + const shiftMs = ev('(()=>{const t=performance.now();opsDay(S.day);return performance.now()-t;})()'); + console.log(`# big network: plan ${plan.toFixed(1)} ms (${jobs} jobs), one shift ${shiftMs.toFixed(1)} ms with its recompute`); + assert.ok(jobs > 0); + assert.ok(plan < 250, 'planning stays cheap: ' + plan); + assert.ok(ev("S.ops.log[0].r.find(x=>x[0]==='std')[1]") <= ev('BSTD_MAX'), 'a few jobs a shift'); + // Second buildings the month's budget cannot pay for: the LAG splits that need them wait with them, instead of being + // tried (two opsMoNow runs each) and failing at every POP, every shift. + ev('for(const t of S.transit)t.n=Math.max(2,t.n||1);S.ixn=S.ixn||{};for(const x in S.ixp)if(!S.myIx[x])S.ixn[x]=Math.max(2,S.ixn[x]||1);for(const p of S.pni)if(pniOn(p)&&!p.up)p.n=Math.max(2,p.n||1)'); + ev('for(const k in S.ops.on)S.ops.on[k]=false;S.ops.on.std=true;S.popStd={rt:1,site2:true,split:true};S.ops.cap.std=OPS_CAPS[0];window.__m=0;const _m=opsMoNow;opsMoNow=function(){__m++;return _m.apply(this,arguments);};compute()'); + assert.ok(ev("bstdPlan(true).filter(j=>j.k==='split'&&j.dep).length") > 100, 'many splits wait for a building'); + for (let d = 0; d < 3; d++) { + const ms = ev("(()=>{__m=0;S.day++;S.ops.mon=monthIdx(S.day);S.ops.spent.std=OPS_CAPS[0];const t=performance.now();opsDay(S.day);return performance.now()-t;})()"); + const did = ev("(S.ops.log[0].d===S.day&&(S.ops.log[0].r.find(x=>x[0]==='std')||[])[1])||0"); + console.log(`# big network, budget spent: shift ${ms.toFixed(1)} ms, ${did} splits done, ${ev('__m')} opsMoNow runs`); + assert.equal(ev('__m'), 2 * did, 'every job tried was one that could be done'); + assert.ok(did <= ev('BSTD_MAX')); + } + assert.deepEqual(errors, []); +}); diff --git a/tests/build.test.js b/tests/build.test.js index a6c9966..cbc6d78 100644 --- a/tests/build.test.js +++ b/tests/build.test.js @@ -5,6 +5,7 @@ const path = require('node:path'); const { execFileSync } = require('node:child_process'); const OUT = require('node:fs').mkdtempSync(require('node:path').join(require('node:os').tmpdir(), 'tubes-build-')); +const { JSDOM } = require('jsdom'); const root = path.join(__dirname, '..'); test('build stamps version and date into the site', () => { @@ -31,9 +32,9 @@ test('head carries the SEO and social metadata', () => { for (const needle of ['', 'property="og:image"', 'name="twitter:card"', 'application/ld+json', 'rel="manifest"', 'name="description"']) { assert.ok(html.includes(needle), `missing ${needle}`); } - for (const block of html.match(/