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).
This commit is contained in:
jvanvik 2026-11-12 01:30:22 +01:00
parent 9067bae1ce
commit dcdb501f16
51 changed files with 476 additions and 76 deletions

View file

@ -1 +1 @@
{"t":"clock","speed":1,"eff":1,"run":true,"why":null,"votes":{"efgh5678":4},"tally":{"4":1},"need":2,"active":["abcd1234","efgh5678"],"hold":[],"idle":[],"day":518,"last":1,"max":8,"off":{"abcd1234":-473,"efgh5678":0}}
{"t":"clock","speed":1,"eff":1,"run":true,"why":null,"votes":{"efgh5678":4},"tally":{"4":1},"need":2,"active":["abcd1234","efgh5678"],"hold":[],"idle":[],"day":518,"last":1,"max":8}

View file

@ -1 +1 @@
{"t":"roster","code":"K7Q2XD","title":"Friday","preset":"oncall","seed":424242,"created":1730913600000,"players":[{"pid":"abcd1234","name":"Packet Pals","asn":201234,"color":"#3a86ff","card":{"day":45,"name":"Packet Pals","asn":201234,"tier":"t3","t1":false,"lvl":2,"pops":["fra","ams"],"links":[["ams","fra",10]],"ix":[],"transit":["cog"],"ppol":"open","reach":1,"peak":47.5,"served":47.5,"cust":0,"rev":7126,"cashB":5,"score":48},"seen":1731000000000,"joined":1730913600000},{"pid":"efgh5678","name":"Tubular Bells","asn":207777,"color":"#ff4f9a","card":null,"seen":1730999940000,"joined":1730996400000}],"feed":[{"k":"join","pid":"abcd1234","name":"Packet Pals","at":1730913600000},{"k":"join","pid":"efgh5678","name":"Tubular Bells","at":1730996400000},{"k":"chat","pid":"efgh5678","name":"Tubular Bells","at":1730999940000,"text":"peer with me?"}],"on":["abcd1234","efgh5678"]}
{"t":"roster","code":"K7Q2XD","title":"Friday","preset":"oncall","seed":424242,"created":1730913600000,"players":[{"pid":"abcd1234","name":"Packet Pals","asn":201234,"color":"#3a86ff","card":{"day":518,"name":"Packet Pals","asn":201234,"tier":"t3","t1":false,"lvl":2,"pops":["fra","ams"],"links":[["ams","fra",10]],"ix":[],"transit":["cog"],"ppol":"open","reach":1,"peak":47.5,"served":47.5,"cust":0,"rev":14252,"cashB":5,"score":48},"seen":1731000000000,"joined":1730913600000},{"pid":"efgh5678","name":"Tubular Bells","asn":207777,"color":"#ff4f9a","card":null,"seen":1730999940000,"joined":1730996400000}],"feed":[{"k":"join","pid":"abcd1234","name":"Packet Pals","at":1730913600000},{"k":"join","pid":"efgh5678","name":"Tubular Bells","at":1730996400000},{"k":"chat","pid":"efgh5678","name":"Tubular Bells","at":1730999940000,"text":"peer with me?"}],"on":["abcd1234","efgh5678"]}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -563,6 +563,29 @@ test('F10: growth goes sideways, plus one paid way up (#61, #323)', () => {
fail('F10', J("MEGA.filter(m=>!CITY[m.c]).map(m=>m.c)"), 'campuses sit in real cities');
});
test('F11: a late joiner starts on the session\'s date with F1\'s gentle start, a hardware top-up and a year of home broadband matched', () => {
const g = load();
const D = 1868, MP = { code: 'K7Q2XD', pid: 'abcd1234', asn: 201234, seed: 424242, preset: 'oncall', color: '#3a86ff', title: 'Friday' };
g.ev(`UI.pitched=true;beginState('Late','fra',{mode:'normal',preset:'oncall',mp:${lit(MP)},day:${D}});S.mp.sim=1;compute()`);
// The session's date, F1's start counted from its own first day.
assert.deepEqual(JSON.parse(g.ev('JSON.stringify([S.day,S.day0,S.nextFail-S.day0,S.nextEvent-S.day0])')), [D, D, 45, 40], 'F11: the session\'s date, and F1\'s first outage and event');
const opts = JSON.parse(g.ev(`(()=>{let o=null;const f=eval('('+fireEvent.toString().replace('const e=pick(opts);','o=opts.slice();return;')+')');S.day=S.day0+45;f();S.day=S.day0;return JSON.stringify(o);})()`));
fail('F11', opts.filter((e) => !['viral', 'price', 'grant'].includes(e)), 'no bad events before its day 50 (count S.day-S.day0: netAge())');
assert.equal(g.ev("(()=>{for(let a=0;a<90;a++){S.day=S.day0+a;if(CITIES.some(c=>soldOut('fra',c.id,1)))return true;}S.day=S.day0;return false;})()"), false, 'F11: nothing sold out in its first 90 days');
// The top-up: the rise in hardware prices on START_CASH, at most $60k; the market stays on the session's date.
const top = g.ev('S.cash-START_CASH');
assert.ok(top === Math.round(g.ev(`START_CASH*(hwTrend(${D})-1)`) / 1000) * 1000 && top > 0 && top <= 60000, `F11: a top-up of ${top}`);
assert.equal(g.ev('lateCash(1e6)'), 60000, 'F11: never more than $60k');
assert.equal(g.ev('hwMul("rt")'), g.ev(`hwTrend(${D})`), 'F11: hardware at the session\'s price');
// The match: what homes pay after wholesale, for 365 days, outside investors' share.
g.ev("S.cash=1e7;ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});S.loans.push({id:'v',bank:'vult',start:S.day,amount:1,got:1,bal:0,share:0.1,covs:[]});compute()");
const r = JSON.parse(g.ev('JSON.stringify([R.rev.eyeballs,R.rev.late,R.cost.revshare])'));
assert.ok(r[0] > 0 && r[1] === r[0], 'F11: home broadband matched');
assert.ok(Math.abs(r[2] - 0.1 * r[0]) < 1e-6, 'F11: investors take no share of the match');
assert.equal(g.ev('(()=>{S.day=S.day0+366;compute();const v=R.rev.late;S.day=S.day0;compute();return v===undefined;})()'), true, 'F11: for one year');
assert.deepEqual(g.errors, []);
});
test('F12: island Wi-Fi pays on its own books on some way in; a spur beats every satellite, and pays back within 5 years up to 250 km, 10 up to 1,000 km', () => {
// The zone's own books at full take-up, era 1: its homes at island prices, less the towers' upkeep and the backhaul
// rent. The teleport, tracking antennas and a Starblink gateway serve more than one zone and are left out. Each way in

219
tests/late-joiners.test.js Normal file
View file

@ -0,0 +1,219 @@
// 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, []);
});

