seriesoftubes/tests/late-joiners.test.js
jvanvik 66ac7d0af1 Island Wi-Fi, Starblink and late joiners work together
Checked after merging the three, and pinned with a test (tests/late-joiners.test.js): a late network with a Starblink
zone and a lit spur pays its islanders' income in full but has only its homes matched; investors on a revenue share
take their cut of homes, islands and an IPv4 lease, never of the match; a spur cut and a solar storm need a lit spur or
a LEO circuit, not a number of days, and come on the network's own outage schedule (S.nextFail, counted from S.day0),
so no grace needed moving; a reload keeps the game.

- CHANGELOG: Island Wi-Fi names zones as the game does (Abaco and Eleuthera) and says a spur has upkeep but no rent.
- Agent: a stray "., " in the pops doc where the Starblink and Island Wi-Fi lines met.
- Plans: open question 6 (WISP zones and a rented LEO tier) marked answered and built.
2026-11-12 02:25:24 +01:00

254 lines
18 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

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

// Late joiners (src/game/60-features/81-late-joiners.js, docs/plans/server-run.md "What Q1 changes"): a network that
// joins a server session after day 180 begins on the session's date (S.day0), counts its first-days rules from there
// (netAge()), gets a top-up as large as the rise in hardware prices and has its first year of home broadband income
// matched, outside investors' share. The market and the calendar stay the session's. Nothing of it outside a session.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const { lit } = require('../scripts/lib/js-literal');
const MP = { code: 'K7Q2XD', pid: 'abcd1234', asn: 201234, seed: 424242, preset: 'oncall', color: '#3a86ff', title: 'Friday' };
const D = 1868;
// A network of a server session, begun the way the server begins one (srvBegin), on day `day` of the session.
function late(t, { day = D, home = 'fra', preset = 'oncall', mp = MP } = {}) {
const h = load();
t.after(() => h.dom.window.close());
h.ev(`Date.now=()=>1.7e12;UI.pitched=true;beginState('Late Bloomers',${lit(home)},{mode:'normal',preset:${lit(preset)},${mp ? `mp:${lit(mp)},` : ''}day:${day}});
if(S.mp)S.mp.sim=1;compute();beginHello();UI.started=true;UI.speed=0;`);
return h;
}
const J = (ev, x) => JSON.parse(ev(`JSON.stringify(${x})`));
// Live S against what a reload makes of it, as text (never deep-compared as objects).
const same = (ev) => ev('(()=>{const u=uidN,r=S.rng;try{return JSON.stringify(S)===JSON.stringify(migrate(JSON.parse(JSON.stringify(S))));}finally{uidN=u;S.rng=r;}})()');
const homes = (ev, c = 'fra') => ev(`S.cash=1e7;ACT.launchBB({city:${lit(c)}});S.pops[${lit(c)}].bb.d=40;ACT.buyTransit({city:${lit(c)},net:NETS.filter(n=>sellsAt(n,${lit(c)}))[0].id,tier:1});compute();
if(!S.transit.length||!(R.rev.eyeballs>0))throw new Error('no homes served');`);
test('a late network starts on the session\'s date, its schedules and first block stamped with it, and a reload keeps it', (t) => {
const { ev, errors } = late(t);
assert.deepEqual(J(ev, '[S.day,S.day0,S.nextFail,S.nextEvent,S.pops.fra.day]'), [D, D, D + 45, D + 40, D]);
assert.deepEqual(J(ev, 'S.ip4.b.map(b=>[b.d,ip4Held(b)])'), [[D, true]], 'its RIR block cannot be sold on day one at the session\'s price');
assert.equal(ev('S.cash'), ev('START_CASH') + 37000, 'hardware costs 18% more on day 1868: the bank adds $37k');
assert.equal(ev('netAge()'), 0);
// The welcome, then the late welcome, which opens the bank (newest first in the log).
const log = J(ev, 'S.log.slice(0,2).map(x=>[x.k,x.h,x.o&&x.o.a])');
assert.deepEqual(log, [['goal', 'Late to the party, but welcome.', 'bank'], ['goal', 'Welcome, Late Bloomers!', 'city']]);
assert.match(ev('S.log[0].t'), /This session is 1868 days old and hardware costs 18% more than on its first day, so the bank adds \$37\.0k to your starting cash\./);
assert.equal(same(ev), true, 'a reload makes the same game');
ev('S.nextFail=S.nextEvent=1e9');
homes(ev);
for (let i = 0; i < 30; i++) {
ev('dayTick()');
assert.equal(same(ev), true, `day ${i + 1}: a reload makes the same game`);
}
assert.equal(ev('netAge()'), 30);
assert.deepEqual(errors, []);
});
test('the first-days rules count the network\'s age, not the calendar', (t) => {
const { ev, errors } = late(t);
homes(ev);
// Events: none of the world's bad news before age 50, no shortage before 180 (F1's trick: what fireEvent picks from;
// a network's own events, like its traffic through the Great Firewall, come whatever its age).
const evOpts = (age) => J(ev, `(()=>{let o=null;const f=eval('('+fireEvent.toString().replace('const e=pick(opts);','o=opts.slice();return;')+')');S.day=S.day0+${age};f();return o;})()`);
const early = ['sanction', 'tariff', 'hijack', 'landban', 'shutdown', 'redsea', 'baltic', 'hwshock'];
assert.deepEqual(evOpts(45).filter((e) => early.includes(e)), [], 'no bad news at age 45');
assert.ok(evOpts(51).includes('sanction') && !evOpts(51).includes('hwshock'), 'bad news possible from age 51, a shortage not yet');
assert.ok(evOpts(181).includes('hwshock'), 'a shortage from age 181');
// Failures: no route leak before age 60, no RPKI mess before age 30.
const failOpts = (age) => J(ev, `(()=>{window.__o=null;window.__f=null;S.day=S.day0+${age};const g=eval('('+failureRun.toString().replace('if(!opts.length)return;','__o=opts.map(o=>o[0]);if(!opts.length)return;').replace('type=pick(f);','__f=f.slice();return;')+')');g('funny').next();return {o:__o,f:__f};})()`);
let f = failOpts(25);
assert.ok(!f.o.includes('leak') && !f.f.includes('rpki'), 'nothing of the sort at age 25');
f = failOpts(61);
assert.ok(f.o.includes('leak') && f.f.includes('rpki'), 'both from age 61');
// DDoS: none through age 40, even with the dice always low; then one may come.
ev('S.day=S.day0;window.__r=Math.random;Math.random=()=>0.001');
const attacks = J(ev, '(()=>{const n=[];for(let a=1;a<=41;a++){S.day=S.day0+a;ddosTick();n.push(ddosAll().length);}return n;})()');
ev('Math.random=__r');
assert.deepEqual(attacks.slice(0, 40), Array(40).fill(0), 'no attack through age 40');
assert.equal(attacks[40], 1, 'the first at age 41');
// Attack sizes stay within twice your biggest port until age 180, with two POPs.
ev("S.ev.ddos=null;S.ev.ddosMore=[];S.ddosStarts=[];ACT.buildPop({city:'ams'});compute()");
const maxAt = (age) => ev(`(()=>{S.day=S.day0+${age};__reseed(8);return Math.max(...Array.from({length:500},()=>ddosSize({tgt:'d'})));})()`);
assert.ok(maxAt(100) <= 2 * ev('ddMaxPort()'), 'early floods stay small');
assert.ok(maxAt(400) > 2 * ev('ddMaxPort()'), 'later ones do not');
// Sold-out routes: none in the first 90 days of the network.
assert.equal(ev('(()=>{for(let a=0;a<90;a++){S.day=S.day0+a;if(CITIES.some(c=>soldOut(\'fra\',c.id,1)))return true;}return false;})()'), false);
// Loan offers: none spawned through age 20, even with the dice always low.
ev('S.loanOffers=[];window.__r=Math.random;Math.random=()=>0.001');
const offers = J(ev, '(()=>{const n=[];for(let a=1;a<=21;a++){S.day=S.day0+a;loanTick(S.day);n.push(S.loanOffers.length);}return n;})()');
ev('Math.random=__r');
assert.deepEqual(offers.slice(0, 20), Array(20).fill(0), 'no loan offer through age 20');
assert.ok(offers[20] > 0, 'the banks call from age 21');
assert.deepEqual(errors, []);
});
test('the charter window, the tutorial, the badges and the win count the network\'s days', (t) => {
const { ev, dom, errors } = late(t);
ev('S.nextFail=S.nextEvent=1e9');
// The charter is still open at age 10, a reload keeps it open, and it closes after 30 days.
ev('S.day=S.day0+10');
assert.equal(ev('S.chartSet'), false);
ev('S=migrate(JSON.parse(JSON.stringify(S)));compute()');
assert.equal(ev('S.chartSet'), false, 'a reload keeps the choice open');
ev('S.day=S.day0+30;dayTick()');
assert.equal(ev('S.chartSet'), true, 'the classic charter once its days are over');
// The tutorial's "start the clock" step: five days of the network's own.
const tut = (age) => ev(`(()=>{S.day=S.day0+${age};return TUT.find(s=>s.sel==='#sp1').ok();})()`);
assert.deepEqual([tut(4), tut(5)], [false, true]);
// Speedrun: Tier 1 within three years of the network's start.
const speed = (age) => ev(`(()=>{S.won=true;S.day=S.day0+${age};return BADGES.find(b=>b.id==='speed').ok();})()`);
assert.deepEqual([speed(1095), speed(1096)], [true, false]);
ev('S.day=S.day0+700;showWin()');
const txt = dom.window.document.getElementById('modalCard').textContent;
assert.match(txt, /Took you 700 days/);
assert.deepEqual(errors, []);
});
test('the match: home broadband pays double for a year, net of wholesale, outside investors\' share', (t) => {
const { ev, errors } = late(t);
ev('S.nextFail=S.nextEvent=1e9');
homes(ev);
const rev = J(ev, 'R.rev');
assert.ok(rev.eyeballs > 0 && rev.late === rev.eyeballs, 'every dollar homes pay is matched');
assert.ok(Math.abs(ev('R.revMo') - (rev.eyeballs + rev.business + rev.ix + rev.grant + rev.late)) < 1e-6, 'and counts as revenue');
// Investors and the IPv4 bill see what homes pay, never the match.
ev("S.loanOffers.push({id:'v1',bank:'vult',amount:500000,exp:S.day+20,covs:['blitz'],share:0.1});ACT.takeLoan({id:'v1'});S.pops.fra.bb.d=400;compute()");
const a = J(ev, '[R.cost.revshare,R.cost.ip4||0,R.rev.late]');
const b = J(ev, '(()=>{const d0=S.day0;S.day0=0;compute();const o=[R.cost.revshare,R.cost.ip4||0,R.rev.late];S.day0=d0;compute();return o;})()');
assert.ok(a[0] > 0 && a[1] > 0 && a[2] > 0, `a share, an IPv4 bill and a match (${a})`);
assert.deepEqual(b.slice(0, 2), a.slice(0, 2), 'the same share and IPv4 bill without the match');
assert.equal(b[2], null, 'no match for a network that began on day 0');
// The last matched day is day0+365; the next day says the year is over.
ev('S.day=S.day0+364;dayTick()');
assert.equal(ev('S.day'), D + 365);
assert.ok(ev('R.rev.late') > 0, 'still matched on day 365');
ev('dayTick()');
assert.equal(ev('R.rev.late'), undefined, 'not on day 366');
assert.ok(ev("S.log.some(x=>x.t===tr('late.over'))"), 'the year is over, in the log');
assert.deepEqual(errors, []);
});
test('the match is net of the Australian wholesale cut', (t) => {
const { ev, errors } = late(t, { home: 'syd' });
homes(ev, 'syd');
const r = J(ev, '[R.rev.eyeballs,R.rev.late,R.cost.wholesale,AU_WHOLESALE]');
assert.ok(r[0] > 0 && r[2] > 0);
assert.ok(Math.abs(r[1] - r[0] * (1 - r[3])) < 1e-6, 'what homes pay after the wholesale cut');
assert.deepEqual(errors, []);
});
test('five seeded days: the match is the only difference in cash, a monthly match paid by the day', (t) => {
const { ev, errors } = late(t);
ev('S.nextFail=S.nextEvent=1e9');
homes(ev);
ev('window.__s0=JSON.stringify(S);window.__lm=lateMoney;window.__vd=volDay;window.__late=[];volDay=function(){__late.push((R.rev.late||0)/monLen(S.day));return __vd.apply(this,arguments);}');
const run = (match) => ev(`(()=>{S=migrate(JSON.parse(__s0));lateMoney=${match ? '__lm' : '()=>{}'};compute();__reseed(77);__late=[];for(let i=0;i<5;i++)dayTick();return S.cash;})()`);
const withM = run(true), sum = J(ev, '__late').reduce((x, y) => x + y, 0), without = run(false);
ev('lateMoney=__lm;volDay=__vd');
assert.ok(sum > 0);
assert.ok(Math.abs(withM - without - sum) < 1e-6, `cash ${withM} − ${without} is the match, ${sum}`);
assert.deepEqual(errors, []);
});
test('who is late: after day 180 only, the top-up with the market rule only', (t) => {
for (const [day, preset, isLate, topUp] of [[180, 'oncall', false, 0], [181, 'oncall', true, 0], [D, 'freeze', true, 0], [D, 'bgp', true, 37000]]) {
const { ev, dom, errors } = late(t, { day, preset });
assert.equal(ev('S.day0'), day);
assert.equal(ev('lateIs()'), isLate, `day ${day} ${preset}`);
assert.equal(ev('S.cash'), ev('START_CASH') + topUp, `day ${day} ${preset}: top-up`);
assert.equal(ev("S.log.filter(x=>/Late to the party/.test(x.t)).length"), isLate ? 1 : 0, `day ${day} ${preset}: the late welcome`);
homes(ev);
assert.equal(ev("'late' in R.rev"), isLate, `day ${day} ${preset}: the match`);
assert.deepEqual(errors, []);
dom.window.close();
}
});
test('outside a server session nothing changes: day 0, no match, and saves repair the start day', (t) => {
const { ev, errors } = load();
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();compute()");
assert.deepEqual(J(ev, "[S.day,S.day0,'late' in R.rev,Object.keys(S).indexOf('day0')-Object.keys(S).indexOf('day')]"), [0, 0, false, 1]);
// A day without a session, or a session in sandbox or a scenario, begins on day 0.
ev(`beginState('Solo','fra',{mode:'normal',preset:'oncall',day:${D}})`);
assert.deepEqual(J(ev, '[S.day,S.day0]'), [0, 0], 'no session, no start day');
ev(`beginState('Box','fra',{mode:'sandbox',mp:${lit(MP)},day:${D}})`);
assert.deepEqual(J(ev, '[S.day,S.day0,S.mp]'), [0, 0, null], 'sandbox never is a session network');
// Saves: a start after the day is the day, a negative one 0, an old save without one 0.
const fix = (x) => J(ev, `(()=>{const s=JSON.parse(JSON.stringify(S));Object.assign(s,${lit(x)});if(${lit(x)}.day0===undefined)delete s.day0;const m=migrate(s);return [m.day,m.day0];})()`);
assert.deepEqual(fix({ day: 100, day0: 500 }), [100, 100]);
assert.deepEqual(fix({ day: 100, day0: -3 }), [100, 0]);
assert.deepEqual(fix({ day: 100, day0: 'x' }), [100, 0]);
assert.deepEqual(fix({ day: 100 }), [100, 0]);
assert.deepEqual(errors, []);
});
test('a late network sees its head start on the Goals tab, in the bank and in a city\'s pitch, also on a phone', (t) => {
const { ev, dom, errors } = late(t);
const doc = dom.window.document;
ev("window.innerWidth=360;window.innerHeight=740;UI.left='goals';UI.leftOpen=true;UI.sel=null;renderAll();renderLeft()");
// The city pitch before broadband launches.
ev("UI.tab='cust';selectCity('fra');renderAll()");
assert.match(doc.getElementById('panel').textContent, /You joined late: for 365 more days, what homes here pay you is matched\./);
homes(ev);
ev("UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft()");
const card = [...doc.querySelectorAll('#leftBody .inc')].find((e) => /Late joiner's head start/.test(e.textContent));
assert.ok(card, 'the Goals card');
assert.match(card.textContent, new RegExp(`Home broadband pays double for 365 more days: \\+${ev('fmt$(R.rev.late)').replace('$', '\\$')}/mo right now\\.`));
ev('ACT.bank()');
const bank = doc.getElementById('bankCard').textContent;
assert.match(bank, /Late joiner's head start/);
assert.match(bank, /Starting cash top-up\$37\.0k/);
assert.ok(bank.includes('until ' + ev('dateStr(S.day0+365)')));
// The "since you started" lines measure from the network's own first day.
assert.equal(ev('mktTxt()'), ev("tr('lifecycle.market_as_start')"));
assert.match(ev('hwCard()'), /as when you started/);
assert.doesNotMatch(ev("marketNote('fra','ams',false)"), /fallen/);
assert.match(ev("(()=>{S.day+=400;const t=marketNote('fra','ams',false)+mktTxt();S.day-=400;return t;})()"), /fallen|below/, 'and move once it ages');
assert.deepEqual(errors, []);
});
test('a network that began on day 0 shows none of it', (t) => {
const { ev, dom, errors } = load();
ev("ACT.start({});if(UI.pendGame)ACT.pitchSkip();S.cash=1e7;UI.tab='cust';selectCity(S.home);renderAll()");
assert.doesNotMatch(dom.window.document.getElementById('panel').textContent, /You joined late/);
ev("ACT.launchBB({city:S.home});compute();UI.left='goals';UI.leftOpen=true;UI.sel=null;renderLeft();ACT.bank()");
assert.doesNotMatch(dom.window.document.getElementById('leftBody').textContent, /Late joiner/);
assert.doesNotMatch(dom.window.document.getElementById('bankCard').textContent, /Late joiner/);
assert.deepEqual([ev('lateCard()'), ev('lateBank()')], ['', '']);
assert.deepEqual(errors, []);
});
// Island Wi-Fi and Starblink (#83) on a late network: what islanders pay is theirs to share with investors (as an IPv4
// lease is) and is never matched; a spur cut or a solar storm is a failure like any other, drawn only once a lit spur or
// a LEO circuit is up and only on the network's own outage schedule (S.nextFail, counted from S.day0), no calendar grace.
test('a late network with island Wi-Fi and Starblink: islanders are not matched, investors share islands and IPv4 leases but not the match', (t) => {
const { ev, errors } = late(t, { home: 'suv' });
const Z = "wispZ('vanualevu')", sp = "wispZ('tobago')";
assert.equal(ev('S.nextFail-S.day0'), 45, 'the first outage 45 days into its own life');
ev(`S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;S.lvl=5;
ACT.launchBB({city:'suv'});S.pops.suv.bb.d=8;ACT.buyTransit({city:'suv',net:NETS.find(n=>sellsAt(n,'suv')).id,tier:1});
ACT.teleBuild({city:'suv'});ACT.teleLeo({city:'suv'});ACT.wispSat({z:'vanualevu',bird:LEO_BIRD,g:5});
ACT.buildPop({city:'pos'});ACT.buyTransit({city:'pos',net:NETS.find(n=>sellsAt(n,'pos')).id,tier:1});ACT.wispSpur({z:'tobago'});
${Z}.sat.ready=S.day;${sp}.sp.ready=S.day;${Z}.d=4;${sp}.d=2;compute()`);
assert.equal(ev('netAge()'), 0);
assert.equal(ev('leoLive()') && ev('wispSpurs().length'), 1, 'a LEO zone in the sky and a lit spur on its first day');
// The pool a failure draws from, on its first day: both are there, with no grace of their own.
const pool = () => J(ev, "(()=>{window.__o=null;runNow(eval('('+failureRun.toString().replace('if(!opts.length)return;','__o=opts.map(o=>o[0]);return;')+')')());return __o;})()");
assert.ok(pool().includes('leostorm') && pool().includes('wspur'), 'a storm and a cut are possible failures from day one');
// The money: islanders pay, homes are matched, the islands are not.
const r = J(ev, 'R.rev');
assert.ok(r.wisp > 0 && r.eyeballs > 0, `islanders and homes both pay (${r.wisp}, ${r.eyeballs})`);
assert.equal(r.late, r.eyeballs, 'the match is what homes pay, never what islanders pay');
// Investors: their share of homes, islands and an IPv4 lease, never of the match.
ev("S.loans.push({id:'v',bank:'vult',start:S.day,amount:1,got:1,bal:0,share:0.1,covs:[]});ACT.ip4Buy({len:20});ACT.ip4Out({id:S.ip4.b.find(b=>b.k==='buy').id});compute()");
const m = J(ev, '[R.rev,R.cost.revshare,R.revMo]'), v = m[0];
assert.ok(v.ip4 > 0 && v.wisp > 0 && v.late > 0, `a lease, islanders and a match (${v.ip4}, ${v.wisp}, ${v.late})`);
assert.ok(Math.abs(m[1] - 0.1 * (v.eyeballs + v.business + v.ix + (v.orbit || 0) + v.ip4 + v.wisp)) < 1e-6, 'investors take 10% of homes, islands and the lease');
assert.ok(Math.abs(m[1] - 0.1 * (m[2] - v.grant - (v.gov || 0) - v.late)) < 1e-6, 'of every revenue but grants and the match');
// Its first outage comes on its own schedule, and the pool still holds both: a storm or a cut can be that outage.
ev("window.__fr=[];const f0=failureRun;failureRun=function*(o){__fr.push(netAge());yield* f0(o);};S.nextEvent=1e9;__reseed(5)");
for (let i = 0; i < 46; i++) ev('dayTick()');
assert.equal(J(ev, '__fr')[0], 45, 'no failure before age 45');
assert.equal(same(ev), true, 'a reload makes the same game');
assert.deepEqual(errors, []);
});