Merge v2 into v2-gamerules

This commit is contained in:
Frederic Jung 2026-10-29 07:15:56 +01:00
commit 5f09111a95
No known key found for this signature in database
59 changed files with 2256 additions and 199 deletions

View file

@ -135,3 +135,37 @@ test('the share card rings the variant badges', () => {
assert.ok(fiery > plain, `the ring and the tally are drawn (${fiery} > ${plain} calls)`);
assert.deepEqual(errors, []);
});
test('a variant named after an Object prototype key is not a variant', () => {
const { ev, errors } = load();
start(ev);
for (const k of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) {
ev(`const o=JSON.parse(JSON.stringify(S));o.ach={hello:3};o.achP={hello:${JSON.stringify(k)}};S=migrate(o)`);
assert.equal(ev('S.achP.hello'), 'oncall', k);
assert.equal(ev(`bvar(${JSON.stringify(k)}).k`), 'oncall', `bvar(${k})`);
ev(`S.rules={preset:${JSON.stringify(k)}}`);
assert.equal(ev('badgeVar()'), 'oncall', `badgeVar() under preset ${k}`);
}
ev("S.rules={preset:'oncall'};S.achP.hello='constructor';shareCanvas()");
assert.deepEqual(errors, []);
});
test('"Badge upgraded" means the collection on this device got a better variant', () => {
const { ev, errors } = load();
const spy = () => ev("window.__t=[];if(!window.__sp){window.__sp=1;const _t=toast;toast=(h,...a)=>{window.__t.push(h);return _t(h,...a);};}");
// a new game, but this device already holds the frosted badge: the standard one upgrades it
start(ev, 'oncall');
ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2026-01-01',n:'Old',vs:{freeze:'2026-01-01'}}}))");
spy(); earnHello(ev);
assert.match(ev("window.__t.join(' ')"), /Badge upgraded/);
assert.equal(hof(ev).hello.v, 'oncall');
// another new game, the device already holds the fiery one: earning the frosted one is a plain unlock
start(ev, 'freeze');
ev("localStorage.setItem('sot-badges',JSON.stringify({hello:{d:'2026-01-01',n:'Old',vs:{bgp:'2026-01-01'}}}))");
spy(); earnHello(ev);
const t = ev("window.__t.join(' ')");
assert.match(t, /Badge unlocked/);
assert.doesNotMatch(t, /Badge upgraded/);
assert.equal(hof(ev).hello.v, 'bgp', 'the best variant stays on the shelf');
assert.deepEqual(errors, []);
});

24
tests/link-trial.test.js Normal file
View file

@ -0,0 +1,24 @@
// #62 on a big network: a redundancy check routes once (the failed link), and uses the live routing as "before".
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
test('#62 a redundancy check computes only the trial, and matches comparing two fresh routings', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e8;ACT.buildPop({city:'bde'});ACT.buildPop({city:'ams'});S.biz=[{id:'circuit',name:'Test Circuit',type:'l2vpn',city:'fra',city2:'bde',bw:80,rate:1,reqs:[]}]");
ev("S.links=[{id:'main',a:'fra',b:'bde',kind:'wave',tier:1,km:100,mo:100,cut:0},{id:'a',a:'fra',b:'ams',kind:'wave',tier:0,km:100,mo:100,cut:0},{id:'b',a:'ams',b:'bde',kind:'wave',tier:0,km:100,mo:100,cut:0}];compute()");
ev("window.__n=0;window.__c=compute;compute=function(){window.__n++;return window.__c.apply(this,arguments);}");
const t = JSON.parse(ev("JSON.stringify(linkTrial('main'))"));
assert.equal(ev('window.__n'), 1, 'one routing pass per check');
assert.equal(t.split, false);
assert.equal(t.loss, 70);
assert.equal(ev("linkTrial('nope')"), null);
assert.equal(ev('window.__n'), 1, 'an unknown link costs nothing');
ev('compute=window.__c');
// the old way: route the copy twice, before and after the cut
const old = ev(`(()=>{const save=S,live=R;try{S=JSON.parse(JSON.stringify(save));compute();const b=R;S.links[0].cut=S.day+1;compute();
const g=c=>Math.max(0,(b.citySrv[c]||0)-(R.citySrv[c]||0)),l2=Math.max(0,(b.l2.circuit||0)-(R.l2.circuit||0));
return Object.keys(S.pops).reduce((a,c)=>a+(g(c)>.01?g(c):0),0)+(l2>.01?l2:0);}finally{S=save;R=live;}})()`);
assert.equal(t.loss, old);
assert.deepEqual(errors, []);
});

View file

@ -0,0 +1,40 @@
// #131 on Safari: the custom metric field keeps focus through a button tap, and the panel skips re-rendering a
// focused field, so switching between multiplier and cost (or to a preset) left the old panel on screen.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const setup = (ev) => {
ev("ACT.start({});S.cash=1e9;S.lvl=4;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal()");
ev("window.L=S.links[0].id;ACT.selLink({id:L});renderAll();ACT.setMetric({id:L,v:'custom'});renderAll()");
};
test('#131 switching the custom metric mode re-renders even while the field has focus', () => {
const { ev, dom, errors } = load();
const d = dom.window.document;
setup(ev);
d.getElementById('metIn').focus();
assert.equal(d.activeElement.id, 'metIn');
ev("ACT.metricMode({id:L,k:'w'})");
assert.equal(d.getElementById('metIn').getAttribute('step'), '1', 'the field is now the exact cost');
assert.equal(+d.getElementById('metIn').value, ev("S.pairMet[edgeKey(S.links[0])].v"));
d.getElementById('metIn').focus();
ev("ACT.metricMode({id:L,k:'f'})");
assert.equal(d.getElementById('metIn').getAttribute('step'), '0.1', 'and back to a multiplier');
d.getElementById('metIn').focus();
ev("ACT.setMetric({id:L,v:'normal'})");
assert.equal(d.getElementById('metIn'), null, 'a preset hides the field');
assert.deepEqual(errors, []);
});
test('#131 the daily re-render still keeps a half-typed value', () => {
const { ev, dom, errors } = load();
const d = dom.window.document;
setup(ev);
const t = d.getElementById('metIn');
t.focus(); t.value = '3.5';
ev("S.day++;renderPanel()");
assert.equal(d.getElementById('metIn').value, '3.5');
assert.equal(d.activeElement.id, 'metIn');
assert.deepEqual(errors, []);
});

View file

