Merge branch 'claude/latency-contracts' into trial

# Conflicts:
#	.claude/skills/gameplay-rules/SKILL.md
#	CHANGELOG.md
#	tests/day-steps.test.js
#	tests/route-fuzz.test.js
This commit is contained in:
Frederic Jung 2026-11-10 09:36:11 +00:00
commit e8cbb9b440
No known key found for this signature in database
45 changed files with 1147 additions and 47 deletions

226
tests/bulk-actions.test.js Normal file
View file

@ -0,0 +1,226 @@
// Late-game busywork: one policy or one button instead of many clicks, never a decision taken away.
// #316 the intern can leave new fiber dark, #119 the link panel stays open on a sibling, #317 the kit at every POP,
// #241 buy what a customer needs on signing, #315 POP standards by kind, #199 find a network at a POP.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
function setup(t, extra = '') {
const h = load();
t.after(() => h.dom.window.close());
h.ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.nextFail=S.nextEvent=1e9;UI.speed=0;compute();" + extra);
return h;
}
const doc = h => h.dom.window.document;
const text = (h, sel) => [...doc(h).querySelectorAll(sel)].map(e => e.textContent).join('\n');
const reload = ev => ev("save();S=migrate(JSON.parse(slotRaw(UI.slot)));compute()");
/* ---------- #316: new fiber stays dark when the player says so ---------- */
const FIBER = "S.lvl=4;S.rules=makeRules('freeze');ACT.launchBB({city:'fra'});S.pops.fra.rgen=2;ACT.buildPop({city:'ams'});S.pops.ams.rgen=2;compute();" +
"ACT.opsHire({id:'kevin'});S.ops.floor=0;closeModal();" +
"S.links.push({id:'f',a:'fra',b:'ams',kind:'df',sys:'roadm',ch:[],km:450,sub:false,ready:0,cut:0,mo:1,trench:'f'});compute();S.ops.on.optics=true;";
const ch = ev => JSON.parse(ev("JSON.stringify(S.links.find(l=>l.id==='f').ch)"));
test('#316 by default the intern still lights new fiber, also in a save from before the switch', t => {
const { ev, errors } = setup(t, FIBER);
assert.equal(ev("opsP('optics','fresh')"), true);
ev("S.ops.p.optics={}");
reload(ev);
assert.equal(ev("opsP('optics','fresh')"), true, 'an old save has no setting: the old behaviour');
ev('opsDay(S.day)');
assert.ok(ch(ev).length > 0);
assert.deepEqual(errors, []);
});
test('#316 told not to, the intern leaves new fiber dark but still grows hot lit fiber', t => {
const { ev, errors } = setup(t, FIBER);
ev("ACT.opsOpen();ACT.opsParam({k:'optics',p:'fresh',v:1})");
assert.equal(ev("opsP('optics','fresh')"), false);
ev('opsDay(S.day)');
assert.deepEqual(ch(ev), [], 'dark fiber stays dark');
ev("S.links.find(l=>l.id==='f').ch=['zr8'];compute();R.load.f=dfCap(S.links.find(l=>l.id==='f'))*0.95;opsDay(S.day)");
assert.ok(ch(ev).length > 1, 'a lit, hot fiber still gets more optics');
reload(ev);
assert.equal(ev("opsP('optics','fresh')"), false, 'the switch survives a reload');
ev("S.ops.p.optics.fresh='maybe';S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev("opsP('optics','fresh')"), true, 'a bad value is repaired to the default');
assert.deepEqual(errors, []);
});
test('#316 the switch is in the Ops sheet', t => {
const h = setup(t, FIBER);
h.ev('ACT.opsOpen()');
assert.match(h.ev("document.getElementById('modalCard').textContent"), /Light new fiber/);
assert.deepEqual(h.errors, []);
});
/* ---------- #119: decommissioning one of several waves keeps the panel open ---------- */
test('#119 the link panel moves on to the next parallel link, and closes after the last', t => {
const h = setup(t, "ACT.buildPop({city:'ams'});" +
"for(const id of ['w1','w2','w3'])S.links.push({id,a:'fra',b:'ams',kind:'wave',tier:0,km:450,sub:false,cut:0,mo:1000});compute();UI.sel={type:'link',id:'w1'};renderAll()");
const { ev, errors } = h;
ev("ACT.rmLink({id:'w1'});ACT.rmLink({id:'w1'})");
assert.equal(ev("S.links.some(l=>l.id==='w1')"), false);
assert.equal(ev('JSON.stringify(UI.sel)'), JSON.stringify({ type: 'link', id: 'w2' }));
assert.equal(ev("document.getElementById('panel').hidden"), false, 'the panel is still open');
ev("ACT.rmLink({id:'w2'});ACT.rmLink({id:'w2'})");
assert.equal(ev('UI.sel.id'), 'w3');
ev("ACT.rmLink({id:'w3'});ACT.rmLink({id:'w3'})");
assert.equal(ev('UI.sel'), null, 'the last link closes it');
assert.deepEqual(errors, []);
});
/* ---------- #317: the redundancy kit at every POP ---------- */
const POPS = "for(const c of ['ams','lon','par'])ACT.buildPop({city:c});compute();";
test('#317 one button kits every POP, at the sum of the per-POP quotes', t => {
const { ev, errors } = setup(t, POPS + 'S.lvl=2;');
const q = JSON.parse(ev('JSON.stringify(utilityKitAll())'));
assert.equal(q.cities.length, 4);
assert.equal(q.cost, ev("Object.keys(S.pops).reduce((a,c)=>a+utilityKit(c).cost,0)"));
ev("ACT.utilities({})");
assert.match(ev("document.getElementById('modalCard').textContent"), /Kit all 4 POPs/);
const cash = ev('S.cash');
ev(`ACT.utilityKitAll({cost:${q.cost + 1}})`);
assert.equal(ev('S.cash'), cash, 'a stale quote buys nothing');
assert.match(ev("document.getElementById('modalCard').textContent"), /quote changed/);
ev(`ACT.utilityKitAll({cost:${q.cost}})`);
assert.equal(ev('S.cash'), cash - q.cost);
assert.equal(ev("Object.values(S.pops).every(p=>p.gen&&p.site2&&p.routers>=2)"), true);
assert.match(ev("document.getElementById('modalCard').textContent"), /Every POP has the full kit/);
assert.deepEqual(errors, []);
});
test('#317 needs level 2, never spends what is not there, and can put the kit in the intern\'s template', t => {
const { ev, errors } = setup(t, POPS);
ev('S.lvl=1;ACT.utilities({})');
assert.equal(ev('utilityKitAll()'), null);
assert.doesNotMatch(ev("document.getElementById('modalCard').textContent"), /Redundancy kit everywhere/);
ev('S.lvl=2;window.q=utilityKitAll().cost;S.cash=q-1;ACT.utilityKitAll({cost:q})');
assert.equal(ev('S.cash'), ev('q-1'));
assert.equal(ev("Object.values(S.pops).some(p=>p.gen)"), false);
ev("S.cash=1e8;ACT.opsHire({id:'annie'});closeModal();S.ops.tpl.kit=false;ACT.utilities({})");
assert.match(ev("document.getElementById('modalCard').textContent"), /come without the kit/);
ev('ACT.utilityKitNew({})');
assert.equal(ev('S.ops.tpl.kit'), true);
assert.match(ev("document.getElementById('modalCard').textContent"), /get the kit too/);
assert.deepEqual(errors, []);
});
/* ---------- #241: buy what the customer asks for, on signing ---------- */
const OFFER = (reqs, extra = {}) => `ACT.buildPop({city:'ams'});S.offers.push(${lit({ id: 'o1', city: 'fra', city2: 'ams', name: 'Needy Corp', type: 'l2vpn', bw: 1, rate: 900, reqs, exp: 30, ...extra })});compute();`;
test('#241 the offer shows what is missing with its price, and one button buys it and signs', t => {
const h = setup(t, OFFER(['gen', 'routers']));
const { ev, errors } = h;
const q = JSON.parse(ev("JSON.stringify(reqFix(S.offers[0]))"));
assert.deepEqual(q.items.map(x => x.k + '@' + x.city), ['gen@fra', 'gen@ams', 'routers@fra']);
assert.equal(q.cost, ev("2*GEN_COST+routerCost(0,1)"));
ev("UI.left='deals';UI.leftOpen=true;window.innerWidth=390;renderAll()");
const card = text(h, '#left');
assert.match(card, /Missing: a backup generator in Frankfurt, a backup generator in Amsterdam, a second router in Frankfurt/);
assert.match(card, /Buy it and sign/);
assert.ok(doc(h).querySelector('[data-act="acceptFix"]'), 'the button is there on a phone');
const cash = ev('S.cash');
ev(`ACT.acceptFix({id:'o1',cost:${q.cost}})`);
assert.equal(ev('S.cash'), cash - q.cost);
assert.equal(ev("S.pops.fra.gen&&S.pops.ams.gen&&S.pops.fra.routers===2"), true);
assert.equal(ev("S.biz.some(b=>b.id==='o1')&&!S.offers.length"), true, 'signed');
assert.equal(ev("reqOk(S.biz.find(b=>b.id==='o1'))"), true, 'and every requirement is met');
assert.deepEqual(errors, []);
});
test('#241 never silent: a stale price, too little cash or a deal that cannot be signed buys nothing', t => {
const { ev, errors } = setup(t, OFFER(['metro']));
const cost = ev("reqFix(S.offers[0]).cost");
assert.equal(cost, ev('2*SITE2_COST'));
ev(`ACT.acceptFix({id:'o1',cost:${cost - 1}})`);
assert.equal(ev("!!S.pops.fra.site2||S.biz.length>0"), false);
ev(`S.cash=${cost - 1};ACT.acceptFix({id:'o1',cost:${cost}})`);
assert.equal(ev("!!S.pops.fra.site2||S.biz.length>0"), false);
ev(`S.cash=1e8;S.offers[0].city2='lon';ACT.acceptFix({id:'o1',cost:${cost}})`);
assert.equal(ev("!!S.pops.fra.site2||S.biz.length>0"), false, 'no POP in London: nothing is bought');
assert.equal(ev("reqFixHtml(S.offers[0])"), '');
ev("S.offers[0].city2='ams';S.offers[0].reqs=['nocog']");
assert.equal(ev("reqFix(S.offers[0])"), null, 'only hardware at a POP is offered');
assert.deepEqual(errors, []);
});
/* ---------- #315: POP standards by kind ---------- */
test('#315 save a standard, bring a POP up to it, then every POP of that kind at once', t => {
const h = setup(t, POPS + "S.lvl=4;S.pops.fra.routers=2;S.pops.fra.rgen=1;compute();");
const { ev, errors } = h;
ev("UI.sel={type:'city',id:'fra'};UI.tab='links';window.innerWidth=390;renderAll()");
assert.match(text(h, '#panel'), /POP standards/);
assert.match(text(h, '#panel'), /Regional hub/);
ev("ACT.ptSave({city:'fra',k:'medium'})");
assert.equal(ev("JSON.stringify(S.popTiers.def.medium)"), JSON.stringify({ g: 1, rt: 2 }));
assert.equal(ev('S.popTiers.at.fra'), 'medium');
const q = JSON.parse(ev("JSON.stringify(ptPlan('ams','medium'))"));
assert.deepEqual(q.steps, ['swap', 'add'], 'an empty POP swaps first, then adds');
const cash = ev('S.cash');
ev(`ACT.ptApply({city:'ams',k:'medium',cost:${q.cost}})`);
assert.equal(ev('S.cash'), cash - q.cost, 'charged exactly the quote');
assert.equal(ev("S.pops.ams.routers===2&&S.pops.ams.rgen===1&&S.popTiers.at.ams==='medium'"), true);
// The standard grows: one button brings both medium POPs up.
ev("S.pops.fra.routers=3;S.pops.fra.rgen=2;S.pops.fra.rupDay=-1;ACT.ptSave({city:'fra',k:'medium'});S.pops.fra.routers=2;S.pops.fra.rgen=1;S.pops.ams.rupDay=-1;compute()");
const A = JSON.parse(ev("JSON.stringify({n:ptAll('medium').todo.length,cost:ptAll('medium').cost})"));
assert.equal(A.n, 2);
ev('ACT.utilities({})');
assert.match(ev("document.getElementById('modalCard').textContent"), /Bring 2 POPs up/);
ev(`ACT.ptAll({k:'medium',cost:${A.cost}})`);
assert.equal(ev("['fra','ams'].every(c=>S.pops[c].routers===3&&S.pops[c].rgen===2)"), true);
assert.equal(ev("ptAll('medium').todo.length"), 0);
assert.deepEqual(errors, []);
});
test('#315 a busy lone router gets its partner before the swap, and never a step down', t => {
const { ev, errors } = setup(t, POPS + "S.lvl=4;ACT.launchBB({city:'ams'});S.popTiers.def.hub={g:2,rt:2};S.popTiers.def.micro={g:0,rt:1};compute();");
assert.deepEqual(JSON.parse(ev("JSON.stringify(ptPlan('ams','hub').steps)")), ['add', 'swap']);
ev("ACT.ptApply({city:'ams',k:'hub',cost:ptPlan('ams','hub').cost})");
assert.equal(ev("S.pops.ams.routers===2&&S.pops.ams.rgen===2"), true);
assert.equal(ev("S.inc.some(i=>i.type==='maint'&&i.ref==='ams')"), false, 'a rolling upgrade, no maintenance window');
assert.equal(ev("ptPlan('ams','micro')"), null, 'a smaller standard asks for nothing');
ev("ACT.ptApply({city:'ams',k:'micro',cost:0})");
assert.equal(ev("S.pops.ams.rgen===2&&S.pops.ams.routers===2&&S.popTiers.at.ams==='micro'"), true, 'only marked');
assert.deepEqual(errors, []);
});
test('#315 level 1 has no standards, and saves old and broken load', t => {
const h = setup(t, POPS);
const { ev, errors } = h;
ev("UI.sel={type:'city',id:'fra'};UI.tab='links';renderAll()");
assert.doesNotMatch(text(h, '#panel'), /POP standards/);
ev("ACT.ptSave({city:'fra',k:'micro'})");
assert.equal(ev('S.popTiers.def.micro'), null);
ev('delete S.popTiers;S=migrate(JSON.parse(JSON.stringify(S)))');
assert.equal(ev('JSON.stringify(S.popTiers)'), JSON.stringify({ def: { micro: null, medium: null, hub: null }, at: {} }));
ev("S.popTiers={def:{micro:{g:999,rt:2},hub:{g:1,rt:99},bogus:{g:1,rt:1}},at:{fra:'hub',ams:'nope',xyz:'micro',ber:'hub'}};S=migrate(JSON.parse(JSON.stringify(S)))");
assert.equal(ev('JSON.stringify(S.popTiers)'), JSON.stringify({ def: { micro: null, medium: null, hub: { g: 1, rt: ev('RMAX') } }, at: { fra: 'hub' } }));
assert.deepEqual(errors, []);
});
/* ---------- #199: find a network at a POP ---------- */
test('#199 search and connected-only filter the transit, exchange and PNI lists, on a phone', t => {
const h = setup(t, "S.lvl=4;ACT.buyTransit({city:'fra',net:'cog',tier:0});compute();window.innerWidth=390;UI.sel={type:'city',id:'fra'};UI.tab='up';renderAll()");
const { ev, errors } = h;
const rows = () => [...doc(h).querySelectorAll('#panel .row .nm')].map(e => e.textContent.trim());
const all = rows().length;
assert.ok(doc(h).getElementById('netQ'), 'the search box is there');
ev("ACT.netOnly()");
assert.equal(rows().length, 1);
assert.match(rows()[0], /Cogentle/);
ev("ACT.netClear()");
assert.equal(rows().length, all);
// Typing into the box filters as you go, and the box keeps focus and text.
ev("const i=document.getElementById('netQ');i.focus();i.value='goggle';i.dispatchEvent(new window.Event('input',{bubbles:true}))");
assert.equal(ev("document.activeElement.id"), 'netQ');
assert.equal(ev("UI.netQ"), 'goggle');
ev("UI.tab='peer';renderAll()");
const peer = rows();
assert.ok(peer.length > 0 && peer.every(r => /Goggle/.test(r)), peer.join(' | '));
ev("ACT.netFind({q:'zzzz'})");
assert.match(text(h, '#panel'), /No network here matches this filter/);
ev("ACT.netFind({q:String(NET.ggl.asn)})");
assert.match(text(h, '#panel'), /Goggle/, 'an AS number finds the network');
assert.deepEqual(errors, []);
});

View file

@ -189,8 +189,8 @@ test('a customer dropped while a sales trial routes: the trial runs again on the
p.ev(TICK_ERR);
p.ev("window.__ot=0;const ot=offerTrial;offerTrial=(...a)=>{__ot++;return ot(...a);};");
let found = false;
// Played until such a trial comes: on the big save that is day 51 (where each city's traffic goes decides which
// offers pass, #48).
// Played until such a trial comes: on the big save that depends on the offers the seeded game draws and on where
// each city's traffic goes (#48, #137).
for (let d = 0; d < 60 && !found; d++) {
p.ev('rwDay()');
for (let k = 0; k < 400 && p.ev('!!RW.job'); k++) {

View file

@ -495,19 +495,43 @@ test('F8: a managed wave costs your own capacity, rides one optic, and is priced
assert.deepEqual(g.errors, []);
});
test('F9: a latency contract is late, capped, achievable, paid for its latency and credited when over it (#137)', () => {
const T = J('BIZ_T.lowlat');
assert.ok(T.lv >= 7, `F9: from customer level 7, not ${T.lv}`);
assert.ok(T.l2 && T.lat && T.sla, 'F9: a circuit with a latency limit and an SLA');
assert.ok(Math.min(...T.opts) >= 1600 && Math.max(...T.opts) <= T.max && T.max <= 3200, 'F9: 1.6T and up, never past 3.2T');
assert.equal(ev("(()=>{const x={type:'lowlat',bw:BIZ_T.lowlat.max};return clGrow(x)||x.bw!==BIZ_T.lowlat.max;})()"), false, 'F9: never grows past its most');
// Per Gbps on the same route, the bare contract beats any other big circuit with every extra it can ask for.
const best = ev("Math.max(...['hyper','ai','aiwan'].map(t=>BIZ_T[t].km))*(1+REQS.diverse.bonus+REQS.metro.bonus+REQS.sharks.bonus+REQS.gen.bonus)");
assert.ok(T.km > best, `F9: ${T.km} per km-unit against the best other big circuit's ${best}`);
const g = load();
g.ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e9;S.lvl=BIZ_T.lowlat.lv-1;S.biz=[];S.offers=[];for(const c of ['nyc','chi','lon','fra','tok','sin'])if(!S.pops[c])ACT.buildPop({city:c});compute()");
const spawn = (n) => g.ev(`(()=>{const out=[];for(let i=0;i<${n};i++){S.offers=[];spawnOffer();out.push(...S.offers.filter(o=>o.type==='lowlat'));}S.offers=[];return JSON.stringify(out);})()`);
assert.deepEqual(JSON.parse(spawn(400)), [], 'F9: none below its level');
g.ev('S.lvl=BIZ_T.lowlat.lv');
const os = JSON.parse(spawn(400));
assert.ok(os.length > 0, 'F9: offered at its level');
for (const o of os) assert.ok(g.ev(`Math.min(latFloor('${o.city}','${o.city2}'),bestLat('${o.city}','${o.city2}'))<=${o.latMax}`), `F9: ${o.city}–${o.city2} in ${o.latMax} ms can be built`);
g.ev("S.biz.push({id:'x',type:'lowlat',name:'X',city:'nyc',city2:'chi',bw:1600,rate:100,reqs:['lat'],latMax:0.1,mood:100,since:S.day-30});compute()");
const cash = g.ev('S.cash');
assert.equal(g.ev("lcBreach(S.biz.find(b=>b.id==='x'),S.day)"), g.ev('LC_MOOD'), 'F9: over its limit, it loses patience');
assert.equal(Math.round(cash - g.ev('S.cash')), g.ev('Math.round(1600*100/monLen(S.day))'), "F9: and a day's fee comes back as a credit");
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('F9: growth goes sideways, plus one paid way up (#61, #323)', () => {
test('F10: growth goes sideways, plus one paid way up (#61, #323)', () => {
// A PNI bundles eight members per router at its POP, up to 32; every other LAG stays at eight.
assert.equal(ev('LAG_MAX'), 8, 'F9: transit, exchange and fabric LAGs hold eight members');
assert.equal(ev('LAG_MAX'), 8, 'F10: transit, exchange and fabric LAGs hold eight members');
const lim = J("[1,2,3,4,5,16].map(r=>{const o=S.pops.fra;S.pops.fra={routers:r};const m=pniLagMax('fra');if(o)S.pops.fra=o;else delete S.pops.fra;return m;})");
assert.deepEqual(lim, [8, 16, 24, 32, 32, 32], 'F9: a PNI grows by eight members per router, up to 32');
assert.deepEqual(lim, [8, 16, 24, 32, 32, 32], 'F10: a PNI grows by eight members per router, up to 32');
// Giant AI circuits land at campuses spread over many metros, no city more than two.
const per = J("MEGA.reduce((m,x)=>(m[x.c]=(m[x.c]||0)+1,m),{})");
assert.ok(Object.keys(per).length >= 30, `F9: campuses in at least 30 metros (${Object.keys(per).length})`);
fail('F9', Object.entries(per).filter(([, n]) => n > 2).map(([c]) => c), 'no metro holds more than two campuses');
fail('F9', J("MEGA.filter(m=>!CITY[m.c]).map(m=>m.c)"), 'campuses sit in real cities');
assert.ok(Object.keys(per).length >= 30, `F10: campuses in at least 30 metros (${Object.keys(per).length})`);
fail('F10', Object.entries(per).filter(([, n]) => n > 2).map(([c]) => c), 'no metro holds more than two campuses');
fail('F10', J("MEGA.filter(m=>!CITY[m.c]).map(m=>m.c)"), 'campuses sit in real cities');
});
test('D1: attack sizes come from the world, never from your network', () => {

View file

@ -0,0 +1,162 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
// Strict latency contracts (#137): big customers who pay for a latency SLA on one route, late in the game.
const start = "ACT.start({});S.cash=1e9;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'nyc'})";
const pop = (c) => `S.pops['${c}']=S.pops['${c}']||{day:0,bb:null,boost:0,down:0,routers:1,gen:false,rgen:0};S.pops['${c}'].rgen=RG.length-1;`;
const wave = (id, a, b) => `S.links.push({id:'${id}',a:'${a}',b:'${b}',kind:'wave',tier:6,n:1,km:kmBetween('${a}','${b}'),cut:0,mo:0,day:0,ready:0});`;
const CITIES = ['nyc', 'chi', 'ash', 'mia', 'lon', 'fra'];
const net = () => CITIES.map(pop).join('') + wave('nc', 'nyc', 'chi') + wave('na', 'nyc', 'ash') + wave('am', 'ash', 'mia') + wave('mc', 'mia', 'chi') + 'compute();';
// Spawn n offers, each on its own, and keep them all.
const spawnMany = (ev, n) => JSON.parse(ev(`(()=>{const out=[];for(let i=0;i<${n};i++){S.offers=[];spawnOffer();out.push(...S.offers);}S.offers=[];return JSON.stringify(out);})()`));
// A latency contract on New York ⇄ Chicago, signed long enough ago that its provisioning grace is over.
const sign = (bw = 1600) => `(()=>{const b={id:'lc1',city:'nyc',city2:'chi',name:'Shortest Path Securities',type:'lowlat',bw:${bw},rate:500,reqs:['lat'],latMax:latMaxOf('nyc','chi'),route:'fast',mood:100,since:S.day-30};S.biz.push(b);compute();return b.id;})()`;
test('#137 latency contracts are offered only from their customer level, sized and priced as promised', () => {
const { ev, errors } = load();
ev(start);
ev(net());
ev('S.lvl=LC_LV-1');
assert.ok(ev('LC_LV') >= 7, 'a late-game customer');
const early = spawnMany(ev, 600);
assert.equal(early.filter((o) => o.type === 'lowlat').length, 0, 'never below its level');
ev('S.lvl=LC_LV');
const late = spawnMany(ev, 600);
const lc = late.filter((o) => o.type === 'lowlat');
assert.ok(lc.length >= 5, `they call at their level (${lc.length})`);
for (const o of lc) {
assert.ok([1600, 3200].includes(o.bw), 'big: 1.6T or 3.2T');
assert.equal(o.reqs[0], 'lat', 'always a latency limit');
assert.equal(o.latMax, ev(`latMaxOf('${o.city}','${o.city2}')`), 'the limit every latency customer gets');
assert.ok(ev(`Math.min(latFloor('${o.city}','${o.city2}'),bestLat('${o.city}','${o.city2}'))<=${o.latMax}`), 'and one something you can build meets');
}
// Pay: per Gbps on the same route, above any other high-volume circuit (hyperscaler DCI, AI interconnects), whatever they ask for.
const per = (o) => o.rate / ev(`150+kmBetween('${o.city}','${o.city2}')*0.08`);
const big = late.filter((o) => ['hyper', 'ai', 'aiwan'].includes(o.type));
assert.ok(big.length >= 5, 'there are other big circuits to compare with');
assert.ok(Math.min(...lc.map(per)) > Math.max(...big.map(per)), 'a latency contract pays more per Gbps than any other big circuit');
// Same size, same route: a 1.6T latency contract against a 1.6T hyperscaler DCI with every extra a DCI can ask for.
const o = lc[0], km = ev(`kmBetween('${o.city}','${o.city2}')`);
const dciBest = (150 + km * 0.08) * ev('BIZ_T.hyper.km') * (1 + ev("REQS.diverse.bonus+REQS.metro.bonus+REQS.sharks.bonus+REQS.gen.bonus"));
assert.ok(1600 * o.rate > 1600 * dciBest, 'beats a fully loaded DCI of the same size');
assert.deepEqual(errors, []);
});
test('#137 the latency limit is the circuit latency the game already measures, and breaking it costs credits and the customer', () => {
const { ev, errors } = load();
ev(start);
ev(net());
ev('S.lvl=LC_LV');
ev(sign());
const b = "S.biz.find(b=>b.id==='lc1')";
assert.ok(ev(`R.l2lat['lc1']<=${b}.latMax`), 'the direct wave meets it');
assert.ok(ev(`REQS.lat.ok(${b})`));
assert.ok(ev(`bizSf(${b})>=0.95`), 'and carries all of it');
// Cut the direct wave: the circuit reroutes the long way round, still carried in full but too slow.
ev("S.links.find(l=>l.id==='nc').cut=S.day+400;compute()");
assert.ok(ev(`bizSf(${b})>=0.95`), 'all the bandwidth still arrives');
assert.ok(ev(`R.l2lat['lc1']>${b}.latMax`), 'over its limit');
assert.ok(!ev(`REQS.lat.ok(${b})`), 'REQS.lat says so');
assert.ok(ev(`bizWhy(${b}).some(w=>/latency/i.test(w))`), 'and the customer row says why');
// A day over: a day's fee back as an SLA credit, and more patience lost than a plain latency customer (HFT) loses.
const cash = ev('S.cash'), mo = ev(`bizMo(${b})`), days = ev('monLen(S.day)');
const extra = ev(`lcBreach(${b},S.day)`);
assert.equal(extra, ev('LC_MOOD'));
assert.equal(Math.round(cash - ev('S.cash')), Math.round(mo / days), "a day's fee credited");
assert.equal(ev(`${b}.lcCr`), Math.round(mo / days));
assert.equal(ev("lcBreach({type:'hft',since:0,latMax:1,city:'nyc',city2:'chi',reqs:['lat'],id:'x'},S.day)"), 0, 'only latency contracts pay credits');
// In the provisioning grace (rule F1) nothing is credited and nothing is lost.
assert.equal(ev(`(()=>{const x={...${b},id:'lc2',since:S.day-3};return lcBreach(x,S.day);})()`), 0);
// Day after day over the limit: unhappy, warned, and gone, with credits paid every day.
const m0 = ev(`${b}.mood`);
ev('dayTick()');
const m1 = ev(`${b}.mood`);
assert.ok(m0 - m1 >= 6 - 1e-9, `loses at least 6 a day over its SLA (${m0} → ${m1})`);
let gone = false;
for (let i = 0; i < 40 && !gone; i++) {
ev("S.links.find(l=>l.id==='nc').cut=S.day+400;dayTick()");
gone = !ev("S.biz.some(b=>b.id==='lc1')");
}
assert.ok(gone, 'a contract over its latency for weeks cancels');
assert.deepEqual(errors, []);
});
test('#137 a latency contract within its limit stays happy and pays no credits', () => {
const { ev, errors } = load();
ev(start);
ev(net());
ev(sign());
ev("S.biz.find(b=>b.id==='lc1').mood=90");
for (let i = 0; i < 5; i++) ev("S.links.forEach(l=>l.cut=0);dayTick()");
const b = ev("JSON.stringify(S.biz.find(b=>b.id==='lc1')||null)");
const o = JSON.parse(b);
assert.ok(o, 'still a customer');
assert.equal(o.lcCr, undefined, 'no credits');
assert.equal(o.lcB, undefined, 'not in breach');
assert.ok(o.mood > 90, `happier every day it is served (${o.mood})`);
assert.deepEqual(errors, []);
});
test('#137 the volume cap holds: renewals, a sales shark and an edited save never take one past 3.2T', () => {
const { ev, errors } = load();
ev(start);
ev(net());
ev(sign(1600));
const b = "S.biz.find(b=>b.id==='lc1')";
assert.ok(ev('Math.max(...BIZ_T.lowlat.opts)<=BIZ_T.lowlat.max'), 'a shark bumps an offer one size up its list, never past the most');
assert.equal(ev(`clGrow(${b})`), true, 'grows to the next size once');
assert.equal(ev(`${b}.bw`), 3200);
assert.equal(ev(`clGrow(${b})`), false, 'and never past it');
assert.equal(ev(`${b}.bw`), 3200);
assert.equal(ev("(()=>{const x={type:'hyper',bw:6400};clGrow(x);return x.bw;})()"), 12800, 'other customers still double past their top size');
// An edited save asking for more is cut back to the most the type sells.
ev(`${b}.bw=51200`);
ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()');
assert.equal(ev(`${b}.bw`), 3200);
assert.deepEqual(errors, []);
});
test('#137 old saves load, and new fields from a save are checked', () => {
const { ev, errors } = load();
ev(start);
ev(net());
// A save from before latency contracts: nothing of theirs in it.
ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()');
assert.ok(!ev("S.biz.some(b=>b.type==='lowlat')"));
// A save with a contract whose fields were edited or lost.
ev(sign());
ev(`(()=>{const s=JSON.parse(JSON.stringify(S)),b=s.biz.find(b=>b.id==='lc1');b.lcCr='lots';b.lcB='yes';delete b.latMax;b.reqs=[];S=migrate(s);compute();})()`);
const b = JSON.parse(ev("JSON.stringify(S.biz.find(b=>b.id==='lc1'))"));
assert.equal(b.lcCr, undefined, 'junk credits dropped');
assert.equal(b.lcB, 1, 'flag as a flag');
assert.equal(b.latMax, ev("latMaxOf('nyc','chi')"), 'the latency limit comes back');
assert.ok(b.reqs.includes('lat'), 'and its requirement');
ev(`(()=>{const s=JSON.parse(JSON.stringify(S));s.biz.find(b=>b.id==='lc1').lcCr=${lit(1234.4)};S=migrate(s);})()`);
assert.equal(ev("S.biz.find(b=>b.id==='lc1').lcCr"), 1234);
assert.deepEqual(errors, []);
});
test('#137 offer and customer rows on a 390 px phone', () => {
const { ev, dom, errors } = load();
ev(start);
ev(net());
ev('S.lvl=LC_LV');
ev("S.offers.push({id:'o1',city:'nyc',city2:'chi',name:'Great Circle Clearing House',type:'lowlat',bw:3200,rate:900,reqs:['lat'],latMax:latMaxOf('nyc','chi'),exp:S.day+40})");
dom.window.innerWidth = 390;
ev("ACT.leftTab({t:'deals'});renderAll()");
const html = dom.window.document.body.innerHTML;
assert.match(html, /Great Circle Clearing House/);
assert.match(html, /Low-latency wholesale route/);
assert.match(html, /Latency SLA [\d.]+ ms: a day's fee back for every day over it · never more than 3\.20 Tbps/);
ev("ACT.accept({id:'o1'})");
const c = JSON.parse(ev("JSON.stringify(S.biz.find(b=>b.name==='Great Circle Clearing House'))"));
assert.equal(c.route, 'fast', 'routed for latency');
assert.equal(c.latMax, ev("latMaxOf('nyc','chi')"));
ev(`S.biz.find(b=>b.id===${lit(c.id)}).lcCr=5000;renderAll()`);
const cs = ev('custSection()');
assert.match(cs, /Low-latency wholesale route/);
assert.match(cs, /\$5\.0k paid in SLA credits/);
assert.deepEqual(errors, []);
});

View file

@ -0,0 +1,58 @@
// #196: the two city names at the top of a link panel (wave, dark fiber, virtual circuit) open that city's panel.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const start = "ACT.start({});S.cash=1e9;S.lvl=13;S.nextFail=S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;";
const ends = ev => JSON.parse(ev("JSON.stringify([...document.querySelectorAll('#panel .ph h2 button[data-act=\"popGo\"]')].map(b=>[b.textContent,JSON.parse(b.dataset.args).city]))"));
const click = (ev, i) => ev(`document.querySelectorAll('#panel .ph h2 button[data-act="popGo"]')[${i}].click()`);
function setup(ev) {
ev(start + "ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'});compute()");
ev("S.links.push({id:'w1',a:'fra',b:'ams',kind:'wave',tier:0,km:360,sub:false,mo:1,cut:0,day:0})");
ev("S.links.push({id:'df1',a:'fra',b:'ams',kind:'df',own:false,sys:'lite',ch:[],km:360,sub:false,mo:1,ready:0,cut:0,day:0})");
ev("S.links.push({id:'vx1',a:'fra',b:'ams',kind:'vxc',prov:Object.keys(FAB)[0],vt:0,km:360,sub:false,mo:1,cut:0,day:0});compute()");
}
for (const [id, kind] of [['w1', 'wave'], ['df1', 'dark fiber'], ['vx1', 'virtual circuit']]) {
test(`#196 a ${kind} panel links both of its cities, and a click opens the city`, () => {
const { ev, errors } = load();
setup(ev);
ev(`selectLink('${id}')`);
assert.deepEqual(ends(ev), [['Frankfurt', 'fra'], ['Amsterdam', 'ams']]);
assert.match(ev("document.querySelector('#panel .ph h2').textContent"), /Frankfurt ⇄ Amsterdam/);
click(ev, 1);
assert.equal(ev("UI.sel.type+':'+UI.sel.id"), 'city:ams', 'the far end is selected');
assert.equal(ev("cam.x"), ev("CITY.ams.x"), 'and the map moves to it');
assert.match(ev("document.querySelector('#panel .ph h2').textContent"), /Amsterdam/);
ev(`selectLink('${id}')`);
click(ev, 0);
assert.equal(ev("UI.sel.id"), 'fra');
assert.deepEqual(errors, []);
});
}
test('#196 on a 390 px phone the city links sit in the bottom sheet header and still open the city', () => {
const { ev, errors } = load();
setup(ev);
ev("window.innerWidth=390;renderAll();selectLink('w1')");
assert.equal(ev("isPhone()"), true);
assert.equal(ends(ev).length, 2);
// The link styling: reads as heading text that wraps, not a button that pushes the header wider.
assert.match(ev("document.querySelector('#panel .ph h2 button').className"), /\bclink\b/);
click(ev, 0);
assert.equal(ev("UI.sel.type+':'+UI.sel.id"), 'city:fra');
assert.deepEqual(errors, []);
});
test('#196 a city the map does not show stays plain text', () => {
const { ev, errors } = load();
setup(ev);
ev("selectLink('w1')");
// cityOn() is false for an off-map city without a POP or IX port: no button to a panel that would not open.
ev("CITY.ams.off=true;delete S.pops.ams;renderPanel()");
assert.deepEqual(ends(ev), [['Frankfurt', 'fra']]);
assert.match(ev("document.querySelector('#panel .ph h2').textContent"), /Frankfurt ⇄ Amsterdam/);
ev("delete CITY.ams.off");
assert.deepEqual(errors, []);
});

View file

@ -226,7 +226,7 @@ test('a dry run prices every command that has a price, and changes nothing', ()
setChCount: { id: df, o: 'zr4', n: 2 }, repayLoan: { id: 'none' }, buildScrub: { city: 'ams', tier: 1 }, scrubUp: { city: 'fra', tier: 1 },
fixInc: { id: 'none' }, confGo: { key: T('catalog', { name: 'conferences' })[0].key }, confSponsor: { key: T('catalog', { name: 'conferences' })[0].key },
opsHire: { id: ev('Object.keys(INTERNS)[0]') }, opsNewPop: { city: 'nyc' }, pniAll: { net: 'cog', tier: 1 }, seatBuy: { n: 2 }, layShip: { id: df }, seaRush: { id: df },
utilityKit: { city: 'fra' }, utilityCaches: { city: 'fra' }, teDeploy: { script: 'spill at 85%' }, upLinkX: {},
utilityKit: { city: 'fra' }, utilityCaches: { city: 'fra' }, acceptFix: { id: 'none' }, ptApply: { city: 'fra', k: 'medium' }, ptAll: { k: 'medium' }, teDeploy: { script: 'spill at 85%' }, upLinkX: {},
pieRd: { k: 'reuse' }, pieAnt: { id: 'none' },
};
const missing = quoted.filter((n) => !sample[n] && T('schema', { section: 'commands' })[n].args.some((a) => a.required));

View file

@ -0,0 +1,72 @@
// #292: a renewal haggle in Deals shows what is at stake: traffic booked and served, the price per Gbps now and asked,
// and the path terms the customer signed for, each ticked as it stands today. It fits on a phone.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const start = "ACT.start({});S.cash=1e9;S.lvl=6;S.nextFail=S.nextEvent=1e9;for(const g of GOALS)S.done[g.id]=0;";
// Frankfurt, Paris and Amsterdam in a triangle, so Frankfurt-Amsterdam has a direct path and one round through Paris.
function net(ev) {
ev(start + "ACT.launchBB({city:'fra'});ACT.buildPop({city:'par'});ACT.buildPop({city:'ams'});for(const c in S.pops){S.pops[c].rgen=3;S.pops[c].routers=2}");
for (const [a, b] of [['fra', 'par'], ['par', 'ams'], ['fra', 'ams']]) ev(`UI.via=null;openLinkModal('${a}','${b}');ACT.buildLink({tier:1});closeModal()`);
}
const deals = ev => { ev("UI.left='deals';renderLeft()"); return ev("document.getElementById('left').innerHTML"); };
const row = (ev, name) => ev(`(()=>{const r=[...document.querySelectorAll('#left .row')].find(r=>r.querySelector('.nm')&&r.querySelector('.nm').textContent==='${name}');return r?r.textContent:''})()`);
test('#292 an IP customer\'s renewal shows booked and served traffic and the price per Gbps', () => {
const { ev, errors } = load();
net(ev);
ev("S.biz.push({id:'h1',city:'ams',city2:null,name:'Haggle Hosting',type:'dia',bw:5,rate:600,reqs:[],mood:90,since:S.day-800,te:S.day+20,mk:1,hag:{rate:540,until:S.day+20}});compute()");
deals(ev);
const t = row(ev, 'Haggle Hosting');
assert.match(t, /5\.0 Gbps booked, [\d.]+ Gbps served/);
assert.ok(t.includes(ev("fmt$(600)") + ' → ' + ev("fmt$(540)") + ' per Gbps'), t);
assert.match(t, /Pays .* wants .* to renew/, 'the monthly bills are still there');
assert.deepEqual(errors, []);
});
test('#292 a circuit\'s renewal shows its latency limit and path terms, ticked as they stand today', () => {
const { ev, errors } = load();
net(ev);
ev("S.biz.push({id:'c1',city:'fra',city2:'ams',name:'Tulip Bank',type:'l2vpn',bw:10,rate:300,reqs:['lat','diverse','sharks'],latMax:50,route:'fast',mood:90,since:S.day-800,te:S.day+20,mk:1,hag:{rate:250,until:S.day+20}});compute()");
deals(ev);
let t = row(ev, 'Tulip Bank');
assert.match(t, /10\.0 Gbps booked, 10\.0 Gbps served/);
assert.match(t, /✓ latency within 50 ms \(now [\d.]+ ms one-way\)/);
assert.match(t, /✓ two diverse paths/, 'direct and round through Paris');
assert.match(t, /✓ no subsea cable/);
// A tight budget the network cannot meet is crossed out, with what it gets today.
ev("S.biz.find(b=>b.id==='c1').latMax=0.5;compute()");
deals(ev);
t = row(ev, 'Tulip Bank');
assert.match(t, /✗ latency within 0\.5 ms/);
assert.doesNotMatch(t, /undefined|NaN/);
assert.deepEqual(errors, []);
});
test('#292 SD-WAN shows its sites, fiber deals show no Gbps, and served traffic below what is booked is red', () => {
const { ev, errors } = load();
net(ev);
ev("S.biz.push({id:'s1',city:'fra',city2:null,sites:['fra','par','ams'],name:'Kebab Kingdom',type:'sdwan',bw:2,rate:400,reqs:[],mood:90,since:S.day-800,te:S.day+20,mk:1,hag:{rate:360,until:S.day+20}});compute()");
deals(ev);
assert.match(row(ev, 'Kebab Kingdom'), /3 sites × 2\.0 Gbps booked/);
assert.doesNotMatch(row(ev, 'Kebab Kingdom'), /✓|✗/, 'no path terms when they asked for none');
assert.equal(ev("clRenInfo({...S.biz.find(b=>b.id==='s1'),type:'dfpair'})"), '', 'a fiber pair is not sold by the Gbps');
ev("R.l2['s1']=0.5");
assert.match(ev("clRenInfo(S.biz.find(b=>b.id==='s1'))"), /color:var\(--bad\)">0\.5 Gbps/);
assert.deepEqual(errors, []);
});
test('#292 the renewal row fits a 390 px phone', () => {
const { ev, errors } = load();
net(ev);
ev("S.biz.push({id:'c1',city:'fra',city2:'ams',name:'Tulip Bank',type:'l2vpn',bw:10,rate:300,reqs:['lat','diverse'],latMax:50,route:'fast',mood:90,since:S.day-800,te:S.day+20,mk:1,hag:{rate:250,until:S.day+20}});compute()");
ev("window.innerWidth=390;renderAll()");
deals(ev);
assert.match(row(ev, 'Tulip Bank'), /booked, .* served/);
// Every new line is a wrapping meta line, never one wide nowrap element.
const info = ev("clRenInfo(S.biz.find(b=>b.id==='c1'))");
assert.match(info, /^<div class="meta">/);
assert.doesNotMatch(info, /nowrap|width:\s*\d{3,}px/);
assert.deepEqual(errors, []);
});

View file

@ -17,10 +17,10 @@ function pages() {
let base = head;
try { const b = path.join(os.tmpdir(), `tubes-fuzz-test-${process.pid}-base.html`); fs.writeFileSync(b, page.assembleRef('origin/main')); base = b; } catch (e) {}
let P = { base: openPage(base, 'base'), head: openPage(head, 'head') };
// A change to the world itself (cities, networks, cables, AI campuses), to what links cost or to where each city's
// A change to the world itself (cities, networks, cables, AI campuses, the kinds of customers that call), to what links cost or to where each city's
// traffic goes (locSh(), #48) cannot route like main: there is no same game to compare. Then the base is this checkout
// too, and the cache on/off check still runs; equivalence with main resumes once it lands.
const world = (p) => p.ev("JSON.stringify([CITIES.map(c=>[c.id,c.land,c.P]),NETS.map(n=>[n.id,n.pops,n.ix,n.share,n.price,n.up]),CABLES.map(c=>[c.id,c.pairs.map(q=>[q[0],q[1]])]),[1,300,3000].map(k=>[dfLeaseMo(k),waveMo(k,false,2),dfBuildCost(k)]),MEGA.map(m=>m.c),['nyc','fra','sin'].map(c=>typeof locSh==='function'?Array.from(locSh(NSH,c)):null)])");
const world = (p) => p.ev("JSON.stringify([CITIES.map(c=>[c.id,c.land,c.P]),NETS.map(n=>[n.id,n.pops,n.ix,n.share,n.price,n.up]),CABLES.map(c=>[c.id,c.pairs.map(q=>[q[0],q[1]])]),[1,300,3000].map(k=>[dfLeaseMo(k),waveMo(k,false,2),dfBuildCost(k)]),Object.keys(BIZ_T).map(t=>[t,BIZ_T[t].lv||1,BIZ_T[t].opts]),MEGA.map(m=>m.c),['nyc','fra','sin'].map(c=>typeof locSh==='function'?Array.from(locSh(NSH,c)):null)])");
if (base !== head && world(P.base) !== world(P.head)) { console.log('# route fuzz: the world or its prices differ from main, so both pages are this checkout'); P = { base: openPage(head, 'base'), head: P.head }; }
return P;
}