seriesoftubes/tests/late-joiners.test.js
jvanvik dcdb501f16 Late joiners: a network that joins a server session late starts on its date, with a head start
One calendar for a server session (the user's answer to Q1): a network that joins begins on the session's date, and
one that joins after day 180, when the shared market starts to move, gets a head start (answered 2026-11-11).
Dormant until the host (T3) passes a start day: in the plain build and in single-device play S.day0 is 0 and the
game is as before.

- S.day0, the calendar day a network began: 0 in newGame(), repaired in sanitize() (at most S.day), so old saves load.
  netAge() is the network's age; the first-days rules count it: the charter window (and specSanitize), the tutorial's
  five days, the DDoS grace and early size cap, route leaks, RPKI, the world's bad news, shortages and control-plane
  events, sold-out routes, the scrubbing customers, loan offers, the broker's first calls, the Speedrun and Blitz
  badges and the day counts in the win, lose and Glass Baron windows. The market, the calendar and world events stay
  on the session's date.
- beginState() takes o.day for a session network in Normal mode (lateStart()): the day, the first outage and event,
  the home POP and the first IPv4 block are stamped with it, so the block cannot be sold on day one at the session's
  price.
- The head start (60-features/81-late-joiners.js): starting cash topped up by the rise in hardware prices (START_CASH
  x (hwTrend - 1), to $1,000, at most $60k, with the market rule only) and the first 365 days of home broadband
  matched (R.rev.late: what homes pay after the Australian wholesale cut or levy; outside investors' share, inside
  revMo). A second welcome with a button to the bank, a Goals card, a bank section, a line in a city's broadband pitch
  and a toast when the year is over; every label in all six dictionaries.
- The "since you started" lines (supply chain, bandwidth market, wave prices) measure from the network's own start.
- Server-run engine: srvBegin takes begin.day (an integer from 0, else the begin fails), the fake engine begins there
  and keeps day0 in its saves, CLOCK.off leaves the shape checker and the contract test, and the fixtures' network
  begins on day 473 (written again with tests/lib/mp-sim-fixtures.js; a second run changes nothing).
- Gameplay rule F11, the agent's day0 doc and status age, ARCHITECTURE and the plans (Q1's game side built, open
  question 1 answered).
- tests/late-joiners.test.js; F11 in tests/gameplay-rules.test.js; a late begin in tests/mp-sim-engine.test.js; one
  calendar in tests/mp-sim-contract.test.js.

Merged onto Starblink and Island Wi-Fi: revMo counts both the islands (V.wisp) and the match (V.late), the revenue
share base keeps V.wisp and leaves V.late out; F11 sits before F12 in the gameplay rules and their test; the mp-sim
fixtures were written again with tests/lib/mp-sim-fixtures.js (a second run changes nothing).
2026-11-12 02:16:44 +01:00

219 lines
15 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, []);
});