View file

@ -6,7 +6,8 @@
// const engine = createFakeEngine({onLost});
// engine.load(code, nets:[{nid, env?, begin?, lang, prefs}]) → [{t:'loaded', nid, epoch, day, lost, saved?}], one per
// net; a network that did not load is {t:'loaded', nid, err} (broken, 4.7): one with
// neither a save (env.s, the save text) nor a begin answers err 'no save to load'
// neither a save (env.s, the save text) nor a begin answers err 'no save to load'; a begin
// starts on begin.day (the session's date; 0 when it is none)
// engine.day(code, {d, speed, last, alone:[nid], nets:[nid], mute}) → {t:'dayDone', code, d, nets:{[nid]:{day, lost,
// pause?, err?, retried?, ms}}}; a network of nets that is not loaded is left out
// engine.act(code, nid, msg) → {t:'actDone', nid, epoch, rid, outcome, why?, v, upd, ms} (msg: the request body, 5.8)
@ -58,6 +59,8 @@ function createFakeEngine(opts = {}) {
const hasSession = (code) => [...realms.keys()].some((k) => k.startsWith(code + '/'));
// The day of a save text (the real engine reads the save); else the canned one.
const dayOf = (s) => { try { const d = JSON.parse(s).day; return Number.isInteger(d) ? d : F.snap.S.day; } catch (e) { return F.snap.S.day; } };
// The day a save's network began (S.day0), at most its day; 0 for a save that does not say.
const day0Of = (s, day) => { try { const d = JSON.parse(s).day0; return Number.isInteger(d) && d >= 0 ? Math.min(d, day) : 0; } catch (e) { return 0; } };
// A realm the worker had to build again after a timeout: a new epoch, versions from 0.
const rebuilt = (r) => { if (r) { r.epoch = newEpoch(); r.v = 0; r.dirty = false; } };
// Every answer goes through here: held back, failed, or rejected when the worker exits meanwhile. failed(f): the reply
@ -102,7 +105,7 @@ function createFakeEngine(opts = {}) {
}
return o;
};
const savedOf = (code, nid, r) => ({ t: 'saved', nid, txt: JSON.stringify({ ...F.snap.S, day: r.day, lost: r.lost, mp: { ...F.snap.S.mp, code, pid: nid } }), uidN: 100 + r.day, rt: { load: {}, l2route: {}, efg: {} }, day: r.day, lost: r.lost });
const savedOf = (code, nid, r) => ({ t: 'saved', nid, txt: JSON.stringify({ ...F.snap.S, day: r.day, day0: r.day0, lost: r.lost, mp: { ...F.snap.S.mp, code, pid: nid } }), uidN: 100 + r.day, rt: { load: {}, l2route: {}, efg: {} }, day: r.day, lost: r.lost });
const CLOSED = () => Promise.reject(coded('engine closed', 'CLOSED'));
const engine = {
@ -123,8 +126,8 @@ function createFakeEngine(opts = {}) {
const one = (n, err) => {
if (!err && !n.begin && !(n.env && typeof n.env === 'object' && typeof n.env.s === 'string')) err = 'no save to load';
if (err) { realms.delete(key(code, n.nid)); return { t: 'loaded', nid: n.nid, err }; }
const day = n.begin ? 0 : Number.isInteger(n.env.day) ? n.env.day : dayOf(n.env.s);
const r = { epoch: newEpoch(), v: 0, day, lost: false, broken: false, dirty: false, greeted: false, pause: false, loseNext: false, keep: [], lang: n.lang || 'en' };
const day = n.begin ? (Number.isInteger(n.begin.day) ? n.begin.day : 0) : Number.isInteger(n.env.day) ? n.env.day : dayOf(n.env.s);
const r = { epoch: newEpoch(), v: 0, day, day0: n.begin ? day : day0Of(n.env.s, day), lost: false, broken: false, dirty: false, greeted: false, pause: false, loseNext: false, keep: [], lang: n.lang || 'en' };
realms.set(key(code, n.nid), r);
return { t: 'loaded', nid: n.nid, epoch: r.epoch, day, lost: false, ...(n.begin ? { saved: savedOf(code, n.nid, r) } : {}) };
};

View file

@ -28,7 +28,8 @@ function make() {
ev(`Date.now=()=>${NOW};`);
// A network of a server session, built the way the server builds one (beginState, then the server's own marks), with
// the intern on every order and a fiber cut it rushes: the snapshot carries a shift's log and the week's tally.
ev(`UI.pitched=true;beginState('Packet Pals','fra',{mode:'normal',preset:'oncall',mp:${JSON.stringify(MP)}});S.mp.sim=1;S.tut=null;compute();beginHello();
// It joined the session late (day 473): the session's date, one calendar for every network (S.day0).
ev(`UI.pitched=true;beginState('Packet Pals','fra',{mode:'normal',preset:'oncall',mp:${JSON.stringify(MP)},day:473});S.mp.sim=1;S.tut=null;compute();beginHello();
S.nextFail=S.nextEvent=1e9;UI.speed=0;UI.started=true;ACT.charter({k:'global'});
ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buildPop({city:'ams'});ACT.launchBB({city:'ams'});
UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:0});closeModal();
@ -43,7 +44,7 @@ function make() {
return { s, del, keys: now }; };
const fx = () => JSON.parse(ev('JSON.stringify(__fx.splice(0))'));
const clock = { t: 'clock', speed: 1, eff: 1, run: true, why: null, votes: { [PID2]: 4 }, tally: { 4: 1 }, need: 2, active: [PID, PID2], hold: [], idle: [],
day: 518, last: 1, max: 8, off: { [PID]: S0day(snapS) - 518, [PID2]: 0 } };
day: snapS.day, last: 1, max: 8 };
const card = JSON.parse(ev('JSON.stringify(mpCard())'));
const roster = { t: 'roster', code: CODE, title: 'Friday', preset: 'oncall', seed: MP.seed, created: NOW - 864e5,
players: [{ pid: PID, name: 'Packet Pals', asn: MP.asn, color: MP.color, card, seen: NOW, joined: NOW - 864e5 },
@ -76,9 +77,6 @@ function make() {
dom.window.close();
return { snap, 'upd-day': updDay, 'upd-act': updAct, sub, clock, roster };
}
// The calendar offset of the network in the fixtures: its own date against the session day (open question 1).
function S0day(S) { return S.day; }
function write() {
fs.mkdirSync(DIR, { recursive: true });
const out = make();

View file

@ -102,10 +102,8 @@ const fxList = (v, w, out) => { if (!Array.isArray(v)) return false; v.forEach((
const CLOCK = { t: (v) => v === 'clock', speed: (v) => SPEEDS.includes(v), eff: (v) => num(v) && v >= 0, run: bool, why: (v) => WHY.includes(v),
votes: mapOf((k) => PID.test(k), (v) => v === null || SPEEDS.includes(v)), tally: mapOf((k) => SPEEDS.includes(+k), nat), need: (v) => int(v) && v >= 1,
active: listOf((v) => PID.test(v)), hold: listOf((v) => PID.test(v)), idle: listOf((v) => PID.test(v)), day: nat, last: (v) => SPEEDS.includes(v) && v > 0,
max: (v) => SPEEDS.includes(v) && v > 0,
// The calendar offset of every network of the session: its own S.day minus the session day (open question 1: "own
// date"). One field, so a shared date later only means all zeros.
off: mapOf((k) => PID.test(k), int) };
// day: the session's date, and every network's (one calendar: a network that joins late begins on it, S.day0).
max: (v) => SPEEDS.includes(v) && v > 0 };
const PLAYER = { pid: (v) => PID.test(v), name: str, asn: nat, color: (v) => /^#[0-9a-f]{6}$/i.test(v), card: (v) => v === null || obj(v), seen: nat, joined: nat,
lost: [bool, 'opt'], broken: [bool, 'opt'] };
const ROSTER = { t: (v) => v === 'roster', code: (v) => CODE.test(v), title: str, preset: str, seed: int, created: nat,

View file

@ -153,12 +153,15 @@ test('the canned stream: every fixture passes the shape checker, and the shape c
assert.equal(upd.v, upd.from + 1);
assert.equal(fixture('upd-day').from, fixture('snap').v, 'the day follows the snapshot');
assert.equal(upd.from, fixture('upd-day').v, 'the actions follow the day');
assert.ok('off' in fixture('clock'), 'the clock carries each network\'s calendar offset');
// One calendar for the session: no offsets, and the network in the snapshot is on the clock's day (it joined late).
assert.ok(!('off' in fixture('clock')), 'the clock carries no calendar offsets');
assert.equal(fixture('snap').S.day, fixture('clock').day);
assert.ok(fixture('snap').S.day0 > 0 && fixture('snap').S.day0 < fixture('snap').S.day, 'the canned network began on the session\'s date');
const broken = [
[{ ...upd, v: upd.from + 2 }, /from \+ 1/], [{ ...upd, r: { ...upd.r, ef: {} } }, /never carries/], [{ ...upd, fx: [['boom', 1]] }, /unknown effect/],
[{ ...upd, acts: [{ rid: 'x', dev: '9f8e7d6c', ui: {} }] }, /rid/], [{ ...fixture('clock'), speed: 3 }, /speed/], [{ ...fixture('roster'), on: ['NOPE'] }, /on/],
[{ ...fixture('snap'), S: { ...fixture('snap').S, mp: { ...fixture('snap').S.mp, sim: undefined } } }, /server network/], [{ t: 'bye', why: 'tired' }, /why/], [{ t: 'nope' }, /unknown event/],
[{ ...upd, s: { ...upd.s, day: 1 }, day: 2 }, /day/],
[{ ...upd, s: { ...upd.s, day: 1 }, day: 2 }, /day/], [{ ...fixture('clock'), off: {} }, /unknown field/],
];
for (const [e, re] of broken) assert.match(checkEvent(e).join('\n'), re);
assert.deepEqual(checkFx(['floater', [1, 2, 'x', '#fff']]), []);
@ -188,12 +191,14 @@ test('the canned state is the game\'s own: migrate() keeps the snapshot and ever
test('the fake engine answers every call in the shapes of section 4.2', async () => {
const e = createFakeEngine(), code = 'K7Q2XD', a = 'abcd1234', b = 'efgh5678';
const all = [];
const L = await e.load(code, [{ nid: a, begin: { name: 'Packet Pals', home: 'fra', preset: 'oncall', asn: 201234, mp: {}, tut: false }, lang: 'en', prefs: {} }, { nid: b, env: { s: sv(40) }, lang: 'de', prefs: {} }]);
// A network that joins the session on its day 40 begins on it, beside one loaded at 40: one calendar.
const L = await e.load(code, [{ nid: a, begin: { name: 'Packet Pals', home: 'fra', preset: 'oncall', asn: 201234, mp: {}, tut: false, day: 40 }, lang: 'en', prefs: {} }, { nid: b, env: { s: sv(40) }, lang: 'de', prefs: {} }]);
assert.equal(L.length, 2); assert.ok(L[0].saved, 'a new network is checkpointed at once');
assert.deepEqual([L[0].day, L[1].day, JSON.parse(L[0].saved.txt).day0], [40, 40, 40]);
assert.ok(L[0].epoch && L[1].epoch && L[0].epoch !== L[1].epoch, 'each realm load has its own epoch');
all.push(...L);
const D = await e.day(code, { d: 1, speed: 1, last: 1, alone: [], nets: [b, a] });
assert.deepEqual(Object.keys(D.nets), [a, b]); assert.equal(D.nets[b].day, 41);
const D = await e.day(code, { d: 41, speed: 1, last: 1, alone: [], nets: [b, a] });
assert.deepEqual(Object.keys(D.nets), [a, b]); assert.deepEqual([D.nets[a].day, D.nets[b].day], [41, 41]);
all.push(D);
const P1 = await e.pull(code, a, {}), P2 = await e.pull(code, a, {});
assert.ok(P1.upd && !P2.upd, 'a pull sends what changed, once'); assert.equal(P2.v, P1.v, 'only a pull with something to send is a version');
@ -204,9 +209,9 @@ test('the fake engine answers every call in the shapes of section 4.2', async ()
await e.sub(code, a, { views: [{ link: 'l1' }] }), await e.greet(code, a), await e.save(code, b), await e.card(code, a));
assert.equal(await e.prefs(code, a, { prefs: { pauseFurious: true } }), undefined);
e.lose(code, b);
const D2 = await e.day(code, { d: 2, nets: [a, b] });
const D2 = await e.day(code, { d: 42, nets: [a, b] });
assert.equal(D2.nets[b].lost, true);
const D3 = await e.day(code, { d: 3, nets: [a, b] });
const D3 = await e.day(code, { d: 43, nets: [a, b] });
assert.equal(D3.nets[b], undefined, 'a lost network has no more days');
assert.equal((await e.act(code, b, env('buildPop', { city: 'par' }))).outcome, 'stopped');
e.failNext('act', 'timeout');
@ -224,7 +229,7 @@ test('the fake engine answers every call in the shapes of section 4.2', async ()
for (const m of all) assert.deepEqual(checkWorker(m), [], JSON.stringify(m).slice(0, 80));
// Held answers wait; a worker that dies rejects everything pending.
e.hold('day');
let done = false; const p = e.day(code, { d: 4, nets: [a] }).then(() => { done = true; });
let done = false; const p = e.day(code, { d: 44, nets: [a] }).then(() => { done = true; });
await new Promise((r) => setImmediate(r));
assert.equal(done, false, 'held');
e.release('day'); await p; assert.equal(done, true);

View file

@ -106,6 +106,28 @@ test('a new network: begin, a snapshot, its welcome, actions, days, a what-if, v
await assert.rejects(E.act(code, nid, msg('launchBB', { city: 'ams' })), (e) => e.code === 'NO_REALM');
});
test('a network that joins a session late begins on the session\'s date, with its head start; a start day that is none is refused', async () => {
const code = 'J01NER', nid = 'late0001';
const [L] = await E.load(code, [begin(nid, { day: 518 })]);
checked(L);
assert.equal(L.day, 518);
const sv = JSON.parse(L.saved.txt);
assert.deepEqual([sv.day, sv.day0, sv.nextFail, sv.nextEvent], [518, 518, 563, 558], 'its schedules count from its own start');
assert.equal(sv.cash, await ev(code, nid, 'return START_CASH+7000'), 'hardware costs 3.7% more by day 518: the bank adds $7k');
checked(await E.pull(code, nid, { snap: true }));
const G = checked(await E.greet(code, nid));
assert.ok(updOf(G).fx.some(([k, p]) => k === 'toast' && p.k === 'goal' && /Late to the party/.test(p.h) && p.a[0].act === 'bank'), 'the late welcome, with a button to the bank');
assert.ok(updOf(G).fx.some(([k, p]) => k === 'toast' && /AS201234/.test(p.h)), 'after the usual welcome');
const D = await day(code, 519, [nid]);
assert.equal(D.nets[nid].day, 519);
for (const bad of [-1, 1.5, '518']) {
const [B] = await E.load(code, [begin('latebad1', { day: bad })]);
checked(B);
assert.match(String(B.err), /start day/, JSON.stringify(bad));
}
await E.unload(code);
});
test('the capture table: every kind of effect comes out as an fx in its shape, at most 60 an update', async () => {
const code = 'CAPTVR', nid = 'capt0001';
checked((await E.load(code, [begin(nid)]))[0]);