seriesoftubes/tests/gameplay-rules.test.js
Frederic Jung b8d313b029
Alien waves priced against their fiber; crews halve a build at most (#203)
An alien wave rented for about as much as leasing the whole fiber, so a
route sold out to its market earned 11 to 35 times its lease and the
gear paid back in one to three months. A wave now rents for 30% of the
fiber's monthly cost (lease plus amplifiers), and each one sold between
the same two cities goes cheaper, down to 40% of the first: a full
route earns 2 to 6 times its lease. Signed contracts keep their price.
Gameplay rule F6.

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

A typed order (the agent API) could end a wave, dark fiber or cable in a
city the map does not show, and opened a POP there.
2026-11-05 06:50:25 +00:00

491 lines
37 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The game's design rules (.claude/skills/gameplay-rules/SKILL.md): one test per rule id, on the live data.
// A rule may only be broken by an entry in EXCEPTIONS below, with its reason. Never delete a check to make it pass.
const test = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const fs = require('node:fs');
const { execFileSync } = require('node:child_process');
const { load } = require('./harness');
// Every exception names what breaks the rule and why. One per line, sorted within each rule.
const EXCEPTIONS = {
// W2: countries with fewer than two consumer networks of their own, because real life has fewer.
W2: {
AD: 'Andorra Telecom is by law the only telecom operator',
BN: "Since 2019 the state's UNN owns every network in Brunei; the retail brands have none of their own",
CU: 'Cuba has one state operator (ETECSA); Cubacel is its own mobile brand',
DJ: 'Djibouti Telecom is the monopoly for homes and phones',
ER: "EriTel, the state's, is the only network in Eritrea",
FM: 'FSM Telecom is the only operator on Pohnpei',
GL: 'Greenland has one operator (Tusass), for homes, phones and the cables',
KP: 'Star JV is the only network in North Korea',
MC: "Monaco Telecom is the principality's only fixed and mobile operator",
MH: 'the Marshall Islands have one telco (NTA)',
PN: 'Pitcairn has no network at all: land your own cable (#124)',
SH: 'St Helena has one operator (Sure South Atlantic)',
TM: 'Turkmentelecom is the state gateway, and TMCell the state mobile operator behind it',
TV: 'Tuvalu Telecommunications Corporation is the only telco',
YE: "In Sanaa, YemenNet is the only internet gateway; the mobile operators' data goes through it",
},
// W3: cities nobody sells transit in.
W3: {
ivc: 'Invercargill waits for its AI campus; nobody sells transit there yet',
jub: 'Nobody sells transit in Juba: MTN and Zain haul it in from abroad',
pcn: 'Pitcairn: no cable, no network, land your own (#124)',
prr: 'Prince Rupert is a remote town with no carrier in it',
smr: 'San Marino buys its transit from Italian carriers in Bologna and Rimini; nobody sells it in the town',
sre: "Sucre has no exchange or carrier facility: Bolivia's transit is bought in La Paz",
stg: 'Stuttgart is the Only Spätzle-IX scenario city: peering only, by design (#114)',
yfb: 'Iqaluit has no fiber, only satellite: land your own cable (the real plan runs from Nuuk)',
yyj: 'Victoria buys from Telus and Rogers, consumer networks only in the game: link it from Vancouver',
},
// N3: networks in no founding Tier 1's customer cone. Old saves need PNIs with the founding five for Tier 1,
// so anyone outside their cones has to be peered with directly.
N3: {
abb: 'Australians buy only from Australian carriers (#148)',
atl: 'transit-free in India',
bcd: 'transit-free in Canada',
blg: 'Australian, buys from Telstraya (#148)',
btt: 'transit-free incumbent',
cht: 'transit-free in Taiwan',
clr: 'America Movil, transit-free across Latin America',
cmb: 'China (#59): reached through the Chinese carriers',
cmc: 'transit-free incumbent',
cos: 'Greek incumbent, peers for its own reach',
ctc: 'China (#59)',
cun: 'China (#59)',
cxc: 'buys from Spectre-um, which is transit-free',
drz: 'a transit-free Tier 2',
ert: 'Russia: buys from Rostelecomedy (#70)',
etc: 'Cuba: buys from Sparkly Seabone, a Tier 1 only for games since 1.12',
ets: 'transit-free in the Gulf',
ftr: 'buys from Very-Zone, which is transit-free',
inp: 'Australian, buys from Toilet Paper Group (#148)',
jio: 'transit-free in India',
kdi: 'transit-free in Japan',
ktt: 'Korea: sender pays, peer with it yourself',
lgu: 'Korea: sender pays',
lnt: 'Australian (#148)',
lpt: 'Australian (#148)',
meo: 'Portuguese incumbent, peers for its own reach',
mgf: 'Russia: buys from Rostelecomedy (#70)',
npt: 'Australian (#148)',
opt: 'Australian, buys from SingTell (#148)',
pnt: 'Australian (#148)',
rtc: 'Russia (#70)',
sgt: 'a transit-free Tier 2',
skb: 'Korea: sender pays',
spc: 'transit-free incumbent',
stb: 'satellite: peers for its own reach',
stc: 'transit-free in Saudi Arabia',
stj: 'North Korea’s only links are China Unicorn and Rostelecomedy',
teg: 'owns the land crossing; transit-free',
tim: 'buys from Sparkly Seabone, a Tier 1 only for games since 1.12',
tmt: 'buys from Sparkly Seabone, a Tier 1 only for games since 1.12',
tmx: 'transit-free in Mexico',
tmy: 'Malaysian incumbent, peers for its own reach',
tpr: 'Australian (#148)',
tsf: 'Indonesian incumbent, peers for its own reach',
tsy: 'Australian, transit-free (#148)',
ttk: 'transit-free in Turkey',
ups: 'European cable group, peers for its own reach',
vdp: 'a transit-free Tier 2',
viv: 'transit-free in Brazil',
vzn: 'transit-free incumbent',
},
// N7: an exchange port where the network has no PoP.
N7: {
'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: {},
};
// The real names the puns are based on. No network, cable, exchange, data center, router or optic may be called one.
const REAL_NAMES = [
// Tier 1s and carriers
'AT&T', 'Bell Aliant', 'BICS', 'Cogent', 'GlobalConnect', 'GTT', 'Hurricane Electric', 'Level 3', 'Level3', 'Liquid', 'Liquid Intelligent Technologies', 'Lumen', 'Northwestel', 'NTT', 'Orange', 'PCCW', 'SaskTel', 'Seacom', 'Singtel', 'Sparkle', 'Tata', 'Tata Communications', 'Telia', 'Telxius', 'Tusass', 'Vodafone', 'Zayo',
// content and clouds
'Akamai', 'Alibaba Cloud', 'Amazon', 'Amazon Web Services', 'AWS', 'Baidu', 'ByteDance', 'Cloudflare', 'Facebook', 'Fastly', 'Google', 'Mercado Libre', 'Meta', 'Microsoft', 'Netflix', 'Tencent', 'TikTok', 'VK', 'VKontakte', 'Yandex',
// eyeballs and incumbents
', ', 'A1', 'A1 Telekom Austria', 'Afghan Telecom', 'Africell', 'Airtel', 'AIS', 'Algérie Télécom', 'Altibox', 'Altice', 'America Movil', 'Andorra Telecom', 'Angola Cables', 'Antel', 'Areeba', 'ASTCA', 'ATH Kiribati', 'Aussie Broadband', 'AWCC', 'Azercell', 'Aztelekom', 'Batelco', 'Belize Telemedia', 'Bell', 'Bell Canada', 'Belong', 'Beltelecom', 'Bemobile', 'Bezeq International', 'BH Telecom', 'Bhutan Telecom', 'Bitė', 'Brisanet', 'BT', 'BTC', 'Cable & Wireless', 'Cable Bahamas', 'Cablenet', 'Celtiis', 'Cenpac', 'Comores Telecom', 'Congo Telecom', 'Crnogorski Telekom', 'CST', 'Cyta', 'Earthlink', 'Econet', 'EPTC', 'EriTel', 'FL1', 'FSM Telecommunications Corporation', 'Gabon Telecom', 'Gamtel', 'GETESA', 'GO', 'Guyana Telephone & Telegraph', 'Hoi Internet', 'Hormuud', 'Hrvatski Telekom', 'Kazakhtelecom', 'Kcell', 'Kyrgyztelecom', 'L", ', 'Lao Telecom', 'Libyana', 'LTT', 'Magticom', 'Mattel', 'Mauritel', 'MCI', 'Melita', 'MobiCom', 'Moldtelecom', 'Monaco Telecom', 'MPT', 'Muni', 'Natcom', 'Ncell', 'Nepal Telecom', 'Niger Telecoms', 'O!', 'Ocean Link', 'Ogero', 'One Albania', 'Partner', 'SAFITEL', 'SBIN', 'Silknet', 'Slovak Telekom', 'SMART', 'Smart Axiata', 'Somtel', 'Speednet', 'Star JV', 'Sudani', 'Sudatel', 'Syrian Telecom', 'Syriatel', 'Tashi InfoComm', 'TashiCell', 'TCI', 'Team Telecom Armenia', 'Telecel', 'Telecom Liechtenstein', 'Telecom Vanuatu', 'Telekom Slovenije', 'Telenet San Marino', 'Telesur', 'Telia Lietuva', 'Timor Telecom', 'TNM', 'Togocom', 'Tojiktelecom', 'touch', 'Turkmentelecom', 'Tuvalu Telecommunications Corporation', 'Ucom', 'Unified National Networks', 'Unitel', 'Univision', 'UNN', 'Uztelecom', 'YemenNet', 'Zain',
// exchanges and data centers
'AMS-IX', 'ANIX', 'Any2', 'ArmIX', 'BALT-IX', 'BCIX', 'BENIN-IX', 'BFIX', 'BHNIX', 'Borneo-IX', 'btIX', 'BY-IX', 'CAMIX', 'CIX', 'CNX', 'CoreSite', 'CyIX', 'DANIX', 'DE-CIX', 'DigiCo', 'Digital Realty', 'Equinix', 'France-IX', 'GABIX', 'GREX', 'HIX', 'Interxion', 'IRAQ-IXP', 'iseek', 'IX.br', 'ix.kw', 'IXP-GUINEE', 'IXP-HN', 'IXP.ge', 'IXP.mk', 'IXPN', 'JPIX', 'KAZ-GOV-IX', 'KG-IX', 'KIVIX', 'LebIX', 'LINX', 'LIONEX1', 'Manama IX', 'MD-IX', 'Michcom-IX', 'MISPA-IXP', 'MIXP', 'MLIX', 'NAPAfrica', 'NetIX', 'NEXTDC', 'NIX', 'NIX.SK', 'NIXA', 'NL-ix', 'npIX', 'RegPEX', 'SIX', 'SIX.SK', 'SIXP', 'SKNIX', 'SNS-IX', 'SUR-IX', 'SVGIX', 'Tehran IX', 'Telehouse', 'TGIX', 'TIX', 'TJ-IX', 'VIX.VU', 'VNIX-HN', 'WIX-NZ', 'WLG-IX',
// cables
'2Africa', 'Amitié', 'BDSNi', 'CADMOS', 'CARCIP', 'Ceiba-1', 'Ceiba-2', 'DARE1', 'Darwin-Jakarta-Singapore Cable', 'Deep Blue One', 'Dunant', 'East Micronesia Cable', 'Eastern Caribbean Fiber System', 'EllaLink', 'Epic Malta-Sicily Cable System', 'Equiano', 'FALCON', 'Fibralink', 'GO-1', 'Grace Hopper', 'Greenland Connect', 'Greenland Connect North', 'Hibernia Express', 'ICN1', 'Interchange Cable Network 1', 'Jupiter', 'MAREA', 'MedNautilus', 'Melita 1', 'North West Cable System', 'PEACE', 'SEA-ME-WE 6', 'SG-SCS', 'Southern Caribbean Fiber', 'TLSSC', 'Tuvalu Vaka Cable', 'UGARIT', 'Vaka', 'X-Link',
// cable ships, their operators and maintenance clubs
'ACMA', 'ASEAN Explorer', 'ASEAN Protector', 'ASEAN Restorer', 'Cable Innovator', 'Cable Retriever', 'Global Marine', 'Léon Thévenin', 'MECMA', 'Orange Marine', 'Pierre de Fermat', 'René Descartes', 'SEAIOCMA', 'Sophie Germain', 'Sovereign', 'Wave Sentinel', 'Yokohama Zone',
// vendors
'Arista', 'Brocade', 'Ciena', 'Cisco', 'Extreme Networks', 'Huawei', 'Infinera', 'Juniper', 'MikroTik', 'Nokia',
];
const { ev, errors } = load();
ev('ACT.start({})');
const J = (s) => JSON.parse(ev(`JSON.stringify(${s})`));
const country = (cc) => { try { return new Intl.DisplayNames(['en'], { type: 'region' }).of(cc); } catch (e) { return cc; } };
const fail = (id, bad, fix) => assert.deepEqual(bad, [], `${id}: ${bad.join('; ')}. ${fix}`);
const ex = (id, k) => Object.prototype.hasOwnProperty.call(EXCEPTIONS[id] || {}, k);
// ---------- World ----------
test('W1: every city has a country code, a region and real coordinates', () => {
const bad = J(`CITIES.filter(c=>!/^[A-Z]{2}$/.test(c.cc||'')||!['AM','SA','EU','AS','OC','AF'].includes(c.reg)||!(Math.abs(c.lat)<=90&&Math.abs(c.lon)<=180&&CITY_LL[c.id])||!c.land).map(c=>c.id+' ('+c.name+')')`);
fail('W1', bad, 'give it cc (ISO 3166-1 alpha-2; territories have their own), reg, land and an entry in CITY_LL');
});
test('W2: every country on the map has at least two consumer networks of its own', () => {
// "Own": the network names the country in its home markets (cc) and has a PoP there. Consumer networks are the
// eyeballs, and the Tier 1 and Tier 2 incumbents (Doitsche, Tangerine) that sell to homes and phones there.
const rows = J(`(()=>{const cs={};for(const c of CITIES)if(!c.off)(cs[c.cc]=cs[c.cc]||[]).push(c.id);
return Object.keys(cs).sort().map(cc=>[cc,NETS.filter(n=>n.type!=='cdn'&&[].concat(n.cc||[]).includes(cc)&&n.pops.some(p=>CITY[p].cc===cc)).map(n=>n.name)]);})()`);
const bad = rows.filter(([cc, own]) => own.length < 2 && !ex('W2', cc))
.map(([cc, own]) => `${country(cc)} (${cc}) has ${own.length} own eyeball network${own.length === 1 ? '' : 's'}${own.length ? ': ' + own.join(', ') : ''}`);
fail('W2', bad, 'add a real operator of that country (src/game/30-networks/32-homegrown-eyeballs.js) or list it in EXCEPTIONS with a reason');
const stale = Object.keys(EXCEPTIONS.W2).filter((cc) => (rows.find((r) => r[0] === cc) || [cc, [1, 2]])[1].length >= 2);
assert.deepEqual(stale, [], 'W2: these exceptions are no longer needed; remove them');
// a network's home markets are places it really is
const homeless = J(`NETS.filter(n=>n.cc).flatMap(n=>[].concat(n.cc).filter(cc=>!n.pops.some(p=>CITY[p].cc===cc)).map(cc=>n.name+' has no PoP in '+cc))`);
fail('W2', homeless, 'a home market (cc) needs a PoP in that country');
});
test('W3: every city can buy transit from someone, or is a documented exception', () => {
const bad = J(`CITIES.filter(c=>!c.off&&!NETS.some(n=>sellsAt(n,c.id))).map(c=>c.id)`).filter((c) => !ex('W3', c));
fail('W3', bad, 'give a carrier a PoP there (with a price) or list the city in EXCEPTIONS with a reason');
});
test('W4: cables are consistent: real cities, two distinct ends, a length and unique ids', () => {
const bad = J(`CABLE_PAIRS.filter(p=>!CITY[p.a]||!CITY[p.b]||p.a===p.b||!(p.km>0)||!CAB[p.cid]).map(p=>p.cid+':'+p.a+'-'+p.b)`);
fail('W4', bad, 'fix the cable pair in src/game/20-world/60-cables.js');
const ids = J('CABLES.map(c=>c.id)');
assert.equal(new Set(ids).size, ids.length, 'W4: cable ids are unique');
fail('W4', J("CABLES.filter(c=>!c.name||!c.pairs||!c.pairs.length).map(c=>c.id)"), 'every cable has a name and at least one landing pair');
});
test('W5: every island city can be reached: it shares its land, has a cable, or a beach to land one', () => {
const bad = J(`CITIES.filter(c=>!c.off&&!CITIES.some(o=>o!==c&&!o.off&&(o.land===c.land||o.land2===c.land||c.land2===o.land))&&!landing(c.id)).map(c=>c.id)`);
fail('W5', bad, 'land a cable there or give it beach:true');
});
// ---------- Networks ----------
test('N1: network ids and ASNs are unique, ASNs are valid', () => {
const ids = J('NETS.map(n=>n.id)'), asns = J('NETS.map(n=>n.asn)');
fail('N1', ids.filter((x, i) => ids.indexOf(x) !== i), 'network ids must be unique');
fail('N1', asns.filter((x, i) => asns.indexOf(x) !== i).map(String), 'ASNs must be unique');
fail('N1', J("NETS.filter(n=>!Number.isInteger(n.asn)||n.asn<1||n.asn>4294967294||n.asn>=64512&&n.asn<=65534).map(n=>n.id)"), 'use the real, public ASN');
});
test('N2: names are puns: no network, cable, exchange, data center, router, optic or cable ship carries a real name', () => {
const norm = (s) => String(s).toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[’`]/g, "'").replace(/\s+/g, ' ').trim();
const real = new Set(REAL_NAMES.map(norm));
const names = J(`[...NETS.map(n=>['network',n.name]),...CABLES.map(c=>['cable',c.name]),...XIX.map(x=>['exchange',x.name]),
...CITIES.flatMap(c=>[['exchange',c.ix],['data center',c.dc],['data center',c.dc2]]),...RG.map(r=>['router',r.n]),...Object.values(OPT).map(o=>['optic',o.n]),...Object.values(SEAT_ROUTES).flat().map(r=>['cable',r[2]]),...SHIPS.map(x=>['cable ship',x.n]),...LAY_SHIPS.map(n=>['cable ship',n]),...Object.values(SHIP_CLUBS).map(c=>['maintenance club',c.n])].filter(x=>x[1])`);
fail('N2', names.filter(([, n]) => real.has(norm(n))).map(([k, n]) => `${k} “${n}” is a real name`), 'find a pun');
fail('N2', names.filter(([, n]) => /-ish\b/i.test(n)).map(([k, n]) => `${k} “${n}”`), 'no lazy -ish names: find a real pun, or keep the plain word');
});
test('N3: every network sits in a founding Tier 1’s customer cone, or is a documented island', () => {
// The founding five (t1Need() of the oldest saves): every save can reach a network in their cones by peering with them.
const out = J(`NETS.filter(n=>n.type!=='t1'&&n.type!=='cdn'&&!['lvl','ntt','tly','cog','tat'].some(t=>CONE_S[t].has(n.id))).map(n=>n.id)`);
fail('N3', out.filter((id) => !ex('N3', id)).map((id) => `${id} (${ev(`NET.${id}.name`)})`), 'give it a realistic upstream (up) in a founding Tier 1’s cone, or list it in EXCEPTIONS with a reason');
fail('N3', Object.keys(EXCEPTIONS.N3).filter((id) => !out.includes(id)), 'these exceptions are no longer needed; remove them');
fail('N3', J("NETS.filter(n=>(n.up||[]).some(u=>!NET[u]||NET[u].type==='cdn'||u===n.id)).map(n=>n.id)"), 'an upstream is another network that exists and sells transit, never content');
});
test('N4: no upstream cycles', () => {
const bad = J(`(()=>{const o=[];for(const n of NETS){const seen=new Set(),q=(n.up||[]).slice();while(q.length){const u=q.pop();if(u===n.id){o.push(n.id);break;}if(seen.has(u))continue;seen.add(u);q.push(...((NET[u]||{}).up||[]));}}return o;})()`);
fail('N4', bad, 'a network cannot buy transit from its own customers');
});
test('N5: traffic shares are sane', () => {
fail('N5', J("NETS.filter(n=>!(n.share>0&&n.share<0.2)).map(n=>n.id)"), 'every share is positive and below 20%');
for (const t of ['NSH', 'NSH_CN', 'NSH_RU', 'NSH_KRX']) {
assert.ok(Math.abs(ev(`Object.values(${t}).reduce((a,b)=>a+b,0)`) - 1) < 1e-9, `N5: ${t} sums to 1`);
fail('N5', J(`Object.entries(${t}).filter(([k,v])=>!NET[k]||!(v>=0)).map(([k])=>k)`), `${t} only holds real networks, never negative`);
}
// the content giants carry the traffic, eyeballs mostly ask for it
assert.ok(ev("NETS.filter(n=>n.type==='cdn').reduce((a,n)=>a+NSH[n.id],0)") > 0.3, 'N5: content is at least 30% of traffic');
});
test('N6: every network has a type, a peering policy and a translated blurb', () => {
fail('N6', J(`NETS.filter(n=>!['t1','t2','cdn','eye'].includes(n.type)||!['open','selective','restrictive','paid'].includes(n.pol)||!n.blurb||!n.col).map(n=>n.id)`), 'set type, pol, col and blurb:tr(...)');
fail('N6', J("NETS.filter(n=>n.pol==='selective'&&!(n.minIx>=1&&n.minPni>=1)).map(n=>n.id)"), 'selective networks state minIx and minPni');
fail('N6', J("NETS.filter(n=>n.type==='t1'||n.type==='t2'?!(n.price>0):false).map(n=>n.id)"), 'carriers have a transit price');
});
test('N7: presence is real: PoPs are cities, exchange ports only where the network is', () => {
fail('N7', J("NETS.filter(n=>!n.pops.length||n.pops.some(c=>!CITY[c])||new Set(n.pops).size!==n.pops.length).map(n=>n.id)"), 'PoPs are real, distinct city ids');
const bad = J(`NETS.filter(n=>Array.isArray(n.ix)).flatMap(n=>n.ix.filter(c=>!XIXM[c]&&(!CITY[c]||!CITY[c].ix||!n.pops.includes(c))).map(c=>n.id+':'+c))`).filter((k) => !ex('N7', k));
fail('N7', bad, 'an exchange port needs an exchange in that city and a PoP there');
});
// ---------- Modes and rules ----------
test('M1: On-call is the classic game: the default rules, and what old saves load as', () => {
assert.deepEqual(J("(({preset,mods,...r})=>r)(makeRules('oncall'))"), J("(({mods,...r})=>{for(const k of RULE_LATE)delete r[k];return r;})(RULE_DEF)"), 'M1: On-call is RULE_DEF');
assert.deepEqual(J("(()=>{const o=S.rules;S.rules=makeRules('oncall');const v=Object.keys(RULE_OK).map(rule);S.rules=o;return v;})()"), J("Object.keys(RULE_OK).map(k=>RULE_DEF[k])"), 'M1: and plays as RULE_DEF');
assert.equal(ev("(()=>{const o=S.rules;delete S.rules;const p=rulePreset();S.rules=o;return p;})()"), 'oncall', 'M1: no rules means On-call');
// the seeded On-call games are the rest of the suite (tests/game.test.js, tests/rules.test.js); they must stay green
});
test('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', () => {
const P = J('PRESETS'), C = J('CHAOS'), D = J('RULE_DEF'), lead = { quick: 0, real: 1 }, v = (p, k) => P[p][k] !== undefined ? P[p][k] : D[k];
assert.ok(C[P.soft.chaos].m <= C[P.freeze.chaos].m && C[P.freeze.chaos].m <= C[P.oncall.chaos].m && C[P.oncall.chaos].m <= C[P.bgp.chaos].m, 'M2: chaos');
assert.ok(lead[P.soft.lead] <= lead[P.freeze.lead] && lead[P.freeze.lead] <= lead[P.oncall.lead] && lead[P.oncall.lead] <= lead[P.bgp.lead], 'M2: lead times');
assert.ok((!P.soft.market || P.freeze.market) && (!P.freeze.market || P.oncall.market), 'M2: market');
// The softenings only Best Effort has: every other Normal preset keeps the classic game's.
for (const k of ['sea', 'confs', 'broke', 'moods', 'pnis']) for (const p of ['freeze', 'oncall', 'bgp']) assert.equal(v(p, k), D[k], `M2: ${p} keeps ${k}`);
assert.deepEqual(['sea', 'confs', 'broke', 'moods', 'pnis'].map((k) => v('soft', k)), ['timer', false, 'rescue', 'patient', 'instant'], 'M2: Best Effort softens them all');
assert.ok(P.bgp.market && P.bgp.money === 'normal' && P.bgp.gates === 'ladder', 'M2: BGP keeps every hardship');
// seeded: the same network for a year under each preset
const n = {};
for (const p of ['soft', 'freeze', 'oncall', 'bgp']) {
const g = load();
g.ev(`beginGame('Order','fra',${JSON.stringify({ mode: 'normal', preset: p })});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});__reseed(4242);for(let i=0;i<360;i++)dayTick()`);
n[p] = g.ev('S.inc.length+S.stats.survived+(S.stats.incidents||0)');
assert.deepEqual(g.errors, []);
}
assert.ok(n.soft <= n.freeze && n.freeze <= n.oncall && n.oncall <= n.bgp, `M2: incidents in a year: soft ${n.soft}, freeze ${n.freeze}, on-call ${n.oncall}, bgp ${n.bgp}`);
});
test('M3: every subsystem that can annoy the player reads a rule', () => {
// [function, what it must read]
const reads = [['dayPost', 'chaosMul()'], ['fireEvent', "rule('market')"], ['ddosTick', 'ddosOff()'],
['soldOut', "rule('market')"], ['hwMul', "rule('market')"], ['leadDays', "rule('lead')"], ['pniLead', 'leadDays'],
['dfBuildDays', 'leadDays'], ['dayPre', "rule('clock')"], ['snub', "rule('market')"], ['fireFailure', 'shipsOn()'],
['upcomingConfs', 'confsOn()'], ['pniLead', 'pniNow()'], ['dayPost', "rule('broke')"], ['dayPost', "rule('moods')"], ['toast', 'quietOn()']];
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 and no market means a quiet year
const g = load();
g.ev("beginGame('Quiet','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.rules=makeRules('oncall',{chaos:'none',market:false});S.cash=1e9;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});for(let i=0;i<360;i++)dayTick()");
assert.equal(g.ev('S.inc.length+(S.stats.incidents||0)'), 0, 'M3: nothing breaks without chaos');
assert.equal(g.ev("hwMul('rt')"), 1, 'M3: no hardware inflation without the market');
assert.equal(g.ev("CITIES.slice(0,40).some(c=>soldOut('fra',c.id,1))"), false, 'M3: no sold-out routes without the market');
assert.deepEqual(g.errors, []);
assert.ok(Object.keys(EXCEPTIONS.M3).every((f) => ev(`typeof ${f}==='function'`)), 'M3: exceptions name real functions');
});
test('M4: scenarios and the weekly challenge always run On-call', () => {
const g = load();
const bad = [];
for (const id of g.ev('JSON.stringify(SCN.map(x=>x.id))') && JSON.parse(g.ev('JSON.stringify(SCN.map(x=>x.id))'))) {
g.ev(`beginGame('S','${id}'==='weekly'?'fra':SCN.find(x=>x.id==='${id}').city,{mode:'normal',preset:'bgp',rules:{chaos:'spicy'},scn:SCN.find(x=>x.id==='${id}')});if(UI.pendGame)ACT.pitchSkip()`);
if (g.ev('S.rules.preset') !== 'oncall' || g.ev("rule('chaos')") !== 'normal') bad.push(id);
}
g.ev("ACT.startWeekly({sure:1});if(UI.pendGame)ACT.pitchSkip()");
if (g.ev('S.scn&&S.scn.id') !== 'weekly' || g.ev('S.rules.preset') !== 'oncall') bad.push('weekly');
fail('M4', bad, 'beginGame() must give scenarios On-call plus their own S.scn.rules');
assert.deepEqual(g.errors, []);
});
test('M5: Sandbox has no locked feature', () => {
const g = load();
g.ev("beginGame('Box','fra',{mode:'sandbox'});if(UI.pendGame)ACT.pitchSkip()");
assert.equal(g.ev('gatesOpen()'), true, 'M5: gates open');
assert.equal(g.ev('lvl()'), g.ev('LEVELS.length'), 'M5: every level unlocked');
assert.equal(g.ev('cabOpen()'), true, 'M5: own subsea cables');
assert.equal(g.ev("rule('money')"), 'infinite', 'M5: money');
assert.deepEqual(g.errors, []);
});
// ---------- Content ----------
test('C1: every scenario has a goal its card checks, and none is won on day 0', () => {
const g = load();
const ids = JSON.parse(g.ev('JSON.stringify(SCN.map(x=>x.id))'));
assert.equal(new Set(ids).size, ids.length, 'C1: scenario ids are unique');
const bad = [];
for (const id of ids) {
g.ev(`ACT.startScn({id:'${id}',sure:1});if(UI.pendGame)ACT.pitchSkip()`);
const def = `SCN.find(x=>x.id==='${id}')`;
if (!g.ev(`!!(${def}.n&&${def}.d&&${def}.goal&&typeof ${def}.ok==='function'&&${def}.days>0&&CITY[${def}.city])`)) bad.push(id + ': incomplete definition');
if (g.ev(`(()=>{try{return !!${def}.ok();}catch(e){return false;}})()`)) bad.push(id + ': won on day 0');
if (!g.ev(`typeof SCN_PROG['${id}']==='function'&&scnProg().items.length>0`)) bad.push(id + ': no progress card (SCN_PROG)');
}
// The published weekly scenarios too: each committed week starts, has its goal type's card, and needs play.
const wdir = path.join(__dirname, '..', 'site', 'scenarios', 'weekly');
for (const f of fs.readdirSync(wdir).filter((x) => /^\d{4}-W\d{2}\.json$/.test(x))) {
const j = fs.readFileSync(path.join(wdir, f), 'utf8'), id = 'weekly ' + f.slice(0, -5);
if (!g.ev(`wsBegin(${j},'S')`)) { bad.push(id + ': the game rejects it'); continue; }
g.ev('if(UI.pendGame)ACT.pitchSkip();closeModal();compute()');
if (g.ev('wsOk()')) bad.push(id + ': won on day 0');
if (!g.ev('scnProg().items.length>0&&!!scnName()&&!!wsGoalTxt(S.scn.wk)')) bad.push(id + ': no progress card or goal');
if (g.ev('S.rules.preset') !== 'oncall') bad.push(id + ': not On-call (M4)');
}
fail('C1', bad, 'give it n, d, goal, ok(), days, a city and a SCN_PROG entry; its goal must need play');
assert.deepEqual(g.errors, []);
});
test('C2: every puzzle has a 1-star and a 3-star reference solution (tests/puzzles.test.js)', () => {
const src = fs.readFileSync(path.join(__dirname, 'puzzles.test.js'), 'utf8');
const refs = [...src.matchAll(/^\s{2}([a-z0-9]+): \{ one: .*three: /gm)].map((m) => m[1]);
fail('C2', J('PZ.map(p=>p.id)').filter((id) => !refs.includes(id)), 'add its reference solutions to REF in tests/puzzles.test.js (that suite builds and scores them)');
});
test('C3: every player-facing string is translated in every language', () => {
const out = execFileSync(process.execPath, [path.join(__dirname, '..', 'scripts', 'i18n-check.js')], { encoding: 'utf8' });
assert.match(out, /en\.js: \d+ labels, 0 problems/, 'C3: ' + out);
const langs = out.split('\n').filter((l) => /^[a-z]{2}\.js: \d+ missing/.test(l));
assert.ok(langs.length >= 5, 'C3: every language is checked');
fail('C3', langs.filter((l) => !/0 missing, 0 unused, 0 broken/.test(l)), 'run node scripts/i18n-add.js (add-strings skill)');
});
// ---------- Fun and fairness ----------
test('F1: new players get a gentle start: nothing breaks for 45 days, no sold-out routes for 90, no hardware inflation for 180', () => {
const g = load();
g.ev("beginGame('New','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip()");
assert.ok(g.ev('S.nextFail') >= 45 && g.ev('S.nextEvent') >= 40, 'F1: first outage after day 45, first event after day 40');
// the first events are only good news or harmless (a viral hit, a price change, a grant)
const opts = JSON.parse(g.ev(`(()=>{let o=null;const f=eval('('+fireEvent.toString().replace('const e=pick(opts);','o=opts.slice();return;')+')');S.day=45;f();return JSON.stringify(o);})()`));
fail('F1', opts.filter((e) => !['viral', 'price', 'grant'].includes(e)), 'no bad events before day 50');
assert.equal(g.ev("(()=>{for(let d=0;d<90;d++){S.day=d;if(CITIES.some(c=>soldOut('fra',c.id,1)))return true;}return false;})()"), false, 'F1: nothing sold out in the first 90 days');
assert.equal(g.ev("(()=>{S.day=180;return hwMul('rt');})()"), 1, 'F1: hardware prices hold for 180 days');
// customers get 15 days before a bad day costs them mood
g.ev("S.day=10;S.biz=[{id:'b1',city:'fra',city2:null,reqs:[],name:'X',type:'host',bw:5,rate:100,mood:80,since:5}];compute();dayTick()");
assert.ok(g.ev("(S.biz[0]||{mood:0}).mood") >= 80, 'F1: no mood loss in a customer’s first 15 days');
assert.deepEqual(g.errors, []);
});
test('F2: a simple build in a start city makes money within three months on On-call', () => {
// Reference build: launch broadband, the cheapest 100G transit in town, and a port with a route server where there is an exchange.
const bad = [];
for (const city of ['fra', 'nyc', 'sin', 'jnb']) {
const g = load();
g.ev(`beginGame('Ref','${city}',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip()`);
g.ev(`(()=>{const c='${city}',n=NETS.filter(n=>sellsAt(n,c)).sort((a,b)=>a.price*netMult(a,c)-b.price*netMult(b,c))[0];
ACT.launchBB({city:c});ACT.buyTransit({city:c,net:n.id,tier:1});if(ixName(c)){ACT.buyIx({city:c,tier:1,signed:true});ACT.rs({city:c});}})()`);
let month = 0;
for (let m = 1; m <= 3 && !month; m++) { g.ev('for(let i=0;i<30;i++)dayTick()'); if (g.ev('R.revMo-R.costMo') > 0) month = m; }
if (!month || g.ev('S.lost')) bad.push(`${city}: still losing money after 3 months (${Math.round(g.ev('R.revMo-R.costMo'))}/mo)`);
assert.deepEqual(g.errors, []);
}
fail('F2', bad, 'a balance change made the start too hard; fix the balance, or argue for a new N in the gameplay-rules skill');
});
test('F3: a specialist path only brings customers you can already serve', () => {
const g = load();
g.ev("ACT.start({});S.cash=1e9;S.lvl=1;for(const c of ['nyc','chi','ash'])S.pops[c]=S.pops[c]||{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0}");
g.ev("S.links.push({id:'w',a:'nyc',b:'chi',kind:'wave',tier:2,km:kmBetween('nyc','chi'),cut:0,mo:0},{id:'d',a:'chi',b:'ash',kind:'df',own:true,sys:'roadm',ch:['zr4','zr4','zr4','zr4'],km:kmBetween('chi','ash'),sub:false,cable:null,mo:0,trench:'d',cut:0,day:0,ready:0,spares:false},{id:'e',a:'nyc',b:'ash',kind:'df',own:true,sys:'roadm',ch:['zr4'],km:kmBetween('nyc','ash'),sub:false,cable:null,mo:0,trench:'e',cut:0,day:0,ready:0,spares:false});compute()");
const Jg = (x) => JSON.parse(g.ev(`JSON.stringify(${x})`));
const sp = Jg('spots()');
assert.ok(sp.length > 0, 'F3: the reference network is spotted');
const bad = [];
for (const s of sp) {
const T = Jg(`BIZ_T.${s.t}`);
if (!(T.lv > 1)) bad.push(`${s.t} needs no spotting at level 1`);
if (![s.a, s.b].filter(Boolean).every((c) => g.ev(`!!S.pops['${c}']`))) bad.push(`${s.t} names a city without a POP`);
if (s.k === 'lat' && !(g.ev(`bestLat('${s.a}','${s.b}')<=latMaxOf('${s.a}','${s.b}')`))) bad.push(`${s.t} ${s.a}–${s.b} is too slow`);
if (s.k === 'df' && !(s.n >= T.opts[0] * 0.75)) bad.push(`${s.t} ${s.a}–${s.b} asks for far more than the fiber carries`);
}
fail('F3', bad, 'spots0() must only name what the network can serve, or nearly');
assert.deepEqual(g.errors, []);
});
test('F4: the chaos monkey only visits On-call and BGP at 3 a.m., late, for 120 to 240 days, instead of the ordinary failures', () => {
for (const preset of ['freeze', 'oncall', 'bgp']) {
const g = load();
g.ev(`beginGame('Monkey','fra',{mode:'normal',preset:'${preset}'});if(UI.pendGame)ACT.pitchSkip()`);
g.ev("S.cash=1e9;S.lvl=4;for(const c of ['ams','lon','par'])ACT.buildPop({city:c});for(const [a,b] of [['fra','ams'],['ams','lon'],['lon','par'],['par','fra']]){UI.pending={a,b};ACT.buildLink({tier:1});}closeModal()");
g.ev('for(let i=0;i<2;i++)dayTick()');
if (preset === 'freeze') { assert.equal(g.ev('mkElig()'), false, 'F4: never in Change Freeze'); continue; }
assert.ok(g.ev('S.monkey.next') >= 180, 'F4: not before day 180');
g.ev('S.monkey.next=S.day;dayTick();S.nextFail=S.day');
const len = g.ev('S.monkey.until-S.monkey.start');
assert.ok(len >= 120 && len <= 240, `F4: a visit of ${len} days`);
g.ev('for(let i=0;i<40;i++)dayTick()');
assert.ok(g.ev('S.nextFail') <= g.ev('S.day'), 'F4: no ordinary failure fired during the visit');
assert.ok(g.ev("S.inc.filter(i=>i.type==='cut').every(i=>i.until-i.start<=(rule('chaos')==='spicy'?11:7))"), 'F4: snips heal within a week (spicy stretches by half)');
assert.deepEqual(g.errors, []);
}
const g = load();
g.ev("beginGame('Monkey','fra',{mode:'normal',preset:'oncall'});if(UI.pendGame)ACT.pitchSkip();S.mode='sandbox'");
assert.equal(g.ev('mkElig()'), false, 'F4: never in Sandbox');
});
test('F5: rented capacity never outgrows the route\'s market (#203)', () => {
const g = load();
g.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.biz=[];S.offers=[];for(const c of ['jed','gdx'])ACT.buildPop({city:c})");
g.ev("S.links.push({id:'f',a:'jed',b:'gdx',kind:'df',own:true,sys:'roadm',ch:[],km:9089,ready:0,day:0,cut:0,mo:1,trench:'own:f',pairs:1});compute();__reseed(5);ACT.listFiber({id:'f',w:120,p:1})");
g.ev('for(let d=0;d<1500;d++){brTick();if(d%7===0)spawnOffer();}for(const o of S.offers.filter(o=>o.link===\'f\'))ACT.accept({id:o.id})');
assert.ok(g.ev("brSold('jed','gdx')") <= g.ev("brMarket('jed','gdx')"), 'F5: no more than the route wants');
assert.deepEqual(g.errors, []);
});
test('F6: an alien wave is priced against its fiber, and a full route earns a few times its lease (#203)', () => {
const g = load();
g.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;S.biz=[];S.offers=[]");
for (const [a, b] of [['lon', 'par'], ['lon', 'nyc'], ['fra', 'sin'], ['nyc', 'sjc'], ['jed', 'gdx']]) {
const r = JSON.parse(g.ev(`(()=>{const l={id:'f6${a}${b}',a:'${a}',b:'${b}',kind:'df',own:true,sys:'cl',ch:[],km:Math.round(kmBetween('${a}','${b}')),ready:0,day:0,cut:0,mo:1,pairs:2};S.links.push(l);
const F=dfLeaseMo(l.km)+ampCount(l.km)*AMP_MO,M=brMarket(l.a,l.b),rs=[];
for(let i=0;i<M;i++){const r=wwRate(l,1);rs.push(r);S.biz.push({id:uid(),type:'wwave',link:l.id,slots:1,rate:r,city:l.a,city2:l.b,name:'n'+i,bw:1,mood:80,since:0,reqs:[]});}
return JSON.stringify({F,rs});})()`));
assert.ok(r.rs[0] <= 0.3 * r.F + 1, `F6: ${a}-${b} first wave ${r.rs[0]} vs fiber ${r.F}`);
for (let i = 1; i < r.rs.length; i++) assert.ok(r.rs[i] <= r.rs[i - 1], `F6: ${a}-${b} never dearer than the one before`);
const full = r.rs.reduce((x, y) => x + y, 0);
assert.ok(full < 8 * r.F, `F6: ${a}-${b} full route ${(full / r.F).toFixed(1)}× its lease`);
}
assert.deepEqual(g.errors, []);
});
test('F7: extra crews cut a build on land to half its planned time at most (#203)', () => {
const g = load();
g.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e11;S.lvl=4;for(const c of ['fra','mad'])if(!S.pops[c])ACT.buildPop({city:c})");
const km = Math.round(g.ev("kmBetween('fra','mad')")), days = g.ev(`dfBuildDays(${km})`), d0 = g.ev('S.day');
g.ev(`S.links.push({id:'f7',a:'fra',b:'mad',kind:'df',own:true,sys:'roadm',ch:[],km:${km},ready:S.day+${days},day:S.day,cut:0,mo:1,trench:'own:f7',pairs:1});ACT.crews({id:'f7',all:1});for(let i=0;i<50;i++)ACT.crews({id:'f7'})`);
assert.ok(g.ev("S.links.find(l=>l.id==='f7').ready") - d0 >= days / 2, 'F7: never under half the planned build');
assert.deepEqual(g.errors, []);
});
// D1–D4: DDoS as networks see it (#242). tests/ddos-model.test.js plays each one in detail.
const ddFra = (ev) => ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=4;S.nextFail=1e9;S.nextEvent=1e9;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=40;ACT.buyTransit({city:'fra',net:'cog',tier:1});S.pops.fra.rgen=RG.findIndex(r=>r.fsN===8);S.biz.push({id:'g',type:'game',name:'G',city:'fra',bw:10,rate:1,mood:80,since:0,reqs:[]},{id:'d',type:'dia',name:'D',city:'fra',bw:5,rate:1,mood:80,since:0,reqs:[]});compute()");
const ddHit = (ev, g) => ev(`S.ev.ddos={id:'x',city:'fra',tgt:'g',vec:'dns',gbps:${g},start:S.day,until:S.day+2,bh:false};compute()`);
test('D1: attack sizes come from the world, never from your network', () => {
const g = load();
ddFra(g.ev);
g.ev('S.day=400');
const draw = () => g.ev("__reseed(8);JSON.stringify(Array.from({length:500},()=>ddosSize({tgt:'d'})))");
const a = draw();
g.ev('S.pops.fra.bb.d*=10;compute()');
assert.equal(draw(), a, 'D1: ten times the subscribers, the same attacks');
assert.ok(Math.max(...JSON.parse(a)) <= g.ev('DD_REC'), 'D1: never past the record');
g.ev('S.day=10');
assert.ok(Math.max(...JSON.parse(g.ev("__reseed(8);JSON.stringify(Array.from({length:500},()=>ddosSize({tgt:'d'})))"))) <= 2 * g.ev('ddMaxPort()'), 'D1: early floods stay within twice your biggest port');
assert.deepEqual(g.errors, []);
});
test('D2: a full port slows everyone on it', () => {
const g = load();
ddFra(g.ev);
ddHit(g.ev, 200);
assert.equal(g.ev('R.ddos[0].full'), 1, 'D2: the port is full');
assert.ok(g.ev("bizSf(S.biz.find(b=>b.id==='d'),linkIds())") < 0.9, 'D2: the bystander loses traffic');
assert.deepEqual(g.errors, []);
});
test('D3: only upstream tools and scrubbing keep a flood off your ports; Flowspec works behind them, within its budget', () => {
const g = load();
ddFra(g.ev);
ddHit(g.ev, 200);
assert.ok(g.ev('R.ddos[0].fs') > 0 && g.ev('R.ddos[0].full') === 1, 'D3: Flowspec drops what got in, the port stays full');
assert.deepEqual(JSON.parse(g.ev('JSON.stringify(R.fsUse.fra)')), { used: 1, cap: 8 }, 'D3: one rule of the router\'s own eight');
g.ev("S.transit[0].clean=true;compute()");
assert.equal(g.ev('R.ddos[0].full'), 0, 'D3: a clean pipe scrubs upstream');
g.ev("S.transit[0].clean=false;S.scrubs=[{city:'fra',tier:1}];S.scrubMode='always';compute()");
assert.equal(g.ev('R.ddos[0].full'), 0, 'D3: an engaged center pulls it off the ports');
assert.deepEqual(g.errors, []);
});
test('D4: RTBH costs only the target', () => {
const g = load();
ddFra(g.ev);
ddHit(g.ev, 200);
g.ev("ACT.rtbh({id:'x'})");
assert.equal(g.ev("bizSf(S.biz.find(b=>b.id==='g'),linkIds())"), 0, 'D4: the target is dark');
assert.ok(g.ev("bizSf(S.biz.find(b=>b.id==='d'),linkIds())") >= 0.97, 'D4: everyone else is saved');
g.ev('S.ev.ddos.until=S.day;dayTick()');
assert.equal(g.ev('S.stats.ddosSac'), 1, 'D4: sacrificed, not held');
assert.equal(g.ev('S.stats.ddosOk||0'), 0);
assert.deepEqual(g.errors, []);
});
test('no page errors while checking the rules', () => {
assert.deepEqual(errors, []);
});