@ -409,8 +409,8 @@ test('#114 Only Spätzle-IX can be won by peering alone', () => {
const { ev, errors } = load();
ev("ACT.startScn({id:'stg',sure:1})");
assert.equal(ev("scnRule('local')&&scnRule('noTransit')"), true);
assert.match(ev("SCN.find(x=>x.id==='stg').goal"), /45%.*300 Gbps/);
assert.deepEqual(JSON.parse(ev("JSON.stringify(scnProg().items.map(x=>x.max))")), [0.45, 300]);
assert.match(ev("SCN.find(x=>x.id==='stg').goal"), /50%.*300 Gbps/);
assert.deepEqual(JSON.parse(ev("JSON.stringify(scnProg().items.map(x=>x.max))")), [0.5, 300]);
// a game saved before the fix picks the rule up on load
ev("const o=JSON.parse(JSON.stringify(S));delete o.scn.rules.local;migrate(o);window.__mig=o.scn.rules.local");
assert.equal(ev('window.__mig'), true);

View file

@ -7,23 +7,24 @@ const { load } = require('./harness');
// `one` earns the goal star, `three` earns all three. A second land link on the same pair is a diverse route.
const REF = {
hello: { one: [['lon', 'nyc', 'grace']], three: [['lon', 'nyc', 'grace'], ['lon', 'nyc', 'amitie']] },
eurotrip: { one: [['lon', 'ams', 'uly'], ['ams', 'fra', 'land']], three: [['lon', 'ams', 'uly'], ['lon', 'ams', 'concerto'], ['ams', 'fra', 'land'], ['ams', 'fra', 'land']] },
shining: { one: [['nyc', 'chi', 'land'], ['chi', 'dal', 'land'], ['dal', 'sjc', 'land']], three: [['nyc', 'chi', 'land'], ['chi', 'sjc', 'land'], ['sjc', 'dal', 'land'], ['dal', 'nyc', 'land']] },
smorgas: { one: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['osl', 'cph', 'land']], three: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['hel', 'cph', 'land'], ['cph', 'osl', 'land']] },
downunder: { one: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['syd', 'bne', 'land']], three: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['adl', 'bne', 'land'], ['bne', 'syd', 'land']] },
aloha: { one: [['sjc', 'hnl', 'scx'], ['hnl', 'syd', 'hwk']], three: [['sjc', 'hnl', 'scx'], ['sjc', 'hnl', 'aag'], ['hnl', 'syd', 'hwk'], ['hnl', 'syd', 'aloha']] },
rimshot: { one: [['sea', 'tok', 'fast'], ['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2']], three: [['sea', 'tok', 'fast'], ['sea', 'tok', 'ncp'], ['tok', 'hkg', 'adc'], ['tok', 'hkg', 'apg'], ['hkg', 'sin', 'sjc2'], ['hkg', 'sin', 'land']] },
fire: { one: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']], three: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']] },
kiwi: { one: [['akl', 'sea', 'hwk'], ['akl', 'syd', 'tasman']], three: [['akl', 'sea', 'hwk'], ['sea', 'hnl', 'hwk'], ['hnl', 'akl', 'hwk'], ['akl', 'syd', 'tasman'], ['akl', 'syd', 'scx']] },
guam: { one: [['tok', 'gum', 'jga'], ['gum', 'syd', 'guam'], ['tok', 'mnl', 'jup']], three: [['tok', 'mnl', 'jup'], ['mnl', 'gum', 'bifrost'], ['gum', 'syd', 'guam'], ['syd', 'tok', 'guam']] },
flash: { one: [['nyc', 'lon', 'hibx']], three: [['nyc', 'lon', 'hibx'], ['nyc', 'lon', 'grace']] },
eurotrip: { one: [['lon', 'ams', 'uly'], ['ams', 'fra', 'land']], three: [['ams', 'lon', 'concerto'], ['ams', 'lon', 'nshuttle'], ['ams', 'fra', 'land'], ['ams', 'fra', 'land']] },
shining: { one: [['nyc', 'chi', 'land'], ['chi', 'dal', 'land'], ['dal', 'sjc', 'land']], three: [['chi', 'nyc', 'land'], ['chi', 'sjc', 'land'], ['dal', 'nyc', 'land'], ['dal', 'sjc', 'land']] },
smorgas: { one: [['osl', 'sto', 'land'], ['sto', 'hel', 'land'], ['osl', 'cph', 'land']], three: [['osl', 'sto', 'land'], ['cph', 'osl', 'land'], ['cph', 'hel', 'land'], ['hel', 'sto', 'land']] },
downunder: { one: [['syd', 'mel', 'land'], ['mel', 'adl', 'land'], ['syd', 'bne', 'land']], three: [['mel', 'syd', 'land'], ['bne', 'syd', 'land'], ['adl', 'mel', 'land'], ['adl', 'bne', 'land']] },
aloha: { one: [['sjc', 'hnl', 'scx'], ['hnl', 'syd', 'hwk']], three: [['hnl', 'sjc', 'scx'], ['hnl', 'sjc', 'aag'], ['hnl', 'syd', 'hwk'], ['hnl', 'syd', 'aloha']] },
rimshot: { one: [['sea', 'tok', 'fast'], ['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2']], three: [['sea', 'tok', 'fast'], ['sea', 'tok', 'ncp'], ['hkg', 'tok', 'apg'], ['hkg', 'tok', 'adc'], ['hkg', 'sin', 'land'], ['hkg', 'sin', 'land']] },
fire: { one: [['tok', 'hkg', 'adc'], ['hkg', 'sin', 'sjc2'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']], three: [['hkg', 'tok', 'adc'], ['hkg', 'sin', 'land'], ['sin', 'syd', 'indigo'], ['syd', 'tok', 'guam']] },
// Hawaiki is Seattle's only cable south, so the second way out runs overland to LA and on via Suva.
kiwi: { one: [['akl', 'sea', 'hwk'], ['akl', 'syd', 'tasman']], three: [['akl', 'syd', 'tasman'], ['akl', 'sea', 'hwk'], ['suv', 'syd', 'scxn'], ['lax', 'sea', 'land'], ['lax', 'suv', 'scxn']] },
guam: { one: [['tok', 'gum', 'jga'], ['gum', 'syd', 'guam'], ['tok', 'mnl', 'jup']], three: [['mnl', 'tok', 'jup'], ['syd', 'tok', 'sushi'], ['gum', 'mnl', 'bifrost'], ['gum', 'syd', 'guam']] },
flash: { one: [['nyc', 'lon', 'hibx']], three: [['lon', 'nyc', 'grace'], ['lon', 'nyc', 'hibx']] },
pingpong: { one: [['lax', 'tok', 'jup']], three: [['lax', 'tok', 'jup'], ['lax', 'sea', 'land'], ['sea', 'tok', 'fast']] },
suez: { one: [['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace']], three: [['fra', 'mrs', 'land'], ['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace'], ['mrs', 'bom', 'twoaf'], ['bom', 'sin', 'land']] },
samba: { one: [['sao', 'mia', 'monet']], three: [['sao', 'mia', 'monet'], ['sao', 'for', 'land'], ['for', 'mia', 'monet']] },
sharks: { one: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land']], three: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land'], ['mil', 'lis', 'land']] },
braces: { one: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix']], three: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix'], ['dub', 'nyc', 'havf']] },
nofra: { one: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']], three: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land'], ['zrh', 'ams', 'land']] },
fatpipes: { one: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1]], three: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1], ['zrh', 'par', 'land', 1]] },
suez: { one: [['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace']], three: [['fra', 'mrs', 'land'], ['fra', 'mrs', 'land'], ['mrs', 'sin', 'peace'], ['bom', 'sin', 'land'], ['bom', 'mrs', 'twoaf']] },
samba: { one: [['sao', 'mia', 'monet']], three: [['for', 'sao', 'land'], ['for', 'sao', 'land'], ['for', 'mia', 'monet'], ['for', 'mia', 'sam1']] },
sharks: { one: [['lis', 'mad', 'land'], ['mad', 'par', 'land'], ['par', 'mil', 'land']], three: [['lis', 'mad', 'land'], ['lis', 'mil', 'land'], ['mad', 'par', 'land'], ['mil', 'par', 'land']] },
braces: { one: [['nyc', 'lon', 'grace'], ['lon', 'dub', 'celtix']], three: [['lon', 'nyc', 'grace'], ['dub', 'nyc', 'havf'], ['dub', 'lon', 'celtix']] },
nofra: { one: [['ams', 'ber', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']], three: [['ams', 'ber', 'land'], ['ams', 'zrh', 'land'], ['ber', 'muc', 'land'], ['muc', 'zrh', 'land']] },
fatpipes: { one: [['par', 'mrs', 'land', 1], ['mrs', 'mil', 'land', 1], ['mil', 'zrh', 'land', 1]], three: [['par', 'zrh', 'land', 1], ['mrs', 'par', 'land', 1], ['mil', 'mrs', 'land', 1], ['mil', 'zrh', 'land', 1]] },
};
// Builds links the way a player does: POP at the first city, then the link picker for each hop.
@ -61,6 +62,45 @@ test('puzzle data: every puzzle is valid, solvable, and its 3-star reference ear
assert.deepEqual(errors, []);
});
// Brute force over every route between the puzzle's cities (one size: 10G, or 100G under minG): is any 3-star build
// cheaper than `limit`? Each cable is one failure unit; each overland link its own trench (a second one is diverse).
function cheaper3(ev, id, limit) {
const D = JSON.parse(ev(`(()=>{pzBegin(pzDef('${id}'));const P=S.pz,cs=[...P.cities,...P.via],tier=P.minG?1:0,o=[];
for(const a of cs)for(const b of cs)if(a<b)for(const r of pzRoutes(a,b)){if((P.noSub&&r.sub)||subWaveWhy(tier,r.km,r.sub))continue;
o.push({a,b,cab:r.cab,cost:pzLinkCost(r,tier,false),ms:r.ms});if(!r.cab)o.push({a,b,cab:null,cost:pzLinkCost(r,tier,true),ms:r.ms,div:1});}
const pop={};for(const c of cs)pop[c]=pzPopCost(c);return JSON.stringify({P,o,pop});})()`));
const { P, o, pop } = D, unit = (i) => o[i].cab ? 'c' + o[i].cab : 't' + i;
const reach = (ls, skip) => { const adj = {}; for (const i of ls) { if (unit(i) === skip) continue; const { a, b } = o[i]; (adj[a] = adj[a] || []).push(b); (adj[b] = adj[b] || []).push(a); }
const seen = new Set([P.cities[0]]), q = [P.cities[0]]; while (q.length) for (const v of adj[q.pop()] || []) if (!seen.has(v)) { seen.add(v); q.push(v); } return P.cities.every((c) => seen.has(c)); };
const lat = (ls) => { const d = { [P.lat[0]]: 0 }, done = new Set(); for (;;) { let u = null; for (const k in d) if (!done.has(k) && (u === null || d[k] < d[u])) u = k; if (u === null) return Infinity; if (u === P.lat[1]) return d[u]; done.add(u);
for (const i of ls) { const l = o[i]; if (l.a !== u && l.b !== u) continue; const v = l.a === u ? l.b : l.a, nd = d[u] + l.ms + 0.05; if (!(nd >= d[v])) d[v] = nd; } } };
const ring = (ls) => { const nb = {}; for (const i of ls) { const { a, b } = o[i]; (nb[a] = nb[a] || new Set()).add(b); (nb[b] = nb[b] || new Set()).add(a); } const ns = Object.keys(nb);
if (ns.length < 3 || !ns.every((c) => nb[c].size === 2)) return false; let prev = null, cur = ns[0], n = 0; do { const nx = [...nb[cur]].find((x) => x !== prev); prev = cur; cur = nx; n++; } while (cur !== ns[0] && n <= ns.length); return n === ns.length; };
const ok = (ls) => { if (!reach(ls, null) || (P.ring && !ring(ls)) || (P.lat && lat(ls) > P.lat[2])) return false; return [...new Set(ls.map(unit))].every((u) => reach(ls, u)); };
let found = null;
const rec = (start, ls, cost) => { if (found) return; if (ls.length && cost < limit - 1) { const pops = new Set(P.cities); for (const i of ls) { pops.add(o[i].a); pops.add(o[i].b); } const tot = cost + [...pops].reduce((x, c) => x + pop[c], 0); if (tot < limit - 1 && ok(ls)) { found = tot; return; } }
if (ls.length >= 7) return; for (let i = start; i < o.length; i++) { if (o[i].div && !ls.some((j) => !o[j].div && !o[j].cab && o[j].a === o[i].a && o[j].b === o[i].b)) continue; if (cost + o[i].cost < limit - 1) rec(i + 1, [...ls, i], cost + o[i].cost); } };
rec(0, [], 0);
return found;
}
test('budgets follow the difficulty curve: roomy first pack, ~10% in the middle, tight N-1 Club', () => {
const { ev, errors } = load();
const SLACK = { hello: [0.15, 0.2], fire: [0.09, 0.11], speed: [0.09, 0.11], n1: [0.05, 0.08] };
const rows = JSON.parse(ev('JSON.stringify(PZ.filter(p=>p.budget).map(p=>({id:p.id,pack:p.pack,budget:p.budget})))'));
for (const { id, pack, budget } of rows) {
ev(`pzBegin(pzDef('${id}'))`);
build(ev, REF[id].three);
const e = evalP(ev);
assert.equal(e.stars, 3, id);
assert.equal(cheaper3(ev, id, e.spend), null, `${id}: the reference is the cheapest 3-star build`);
const slack = budget / e.spend - 1, [lo, hi] = SLACK[pack];
assert.ok(slack >= lo && slack <= hi, `${id}: ${(slack * 100).toFixed(1)}% slack, want ${lo * 100}-${hi * 100}%`);
}
assert.match(ev("PZ_PACKS[0].d"), /Roomy budgets/, 'the first pack does not promise "no budget"');
assert.deepEqual(errors, []);
});
test('stars: goal, budget, N-1 and twists each count', () => {
const { ev, errors } = load();
ev("pzBegin(pzDef('braces'))");
@ -77,6 +117,15 @@ test('stars: goal, budget, N-1 and twists each count', () => {
build(ev, REF.shining.one);
ev("ACT.pzLinkTo({a:'nyc',b:'chi'});ACT.pzVia({v:'land'});ACT.pzDiv({v:0});ACT.pzLink({tier:0})");
assert.equal(ev("new Set(S.links.filter(l=>edgeKey(l)==='chi|nyc').map(pzUnit)).size"), 1, 'same trench shares the cut');
// A cable fails as a whole: two waves on one cable, even between different cities, are one cut.
ev("pzBegin(pzDef('guam'))");
build(ev, [['tok', 'mnl', 'jup'], ['mnl', 'gum', 'bifrost'], ['gum', 'syd', 'guam'], ['syd', 'tok', 'guam']]);
e = evalP(ev);
assert.ok(e.goal && !e.n1, 'both of Sydney\'s links ride the Guam cable: one anchor splits Sydney off');
assert.equal(ev("new Set(S.links.filter(l=>l.cable==='guam').map(pzUnit)).size"), 1, 'one cable, one failure unit');
assert.ok(ev("document.getElementById('pzBox').textContent").includes('One cut splits it: ' + ev('CAB.guam.name')), 'the weak spot names the cable');
ev("ACT.pzRmLink({id:S.links[3].id})");build(ev, [['tok', 'syd', 'sushi']]);
assert.equal(evalP(ev).stars, 3, 'a second cable into Sydney fixes it');
// Twists: no subsea, ring, latency, minimum size, cities to avoid.
ev("pzBegin(pzDef('sharks'))");build(ev, REF.sharks.one);
assert.ok(evalP(ev).goal);
@ -180,16 +229,16 @@ test('weekly puzzle: stable seed per ISO week, solvable, share string and streak
assert.equal(w.key, '2026-W44');
assert.ok(w.cities.length >= 4 && w.cities.length <= 5 && w.budget > 0);
// Every week of a few years can be solved with three stars by its own reference ring.
for (let i = 0; i < 160; i += 7) {
for (let i = 0; i < 400; i += 7) {
ev(`pzBegin(pzWeekly(new Date(2026,0,1+${i})))`);
const ring = JSON.parse(ev('JSON.stringify(pzWeekly(new Date(2026,0,1+' + i + ')).ref)'));
const links = ring.map((x, j) => { const y = ring[(j + 1) % ring.length]; return [x, y, ev(`pzRoutes('${x}','${y}').sort((p,q)=>pzLinkCost(p,0)-pzLinkCost(q,0))[0].via`)]; });
build(ev, links);
const w = JSON.parse(ev('JSON.stringify(pzWeekly(new Date(2026,0,1+' + i + ')))'));
const cabs = w.refVia.filter((v) => v !== 'land');
assert.equal(new Set(cabs).size, cabs.length, `week +${i}: no two hops of the reference ring share a cable`);
build(ev, w.ref.map((x, j) => [x, w.ref[(j + 1) % w.ref.length], w.refVia[j]]));
assert.equal(evalP(ev).stars, 3, `week +${i}`);
}
ev("localStorage.removeItem('sot-puzzles');pzBegin(pzWeekly(new Date(2026,9,28)))");
const ring = w.ref;
build(ev, ring.map((x, j) => { const y = ring[(j + 1) % ring.length]; return [x, y, ev(`pzRoutes('${x}','${y}').sort((p,q)=>pzLinkCost(p,0)-pzLinkCost(q,0))[0].via`)]; }));
build(ev, w.ref.map((x, j) => [x, w.ref[(j + 1) % w.ref.length], w.refVia[j]]));
assert.match(ev('pzShareText(pzEval())'), /^Series of Tubes puzzle 2026-W44 ⭐⭐⭐ \$\d+k · seriesoftub\.es$/);
assert.equal(ev("JSON.parse(localStorage.getItem('sot-puzzles')).streak.n"), 1);
// A streak counts weeks in a row; a gap starts again.
@ -253,3 +302,146 @@ test('puzzles in every language', () => {
assert.deepEqual(errors, [], lang);
}
});
test('a POP in a thin market costs its higher monthly rent too, and the panel says so', () => {
const { ev, errors } = load();
ev("pzBegin(pzDef('kiwi'))");
assert.ok(ev('colo("suv")') > 1, 'Suva is a thin market');
assert.equal(ev("pzPopCost('suv')"), ev("popCost('suv')+12*popMo('suv')"));
assert.ok(ev("pzPopCost('suv')") > ev("popCost('suv')+12*POP_MO"));
ev("selectCity('suv')");
assert.ok(ev("document.getElementById('panelBody').textContent").includes(ev("fmt$(popMo('suv'))") + '/mo'));
assert.deepEqual(errors, []);
});
test('best spend: kept for the best star count, and a cheaper build at the same stars counts', () => {
const { ev, errors } = load();
ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('braces'))");
const rec = () => JSON.parse(ev("JSON.stringify(pzLoad().s.braces||null)"));
build(ev, REF.braces.one);
const two = evalP(ev).spend;
assert.deepEqual(rec(), { st: 2, sp: two });
// A gold-plated third link: N-1 but over budget is still two stars, and dearer, so the best stays.
ev("ACT.pzLinkTo({a:'dub',b:'nyc'});ACT.pzVia({v:'havf'});ACT.pzLink({tier:2});closeModal()");
assert.equal(evalP(ev).stars, 2);
assert.deepEqual(rec(), { st: 2, sp: two });
// Shrinking it to 10G earns the third star: the best spend starts again at the 3-star build.
ev('ACT.pzTier({id:S.links[2].id,tier:0})');
const three = evalP(ev);
assert.equal(three.stars, 3);
assert.deepEqual(rec(), { st: 3, sp: three.spend });
// With a looser budget, a dearer 3-star build does not replace it; going back to the cheaper one keeps it.
ev('S.pz.budget=1e7;ACT.pzTier({id:S.links[0].id,tier:1})');
assert.equal(evalP(ev).stars, 3);
assert.deepEqual(rec(), { st: 3, sp: three.spend });
// A cheaper 3-star build after a dearer first one is recorded (the old code only recorded star rises).
ev("localStorage.removeItem('sot-puzzles')");
ev('ACT.pzTier({id:S.links[1].id,tier:1})');
const dear = evalP(ev).spend;
assert.deepEqual(rec(), { st: 3, sp: dear });
ev('ACT.pzTier({id:S.links[1].id,tier:0});ACT.pzTier({id:S.links[0].id,tier:0})');
assert.deepEqual(rec(), { st: 3, sp: three.spend });
// Fewer stars never overwrite more.
ev('ACT.pzRmLink({id:S.links[2].id})');
assert.deepEqual(rec(), { st: 3, sp: three.spend });
ev('ACT.puzzleMenu({})');
assert.ok(ev("document.getElementById('modalCard').textContent").includes('best ' + ev(`fmt$(${three.spend})`)));
assert.deepEqual(errors, []);
});
test('main-game toasts and leftover buttons do nothing in a puzzle', () => {
const { ev, errors } = load();
ev("ACT.start({});S.cash=1e7;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});save(true)");
ev("toast('main game news','bad',[{l:'Fix',act:'opsOpen',args:{}}]);save(true)");
assert.ok(ev("document.querySelectorAll('#toasts .toast').length") > 0);
const before = ev("localStorage.getItem('sot-save-v1')");
ev("ACT.pzStart({id:'hello'})");
assert.equal(ev("[...document.querySelectorAll('#toasts .toast')].filter(t=>/main game news/.test(t.textContent)).length"), 0, 'main-game toasts are cleared');
ev("ACT.pzPop({city:'lon'})");
const st = () => ev("JSON.stringify({p:S.pops,l:S.links.length,c:S.cash,m:S.mode,te:!!S.te,ops:S.ops,sc:S.scrubs.length,dash:$('dash').hidden,bank:$('bankBox').hidden,left:$('left').hidden,modal:$('modal').hidden,cam:[cam.x,cam.y]})");
const s0 = st();
for (const a of ["opsOpen({})", "inbox({})", "leftTab({t:'noc'})", "focusCity({city:'par'})", "fixInc({id:'x'})", "custGo({id:'x'})", "bank({})", "dash({})",
"exportSave({})", "launchBB({city:'lon'})", "ad({city:'lon'})", "addRouter({city:'lon'})", "upRouter({city:'lon'})", "addSite({city:'lon'})", "buyTE({})",
"buildScrub({city:'lon',tier:0})", "buildPop({city:'par'})", "buyTransit({city:'lon',net:'cog',tier:1})", "scenarios({})", "share({})", "importGo({})", "cont({})", "start({})", "newgame({})"]) {
ev('ACT.' + a);
assert.equal(st(), s0, `${a} does nothing in a puzzle`);
}
assert.equal(ev('S.mode'), 'puzzle');
// A leftover toast button is a no-op too, through the real click path.
ev("toast('stray','',[{l:'Go',act:'opsOpen',args:{}}]);document.querySelector('#toasts [data-act=opsOpen]').click()");
assert.equal(st(), s0);
ev("toast('puzzle news','good')");
ev('ACT.pzLeave({})');
assert.equal(ev("document.querySelectorAll('#toasts .toast').length"), 0, 'puzzle toasts do not follow you home');
assert.equal(ev("localStorage.getItem('sot-save-v1')"), before);
// Back in the main game, the same actions work again.
ev("ACT.addRouter({city:'ams'})");
assert.equal(ev('S.pops.ams.routers'), 2);
assert.deepEqual(errors, []);
});
test('a city to avoid reads as a rule, not a goal that can fail', () => {
const { ev, errors } = load();
ev("pzBegin(pzDef('nofra'))");
const tw = () => ev("[...document.querySelectorAll('#pzBox .pztw')].map(x=>x.className+'|'+x.textContent).join('\\n')");
assert.match(tw(), /pztw rule\|🚫 Rule: not via Frankfurt/);
assert.doesNotMatch(tw(), /[✓✗].*Frankfurt/);
build(ev, REF.nofra.three);
assert.match(tw(), /pztw rule\|🚫 Rule: not via Frankfurt/, 'still a rule once solved');
assert.equal(evalP(ev).stars, 3);
assert.deepEqual(errors, []);
});
test('phone sheet: 40 px touch targets, pinned actions, and goal chips with a clear mark', () => {
const { ev, errors } = load();
// jsdom has no layout: read the phone media rules from the page's stylesheet (Chromium at 360 px measures 40 px).
const rules = JSON.parse(ev(`JSON.stringify([...document.styleSheets].flatMap(s=>[...s.cssRules]).filter(r=>r.media&&/max-width: ?760px/.test(r.media.mediaText))
.flatMap(m=>[...m.cssRules]).filter(r=>/#pzBox/.test(r.selectorText||'')).map(r=>({sel:r.selectorText,mh:r.style.getPropertyValue('min-height'),mw:r.style.getPropertyValue('min-width'),pos:r.style.getPropertyValue('position'),bottom:r.style.getPropertyValue('bottom')})))`));
const tap = rules.find((r) => /#pzBox \.btns \.b/.test(r.sel) && /#pzBox \.pzh \.b/.test(r.sel));
assert.ok(tap && parseFloat(tap.mh) >= 40 && parseFloat(tap.mw) >= 40, `Undo/Reset/Back/☰ are at least 40 px (${JSON.stringify(tap)})`);
const pin = rules.find((r) => /^#pzBox ?> ?\.btns$/.test(r.sel));
assert.ok(pin && pin.pos === 'sticky' && parseFloat(pin.bottom) === 0, `the action row stays at the foot of a scrolling sheet (${JSON.stringify(pin)})`);
ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));pzBegin(pzDef('braces'))");
const chips = () => ev("[...document.querySelectorAll('#pzBox .pzc')].map(x=>x.textContent).join('|')");
assert.equal(chips(), '○ New York|○ London|○ Dublin', 'not reached yet: a hollow mark, nothing that looks cut off');
assert.doesNotMatch(chips(), /…/);
build(ev, [['nyc', 'lon', 'grace']]);
ev("ACT.pzPop({city:'dub'})");
assert.equal(chips(), '✓ New York|✓ London|◐ Dublin');
assert.ok(ev("[...document.querySelectorAll('#pzBox button')].every(b=>b.classList.contains('b'))"), 'every sheet button is a .b the rule sizes');
assert.deepEqual(errors, []);
});
test('results pull you on: Next is the big tap after three stars, stars left in the pack, and a nudge when 3 stars are one link away', () => {
const { ev, errors } = load();
ev("localStorage.removeItem('sot-puzzles');pzBegin(pzDef('braces'))");
build(ev, REF.braces.one);
let card = ev("document.getElementById('modalCard').textContent");
assert.equal(evalP(ev).stars, 2);
assert.match(card, /So close: one more link and a backhoe can't touch you\./, 'Dublin to New York would do it, within budget');
assert.match(ev("document.getElementById('pzBox').textContent"), /So close/);
assert.match(card, /10 ⭐ left in this pack/, '4 puzzles × 3 stars, 2 won');
assert.ok(ev("!!document.querySelector('#modalCard [data-act=pzRetry]')"));
assert.ok(!ev("document.querySelector('#modalCard .btns.cta').classList.contains('pzdone')"));
build(ev, [['dub', 'nyc', 'havf']]);
card = ev("document.getElementById('modalCard').textContent");
assert.match(card, /9 ⭐ left in this pack/);
assert.ok(ev("document.querySelector('#modalCard .btns.cta').classList.contains('pzdone')"), 'three stars: the big Next layout');
assert.ok(ev("document.activeElement===document.querySelector('#modalCard .pznext')"), 'the big button has the focus');
assert.equal(ev("document.querySelector('#modalCard [data-act=pzRetry]')"), null, 'no retry after three stars');
assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /More puzzles/, 'the last pack points back to the list');
ev("pzBegin(pzDef('eurotrip'))");build(ev, REF.eurotrip.three);
assert.match(ev("document.querySelector('#modalCard .pznext').textContent"), /Next puzzle →/);
assert.equal(ev("document.activeElement.dataset.act"), 'pzStart');
// No nudge when no single link fits the budget: an over-budget gold plate is not "close".
ev("pzBegin(pzDef('braces'));S.pz.budget=245000");
build(ev, REF.braces.one);
assert.equal(evalP(ev).stars, 2);
assert.doesNotMatch(ev("document.getElementById('modalCard').textContent"), /So close/);
assert.match(ev("document.getElementById('modalCard').textContent"), /One backhoe away/);
// A finished pack says so.
ev("localStorage.setItem('sot-puzzles',JSON.stringify({s:{sharks:{st:3},braces:{st:3},nofra:{st:3},fatpipes:{st:2}}}));pzBegin(pzDef('fatpipes'))");
build(ev, REF.fatpipes.three);
assert.match(ev("document.getElementById('modalCard').textContent"), /Every star in this pack is yours/);
assert.deepEqual(errors, []);
});

View file

@ -1076,7 +1076,12 @@ test('prices follow real connectivity: thin markets cost more, hubs stay put', (
const { ev, errors } = load();
start(ev);
assert.deepEqual(JSON.parse(ev('JSON.stringify(Object.keys(CITY_PDB).filter(c=>!CITY[c]))')), [], 'every entry is a city on the map');
assert.ok(ev('Object.keys(CITY_PDB).length') >= 190, 'real-world data for most cities');
assert.deepEqual(JSON.parse(ev('JSON.stringify(CITIES.filter(c=>!CITY_PDB[c.id]).map(c=>c.id))')), [], 'every city has data, so none keeps the plain price by accident');
assert.ok(ev('Object.values(CITY_PDB).every(q=>Array.isArray(q)&&q.length===3&&q.every(x=>Number.isInteger(x)&&x>=0)&&q[1]>=0)'), '[facilities, presences, ASNs], whole numbers');
// The cities that used to have none: thin markets cost more than Frankfurt, and the Arctic has no neutral data center.
for (const c of ['dus', 'rix', 'mct', 'mle', 'fuk', 'sju', 'kin', 'anc', 'tik']) assert.ok(ev(`txComp('${c}')`) > 1, `${c} is no hub`);
for (const c of ['brw', 'tik', 'pvs', 'hav']) assert.equal(ev(`colo('${c}')`), 1.5, `${c}: no carrier-neutral data center`);
assert.ok(ev("txComp('dus')") < ev("txComp('rix')") && ev("txComp('rix')") < ev("txComp('mle')"), 'Düsseldorf, Riga, Malé: ever thinner');
// A city without data keeps the plain regional price.
assert.equal(ev("(()=>{const q=CITY_PDB.fra;delete CITY_PDB.fra;const r=[txComp('fra'),colo('fra'),popMo('fra')];CITY_PDB.fra=q;return r.join()})()"), `1,1,${ev('POP_MO')}`);
assert.equal(ev("regionMult('syd')"), ev('AU_TRANSIT'), 'Australia keeps its hand-set transit price');

View file

@ -54,3 +54,28 @@ test('indexed routing matches the simple allocation loop across network changes'
} finally { dom.window.close(); }
});
// Islands: POPs no backbone joins. Exit lists are split per island (a flow only scans exits it can reach),
// and must route exactly like the full scan, also when a cut splits an island or joins two.
test('indexed routing matches the simple allocation loop on a network of islands', () => {
const { ev, dom, errors } = load();
try {
network(ev);
ev("S.links=S.links.filter(l=>!['df4','df9','w3','w4','w8','w9'].includes(l.id));compute()");
assert.ok(ev("Object.keys(S.pops).some(c=>!pathExists('fra',c))"), 'the network is in pieces');
const changes = [
'',
"S.pni.forEach((p,i)=>p.pref=i%3===0?'high':i%3===1?'low':'normal')",
"S.te={on:true,script:'prefer pni for goggle\\nspill at 80%'}",
"S.ev.ddos={city:'fra',until:S.day+3,gbps:300,vec:'syn',entry:{k:'edge'}}",
"S.links[0].cut=S.day+2",
"S.te=null;S.links[0].cut=0;S.links.push({id:'join',a:'par',b:'pek',kind:'wave',tier:2,km:8000,cut:0,mo:100})",
];
for (const change of changes) {
ev(change);
ev('window.priorR=JSON.stringify(R);referenceCompute();window.expectedR=JSON.stringify(R);R=JSON.parse(priorR);compute()');
assert.deepEqual(JSON.parse(ev('JSON.stringify(R)')), JSON.parse(ev('expectedR')), change || 'baseline');
}
assert.deepEqual(errors, []);
} finally { dom.window.close(); }
});

73
tests/sales-trial.test.js Normal file
View file

@ -0,0 +1,73 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('./harness');
// The sales trial (#185, the intern's sales order) runs the pass with the offer first and skips the pass without
// it when it cannot change the answer. It must sign exactly the offers the original two-pass trial signs.
const ORIGINAL = `(function(o){if(!o||!own(BIZ_T,o.type)||!(o.exp>S.day)||!(o.bw>0)||o.rate<0||!bCities(o).length||!bCities(o).every(popUp)||!reqOk(o))return null;
const T=BIZ_T[o.type],b=offerCustomer(o);if(T.event&&(!(o.start>S.day)||!(o.dur>0)))return null;
if(o.type==='capfib'&&S.biz.some(x=>x.type==='capfib'&&capPend(x)&&!x.link&&((x.city===o.city&&x.city2===o.city2)||(x.city===o.city2&&x.city2===o.city))))return null;
if(T.fiber){const l=o.type==='capfib'?capFibLink(b):S.links.find(x=>x.id===o.link);if(!l)return null;b.link=l.id;
if(!fiberOk(b)||(o.type==='wwave'&&(!(o.slots>0)||freeCh(l)<o.slots))||(o.type==='dfpair'&&!pairFree(l))||
(o.type==='pairs'&&(!l.own||S.biz.some(x=>x.link===l.id&&['pairs','capfib','dfpair'].includes(x.type)))))return null;}
const state=S,result=R,hot=UI.hotMap,future=S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day);
try{S={...S,biz:S.biz};
if(future){S.biz=S.biz.map(x=>BIZ_T[x.type].event&&x.start>S.day?{...x,start:S.day}:x);compute();}
const healthy=S.biz.filter(x=>!bizWhy(x).length);if(T.event)b.start=S.day;if(T.cap)b.live=true;S.biz=S.biz.concat(b);compute();
return !bizWhy(b).length&&healthy.every(x=>!bizWhy(x).length)?b:null;
}finally{S=state;R=result;UI.hotMap=hot;b.start=o.start;if(T.cap)delete b.live;}})`;
test('the faster sales trial signs exactly the offers the two-pass trial signs', () => {
const { ev, dom, errors } = load();
try {
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();window.slowOffer=${ORIGINAL};`);
assert.ok(ev('S.biz.some(x=>BIZ_T[x.type].event&&x.start>S.day)'), 'the fixture has events booked ahead, so the shortcut runs');
const seen = { yes: 0, no: 0, skipped: 0, third: 0 };
ev('window.__n=0;const _c=compute;window.compute=function(){__n++;return _c.apply(this,arguments)}');
for (let day = 0; day < 6; day++) {
ev(`__reseed(${1000 + day});S.offers=[];for(let i=0;i<10;i++)spawnOffer();`);
// Small offers that fit, and on alternate days a squeeze, so offers fail on capacity and on others' service too.
ev(`for(const o of S.offers)o.bw=Math.max(1,Math.round(o.bw*${day % 2 ? 1 : 0.05}))`);
if (day % 2) ev('for(const c in S.pops)S.pops[c].bb&&(S.pops[c].bb.d*=1.3)');
// And circuits over the busiest links, which take bandwidth from customers who had it.
ev(`for(const l of S.links.filter(l=>!linkDown(l)&&S.pops[l.a]&&S.pops[l.b]&&R.load[l.id]>1).sort((x,y)=>R.load[y.id]/capOf(y)-R.load[x.id]/capOf(x)).slice(${day},${day}+2))
S.offers.push({id:'sq'+l.id,city:l.a,city2:l.b,name:'Squeeze',type:'l2vpn',bw:${day % 2 ? 300 : 2},rate:100,reqs:[],exp:S.day+30})`);
for (const id of JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))'))) {
const o = `S.offers.find(x=>x.id===${JSON.stringify(id)})`;
const before = ev('JSON.stringify(R.load)+R.served');
ev('__n=0');const fast = ev(`JSON.stringify(autoOffer(${o}))`);const n = ev('__n');
assert.equal(ev('JSON.stringify(R.load)+R.served'), before, 'a trial leaves the live result alone');
const slow = ev(`JSON.stringify(slowOffer(${o}))`);
assert.equal(fast, slow, `offer ${id} (${ev(`${o}.type`)}) on day ${day}`);
if (fast !== 'null') seen.yes++; else seen.no++;
if (n === 1) seen.skipped++;
if (n === 2) seen.third++;
}
ev('S.nextFail=S.day+99;S.nextEvent=S.day+99;dayTick()');
}
assert.ok(seen.yes >= 3 && seen.no >= 3, `both answers come up (${JSON.stringify(seen)})`);
assert.ok(seen.skipped >= 5, `the second pass is often skipped (${JSON.stringify(seen)})`);
assert.ok(seen.third >= 3, `and run when the offer hurts someone (${JSON.stringify(seen)})`);
assert.deepEqual(errors, []);
} finally { dom.window.close(); }
});
test('with a scenic circuit the sales trial keeps both passes in their original order', () => {
const { ev, dom, errors } = load();
try {
const save = fs.readFileSync(path.join(__dirname, 'fixtures', 'big-network.json'), 'utf8');
ev(`S=migrate(JSON.parse(${JSON.stringify(save)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();S.biz.find(b=>BIZ_T[b.type].l2).route='scenic';compute();window.slowOffer=${ORIGINAL};`);
ev('window.__n=0;const _c=compute;window.compute=function(){__n++;return _c.apply(this,arguments)}');
ev('__reseed(77);S.offers=[];for(let i=0;i<6;i++)spawnOffer();');
for (const id of JSON.parse(ev('JSON.stringify(S.offers.map(o=>o.id))'))) {
const o = `S.offers.find(x=>x.id===${JSON.stringify(id)})`;
ev('__n=0');const fast = ev(`JSON.stringify(autoOffer(${o}))`);const n = ev('__n');
assert.equal(fast, ev(`JSON.stringify(slowOffer(${o}))`), id);
assert.ok(n === 0 || n === 2, 'both passes, as before');
}
assert.deepEqual(errors, []);
} finally { dom.window.close(); }
});

View file

@ -231,13 +231,66 @@ test('the shift runs inside dayTick, respects a stopped clock, batches its work
assert.deepEqual(errors, []);
});
test('the daily log line is folded into one NOC notification', t => {
test('the NOC gets one notice a week, the shift report; the daily lines stay in the Ops sheet', t => {
const { ev, errors } = game(t, "S.transit[0].hist=[600]");
hire(ev); on(ev, 'transit', { x: 1.5 });
ev('S.day=14');
hire(ev); on(ev, 'transit', { x: 1.5 }); on(ev, 'sales', { acc: true, min: 5000 });
ev('S.transit[0].tier=3;S.pops.fra.rgen=3;compute()');
const n0 = ev('S.log.length');
shift(ev);
assert.equal(ev('S.log.length'), n0 + 1);
assert.match(ev('S.log[0].t'), /Kevin's shift Kevin topped up transit/);
for (let d = 14; d < 21; d++) {
if (d === 15) ev("S.offers=[{id:'tiny',city:'fra',name:'Tiny',type:'dia',bw:1,rate:600,reqs:[],exp:60},{id:'big',city:'fra',name:'Big',type:'dia',bw:10,rate:600,reqs:[],exp:60}]");
ev(`S.day=${d}`); shift(ev);
}
assert.equal(ev('S.log.length'), n0, 'a whole week of shifts: no NOC notice yet');
assert.ok(ev('S.ops.log.length') >= 2, 'the Ops sheet has the daily detail');
ev('S.day=21'); shift(ev);
assert.equal(ev('S.log.length'), n0 + 1, 'one notice for the week');
assert.match(ev('S.log[0].t'), /^Kevin's week Kevin signed a customer \(\+\$6\.0k\/mo\), topped up transit .*declined a tiny offer.*Week total: \$[\d.]+k up front, \+\$[\d.]+k\/mo\./);
assert.equal(ev('S.log[0].k'), 'good');
ev('S.day=22'); shift(ev);
assert.equal(ev('S.log.length'), n0 + 1, 'and nothing more until the next week ends');
// Only the sales order now: one tiny offer declined on day 23, reported when the week ends.
ev("for(const k in S.ops.on)S.ops.on[k]=false;S.ops.on.sales=true;S.offers=[{id:'t2',city:'fra',name:'T2',type:'dia',bw:1,rate:600,reqs:[],exp:60}];S.day=23");shift(ev);
ev("S.day=28");shift(ev);
assert.equal(ev('S.log.length'), n0 + 2);
assert.match(ev('S.log[0].t'), /declined a tiny offer\.$/, 'nothing spent: no money line');
assert.equal(ev('S.log[0].k'), '');
ev("S.day=35");shift(ev);
assert.equal(ev('S.log.length'), n0 + 2, 'an idle week: no notice');
assert.deepEqual(errors, []);
});
test('the Ops sheet opens with the intern\'s mood and the weekly shift report, at 360 px, in every language', t => {
for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) {
const h = load(lang === 'en' ? {} : { lang });
const { ev, dom, errors } = h;
ev(BASE); ev('S.day=14'); dom.window.innerWidth = 360;
hire(ev);
ev('opsModal()');
const mood = () => dom.window.document.querySelector('#modalCard .ops-mood').textContent;
assert.equal(mood(), ev("tr('ops.mood_new',{name:opsName()})"), lang + ': a new hire says so');
on(ev, 'transit', { x: 1.5 }, 0);
ev("S.transit[0].hist=[600];S.day=21");shift(ev);ev("S.transit[0].hist=[6000];S.day=28");shift(ev);ev('opsModal()');
const reps = [...dom.window.document.querySelectorAll('#modalCard .ops-rep')];
assert.equal(reps.length, 2, lang + ': last week, and this week so far');
assert.equal(reps[0].lastElementChild.textContent, ev('opsWeekLine(S.ops.rep)'), lang);
assert.ok(mood().length > 10, lang);
assert.doesNotMatch(dom.window.document.getElementById('modalCard').textContent, /\bops\.[a-z_]+/, lang);
assert.deepEqual(errors, [], lang);
dom.window.close();
}
});
test('the mood follows the week, with no dice', t => {
const { ev, errors } = game(t);
ev('S.day=100'); hire(ev); ev('S.day=110');
const quiet = ev('opsMood()');
assert.equal(ev('opsMood()'), quiet, 'the same day reads the same');
assert.ok([ev("tr('ops.mood_quiet',{name:'Kevin'})"), ev("tr('ops.mood_kevin')")].includes(quiet));
ev("S.ops.wk=opsWkNew(Math.floor(S.day/7));S.ops.wk.n.sales=1");
assert.equal(ev('opsMood()'), ev("tr('ops.mood_sales',{name:'Kevin'})"));
ev("S.ops.wk.n.broke=1;delete S.ops.wk.n.sales");
assert.equal(ev('opsMood()'), ev("tr('ops.mood_broke',{name:'Kevin'})"));
assert.deepEqual(errors, []);
});
@ -292,6 +345,9 @@ test('saves: old saves load with no intern and everything off, settings survive
assert.equal(ev("JSON.stringify(S.ops.skip)"), '{"fra":["transit"]}');
assert.equal(ev("JSON.stringify(S.ops.log)"), '[{"d":1,"i":"kevin","r":[["transit",2,["fra +1×100G"]]]}]');
assert.equal(ev('S.ops.floor===50000&&S.ops.tpl.bb===true'), true);
ev(`S.ops.wk={w:3,i:'kevin',n:{sales:2,evil:9,transit:'x'},wh:{transit:['fra +1×100G','<b>']},up:-5,mo:'a',rev:41000,ff:99};S.ops.rep={i:'mallory'};S=migrate(S)`);
assert.equal(ev("JSON.stringify(S.ops.wk)"), '{"w":3,"i":"kevin","n":{"sales":2},"wh":{"transit":["fra +1×100G"]},"up":0,"mo":0,"rev":41000,"ff":7}');
assert.equal(ev('S.ops.rep'), null);
assert.deepEqual(errors, []);
});
@ -339,3 +395,170 @@ test('sales trial at most one offer a shift, and an offer that did not fit waits
ev('autoOffer=__a');
assert.deepEqual(errors, []);
});
test('re-hiring in a later month starts on a fresh budget, not last month\'s spending', t => {
const { ev, errors } = game(t);
hire(ev);
ev("S.ops.spent.transit=50000;ACT.opsFire();ACT.opsFire();S.day=400;ACT.opsHire({id:'kevin'});closeModal()");
assert.equal(ev('S.ops.spent.transit'), 0);
assert.equal(ev('S.ops.mon'), ev('Math.floor(S.day/30)'));
ev("S.ops.spent.transit=1234;ACT.opsFire();ACT.opsFire();ACT.opsHire({id:'annie'});closeModal()");
assert.equal(ev('S.ops.spent.transit'), 1234, 'the same month: what was spent stays spent');
assert.deepEqual(errors, []);
});
test('transit never comes from a provider that breaks a promise: no-Cogentle customers, bank covenants, the Spat', t => {
const { ev, errors } = game(t, "S.transit=[];ACT.buyTransit({city:'fra',net:'lvl',tier:0});compute();S.transit[0].hist=Array(30).fill(200)");
hire(ev); on(ev, 'transit', { x: 1.5 });
assert.equal(ev("cheapestTransit('fra').id"), 'cog', 'Cogentle is the cheapest here, so it would be the pick');
ev("S.biz.push({id:'b1',city:'fra',name:'X',type:'dia',bw:1,rate:100,mood:100,since:S.day,reqs:['nocog']})");
assert.equal(ev("reqOk(S.biz[0])"), true);
shift(ev);
assert.ok(ev('S.transit.length') > 1 || ev('S.transit[0].n') > 1, 'the intern still topped up');
assert.equal(ev("S.transit.some(t=>t.net==='cog')"), false);
assert.equal(ev("reqOk(S.biz[0])"), true, 'the customer still gets what they signed for');
ev("S.ops.p.transit={x:1.5,prov:'cog'}");
assert.notEqual(ev("opsProv('fra').id"), 'cog', 'even when the player picked Cogentle');
assert.notEqual(ev("opsTplQuote('ams').net"), 'cog', 'and the new-POP template too');
// A bank covenant says the same.
ev("S.biz=[];S.loans=[{bank:'db',covs:['nocog'],pay:1,bal:1}]");
assert.notEqual(ev("cheapestTransit('fra').id"), 'cog');
// Cogentle is not speaking to Goggle: the Spat scenario, or a de-peering.
ev("S.loans=[]");
assert.equal(ev("cheapestTransit('fra').id"), 'cog');
ev("S.ev.depeer=S.day+5");
assert.notEqual(ev("cheapestTransit('fra').id"), 'cog');
ev("S.ev.depeer=0;S.scn={id:'spat',rules:{spat:true}}");
assert.notEqual(ev("cheapestTransit('fra').id"), 'cog');
// Two upstreams: once met, never undone (adding is fine; the order never removes).
ev("S.scn=null;S.biz=[{id:'b2',city:'fra',name:'Y',type:'dia',bw:1,rate:1,mood:100,since:0,reqs:['twoup']}]");
assert.ok(ev("cheapestTransit('fra')"));
ev("S.transit=[]");
assert.equal(ev("cheapestTransit('fra')"), undefined, 'a lone first upstream would break "two upstreams"');
assert.deepEqual(errors, []);
});
test('decommission keeps its spare in another trench than the big link', t => {
const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;for(const [id,tier,tr] of [['big',2,'T1'],['s1',1,'T1'],['s2',0,'T2']])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:100,trench:tr});compute()");
hire(ev); on(ev, 'decom', { keep: true });
ev("R.load={big:1,s1:0,s2:0}");
shift(ev);
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id).sort())")), ['big', 's2'], 'the 100G in the same trench goes, the 10G in its own trench stays');
// Every small wave shares the big one's trench: keep the largest, as before.
ev("S.links=S.links.filter(l=>l.id==='big');for(const [id,tier] of [['a',1],['b',0]])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:100,trench:'T1'});compute();R.load={big:1}");
shift(ev);
assert.deepEqual(JSON.parse(ev("JSON.stringify(S.links.map(l=>l.id).sort())")), ['a', 'big']);
assert.deepEqual(errors, []);
});
test('decommission sees the traffic of a customer signed earlier in the same shift', t => {
const { ev, errors } = game(t, "S.pops.fra.bb.d=30;ACT.buildPop({city:'ams'});S.pops.ams.rgen=1;for(const [id,tier,tr] of [['big',2,'T1'],['s1',1,'T2'],['s2',1,'T3']])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier,km:400,sub:false,cut:0,mo:1000,trench:tr});compute()");
hire(ev); on(ev, 'sales', { acc: true, min: 0 }); on(ev, 'decom', { keep: false });
ev("S.offers=[{id:'o1',city:'fra',city2:'ams',name:'Bulk Co',type:'l2vpn',bw:450,rate:20,reqs:[],exp:S.day+20}]");
shift(ev);
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.biz.map(b=>b.id))')).length, 1, 'signed');
assert.equal(ev('S.links.length'), 3, 'its 450G needs every wave, so none goes');
ev('compute()');
assert.deepEqual(JSON.parse(ev('JSON.stringify(bizWhy(S.biz[0]))')), []);
assert.deepEqual(errors, []);
});
test('no recompute on a shift that only declined offers or stopped at a budget', t => {
const { ev, errors } = game(t);
hire(ev); on(ev, 'sales', { acc: false, min: 50000 }); on(ev, 'transit', { x: 3 }, 10000);
ev("S.ops.spent.transit=10000;S.transit[0].hist=[600];S.offers=[{id:'tiny',city:'fra',name:'Tiny',type:'dia',bw:1,rate:600,reqs:[],exp:30}]");
const n = ev("window.__c=compute;window.__n=0;compute=()=>{__n++;return __c()};opsDay(S.day);compute=__c;__n");
assert.equal(n, 0, 'nothing in the network changed');
assert.match(ev('opsEntry(S.ops.log[0])'), /declined a tiny offer, stopped at the budget/);
ev("S.ops.spent.transit=0");
assert.equal(ev("window.__n=0;compute=()=>{__n++;return __c()};opsDay(S.day);compute=__c;__n"), 1, 'a real job still recomputes once');
assert.deepEqual(errors, []);
});
test('per-POP exceptions go with the POP: on decommission, and in a save that lost it', t => {
const { ev, errors } = game(t, "ACT.buildPop({city:'ams'});ACT.buildPop({city:'lon'});compute()");
hire(ev);
ev("ACT.opsPop({k:'transit',city:'ams'});ACT.opsPop({k:'caches',city:'lon'});closeModal()");
ev("decommission(['ams'])");
assert.equal(ev('JSON.stringify(S.ops.skip)'), '{"lon":["caches"]}');
ev("ACT.buildPop({city:'ams'});closeModal()");
assert.equal(ev("opsHere('transit','ams')"), true, 'a rebuilt POP starts with every order on');
ev("S.ops.skip.par=['transit'];S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev('JSON.stringify(S.ops.skip)'), '{"lon":["caches"]}', 'no POP in Paris: its exception is dropped on load');
assert.deepEqual(errors, []);
});
test('one order that throws is paused and noted; the rest of the shift and the day still run', t => {
const { ev, errors } = game(t, "S.transit[0].hist=[60,80,70]");
hire(ev); on(ev, 'repair'); on(ev, 'transit', { x: 1.5 });
ev("window.__r=OPS_RUN.repair;OPS_RUN.repair=()=>{throw new Error('boom')};window.__e=console.error;console.error=()=>{}");
const d = ev('S.day'), saves = ev("window.__s=0;window.__sv=save;save=()=>{__s++;return __sv()};S.day=29;dayTick();save=__sv;__s");
ev("OPS_RUN.repair=__r;console.error=__e");
assert.ok(d >= 0 && saves >= 1, 'dayTick reached the save on day 30');
assert.equal(ev('S.ops.on.repair'), false, 'the broken order is paused');
assert.ok(ev("(S.transit[0].n||1)") > 1, 'the next order still ran');
assert.match(ev('opsEntry(S.ops.log[0])'), /got stuck on Rush repairs and paused it/);
assert.deepEqual(errors, []);
});
test('the fat-fingered LAG member respects a paused transit order and per-POP exceptions', t => {
const { ev, errors } = game(t);
hire(ev);
// Each shift rolls: fat finger yes, the only POP, the LAG slip (index 3).
ev("S.rules=makeRules('bgp');window.__r=Math.random;window.__k=0;Math.random=()=>[0,0,0.7][__k++%3]");
const n0 = ev('S.transit[0].n||1'), c0 = cash(ev);
shift(ev);
assert.equal(ev('__k'), 3);
assert.equal(ev('S.ops.log[0].f'), 0, 'transit order paused: a harmless label instead');
assert.equal(ev('S.transit[0].n||1'), n0); assert.equal(cash(ev), c0);
on(ev, 'transit', { x: 1 }); ev("ACT.opsPop({k:'transit',city:'fra'});closeModal();S.transit[0].hist=[0]");
shift(ev);
assert.equal(ev('S.ops.log[0].f'), 0, 'Frankfurt excepted: the same');
ev("ACT.opsPop({k:'transit',city:'fra'});closeModal()");
shift(ev);
assert.equal(ev('S.ops.log[0].f'), 3, 'allowed: the extra member');
assert.equal(ev('S.transit[0].n||1'), n0 + 1);
ev('Math.random=__r');
assert.deepEqual(errors, []);
});
test('caches: the cash floor and a running-cost budget hold; the panel and the log show what a month costs', t => {
const { ev, errors } = game(t);
hire(ev); on(ev, 'caches', { g: 1 });
const add = () => ev("utilityCaches('fra').add.filter(x=>(R.cityDem.fra||0)*NSH[x.net]>=1).length");
assert.ok(add() >= 2, 'several boxes on offer');
ev('S.ops.floor=50000;S.cash=1000');
shift(ev);
assert.equal(ev('S.caches.length'), 0, 'below the floor: no new rent either');
assert.match(ev('opsEntry(S.ops.log[0])'), /stopped at the budget for Accept free caches/);
ev('S.cash=1e8;S.ops.cap.caches=1000');
const m0 = ev('opsMoNow()');
shift(ev);
assert.equal(ev('S.caches.length'), 2, 'a $1k/mo budget fits two $400/mo boxes');
assert.equal(ev('S.ops.addMo.caches'), 800);
assert.equal(ev('opsMoNow()') - m0, 800);
assert.equal(ev('S.ops.log[0].mo'), 800);
assert.match(ev('opsEntry(S.ops.log[0])'), /racked 2 free caches \(Frankfurt\).*Cost: \$0 up front, \+\$800\/mo\./);
ev('opsModal()');
const txt = ev("document.getElementById('modalCard').textContent");
assert.match(txt, /each box costs \$400\/mo/);
assert.match(txt, /Adds at most: \+\$1\.0k\/mo/);
assert.match(txt, /This month: \$0 up front, \+\$800\/mo on the bill/);
ev('S.day+=30;S.ops.cap.caches=0'); shift(ev);
assert.equal(ev('S.ops.addMo.caches'), (ev('S.caches.length') - 2) * 400, 'a new month counts from zero');
assert.deepEqual(errors, []);
});
test('transit: the log line and budget line show the monthly cost a top-up adds', t => {
const { ev, errors } = game(t, "S.transit[0].hist=[60,80,70]");
hire(ev); on(ev, 'transit', { x: 1.5 });
const m0 = ev('opsMoNow()'), c0 = cash(ev);
shift(ev);
const mo = ev('opsMoNow()') - m0;
assert.ok(mo > 0);
assert.equal(ev('S.ops.log[0].up'), c0 - cash(ev));
assert.equal(ev('S.ops.log[0].mo'), Math.round(mo));
assert.equal(ev('Math.round(S.ops.addMo.transit)'), Math.round(mo));
assert.match(ev('opsEntry(S.ops.log[0])'), /Cost: \$[\d.]+k up front, \+\$[\d.]+k?\/mo\./);
assert.deepEqual(errors, []);
});

View file

@ -23,8 +23,12 @@ test('cones are built once at load and hold customers of customers', () => {
assert.equal(ev("NETS.filter(n=>n.tail).every(n=>ANC[n.id].some(u=>NET[u].type==='t1'))"), true, 'from a Tier 1, directly or through a carrier');
assert.equal(ev("NET.tail45.up.join()"), 'mag', 'Auckland has no Tier 1: Hobbit Hole buys from a carrier that is there');
assert.equal(ev("NETS.filter(n=>n.tail).map(n=>n.up.join('+')).join()"), ev("NETS.filter(n=>n.tail).map(n=>tailUp(n.name,n.pops).join('+')).join()"), 'stable: picked by name');
// Australians buy only from Australian carriers, so a Tier 1 PNI is still no back door into Australia.
assert.equal(ev("['opt','tpr','abb','npt','lpt','lnt','pnt','stb','blg'].some(id=>t1Need().some(t=>CONE_S[t.id].has(id)))"), false);
// Australia's big ISPs buy only from Australian carriers, so a Tier 1 PNI is no back door to them.
assert.equal(ev("['opt','tpr','abb','npt','lpt','lnt','pnt','stb','blg','inp'].some(id=>t1Need().some(t=>CONE_S[t.id].has(id)))"), false);
// The smaller ones that buy from a Tier 1 or a carrier of one do come along, and these are exactly the ones.
const au = "NETS.filter(n=>n.type==='eye'&&n.pops.length&&n.pops.every(c=>CITY[c].au)&&t1Need().some(t=>CONE_S[t.id].has(n.id))).map(n=>n.id).sort().join()";
assert.equal(ev(au), 'ddo,ext,spn,tail44', 'Doodoo, Lintel, Spin2wintel, Kangaroo Courier');
assert.equal(ev("[NET.tail44.name,NET.tail44.up.join(),NET.ddo.up.join(),NET.spn.up.join(),NET.ext.up.join(),NET.voc.up.join(),NET.spl.up.join()].join('|')"), 'Kangaroo Courier|cog|voc|voc|spl|ntt,tly|tly');
assert.deepEqual(errors, []);
});
@ -146,3 +150,48 @@ test('routing with cones costs about what it did: exits are asked once, cones ar
assert.ok(t < plain * 2 + 20, `compute() with cones ${t.toFixed(1)} ms vs without ${plain.toFixed(1)} ms`);
assert.deepEqual(errors, []);
});
test('the panel names the peer that really carries a network, not the first Tier 1 it buys from', () => {
const { ev, dom, errors } = load();
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=50");
// a long-tail network that buys from Cogentle first and Level Tree second; peer only with Level Tree
const t = ev("NETS.find(n=>n.tail&&n.up.length===2&&n.up[0]==='cog'&&n.up[1]==='lvl').id");
ev("S.transit=[];S.ixp={};S.peers={};S.grace=null;S.pni=[{id:'pl',net:'lvl',city:'fra',tier:2}];compute()");
assert.equal(ev(`R.cone.${t}`), 'lvl');
ev(`UI.left='goals';UI.leftOpen=true;ACT.netFocus({id:'${t}'})`);
const txt = dom.window.document.getElementById('leftBody').textContent;
assert.match(txt, /Reached through the customer cone of Level Tree/);
assert.doesNotMatch(txt, /customer cone of Cogentle/);
// over an exchange: the member you have a session with
ev("S.pni=[];compute()");
assert.equal(ev(`!!R.cone.${t}`), false);
assert.match(ev(`(ACT.netFocus({id:'${t}'}),document.getElementById('leftBody').textContent)`), /Buys transit from Cogentle/);
assert.deepEqual(errors, []);
});
test('a traceroute down a two-level cone shows every network on the way', () => {
const { ev, errors } = load();
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=6;ACT.launchBB({city:'fra'});S.pops.fra.bb.d=50");
// Doodoo buys from Hocus Pocus, which buys from Not That Telecom; a PNI with Not That Telecom only
ev("S.transit=[];S.ixp={};S.peers={};S.grace=null;S.pni=[{id:'pn',net:'ntt',city:'fra',tier:2}];compute()");
const tr = JSON.parse(ev("JSON.stringify(traceroute('fra',{net:'ddo'}))"));
assert.deepEqual(tr.asPath, [ev('S.asn'), ev('NET.ntt.asn'), ev('NET.voc.asn'), ev('NET.ddo.asn')]);
assert.match(tr.text, /Not That Telecom hands it to its customer Hocus Pocus/);
assert.match(tr.text, /Hocus Pocus hands it to its customer Doodoo/);
assert.equal(ev("coneChain('ntt','ddo').join()"), 'ntt,voc,ddo');
assert.equal(ev("R.cone.ddo"), 'ntt');
assert.deepEqual(errors, []);
});
test('#114 Only Spätzle-IX still takes more than the exchange and two Tier 1 PNIs, now that cones count', () => {
const { ev, errors } = load();
ev("UI.pitched=true;beginGame('T','stg',{scn:SCN.find(x=>x.id==='stg')});S.cash=1e9;S.lvl=10;S.pops.stg.bb={d:400};S.ixp.stg=0;for(const id of ixMembers('stg'))S.peers[id+'@stg']=1;compute()");
const reach = (ts) => ev(`S.pni=[];for(const t of ${JSON.stringify(ts)})S.pni.push({id:'p'+t,net:t,city:'stg',tier:2});compute();R.reach`);
const T = ['lvl', 'ntt', 'tly', 'cog', 'tat'];
const goal = ev("SCN.find(x=>x.id==='stg').ok.toString()");
assert.match(goal, /R\.reach>=0\.5/);
for (let i = 0; i < T.length; i++) for (let j = i + 1; j < T.length; j++)
assert.ok(reach([T[i], T[j]]) < 0.5, `${T[i]}+${T[j]} is not enough`);
assert.ok(reach(['lvl', 'ntt', 'tly']) >= 0.5, 'three Tier 1 PNIs and the exchange can be');
assert.deepEqual(errors, []);
});

View file

@ -136,3 +136,24 @@ test('route-server batch leaves peering policy and player-owned exchanges alone'
assert.equal(ev('S.rs.fra'), false, 'owned exchange has no join-route-server control');
assert.deepEqual(errors, []);
});
test('#192 the Infra tab shows the kit as one line, without repeating its rows', t => {
for (const w of [1280, 360]) {
const { ev, dom, errors } = setup(t);
ev(`window.innerWidth=${w}`);
ev("S.caches=[{id:'c1',city:'fra',net:'cfl'},{id:'c2',city:'fra',net:'cfl'}];compute();selectCity('fra');ACT.tab({t:'links'})");
const body = dom.window.document.getElementById('panelBody');
const txt = body.textContent;
assert.match(txt, /PoP redundancy kit · One-off: /);
assert.doesNotMatch(txt, /Second site(None|Installed)/, 'no second copy of the second-site row');
assert.doesNotMatch(txt, /At least two routers/, 'no second copy of the routers row');
assert.doesNotMatch(txt, /Request missing caches/, 'caches are in the Peering tab and Utilities');
assert.equal(body.querySelectorAll('section h3').length, [...body.querySelectorAll('section h3')].filter(h => h.textContent !== 'PoP redundancy kit').length);
assert.equal(txt.split('Backup generator').length - 1, 1, 'the generator shows once, in Power');
assert.ok(body.querySelector('[data-act="utilityKit"]'), 'the kit is one tap away');
body.querySelector('[data-act="utilities"]').click();
assert.match(dom.window.document.getElementById('modalCard').textContent, /At least two routers/, 'the full kit is in Utilities');
assert.equal(dom.window.document.querySelector('#utilityCity').value, 'fra');
assert.deepEqual(errors, [], `${w}px`);
}
});

240
tests/weekly-puzzle.test.js Normal file
View file

@ -0,0 +1,240 @@
// The published weekly puzzle: Sunday 06:00 Berlin weeks, the generator (scripts/weekly-puzzle.js), its --check,
// and the game's fetch: only when Puzzles opens, validated strictly, with the seeded weekly as the fallback.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { load } = require('./harness');
const G = require('../scripts/weekly-puzzle');
const DIR = path.join(__dirname, '..', 'site', 'puzzles', 'weekly');
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-weekly-'));
const committed = () => G.list(DIR).map((k) => JSON.parse(fs.readFileSync(path.join(DIR, k + '.json'), 'utf8')));
const tick = () => new Promise((r) => setTimeout(r, 30));
test('weeks start Sunday 06:00 Berlin, in winter and in summer, and keys run across New Year', () => {
const { ev, errors } = load();
const key = (iso) => ev(`pzWeekKey(new Date('${iso}'))`), start = (k) => ev(`new Date(pzWeekStart('${k}')).toISOString()`);
// Winter (CET, UTC+1): 06:00 Berlin is 05:00 UTC.
assert.equal(key('2026-11-01T04:59:59Z'), '2026-W44');
assert.equal(key('2026-11-01T05:00:00Z'), '2026-W45', 'the week starting Sunday 1 Nov is named after its Monday');
assert.equal(key('2026-11-07T23:00:00Z'), '2026-W45', 'Saturday night is still the same week');
assert.equal(start('2026-W45'), '2026-11-01T05:00:00.000Z');
// Summer (CEST, UTC+2): 06:00 Berlin is 04:00 UTC.
assert.equal(key('2026-07-05T03:59:00Z'), '2026-W27');
assert.equal(key('2026-07-05T04:00:00Z'), '2026-W28');
// The weekends the clocks change: the change is at 01:00 UTC that same Sunday, before the week starts.
assert.equal(start('2026-W14'), '2026-03-29T04:00:00.000Z', 'spring forward: first CEST Sunday');
assert.equal(start('2026-W13'), '2026-03-22T05:00:00.000Z');
assert.equal(start('2026-W44'), '2026-10-25T05:00:00.000Z', 'fall back: first CET Sunday');
assert.equal(start('2026-W43'), '2026-10-18T04:00:00.000Z');
assert.equal(key('2026-03-29T03:59:00Z'), '2026-W13');
assert.equal(key('2026-03-29T04:00:00Z'), '2026-W14');
assert.equal(key('2026-10-25T04:59:00Z'), '2026-W43');
assert.equal(key('2026-10-25T05:00:00Z'), '2026-W44');
// New Year: 2026 has 53 ISO weeks, 2027 has 52.
assert.equal(key('2026-12-27T05:00:00Z'), '2026-W53');
assert.equal(key('2027-01-03T04:59:00Z'), '2026-W53');
assert.equal(key('2027-01-03T05:00:00Z'), '2027-W01');
assert.equal(key('2027-12-26T05:00:00Z'), '2027-W52');
assert.equal(key('2028-01-02T05:00:00Z'), '2028-W01');
assert.equal(ev("pzKeyAdd('2026-W53',1)"), '2027-W01');
assert.equal(ev("pzPrevKey('2027-W01')"), '2026-W53');
assert.equal(ev("pzPrevKey('2028-W01')"), '2027-W52');
assert.equal(ev("pzWeekStart('2027-W53')"), null, '2027 has no week 53');
assert.equal(ev("pzWeekStart('2026-W00')"), null);
assert.equal(ev("pzWeekStart('nope')"), null);
// Every week of ten years: 7 days apart (give or take the DST hour), keys round-trip, never two Sundays the same key.
let k = '2026-W01', seen = new Set();
for (let i = 0; i < 522; i++) {
const t = ev(`pzWeekStart('${k}')`), n = ev(`pzKeyAdd('${k}',1)`), tn = ev(`pzWeekStart('${n}')`);
assert.equal(new Date(t).getUTCDay(), 0, `${k} starts on a Sunday`);
assert.ok([7 * 864e5, 7 * 864e5 - 3600e3, 7 * 864e5 + 3600e3].includes(tn - t), `${k} → ${n}`);
assert.equal(ev(`pzWeekKey(${t})`), k);
assert.equal(ev(`pzWeekKey(${t - 1})`), ev(`pzPrevKey('${k}')`));
assert.ok(!seen.has(k)); seen.add(k); k = n;
}
// The countdown.
assert.equal(ev("pzWkNext(Date.parse('2026-10-29T14:00:00Z'))"), 'Next weekly puzzle in 2 d 15 h');
assert.equal(ev("pzWkNext(Date.parse('2026-11-01T03:20:00Z'))"), 'Next weekly puzzle in 1 h 40 min');
assert.deepEqual(errors, []);
});
// Weeks already out are not compared with a fresh run: a later release may change prices, and a published week stays as
// it was (--check still makes sure the weeks not over yet can be solved).
test('generator: deterministic for a week', () => {
const g = G.game(), a = tmp(), b = tmp();
const first = G.list(DIR).slice(-3)[0];
const keys = Math.min(3, G.list(DIR).length);
for (const d of [a, b]) for (let i = 0; i < keys; i++) G.writeWeek(d, G.generate(g, g.ev(`pzKeyAdd('${first}',${i})`), d));
for (const k of G.list(a)) {
assert.equal(fs.readFileSync(path.join(a, k + '.json'), 'utf8'), fs.readFileSync(path.join(b, k + '.json'), 'utf8'), `${k} twice the same`);
}
assert.ok(G.list(DIR).length >= 3, 'the release ships with weeklies in place');
});
test('generator: a quarter of weeks, all verified, varied, small and in the schema', () => {
const g = G.game(), d = tmp();
let k = '2027-W10';
const out = [];
for (let i = 0; i < 12; i++, k = g.ev(`pzKeyAdd('${k}',1)`)) { const j = G.generate(g, k, d); G.writeWeek(d, j); out.push(j); }
assert.deepEqual(G.check(g, d, 0), [], 'every week verifies: both references earn their stars in the game');
for (let i = 1; i < out.length; i++) {
assert.notEqual(out[i].theme, out[i - 1].theme, `${out[i].key}: not last week's theme`);
for (const c of out[i].cities) assert.ok(!out[i - 1].cities.includes(c), `${out[i].key}: ${c} was a city last week too`);
}
assert.ok(new Set(out.map((j) => j.theme)).size >= 5, 'most themes come round in a quarter');
for (const j of out) {
assert.ok(j.cities.length >= 3 && j.cities.length <= 6);
assert.ok(j.ref.one <= j.ref.three && j.ref.three <= j.budget && j.budget <= j.ref.three * 1.06 + 10000, `${j.key}: budget ${j.budget} just above the N-1 build ${j.ref.three}`);
assert.ok(JSON.stringify(j).length < 600, 'small file');
assert.deepEqual(Object.keys(j), ['v', 'key', 'theme', 'cities', 'via', 'avoid', 'budget', 'twist', 'name', 'joke', 'ref']);
}
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(d, 'index.json'), 'utf8')).weeks, out.map((j) => j.key));
});
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.
assert.deepEqual(G.check(g, DIR), [], 'committed weeklies verify');
const bad = (edit, why) => {
const d = tmp();
for (const k of G.list(DIR).slice(-3)) fs.copyFileSync(path.join(DIR, k + '.json'), path.join(d, k + '.json'));
G.writeIndex(d);
const k = G.list(d)[0], f = path.join(d, k + '.json'), j = JSON.parse(fs.readFileSync(f, 'utf8'));
const r = edit(j, d, k); fs.writeFileSync(f, typeof r === 'string' ? r : JSON.stringify(j));
assert.notDeepEqual(G.check(g, d, 0), [], why);
};
bad((j) => { j.budget = Math.floor(j.ref.three * 0.8 / 10000) * 10000; j.ref.three = j.budget - 1; }, 'a budget nobody can earn three stars under');
bad((j) => { j.cities[0] = 'xxx'; }, 'an unknown city');
bad((j) => { j.name.l = 'puzzles.hello_world'; }, 'a label that is not a weekly name');
bad((j) => { j.joke.p = { hub: 'fra' }; }, 'parameters the label does not take');
bad((j) => { j.extra = '<img src=x onerror=alert(1)>'; }, 'an unknown field');
bad((j) => { j.key = '2030-W01'; }, 'a file under another week\'s name');
bad((j) => { j.twist = { lat: [j.cities[0], j.cities[1], 0.5] }; }, 'an impossible latency target');
bad(() => '{nope', 'not JSON');
bad((j, d) => { fs.writeFileSync(path.join(d, 'index.json'), '{"v":1,"weeks":[]}'); }, 'an index that misses weeks');
});
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()})}");
ev("showTitle();for(let i=0;i<5;i++)frame(performance.now()+i*1000);renderAll()");
assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 0, 'nothing on the title screen');
assert.equal(ev("UI.pzWk===undefined"), true);
ev("ACT.start({});for(let i=0;i<3;i++)dayTick();renderAll()");
assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 0, 'nothing while playing');
ev('ACT.puzzleMenu({})');
const key = ev('pzWeekKey(new Date())');
assert.deepEqual(ev("JSON.stringify(__f.filter(u=>/puzzles/.test(u)))"), JSON.stringify([`puzzles/weekly/${key}.json`]), 'one relative, same-origin request');
ev('closeModal();ACT.puzzleMenu({})');
assert.equal(ev("__f.filter(u=>/puzzles/.test(u)).length"), 1, 'once is enough while it is loading');
await tick();
assert.deepEqual(errors, []);
});
test('the published puzzle is played when it is good, the seeded one when it is missing, offline or bad', async () => {
const src = committed()[1], { ev, dom, errors } = load();
const key = ev('pzWeekKey(new Date())'), good = { ...src, key };
const serve = (how) => { ev(`UI.pzWk=null;window.fetch=()=>${how}`); ev('ACT.puzzleMenu({})'); };
const seeded = JSON.parse(ev('JSON.stringify(pzWeekly())'));
for (const [how, why] of [
["Promise.resolve({ok:false,status:404,json:()=>Promise.reject()})", 'missing'],
["Promise.reject(new TypeError('offline'))", 'offline'],
["Promise.resolve({ok:true,json:()=>Promise.reject(new SyntaxError('x'))})", 'not JSON'],
[`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, cities: ['fra', 'nope', 'ams'] })})})`, 'an unknown city'],
[`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...good, key: '2020-W01' })})})`, 'another week'],
]) {
serve(how);
await tick();
assert.equal(ev('UI.pzWk.st'), 'fb', why);
assert.deepEqual(JSON.parse(ev('JSON.stringify(pzWkDef().cities)')), seeded.cities, `${why}: the seeded weekly stands in`);
assert.match(ev("document.getElementById('pzWk').textContent"), new RegExp(`Weekly puzzle ${key}`));
assert.equal(ev("document.querySelector('#pzWk [data-act=pzWeekly]').disabled"), false);
}
// While it loads, the button waits a moment.
ev("UI.pzWk=null;window.fetch=()=>new Promise(()=>{})");
ev('ACT.puzzleMenu({})');
assert.match(ev("document.getElementById('pzWk').textContent"), /Loading this week/);
assert.equal(ev("document.querySelector('#pzWk [data-act=pzWeekly]').disabled"), true);
// The good one.
serve(`Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify(good)})})`);
await tick();
assert.equal(ev('UI.pzWk.st'), 'ok');
const row = ev("document.getElementById('pzWk').textContent");
assert.ok(row.includes(ev('pzName(pzWkDef())')), 'its pun name');
assert.ok(row.includes(ev('pzTxt(pzWkDef().wj)')), 'its joke');
assert.match(row, /New this Sunday!/);
assert.match(row, /Next weekly puzzle in \d+ (d \d+ h|h \d+ min)/);
ev("document.querySelector('#pzWk [data-act=pzWeekly]').click()");
assert.equal(ev('S.pz.key'), key);
assert.deepEqual(JSON.parse(ev('JSON.stringify(S.pz.cities)')), good.cities);
assert.equal(ev('S.pz.budget'), good.budget);
assert.match(ev("document.getElementById('pzBox').textContent"), new RegExp(ev('pzTxt(S.pz.wj)').replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
// Solve it with three stars: the share line and the streak use the published key.
const sol = G.solve(G.world(ev), { cities: good.cities, via: good.via, avoid: good.avoid, ring: !!good.twist.ring, noSub: false, lat: good.twist.lat || null }).three;
for (const l of sol.links) {
if (!ev(`!!S.pops['${l.a}']`)) ev(`ACT.pzPop({city:'${l.a}'})`);
ev(`ACT.pzLinkTo({a:'${l.a}',b:'${l.b}'});ACT.pzVia({v:'${l.via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:0})`);
}
assert.equal(ev('pzEval().stars'), 3);
assert.match(ev('pzShareText(pzEval())'), new RegExp(`^Series of Tubes puzzle ${key} ⭐⭐⭐ \\$[\\d.]+[kM] · seriesoftub\\.es$`));
const p = JSON.parse(ev("localStorage.getItem('sot-puzzles')"));
assert.equal(p.wk[key].st, 3);
assert.equal(p.streak.last, key);
ev('ACT.pzLeave({})');
assert.doesNotMatch(ev("document.querySelector('.door[data-door=puzzle]').textContent"), /New this Sunday/, 'played: no badge');
void dom;
assert.deepEqual(errors, []);
});
test('the file is checked field by field', () => {
const { ev, errors } = load();
const j = committed()[0], k = j.key, ok = (o) => ev(`!!pzWkValid(${JSON.stringify(o)},'${k}')`);
assert.ok(ok(j));
const no = (edit, why) => { const o = JSON.parse(JSON.stringify(j)); edit(o); assert.equal(ok(o), false, why); };
no((o) => { o.v = 2; }, 'a newer schema');
no((o) => { o.theme = 'constructor'; }, 'an unknown theme');
no((o) => { o.cities = ['fra']; }, 'too few cities');
no((o) => { o.cities = [...o.cities, o.cities[0]]; }, 'a city twice');
no((o) => { o.via = [o.cities[0]]; }, 'a goal city as a stepping stone');
no((o) => { o.cities[0] = 'pek'; }, 'a city that needs a licence');
no((o) => { o.budget = '240000'; }, 'a budget as text');
no((o) => { o.budget = 1e9; }, 'a silly budget');
no((o) => { o.twist = { ring: 'yes' }; }, 'a twist that is not true');
no((o) => { o.twist = { avoidAll: true }; }, 'an unknown twist');
no((o) => { o.name = { l: 'puzzles_weekly.name_tour_de_reg', p: { reg: 'XX' } }; }, 'an unknown region');
no((o) => { o.name = { l: 'puzzles_weekly.name_race_to_b', p: { b: '<b>' } }; }, 'markup as a city');
no((o) => { o.joke = 'Ha ha'; }, 'raw English');
no((o) => { o.__proto__ = { budget: 1 }; o.extra = 1; }, 'extra fields');
assert.equal(ev(`pzWkValid(null,'${k}')`), null);
assert.equal(ev(`pzWkValid([],'${k}')`), null);
// Every label a theme may use exists in English, and every file names its text in the player's language.
assert.ok(ev("Object.values(PZ_WK_THEMES).every(T=>[T.t,...T.names,...T.jokes].every(l=>typeof EN[l]==='string'))"));
for (const f of committed()) {
const d = ev(`JSON.stringify(pzWkValid(${JSON.stringify(f)},'${f.key}'))`);
assert.ok(d, f.key);
assert.doesNotMatch(ev(`(d=>pzTxt(d.wn)+' '+pzTxt(d.wj))(${d})`), /\{|puzzles_weekly\./, `${f.key}: filled in`);
}
assert.deepEqual(errors, []);
});
test('weekly puzzle in every language and on a 360 px phone', async () => {
const f = committed()[0];
for (const lang of ['de', 'es', 'fr', 'it', 'pt']) {
const { ev, errors } = load({ lang });
const key = ev('pzWeekKey(new Date())');
ev(`window.fetch=()=>Promise.resolve({ok:true,json:()=>Promise.resolve(${JSON.stringify({ ...f, key })})})`);
ev("innerWidth=360;innerHeight=740;dispatchEvent(new Event('resize'));showTitle()");
ev('ACT.puzzleMenu({})');
await tick();
const row = ev("document.getElementById('pzWk').textContent");
assert.doesNotMatch(row, /puzzles(_weekly)?\.|\{/, `${lang}: no raw labels or placeholders`);
assert.notEqual(ev('pzName(pzWkDef())'), ev("EN[pzWkDef().wn.l]"), `${lang}: translated name`);
ev("document.querySelector('#pzWk [data-act=pzWeekly]').click()");
assert.equal(ev("document.getElementById('pzBox').hidden"), false);
assert.doesNotMatch(ev("document.getElementById('pzBox').textContent"), /puzzles(_weekly)?\./);
assert.deepEqual(errors, [], lang);
}
});