From e17ddc247bff6ee82e8d50e4bb3734a57fff28ae Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 09:55:35 +0100 Subject: [PATCH 1/4] Change Freeze stops de-peering at exchanges Snubs (refused and torn-down sessions at exchanges) are part of the market rule now, so Change Freeze and puzzles have none; On-call is unchanged. --- .claude/skills/gameplay-rules/SKILL.md | 2 +- CHANGELOG.md | 2 +- site/i18n/de.js | 2 +- site/i18n/es.js | 2 +- site/i18n/fr.js | 2 +- site/i18n/it.js | 2 +- site/i18n/pt.js | 2 +- src/game/40-progress/30-rules.js | 2 +- src/game/70-rules/50-peering-policy.js | 5 +++-- src/i18n/en.js | 2 +- tests/gameplay-rules.test.js | 6 ++---- tests/peering.test.js | 20 ++++++++++++++++++++ 12 files changed, 34 insertions(+), 15 deletions(-) diff --git a/.claude/skills/gameplay-rules/SKILL.md b/.claude/skills/gameplay-rules/SKILL.md index 98de506..092aa0f 100644 --- a/.claude/skills/gameplay-rules/SKILL.md +++ b/.claude/skills/gameplay-rules/SKILL.md @@ -44,7 +44,7 @@ These are what the game promises, held up by `tests/gameplay-rules.test.js` (one | --- | --- | --- | | 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: Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market, inbox; and a seeded year of incidents). | The names promise it. | -| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, the peering inbox, sold-out routes and hardware prices (`market`), lead times (`lead`), the clock. A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. Open question: de-peering ignores the rules (exception). | +| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, the peering inbox, sold-out routes, de-peering and hardware prices (`market`), lead times (`lead`), the clock. 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. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 4933538..f681b9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ All notable changes to this project are documented here. The project follows - A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle 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. - 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). - 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. -- 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 the peering inbox, hardware shortages and sold-out routes. 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. +- 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 the peering inbox, 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. - 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. - 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. diff --git a/site/i18n/de.js b/site/i18n/de.js index 711b9e0..bd56b10 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3243,6 +3243,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Steck zuerst etwas aus.
{used} Ports sind belegt, und mit einem Router weniger gibt es nur {max}.", "rules.a_billion_dollars_every_unlock_your":"Eine Milliarde Dollar, alles freigeschaltet, dein eigenes Seekabel.", "rules.a_cut_now_and_then":"Ab und zu ein Bagger.", +"rules.a_third_of_the_outages_no_ddos":"Ein Drittel der Ausfälle, kein DDoS. PNIs und Bauten in Tagen. Kein Postfach, keine Lieferengpässe, keine ausverkauften Routen, kein De-Peering.", "rules.bgp_at_3_a_m":"BGP um 3 Uhr nachts", "rules.change_freeze":"Change Freeze", "rules.chaos_calm":"Ruhig", @@ -3250,7 +3251,6 @@ "rules.chaos_normal":"Normal", "rules.chaos_spicy":"Scharf", "rules.everything_is_on_fire_and_it":"Alles brennt, und du hast Bereitschaft.", -"rules.fewer_outages_pnis_and_builds_in":"Ein Drittel der Ausfälle, kein DDoS. PNIs und Bauten in Tagen. Kein Postfach, keine Lieferengpässe, keine ausverkauften Routen.", "rules.infinite_money_everything_unlocked_quick":"Endlos Geld, alles freigeschaltet, kurze Lieferzeiten. Keine Abzeichen.", "rules.like_the_real_game":"Wie im echten Spiel.", "rules.more_and_longer_outages_more_ddos":"Fast doppelt so viele Ausfälle, anderthalbmal so lang, doppelt so viel DDoS. Alles an.", diff --git a/site/i18n/es.js b/site/i18n/es.js index 21a7058..3f3a819 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3241,6 +3241,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Desconecta algo primero.
Hay {used} puertos en uso, y con un router menos solo hay {max}.", "rules.a_billion_dollars_every_unlock_your":"Mil millones de dólares, todo desbloqueado, tu propio cable submarino.", "rules.a_cut_now_and_then":"Algún corte de vez en cuando.", +"rules.a_third_of_the_outages_no_ddos":"Un tercio de las caídas, sin DDoS. PNI y obras en días. Sin bandeja de entrada, sin escasez, sin rutas agotadas, sin de-peering.", "rules.bgp_at_3_a_m":"BGP a las 3 de la mañana", "rules.change_freeze":"Congelación de cambios", "rules.chaos_calm":"Tranquilo", @@ -3248,7 +3249,6 @@ "rules.chaos_normal":"Normal", "rules.chaos_spicy":"Picante", "rules.everything_is_on_fire_and_it":"Todo está ardiendo, y te toca a ti.", -"rules.fewer_outages_pnis_and_builds_in":"Un tercio de las caídas, sin DDoS. PNI y obras en días. Sin bandeja de entrada, sin escasez, sin rutas agotadas.", "rules.infinite_money_everything_unlocked_quick":"Dinero sin fin, todo desbloqueado, plazos cortos. Sin insignias.", "rules.like_the_real_game":"Como el juego de verdad.", "rules.more_and_longer_outages_more_ddos":"Casi el doble de caídas, la mitad más largas, el doble de DDoS. Todo activado.", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index ec80dc5..acdf746 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3241,6 +3241,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Débranche d’abord quelque chose.
{used} ports sont utilisés, et avec un routeur de moins tu n’en aurais que {max}.", "rules.a_billion_dollars_every_unlock_your":"Un milliard de dollars, tout débloqué, ton propre câble sous-marin.", "rules.a_cut_now_and_then":"Une coupure de temps en temps.", +"rules.a_third_of_the_outages_no_ddos":"Un tiers des pannes, pas de DDoS. PNI et chantiers en quelques jours. Pas de boîte de réception, pas de pénurie, pas de routes épuisées, pas de dépeering.", "rules.bgp_at_3_a_m":"BGP à 3 h du matin", "rules.change_freeze":"Gel des changements", "rules.chaos_calm":"Calme", @@ -3248,7 +3249,6 @@ "rules.chaos_normal":"Normal", "rules.chaos_spicy":"Épicé", "rules.everything_is_on_fire_and_it":"Tout brûle, et c’est ton tour d’astreinte.", -"rules.fewer_outages_pnis_and_builds_in":"Un tiers des pannes, pas de DDoS. PNI et chantiers en quelques jours. Pas de boîte de réception, pas de pénurie, pas de routes épuisées.", "rules.infinite_money_everything_unlocked_quick":"Argent infini, tout débloqué, délais courts. Pas de badges.", "rules.like_the_real_game":"Comme le vrai jeu.", "rules.more_and_longer_outages_more_ddos":"Presque deux fois plus de pannes, moitié plus longues, deux fois plus de DDoS. Tout activé.", diff --git a/site/i18n/it.js b/site/i18n/it.js index f6250c9..f959550 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3241,6 +3241,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Prima stacca qualcosa.
Ci sono {used} porte in uso, e con un router in meno ne avresti solo {max}.", "rules.a_billion_dollars_every_unlock_your":"Un miliardo di dollari, tutto sbloccato, il tuo cavo sottomarino.", "rules.a_cut_now_and_then":"Un taglio ogni tanto.", +"rules.a_third_of_the_outages_no_ddos":"Un terzo dei guasti, niente DDoS. PNI e cantieri in pochi giorni. Niente posta, niente carenze, niente rotte esaurite, niente de-peering.", "rules.bgp_at_3_a_m":"BGP alle 3 di notte", "rules.change_freeze":"Change freeze", "rules.chaos_calm":"Calmo", @@ -3248,7 +3249,6 @@ "rules.chaos_normal":"Normale", "rules.chaos_spicy":"Piccante", "rules.everything_is_on_fire_and_it":"Va tutto a fuoco, e tocca a te.", -"rules.fewer_outages_pnis_and_builds_in":"Un terzo dei guasti, niente DDoS. PNI e cantieri in pochi giorni. Niente posta, niente carenze, niente rotte esaurite.", "rules.infinite_money_everything_unlocked_quick":"Soldi infiniti, tutto sbloccato, consegne rapide. Niente medaglie.", "rules.like_the_real_game":"Come il gioco vero.", "rules.more_and_longer_outages_more_ddos":"Quasi il doppio dei guasti, lunghi una volta e mezza, il doppio dei DDoS. Tutto acceso.", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 4308d56..1f7e31c 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3241,6 +3241,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Desconecte algo primeiro.
Há {used} portas em uso, e com um router a menos só teria {max}.", "rules.a_billion_dollars_every_unlock_your":"Um bilhão de dólares, tudo desbloqueado, o seu próprio cabo submarino.", "rules.a_cut_now_and_then":"Um corte de vez em quando.", +"rules.a_third_of_the_outages_no_ddos":"Um terço das falhas, sem DDoS. PNIs e obras em dias. Sem caixa de entrada, sem escassez, sem rotas esgotadas, sem de-peering.", "rules.bgp_at_3_a_m":"BGP às 3 da manhã", "rules.change_freeze":"Congelamento de mudanças", "rules.chaos_calm":"Calmo", @@ -3248,7 +3249,6 @@ "rules.chaos_normal":"Normal", "rules.chaos_spicy":"Apimentado", "rules.everything_is_on_fire_and_it":"Está tudo pegando fogo, e o plantão é seu.", -"rules.fewer_outages_pnis_and_builds_in":"Um terço das falhas, sem DDoS. PNIs e obras em dias. Sem caixa de entrada, sem escassez, sem rotas esgotadas.", "rules.infinite_money_everything_unlocked_quick":"Dinheiro sem fim, tudo desbloqueado, prazos curtos. Sem medalhas.", "rules.like_the_real_game":"Como o jogo de verdade.", "rules.more_and_longer_outages_more_ddos":"Quase o dobro de falhas, metade mais longas, o dobro de DDoS. Tudo ligado.", diff --git a/src/game/40-progress/30-rules.js b/src/game/40-progress/30-rules.js index c61421b..656677e 100644 --- a/src/game/40-progress/30-rules.js +++ b/src/game/40-progress/30-rules.js @@ -7,7 +7,7 @@ const RULE_DEF={clock:true,chaos:'normal',lead:'real',market:true,inbox:true,mon const RULE_OK={clock:[true,false],chaos:['none','calm','normal','spicy'],lead:['real','quick'],market:[true,false],inbox:[true,false],money:['normal','infinite'],gates:['ladder','open']}; // i: icon, n: name, d: the one-line joke, x: what is different, in small print. const PRESETS={ - freeze:{i:'🧊',n:tr('rules.change_freeze'),d:tr('rules.nobody_touches_prod_even_the_backhoes'),x:tr('rules.fewer_outages_pnis_and_builds_in'),clock:true,chaos:'calm',lead:'quick',market:false,inbox:false,money:'normal',gates:'ladder'}, + freeze:{i:'🧊',n:tr('rules.change_freeze'),d:tr('rules.nobody_touches_prod_even_the_backhoes'),x:tr('rules.a_third_of_the_outages_no_ddos'),clock:true,chaos:'calm',lead:'quick',market:false,inbox:false,money:'normal',gates:'ladder'}, oncall:{i:'📟',n:tr('rules.on_call'),d:tr('rules.the_real_thing_your_pager_has'),x:tr('rules.real_lead_times_real_outages_a'),clock:true,chaos:'normal',lead:'real',market:true,inbox:true,money:'normal',gates:'ladder'}, bgp:{i:'🔥',n:tr('rules.bgp_at_3_a_m'),d:tr('rules.everything_is_on_fire_and_it'),x:tr('rules.more_and_longer_outages_more_ddos'),clock:true,chaos:'spicy',lead:'real',market:true,inbox:true,money:'normal',gates:'ladder'}, sandbox:{i:'🏖️',n:tr('common.sandbox'),d:tr('rules.a_billion_dollars_every_unlock_your'),x:tr('rules.infinite_money_everything_unlocked_quick'),clock:true,chaos:'none',lead:'quick',market:true,inbox:true,money:'infinite',gates:'open'}, diff --git a/src/game/70-rules/50-peering-policy.js b/src/game/70-rules/50-peering-policy.js index 48edcd3..93e1913 100644 --- a/src/game/70-rules/50-peering-policy.js +++ b/src/game/70-rules/50-peering-policy.js @@ -1,12 +1,13 @@ /* Big networks sometimes refuse to peer in a particular city, for a while. Each (network, city) - pair gets a stable verdict per window, derived from a hash, so asking again does not reroll it. */ + pair gets a stable verdict per window, derived from a hash, so asking again does not reroll it. + It is part of the market: without one (Change Freeze, puzzles), nobody refuses or drops a session. */ const SNUB_WIN=150,SNUB_P=0.22; const SNUB_IX=[tr('peering_policy.only_peers_over_pnis_in_this'),tr('peering_policy.their_ix_port_here_is_full'),tr('peering_policy.moved_everything_in_this_city_to'),tr('peering_policy.the_peering_coordinator_for_this'),tr('peering_policy.their_policy_here_says_ix_peering')]; const SNUB_ALL=[tr('peering_policy.not_accepting_new_peers_in_this'),tr('peering_policy.region_frozen_while_they_renegotiate'),tr('peering_policy.their_routers_in_this_city_are'),tr('peering_policy.already_reach_you_through_your'),tr('peering_policy.their_lawyers_are_reviewing_every'),tr('peering_policy.a_new_vp_wants_to_monetise')]; function hstr(t){let h=2166136261;for(let i=0;i>>0;} function bigPeer(n){return !!n&&n.pol==='selective'&&n.share>=0.03;} function snub(id,c){ - const n=NET[id];if(!c||!bigPeer(n)||!S||S.myIx[c])return null; + const n=NET[id];if(!c||!bigPeer(n)||!S||S.myIx[c]||!rule('market'))return null; const off=hstr(id+c)%SNUB_WIN,ep=Math.floor((S.day+off)/SNUB_WIN),h=hstr(S.asn+'|'+id+'|'+c+'|'+ep); if(h%1000>=SNUB_P*1000)return null; const all=(h>>>10)%5<2,list=all?SNUB_ALL:SNUB_IX; diff --git a/src/i18n/en.js b/src/i18n/en.js index c8236d6..193d061 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -3242,6 +3242,7 @@ "routing_and_routers.unplug_something_first_used_ports":"Unplug something first.
{used} ports are in use, and one router fewer only has {max}.", "rules.a_billion_dollars_every_unlock_your":"A billion dollars, every unlock, your own subsea cable.", "rules.a_cut_now_and_then":"A cut now and then.", +"rules.a_third_of_the_outages_no_ddos":"A third of the outages, no DDoS. PNIs and builds in days. No inbox, no shortages, no sold-out routes, no de-peering.", "rules.bgp_at_3_a_m":"BGP at 3 a.m.", "rules.change_freeze":"Change Freeze", "rules.chaos_calm":"Calm", @@ -3249,7 +3250,6 @@ "rules.chaos_normal":"Normal", "rules.chaos_spicy":"Spicy", "rules.everything_is_on_fire_and_it":"Everything is on fire, and it's your turn.", -"rules.fewer_outages_pnis_and_builds_in":"A third of the outages, no DDoS. PNIs and builds in days. No inbox, no shortages, no sold-out routes.", "rules.infinite_money_everything_unlocked_quick":"Endless money, everything unlocked, quick lead times. No badges.", "rules.like_the_real_game":"Like the real game.", "rules.more_and_longer_outages_more_ddos":"Almost twice the outages, half as long again, twice the DDoS. Everything on.", diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index 3535fb8..3c2c1f7 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -84,9 +84,7 @@ const EXCEPTIONS = { 'spl:hba': 'Speedyloop reaches Hobart’s exchange over its own backhaul but sells no transit there', }, // M3: subsystems that annoy the player but read no rule. - M3: { - snub: 'de-peering at exchanges happens in every mode (open question: should Change Freeze stop it?)', - }, + M3: {}, }; // The real names the puns are based on. No network, cable, exchange, data center, router or optic may be called one. @@ -234,7 +232,7 @@ test('M3: every subsystem that can annoy the player reads a rule', () => { // [function, what it must read] const reads = [['dayTick', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'], ['inboxDay', "rule('inbox')"], ['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'], - ['dfBuildDays', 'leadDays'], ['dayTick', "rule('clock')"]]; + ['dfBuildDays', 'leadDays'], ['dayTick', "rule('clock')"], ['snub', "rule('market')"]]; fail('M3', reads.filter(([f, r]) => !ev(`typeof ${f}==='function'&&${f}.toString().includes(${JSON.stringify(r)})`)).map(([f, r]) => `${f}() does not read ${r}`), 'gate it on the ruleset (src/game/40-progress/30-rules.js)'); // and in play: no chaos, no market, no inbox means a quiet year const g = load(); diff --git a/tests/peering.test.js b/tests/peering.test.js index 4b51227..4e1d185 100644 --- a/tests/peering.test.js +++ b/tests/peering.test.js @@ -99,6 +99,26 @@ test('a snubbing peer tears down an existing session and the Request button expl assert.deepEqual(errors, []); }); +test('Change Freeze never refuses or tears down a session at an exchange; On-call does', () => { + const { ev, errors } = load(); + setup(ev); + const k = ev(`(()=>{const ok=['fra','ams','lon','par','nyc','ash','sjc','sin','tok','hkg']; + for(let d=0;d<600;d++)for(const n of NETS)for(const c of ok){if(!ixMembers(c).includes(n.id))continue; + S.day=d;const a=snub(n.id,c);S.day=d+1;const b=snub(n.id,c);S.day=0;if(!a&&b)return n.id+'@'+c+'@'+d;}})()`); + assert.ok(k, 'found a snub starting at an IX'); + const [id, c, d] = k.split('@'); + ev(`S.rules=makeRules('freeze');S.day=${d}`); + ev(`ACT.buildPop({city:'${c}'});ACT.buyIx({city:'${c}',tier:1,signed:true});S.peers['${id}@${c}']=true;compute()`); + ev('dayTick()'); + assert.equal(ev(`!!S.peers['${id}@${c}']`), true, 'the session survives the freeze'); + assert.equal(ev(`snub('${id}','${c}')`), null, 'and nobody refuses a new one'); + assert.equal(ev(`ixSessions('${c}').has('${id}')`), true); + assert.equal(ev('S.stats.depeered||0'), 0); + ev(`S.rules=makeRules('oncall');S.day=${+d + 1}`); + assert.ok(ev(`!!snub('${id}','${c}')`), 'On-call still snubs the same pair'); + assert.deepEqual(errors, []); +}); + test('remote peering is offered but costs more, gives less and gets refused more', () => { const { ev, errors } = load(); setup(ev); From 77ec31d1a08774315abdebecefe89c53d90a8b30 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 09:58:01 +0100 Subject: [PATCH 2/4] Give Palau's and the Marshall Islands' networks their real ASNs PNC-See had AS9534 (Maxis, Malaysia) and Never Too Atoll AS21581 (a US host); the real operators are AS17893 (PNCC) and AS24439 (NTA). Saves key on network ids, so nothing stored changes. The fudged numbers of the big carriers and the African/Latin American incumbents are deliberate and stay. --- CHANGELOG.md | 1 + src/game/30-networks/30-long-tail.js | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f681b9b..0c71bd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,7 @@ All notable changes to this project are documented here. The project follows - 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). - 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. - 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). +- Palau's and the Marshall Islands' main networks now show their real AS numbers instead of ones borrowed from networks elsewhere. ## [1.37.0] — 2026-10-28 diff --git a/src/game/30-networks/30-long-tail.js b/src/game/30-networks/30-long-tail.js index fd83534..1304fb8 100644 --- a/src/game/30-networks/30-long-tail.js +++ b/src/game/30-networks/30-long-tail.js @@ -93,8 +93,8 @@ NETS.push( {id:'otk',name:'Ours-Truly Telekom',asn:45891,type:'eye',cc:'SB',pol:'selective',minIx:1,minPni:8,share:.001,up:['tly'],col:'#00843D',pops:['hir'],ix:['hir'],blurb:tr('long_tail.the_solomon_islands_incumbent_yours')}, {id:'tcc',name:'Tongue-in-Cheek Comms',asn:38201,type:'eye',cc:'TO',pol:'selective',minIx:1,minPni:8,share:.001,up:['ntt'],col:'#C10230',pops:['tbu'],ix:[],blurb:tr('long_tail.tonga_s_own_telco_lived_through')}, {id:'bsk',name:'Blue-Sky-Pie Samoa',asn:17993,type:'eye',cc:['WS','AS'],pol:'selective',minIx:1,minPni:8,share:.001,up:['tly'],col:'#0096D6',pops:['apw','ppg'],ix:[],blurb:tr('long_tail.samoa_s_broadband_promised_with_a')}, - {id:'pnc',name:'PNC-See',asn:9534,type:'eye',cc:'PW',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#1B75BB',pops:['ror'],ix:[],blurb:tr('long_tail.palau_s_telco_snorkel_down_and')}, - {id:'nta',name:'Never Too Atoll',asn:21581,type:'eye',cc:'MH',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#2E8B57',pops:['maj'],ix:[],blurb:tr('long_tail.the_marshall_islands_telco_two')}); + {id:'pnc',name:'PNC-See',asn:17893,type:'eye',cc:'PW',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#1B75BB',pops:['ror'],ix:[],blurb:tr('long_tail.palau_s_telco_snorkel_down_and')}, + {id:'nta',name:'Never Too Atoll',asn:24439,type:'eye',cc:'MH',pol:'selective',minIx:1,minPni:8,share:.0005,up:['ntt'],col:'#2E8B57',pops:['maj'],ix:[],blurb:tr('long_tail.the_marshall_islands_telco_two')}); NETS.push( {id:'onc',name:'One Commotion',asn:3855,type:'eye',cc:'BM',pol:'selective',minIx:1,minPni:8,share:.001,up:['lvl','tly'],col:'#E4007C',pops:['bda'],ix:[],blurb:tr('long_tail.bermuda_s_phones_tv_and_internet')}, {id:'cvt',name:'Curriculum Vitae Telecom',asn:37517,type:'t2',cc:'CV',pol:'open',share:.002,price:8,up:['tat','tly'],col:'#004B87',pops:['rai','lis','for','dkr'],ix:['rai'],blurb:tr('long_tail.cape_verde_s_incumbent_and_the')}, From 7cbe0ec09b4d8949a8f789a83d8890bd7f5e52a1 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 10:03:20 +0100 Subject: [PATCH 3/4] Regenerate published weekly puzzles when a release's prices break them --check now re-solves every week not over yet and, when its budget no longer verifies, regenerates it deterministically: the same puzzle with a new budget if that works, else a fresh one for the key. A regenerated file carries rev 2, 3...; the game keeps stars per revision, so only that week's stars reset. Past weeks are left alone unless the game rejects them. release.yml runs it before the tests on every deploy, weekly-puzzle.yml before making the new week; either fails only if a week cannot be regenerated. --- .claude/skills/github-pages/SKILL.md | 3 +- .claude/skills/release/SKILL.md | 7 +++ .github/workflows/release.yml | 14 ++++-- .github/workflows/weekly-puzzle.yml | 3 ++ CHANGELOG.md | 1 + scripts/weekly-puzzle.js | 60 ++++++++++++++++++++--- src/game/60-features/92-puzzles.js | 10 ++-- src/game/60-features/93-puzzles-weekly.js | 8 +-- src/game/95-modals/95-puzzles.js | 2 +- tests/weekly-puzzle.test.js | 50 ++++++++++++++++++- 10 files changed, 135 insertions(+), 23 deletions(-) diff --git a/.claude/skills/github-pages/SKILL.md b/.claude/skills/github-pages/SKILL.md index f57d959..69d4a49 100644 --- a/.claude/skills/github-pages/SKILL.md +++ b/.claude/skills/github-pages/SKILL.md @@ -45,7 +45,8 @@ steps. 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. Weekly files are plain JSON the game fetches only when the +`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. See `docs/ARCHITECTURE.md`. ## Before you hand back a change that touches the build, deploy or loading diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index 0378f48..99f8b4d 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -21,6 +21,13 @@ version for a weekly puzzle. To publish or fix one by hand: `node scripts/weekly `gh workflow run release.yml --ref -f tag= -f weekly=true`). A release includes every weekly file on `main` when it builds. +**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. + ## Only release when Frederic says so Never bump the version on your own. Finished work is committed and pushed with its diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 801aee4..fe2070b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -80,16 +80,20 @@ jobs: echo "Weekly puzzles: $(ls site/puzzles/weekly | grep -c '^[0-9].*\.json$')" fi - run: npm ci - - run: npm test - if: ${{ !inputs.weekly }} - - name: Check the weekly puzzles against this release - if: ${{ inputs.weekly }} + # 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 - npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js + - run: npm test + if: ${{ !inputs.weekly }} + - name: Test the weekly puzzles against this release + if: ${{ inputs.weekly && hashFiles('scripts/weekly-puzzle.js') != '' }} + run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js - name: Build site run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build - uses: actions/upload-pages-artifact@v5 diff --git a/.github/workflows/weekly-puzzle.yml b/.github/workflows/weekly-puzzle.yml index 09cf814..0629330 100644 --- a/.github/workflows/weekly-puzzle.yml +++ b/.github/workflows/weekly-puzzle.yml @@ -45,6 +45,9 @@ jobs: 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 - name: Make the puzzle run: | set -euo pipefail diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c71bd6..e56d08c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,7 @@ All notable changes to this project are documented here. The project follows - 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. - 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). - Palau's and the Marshall Islands' main networks now show their real AS numbers instead of ones borrowed from networks elsewhere. +- 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. ## [1.37.0] — 2026-10-28 diff --git a/scripts/weekly-puzzle.js b/scripts/weekly-puzzle.js index 93b6edd..11c654f 100644 --- a/scripts/weekly-puzzle.js +++ b/scripts/weekly-puzzle.js @@ -7,7 +7,8 @@ // node scripts/weekly-puzzle.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing // node scripts/weekly-puzzle.js --key 2026-W45 that week (--force replaces an existing file) // node scripts/weekly-puzzle.js --next 3 this week and the next two -// node scripts/weekly-puzzle.js --check validate every file (and re-verify the stars of weeks not over yet) +// node scripts/weekly-puzzle.js --check regenerate weeks not over yet whose budget this game no longer verifies +// (see refresh()), then validate every file; fails only if that fails // --page FILE play another build of the game (the live release), see the workflow // --dir DIR where the files live (default site/puzzles/weekly) // @@ -250,6 +251,7 @@ function play(ev, def, links) { ev('closeModal()'); return JSON.parse(ev('JSON.stringify((({stars,spend,goal,n1,cheap})=>({stars,spend,goal,n1,cheap}))(pzEval()))')); } +// A first edition has no rev; refresh() adds rev 2, 3… when it regenerates a week. const fileOf = (key, P, budget, w, sol) => ({ v: SCHEMA, key, theme: P.theme, cities: P.cities, via: P.via, avoid: P.avoid, budget, twist: Object.assign({}, P.ring ? { ring: true } : {}, P.noSub ? { noSub: true } : {}, P.lat ? { lat: P.lat } : {}), name: w.name, joke: w.joke, ref: { one: sol.one.cost, three: sol.three.cost } }); @@ -267,6 +269,14 @@ function verify(g, W, j, key) { return { ok: true, sol, s1, s3 }; } +// Three stars need the smart design: the budget sits just above the cheapest N-1 build found, and below the +// obvious one (a second way along every hop) whenever there is room. +function budgetOf(sol) { + let budget = ceil10k(sol.three.cost * 1.05); + if (sol.naive && budget >= sol.naive.cost) budget = Math.max(ceil10k(sol.three.cost), Math.floor((sol.naive.cost - 1) / 10000) * 10000); + return budget; +} + function generate(g, key, dir) { const { ev } = g, W = world(ev); if (ev(`pzWeekStart('${key}')`) == null) throw new Error(`${key} is not a week`); @@ -281,11 +291,7 @@ function generate(g, key, dir) { if (!P || hist.regs.some((c) => W.C[c] && W.C[c].reg === W.C[P.cities[0]].reg && W.C[c].lands[0] === W.C[P.cities[0]].lands[0])) continue; const sol = solve(W, P); if (!sol.one || !sol.three) continue; - // Three stars need the smart design: the budget sits just above the cheapest N-1 build found, and below the - // obvious one (a second way along every hop) whenever there is room. - let budget = ceil10k(sol.three.cost * 1.05); - if (sol.naive && budget >= sol.naive.cost) budget = Math.max(ceil10k(sol.three.cost), Math.floor((sol.naive.cost - 1) / 10000) * 10000); - const smart = sol.naive ? sol.naive.cost / budget : 1.05, slack = budget / sol.one.cost; + const budget = budgetOf(sol), smart = sol.naive ? sol.naive.cost / budget : 1.05, slack = budget / sol.one.cost; const score = Math.min(smart, 1.6) + Math.min(slack, 2) * 0.2 + r() * 0.05; cands.push({ P, sol, budget, score, w: words(ev, W, P, r) }); } @@ -315,16 +321,54 @@ function check(g, dir, now = Date.now()) { } return bad; } +/* --check, first part: a release can change prices, cables or cities under weeks that are already published. Every + week not over yet is re-solved with this game; when its budget no longer verifies it is regenerated, deterministically: + the same puzzle (theme, cities, twist, name) with a new budget when that still works, else a fresh puzzle for the + same key. Its rev goes up, so players' stars for that week (and only that week) start again; new references alone + keep the rev. Past weeks can no longer be played, so they keep their stars and are only replaced when the game + rejects them outright. Returns what changed and what could not be fixed. */ +function refresh(g, dir, now = Date.now()) { + const { ev } = g, W = world(ev), fixed = [], bad = []; + for (const k of list(dir)) { + const f = path.join(dir, k + '.json'); + let j = null; try { j = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { /* regenerated below */ } + const valid = !!j && ev(`!!pzWkValid(${JSON.stringify(j)},'${k}')`), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now; + if (valid && !live) continue; + const v = valid ? verify(g, W, j, k) : null; + if (v && v.ok) { + if (j.ref && j.ref.one === v.sol.one.cost && j.ref.three === v.sol.three.cost) continue; + j.ref = { one: v.sol.one.cost, three: v.sol.three.cost }; writeWeek(dir, j); fixed.push(`${k}: new references`); continue; + } + const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1; + let n = null; + if (valid) { + const def = JSON.parse(ev(`JSON.stringify(pzWkValid(${JSON.stringify(j)},'${k}'))`)); + const sol = solve(W, { theme: def.theme, cities: def.cities, via: def.via, avoid: def.avoid, noSub: def.noSub, ring: def.ring, lat: def.lat }); + if (sol.one && sol.three) { + const c = Object.assign({}, j, { budget: budgetOf(sol), ref: { one: sol.one.cost, three: sol.three.cost }, rev }); + if (verify(g, W, c, k).ok) n = c; + } + } + if (!n) { try { n = Object.assign(generate(g, k, dir), { rev }); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); continue; } } + writeWeek(dir, n); fixed.push(`${k}: regenerated as rev ${rev}${n.theme === (j && j.theme) && JSON.stringify(n.cities) === JSON.stringify(j.cities) ? ', same puzzle, new budget ' + n.budget : ', a new ' + n.theme + ' puzzle'}`); + } + let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* rewritten */ } + if (list(dir).length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(list(dir)))) { writeIndex(dir); fixed.push('index.json rewritten'); } + return { fixed, bad }; +} const writeIndex = (dir) => fs.writeFileSync(path.join(dir, 'index.json'), JSON.stringify({ v: SCHEMA, weeks: list(dir) }) + '\n'); const writeWeek = (dir, j) => { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify(j) + '\n'); writeIndex(dir); }; -module.exports = { game, generate, check, solve, world, writeWeek, writeIndex, list }; +module.exports = { game, generate, check, refresh, solve, world, writeWeek, writeIndex, list }; if (require.main === module) { const args = process.argv.slice(2), opt = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; }; const dir = path.resolve(ROOT, opt('--dir', 'site/puzzles/weekly')), g = game(opt('--page') && path.resolve(opt('--page'))); if (args.includes('--check')) { - const bad = check(g, dir); + // Fix what a release's new prices broke, then check everything; only what could not be fixed fails. + const r = refresh(g, dir); + for (const x of r.fixed) console.log(`fixed: ${x}`); + const bad = [...r.bad, ...check(g, dir)]; for (const b of bad) console.error(`error: ${b}`); console.log(bad.length ? `${bad.length} problem(s)` : `${list(dir).length} weekly puzzle(s) OK`); process.exit(bad.length ? 1 : 0); diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index fff7bb3..232a4cf 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -10,11 +10,13 @@ const pzName=d=>d.id==='weekly'?(d.wn?pzTxt(d.wn):tr('puzzles.weekly_puzzle_key' const pzStarStr=n=>'⭐'.repeat(n)+'⬜'.repeat(3-n); // ---------- progress (localStorage, never trusted) ---------- function pzClean(j){const o={s:{},wk:{},streak:{last:null,n:0,best:0}};if(!j||typeof j!=='object')return o; - const rec=r=>r&&typeof r==='object'?{st:int(r.st,0,3,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)}:null; + const rec=r=>{if(!r||typeof r!=='object')return null;const o={st:int(r.st,0,3,0),sp:r.sp==null||!isFinite(+r.sp)||+r.sp<0?null:Math.round(+r.sp)},rv=int(r.rv,1,999,1);if(rv>1)o.rv=rv;return o;}; if(j.s&&typeof j.s==='object')for(const k of Object.keys(j.s)){const r=rec(j.s[k]);if(pzDef(k)&&r)o.s[k]=r;} if(j.wk&&typeof j.wk==='object')for(const k of Object.keys(j.wk)){const r=rec(j.wk[k]);if(/^\d{4}-W\d{2}$/.test(k)&&r)o.wk[k]=r;} const st=j.streak;if(st&&typeof st==='object'){o.streak.last=typeof st.last==='string'&&/^\d{4}-W\d{2}$/.test(st.last)?st.last:null;o.streak.n=int(st.n,0,9999,0);o.streak.best=int(st.best,0,9999,0);} return o;} +// A weekly's stars belong to the revision they were earned on: a week regenerated for new prices starts again. +const pzWkRec=(p,d)=>{const r=p.wk[d.key];return r&&(r.rv||1)===(d.rev||1)?r:null;}; function pzLoad(){try{return pzClean(JSON.parse(localStorage.getItem(PZ_KEY)||'{}'));}catch(e){return pzClean(null);}} function pzStore(p){try{localStorage.setItem(PZ_KEY,JSON.stringify(p));}catch(e){}} const pzStarsTotal=p=>PZ.reduce((a,x)=>a+((p.s[x.id]||{}).st|0),0); @@ -86,7 +88,7 @@ const pzToastsClear=()=>{$('toasts').textContent='';}; function pzFlush(){save(true);UI.pzKeep=S;} function pzBegin(def){if(!def)return; const go=()=>{newGame(pzName(def),def.cities[0]);S.pops={};S.mode='puzzle';S.rules=makeRules('puzzle');S.nextFail=S.nextEvent=1e9;S.tut=null; - S.pz={id:def.id,key:def.key||null,cities:def.cities.slice(),via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,minG:def.minG||0,lat:def.lat?def.lat.slice():null,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null}; + S.pz={id:def.id,key:def.key||null,cities:def.cities.slice(),via:(def.via||[]).slice(),avoid:(def.avoid||[]).slice(),budget:def.budget||0,noSub:!!def.noSub,ring:!!def.ring,minG:def.minG||0,lat:def.lat?def.lat.slice():null,wn:def.wn||null,wj:def.wj||null,theme:def.theme||null,rev:def.rev||1}; UI.pzHist=[];UI.pzTop=0;UI.speed=0;UI.resumeSpeed=null;UI.started=true;UI.sel=null;UI.leftOpen=false;UI.confirm=null;UI._pzh=null; $('dash').hidden=true;$('bankBox').hidden=true;closeModal();pzToastsClear();document.body.classList.add('pz'); compute();pzCam();renderAll();track('puzzle_'+def.id); @@ -114,8 +116,8 @@ function pzAfter(){if(UI.sel&&((UI.sel.type==='link'&&!S.links.some(l=>l.id===UI // Every solved state is recorded, so a cheaper build at the same stars counts too. function pzCheck(){const e=pzEval();if(e.stars)pzRecord(e);if(e.stars<=(UI.pzTop||0))return e;const prev=UI.pzTop||0;UI.pzTop=e.stars;pzResults(e,prev);return e;} // The best spend belongs to the best star count: more stars start it again, the same stars keep the lower spend. -function pzRecord(e){const p=pzLoad(),P=S.pz,bag=P.id==='weekly'?p.wk:p.s,k=P.id==='weekly'?P.key:P.id,r=bag[k]||{st:0,sp:null}; +function pzRecord(e){const p=pzLoad(),P=S.pz,bag=P.id==='weekly'?p.wk:p.s,k=P.id==='weekly'?P.key:P.id,r=(P.id==='weekly'?pzWkRec(p,P):bag[k])||{st:0,sp:null}; if(e.stars1)r.rv=P.rev;else delete r.rv;bag[k]=r;if(P.id==='weekly')pzStreak(p,P.key);pzStore(p);} // The next puzzle in the list whose pack is open. function pzNextDef(){const p=pzLoad(),i=PZ.findIndex(x=>x.id===S.pz.id);for(let j=i+1;j0&&v<1000)out[k]=v;else return null;} return {l:o.l,p:out};} -const PZ_WK_FIELDS=['v','key','theme','cities','via','avoid','budget','twist','name','joke','ref']; +// rev: the file's revision, from 2 when a release's new prices made the week regenerate (scripts/weekly-puzzle.js). +const PZ_WK_FIELDS=['v','key','theme','cities','via','avoid','budget','twist','name','joke','ref','rev']; function pzWkValid(j,key){if(!pzObj(j)||Object.keys(j).some(k=>!PZ_WK_FIELDS.includes(k))||j.v!==1||j.key!==key||pzWeekStart(key)==null||typeof j.theme!=='string'||!own(PZ_WK_THEMES,j.theme))return null; const T=PZ_WK_THEMES[j.theme],ids=(a,lo,hi)=>Array.isArray(a)&&a.length>=lo&&a.length<=hi&&a.every(pzCityOk)&&new Set(a).size===a.length?a.slice():null; const cities=ids(j.cities,3,6),via=ids(j.via==null?[]:j.via,0,4),avoid=ids(j.avoid==null?[]:j.avoid,0,2);if(!cities||!via||!avoid)return null; const all=[...cities,...via,...avoid];if(new Set(all).size!==all.length)return null; if(!Number.isInteger(j.budget)||j.budget<50000||j.budget>1e7)return null; const tw=j.twist==null?{}:j.twist;if(!pzObj(tw)||Object.keys(tw).some(k=>!['lat','ring','noSub','minG'].includes(k)))return null; - const d={id:'weekly',key,theme:j.theme,cities,via,avoid,budget:j.budget,noSub:false,ring:false,minG:0,lat:null}; + if(j.rev!==undefined&&!(Number.isInteger(j.rev)&&j.rev>=2&&j.rev<=999))return null; + const d={id:'weekly',key,theme:j.theme,cities,via,avoid,budget:j.budget,noSub:false,ring:false,minG:0,lat:null,rev:j.rev||1}; if(own(tw,'ring')){if(tw.ring!==true)return null;d.ring=true;} if(own(tw,'noSub')){if(tw.noSub!==true)return null;d.noSub=true;} if(own(tw,'minG')){if(![100,400].includes(tw.minG))return null;d.minG=tw.minG;} @@ -72,4 +74,4 @@ function pzWkRefresh(){const el=$('pzWk');if(el)el.outerHTML=pzWkRow();} function pzWkNext(now){const key=pzWeekKey(now),t=pzWeekStart(pzKeyAdd(key,1))-now,m=Math.max(1,Math.ceil(t/60e3)),d=Math.floor(m/1440),h=Math.floor(m%1440/60); return d?tr('puzzles.next_weekly_in_d_h',{d,h}):tr('puzzles.next_weekly_in_h_m',{h,m:m%60});} // The Puzzles door says so when this week's puzzle has not been played yet. -function pzWkNew(){try{return !pzLoad().wk[pzWeekKey(new Date())];}catch(e){return false;}} +function pzWkNew(){try{const k=pzWeekKey(new Date()),w=UI.pzWk;return !pzWkRec(pzLoad(),w&&w.key===k&&w.def?w.def:{key:k});}catch(e){return false;}} diff --git a/src/game/95-modals/95-puzzles.js b/src/game/95-modals/95-puzzles.js index dc45fdf..1a1f639 100644 --- a/src/game/95-modals/95-puzzles.js +++ b/src/game/95-modals/95-puzzles.js @@ -75,7 +75,7 @@ function pzResults(e,prev){const P=S.pz,nx=P.id==='weekly'?null:pzNextDef(),left if(e.stars>=3&&prev<3)setTimeout(()=>sfx('fanfare'),(3-prev)*450+250);} // ---------- the list ---------- // The weekly row: the published puzzle once it has come (or the seeded one), its countdown and the streak. -function pzWkRow(){const p=pzLoad(),w=pzWkDef(),wr=p.wk[w.key],st=p.streak,streak=st.last===w.key||st.last===pzPrevKey(w.key)?st.n:0,T=PZ_WK_THEMES[w.theme],load=pzWkLoading(),tg=pzTwistTag(w); +function pzWkRow(){const p=pzLoad(),w=pzWkDef(),wr=pzWkRec(p,w),st=p.streak,streak=st.last===w.key||st.last===pzPrevKey(w.key)?st.n:0,T=PZ_WK_THEMES[w.theme],load=pzWkLoading(),tg=pzTwistTag(w); return `
📅 ${tr('puzzles.weekly_puzzle_key',{key:esc(w.key)})}${wr?'':` ${tr('puzzles.new_this_sunday')}`}
${load?tr('puzzles.loading_this_week_s_puzzle'):`${T?T.i+' ':''}${esc(pzName(w))}`} ${wr?`${pzStarStr(wr.st)}`:''}
${w.wj?`
${esc(pzTxt(w.wj))}
`:''}
${w.cities.map(c=>esc(CITY[c].name)).join(' · ')} · ${tr('puzzles.budget_x',{x:fmt$(w.budget)})}${tg.length?' · '+tg.join(' · ')+'':''}${wr&&wr.sp!=null?' · '+tr('puzzles.best_x',{x:fmt$(wr.sp)}):''}
diff --git a/tests/weekly-puzzle.test.js b/tests/weekly-puzzle.test.js index f8107f5..e41c26e 100644 --- a/tests/weekly-puzzle.test.js +++ b/tests/weekly-puzzle.test.js @@ -96,7 +96,8 @@ test('generator: a quarter of weeks, all verified, varied, small and in the sche test('--check passes on the committed files and rejects tampered ones', () => { const g = G.game(); - // Weeks still to come are re-solved; past ones are checked the way the game reads them. + // Weeks still to come are re-solved; past ones are checked the way the game reads them. check() only reports; + // refresh() (the first half of --check) is what fixes. assert.deepEqual(G.check(g, DIR), [], 'committed weeklies verify'); const bad = (edit, why) => { const d = tmp(); @@ -117,6 +118,53 @@ test('--check passes on the committed files and rejects tampered ones', () => { bad((j, d) => { fs.writeFileSync(path.join(d, 'index.json'), '{"v":1,"weeks":[]}'); }, 'an index that misses weeks'); }); +test('--check regenerates a published week when new prices break its budget, and only then', () => { + const g = G.game(), d = tmp(); + for (const k of G.list(DIR)) fs.copyFileSync(path.join(DIR, k + '.json'), path.join(d, k + '.json')); + G.writeIndex(d); + const read = (k) => JSON.parse(fs.readFileSync(path.join(d, k + '.json'), 'utf8')), [k0, k1] = G.list(d).slice(-2); + assert.deepEqual(G.refresh(g, d, 0), { fixed: [], bad: [] }, 'the committed weeks still verify: nothing changes'); + // Prices went up: the old budget no longer buys the N-1 build. The same puzzle comes back with a budget that does. + const old = read(k0), j = read(k0); j.budget = Math.floor(j.ref.three * 0.8 / 10000) * 10000; j.ref.three = j.budget - 1; + fs.writeFileSync(path.join(d, k0 + '.json'), JSON.stringify(j)); + const r = G.refresh(g, d, 0); + assert.deepEqual(r.bad, []); + assert.equal(r.fixed.length, 1, r.fixed.join('; ')); + const n = read(k0); + assert.equal(n.rev, 2, 'a new revision'); + assert.deepEqual([n.theme, n.cities, n.via, n.avoid, n.twist, n.name, n.joke], [old.theme, old.cities, old.via, old.avoid, old.twist, old.name, old.joke], 'the same puzzle'); + assert.ok(n.budget >= n.ref.three && n.ref.three > j.budget); + assert.deepEqual(G.check(g, d, 0), [], 'and it verifies'); + assert.deepEqual(G.refresh(g, d, 0), { fixed: [], bad: [] }, 'deterministic and settled: a second run changes nothing'); + // A week the game rejects (a city that is gone) gets a fresh puzzle under the same key. + const b = read(k1); b.cities[0] = 'xxx'; fs.writeFileSync(path.join(d, k1 + '.json'), JSON.stringify(b)); + assert.equal(G.refresh(g, d, 0).fixed.length, 1); + assert.equal(read(k1).key, k1); + assert.equal(read(k1).rev, 2); + assert.deepEqual(G.check(g, d, 0), []); + // Weeks that are over cannot be played again: their stars stay, so a broken budget there is left alone. + const e = read(k0); e.budget = 50000; fs.writeFileSync(path.join(d, k0 + '.json'), JSON.stringify(e)); + assert.deepEqual(G.refresh(g, d, 8.64e15), { fixed: [], bad: [] }); +}); + +test('stars belong to the revision of the week they were earned on', () => { + const { ev, errors } = load(); + const j = committed()[0], k = j.key, ok = (o) => ev(`!!pzWkValid(${JSON.stringify(o)},'${k}')`); + assert.equal(ev(`pzWkValid(${JSON.stringify(j)},'${k}').rev`), 1, 'a first edition is rev 1'); + assert.ok(ok({ ...j, rev: 2 })); + for (const rev of [1, 0, '2', 2.5, 1000]) assert.equal(ok({ ...j, rev }), false, `rev ${rev}`); + ev(`localStorage.setItem('sot-puzzles',JSON.stringify({wk:{'${k}':{st:3,sp:1},'2026-W01':{st:2,sp:5}}}))`); + assert.equal(ev(`pzWkRec(pzLoad(),pzWkValid(${JSON.stringify(j)},'${k}')).st`), 3, 'same week, same revision: the stars stand'); + const d2 = `pzWkValid(${JSON.stringify({ ...j, rev: 2 })},'${k}')`; + assert.equal(ev(`pzWkRec(pzLoad(),${d2})`), null, 'regenerated: that week starts again'); + ev(`pzBegin(${d2});pzRecord({stars:1,spend:9})`); + const p = JSON.parse(ev("localStorage.getItem('sot-puzzles')")); + assert.deepEqual(p.wk[k], { st: 1, sp: 9, rv: 2 }, 'a lower score on the new revision replaces the old one'); + assert.deepEqual(p.wk['2026-W01'], { st: 2, sp: 5 }, 'other weeks keep theirs'); + assert.equal(ev(`pzWkRec(pzLoad(),${d2}).st`), 1); + assert.deepEqual(errors, []); +}); + test('the page never asks for a weekly puzzle on load, only when Puzzles opens', async () => { const { ev, errors } = load(); ev("window.__f=[];window.fetch=(u,o)=>{__f.push(String(u));return Promise.resolve({ok:false,json:()=>Promise.reject()})}"); From cc89a266f3fe4bbbb30012c1d31bc480c99d8cd0 Mon Sep 17 00:00:00 2001 From: Frederic Jung Date: Thu, 29 Oct 2026 10:33:12 +0100 Subject: [PATCH 4/4] Lighter NOC traffic table: fewer elements and inline styles per network row The traffic tab lists every network with traffic, now 63 more, each with a Peer on all POPs button. Rows drop empty traffic-mix segments, the button's wrapper div and two inline styles (now classes), with the same look. On the big fixture the tab has 16% fewer elements; NOC dashboard tabs 390 -> 331 ms against the previous commit (p=0.014). --- src/game/94-dashboard/60-dashboard.js | 2 +- src/styles/40-modal.css | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/game/94-dashboard/60-dashboard.js b/src/game/94-dashboard/60-dashboard.js index f2c1bf7..269f689 100644 --- a/src/game/94-dashboard/60-dashboard.js +++ b/src/game/94-dashboard/60-dashboard.js @@ -20,7 +20,7 @@ function renderDash(){checkLayer(); if(DT==='conn')h+=connSection(); if(DT==='traffic')h+=`
${btn(tr('ops.standing_orders'),'opsOpen',{},'sm')}
`; if(DT==='traffic')h+=`

${tr('dashboard.traffic_by_network_asn')}

${tr('dashboard.where_your_users_traffic_comes_from')}

${['c','p','ix','t'].map(k=>`${EGC[k][0]}`).join('')}
${[['name',tr('common.network_6974'),''],['asn','AS',''],['type',tr('common.type'),''],['traffic',tr('common.traffic'),'r'],['mix',tr('dashboard.how_it_arrives'),''],['cost',tr('common.transit_cost'),'r'],['lost',tr('common.lost'),'r']].map(([k,l,c])=>``).join('')} - ${nets.map(({n,e,t,want})=>{return ``;}).join('')}
${k==='mix'?l:``}
${logo(n)}${esc(n.name)}${n.pops&&n.pops.some(c=>S.pops[c])?`
${btn(tr('pni_all.peer_on_all_pops'),'pniAllOpen',{net:n.id},'ghost sm')}
`:''}
${n.asn}${TYPE_L[n.type]}${fmtG(t)}
${['c','p','ix','t'].map(k=>``).join('')}
${e.t>0.01?tr('common.price_mo',{price:fmt$((R.cost.transit||0)*e.t/tT)}):'—'}${want>0.01?pct(Math.max(0,1-t/want)):'—'}
`; + ${nets.map(({n,e,t,want})=>{return `${logo(n)}${esc(n.name)}${n.pops&&n.pops.some(c=>S.pops[c])?btn(tr('pni_all.peer_on_all_pops'),'pniAllOpen',{net:n.id},'ghost sm pall'):''}${n.asn}${TYPE_L[n.type]}${fmtG(t)}
${t?['c','p','ix','t'].filter(k=>e[k]>0).map(k=>``).join(''):''}
${e.t>0.01?tr('common.price_mo',{price:fmt$((R.cost.transit||0)*e.t/tT)}):'—'}${want>0.01?pct(Math.max(0,1-t/want)):'—'}`;}).join('')}
`; if(DT==='traffic'){const top=transitTop(S.transit.map(t=>t.id),8);if(top.length)h+=`

${tr('dashboard.who_your_transit_carries')}

${tr('dashboard.the_networks_you_pay_transit_to')}

${top.map(([id,v])=>`
${logo(NET[id])}
${esc(NET[id].name)} AS${NET[id].asn} · ${fmtG(v)} · ${tr('dashboard.about_price_mo',{price:fmt$((R.cost.transit||0)*v/tT)})}
${esc(offTransitHint(id))}
${btn(tr('common.where_6276'),'netFocus',{id},'ghost sm')}
`).join('')}
`;} const ls=S.links.filter(l=>capOf(l)>0).map(l=>({l,u:(R.load[l.id]||0)/capOf(l)})).sort((a,b)=>b.u-a.u).slice(0,8); const rs=Object.keys(S.pops).map(c=>({c,u:(R.nodeLoad[c]||0)/(R.nodeCap[c]||1)})).sort((a,b)=>b.u-a.u).slice(0,6); diff --git a/src/styles/40-modal.css b/src/styles/40-modal.css index cfe106c..9853087 100644 --- a/src/styles/40-modal.css +++ b/src/styles/40-modal.css @@ -97,6 +97,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(--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}