Upstream/test/military-rules.test.js
jvanvik 931f59e11e Phase 3: trade/end-game client, bot simulator, first balance pass
Built:
- Client: trade screen, world/end-game screen (landing sites, shipping, node build, final ranking), report sharing + alliance reports tab, alert describers for all notification types, error-code strings (en+nb) for every server CODE.
- tools/bot.js (+ tools/bot/): 50 headless bots against the real server in-process with a fake clock; resource/unit conservation ledger, exit 1 on broken invariants. docs/BALANCE.md has method and every run behind a number.
- Balance changes (evidence in docs/BALANCE.md): secondQueueCoreLevel 10 -> 3, TRANSPORT.capacityPerLink 500 -> 1000 (end game was shipping-limited in bot runs).
- Server fixes: POST /reports/:id/share 500 without a pending reportCleanup; bounced link shipments were silent about cargo overflow.

Tested: npm test 207/207 (new: bot determinism + invariants, client alerts/world/i18n over CODES, two regression tests that failed before their fix); openapi check up to date. Real-browser scratch runs (not in repo): WebSocket push shows an incoming-attack banner ~214 ms after launch, polling fallback ~52 s, 15 scripted flows, 71 screenshots.

NOT tested: Playwright suite (e2e/ still empty), real devices/Safari, nginx proxy websockets, throttled networks, HTTP-level bot load. NOT claimed: balance. Bots are not humans; open balance items (loot waste, escrow refund clipping, no garrisons at landing sites, end game not scaling with world speed) are listed in docs/BALANCE.md.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
2026-10-11 20:24:41 +02:00

159 lines
13 KiB
JavaScript

'use strict';
const test = require('node:test');
const assert = require('node:assert');
const R = require('../public/js/rules.js');
const D = require('../public/js/data.js');
const H = D.HOUR_MS;
const close = (a, b, eps) => Math.abs(a - b) <= (eps || 1e-9);
test('units: data is complete and consistent', () => {
assert.equal(D.UNIT_ORDER.length, Object.keys(D.UNITS).length);
for (const [id, u] of Object.entries(D.UNITS)) {
assert.ok(D.BUILDINGS[u.building], id + ' has a training building');
for (const r of u.requires) assert.ok(D.BUILDINGS[r.type], id + ' requires a real building');
assert.ok(u.draw >= 0 && u.speed >= 0 && u.time > 0, id);
for (const res of D.RESOURCES) assert.ok(u.cost[res] > 0, id + ' costs ' + res);
}
assert.equal(D.UNITS.honeypot.fixed, true);
assert.equal(D.UNITS.honeypot.speed, 0);
});
test('training and research: costs, times, requirements', () => {
assert.deepEqual(R.unitCost('script_crew', 10), { fiber: 800, hardware: 400, capital: 300 });
// building level and world speed shorten training
assert.equal(R.trainTimeMs('script_crew', 1, 0, 1), 180000);
assert.equal(R.trainTimeMs('script_crew', 1, 10, 1), Math.round(180000 / 1.3));
assert.equal(R.trainTimeMs('script_crew', 10, 0, 2), 900000);
const town = { speed: 1, updatedAt: 0, res: { fiber: 1000, hardware: 1000, capital: 1000, battery: 0 }, footprint: 0, unitDraw: 0, bonus: {}, buildings: { ops_lab: { type: 'ops_lab', level: 1 } } };
assert.equal(R.trainPlan(town, 'script_crew', 5, 0, 0).ok, true);
assert.equal(R.trainPlan(town, 'script_crew', 5, 0, 0).dueAt, R.trainTimeMs('script_crew', 5, 1, 1));
assert.equal(R.trainPlan(town, 'script_crew', 5, 0, 99999).startAt, 99999, 'queued behind the tail');
assert.equal(R.trainPlan(town, 'botnet', 1, 0, 0).code, 'requirements_not_met');
assert.deepEqual(R.unitMissing(town, 'botnet').map((m) => m.type).sort(), ['ops_lab', 'research_lab']);
assert.equal(R.trainPlan(town, 'script_crew', 500, 0, 0).code, 'not_enough_resources');
assert.equal(R.trainPlan(town, 'script_crew', 0, 0, 0).code, 'validation_failed');
assert.equal(R.trainPlan(town, 'nope', 1, 0, 0).code, 'unknown_unit');
// research
const t2 = Object.assign({}, town, { buildings: { ops_lab: { type: 'ops_lab', level: 1 }, research_lab: { type: 'research_lab', level: 3 } } });
assert.equal(R.researchPlan(t2, 'script_crew', 'attack', 0, false, 0, 0).ok, true);
assert.equal(R.researchPlan(t2, 'script_crew', 'attack', 1, false, 0, 0).code, 'requirements_not_met', 'level 2 needs lab 4');
assert.equal(R.researchPlan(t2, 'script_crew', 'attack', 0, true, 0, 0).code, 'queue_full');
assert.equal(R.researchPlan(t2, 'script_crew', 'attack', 10, false, 0, 0).code, 'max_level');
assert.equal(R.researchPlan(t2, 'honeypot', 'attack', 0, false, 0, 0).code, 'not_researchable');
assert.equal(R.researchPlan(t2, 'script_crew', 'speed', 0, false, 0, 0).code, 'not_researchable');
assert.ok(R.researchCost('script_crew', 2).fiber > R.researchCost('script_crew', 1).fiber);
assert.ok(R.researchTimeMs('script_crew', 1, 3, 1, 0.1) < R.researchTimeMs('script_crew', 1, 3, 1, 0));
assert.equal(R.researchSpeedBonus(2), 0.2); assert.equal(R.researchSpeedBonus(99), D.INCUMBENT.researchSpeedMax);
});
test('movement rules: slowest unit, latency, unit/role checks', () => {
assert.equal(R.slowestSpeed({ script_crew: 5, botnet: 5 }), 8);
assert.equal(R.slowestSpeed({ script_crew: 0, botnet: 5 }), 14);
assert.equal(R.movementMs(20, { script_crew: 1, ddos_rig: 1 }, 1), Math.round(20 / 5 * H), 'the slowest unit sets the pace');
assert.equal(R.movementMs(20, { script_crew: 1 }, 2), Math.round(20 / 16 * H), 'world speed');
assert.equal(R.movementMs(0.1, { port_scanner: 1 }, 1), 10 * 60 * 1000, 'minimum 10 minutes');
assert.equal(R.checkUnitsForType('raid', { script_crew: 5 }), null);
assert.equal(R.checkUnitsForType('raid', { ddos_rig: 5 }).code, 'validation_failed', 'no siege on raids');
assert.equal(R.checkUnitsForType('attack', { script_crew: 5, ddos_rig: 1, exploit_kit: 1 }), null);
assert.equal(R.checkUnitsForType('scan', { script_crew: 1 }).code, 'validation_failed');
assert.equal(R.checkUnitsForType('attack', { honeypot: 1 }).code, 'validation_failed', 'honeypots never move');
assert.equal(R.checkUnitsForType('attack', {}).code, 'validation_failed');
assert.equal(R.checkUnitsForType('attack', { nope: 1 }).code, 'unknown_unit');
assert.equal(R.checkUnitsForType('settle', { rollout_crew: 3 }), null);
assert.equal(R.checkUnitsForType('settle', { rollout_crew: 4 }).code, 'validation_failed');
assert.equal(R.checkUnitsForType('takeover', { script_crew: 3 }).code, 'validation_failed');
assert.equal(R.checkUnitsForType('takeover', { script_crew: 3, ma_team: 1 }), null);
assert.equal(R.checkUnitsForType('reinforce', { honeypot: 1 }).code, 'validation_failed');
assert.equal(R.isProtected(100, 99), true); assert.equal(R.isProtected(100, 100), false);
});
test('combat: full attack, raid, firewall, rigs, research, ties, empty target', () => {
const att = (units, research) => ({ units, research: research || {} });
// attacker wins a full attack: defender is wiped, attacker loses (D/A)^1.5
let b = R.resolveBattle({ kind: 'attack', attackers: att({ script_crew: 100 }), defenders: [{ id: 'h', units: { soc_analyst: 80 } }], firewall: 0 });
assert.equal(b.A, 4000); assert.equal(b.D, 2010);
assert.equal(b.attackerWins, true);
assert.deepEqual(b.defenders[0].survivors, {});
assert.ok(close(b.attackerLossFraction, Math.pow(2010 / 4000, 1.5)));
assert.equal(b.attacker.lost.script_crew, Math.round(100 * Math.pow(2010 / 4000, 1.5)));
// defender wins: attacker wiped, defender loses (A/D)^1.5
b = R.resolveBattle({ kind: 'attack', attackers: att({ script_crew: 10 }), defenders: [{ id: 'h', units: { blue_team: 10 } }], firewall: 0 });
assert.equal(b.attackerWins, false);
assert.deepEqual(b.attacker.survivors, {});
assert.ok(close(b.defenderLossFraction, Math.pow(400 / 810, 1.5)));
// ties go to the defender
b = R.resolveBattle({ kind: 'attack', attackers: att({ script_crew: 1 }), defenders: [], firewall: 0, staticDefence: 40 });
assert.equal(b.attackerWins, false);
// raid: both lose 0.5 * ratio^1.5
b = R.resolveBattle({ kind: 'raid', attackers: att({ script_crew: 100 }), defenders: [{ id: 'h', units: { soc_analyst: 80 } }], firewall: 0 });
const f = 0.5 * Math.pow(2010 / 4000, 1.5);
assert.ok(close(b.attackerLossFraction, f) && close(b.defenderLossFraction, f));
assert.equal(b.defenders[0].survivors.soc_analyst, 80 - Math.round(80 * f));
// firewall multiplies defence; rigs lower it by one level per 10
const fw = (rigs) => R.resolveBattle({ kind: 'attack', attackers: att(Object.assign({ script_crew: 10 }, rigs ? { ddos_rig: rigs } : {})), defenders: [{ id: 'h', units: { soc_analyst: 10 } }], firewall: 10 });
assert.ok(close(fw(0).D, (250 + 10) * 1.3));
assert.ok(close(fw(20).D, (250 + 10) * 1.24), 'level 10 - 20 rigs / 10 = 8');
assert.equal(fw(20).effectiveFirewall, 8);
assert.equal(R.effectiveFirewall(3, 100), 0, 'never below zero');
// research: +5% per level, per unit type and stat
b = R.resolveBattle({ kind: 'attack', attackers: att({ script_crew: 10 }, { 'script_crew:attack': 4 }), defenders: [{ id: 'h', units: { soc_analyst: 10 }, research: { 'soc_analyst:defence': 2 } }], firewall: 0 });
assert.ok(close(b.A, 400 * 1.2)); assert.ok(close(b.D, 250 * 1.1 + 10));
// empty POP: only the base defence stands
b = R.resolveBattle({ kind: 'raid', attackers: att({ script_crew: 1 }), defenders: [], firewall: 0 });
assert.equal(b.D, 10); assert.equal(b.attackerWins, true); assert.deepEqual(b.attacker.lost, {});
// reinforcements count together with home crews, and the share goes by defence power
b = R.resolveBattle({ kind: 'attack', attackers: att({ botnet: 50 }), defenders: [{ id: 'home', units: { soc_analyst: 10 } }, { id: 'ally', units: { blue_team: 10 } }], firewall: 0 });
assert.ok(close(b.defenceRaw, 250 + 800)); assert.ok(close(b.defenders[1].share, 800 / 1050));
// determinism: the same call gives the same result
assert.deepEqual(R.resolveBattle({ kind: 'raid', attackers: att({ botnet: 7 }), defenders: [{ id: 'h', units: { soc_analyst: 9 } }], firewall: 2 }),
R.resolveBattle({ kind: 'raid', attackers: att({ botnet: 7 }), defenders: [{ id: 'h', units: { soc_analyst: 9 } }], firewall: 2 }));
assert.ok(R.battlePoints({ script_crew: 10 }) > 0);
});
test('loot, cache, siege, loyalty, scan, incumbent, decommission, transport plan', () => {
assert.deepEqual(R.lootSplit(300, { fiber: 1000, hardware: 1000, capital: 1000 }), { fiber: 100, hardware: 100, capital: 100 });
assert.deepEqual(R.lootSplit(300, { fiber: 10, hardware: 1000, capital: 1000 }), { fiber: 10, hardware: 145, capital: 145 }, 'what fiber cannot give is shared');
assert.deepEqual(R.lootSplit(9999, { fiber: 5, hardware: 6, capital: 7 }), { fiber: 5, hardware: 6, capital: 7 }, 'never more than there is');
assert.deepEqual(R.lootSplit(0, { fiber: 5, hardware: 6, capital: 7 }), { fiber: 0, hardware: 0, capital: 0 });
assert.equal(R.carryOf({ script_crew: 10, botnet: 2, soc_analyst: 5 }), 10 * 50 + 2 * 150);
assert.equal(R.cacheFraction(0), 0); assert.ok(close(R.cacheFraction(3), 0.3)); assert.equal(R.cacheFraction(20), 0.5);
assert.equal(R.siegeLevels(4), 0); assert.equal(R.siegeLevels(5), 1); assert.equal(R.siegeLevels(19), 1); assert.equal(R.siegeLevels(45), 2);
assert.equal(R.loyaltyDrop(0), 15); assert.equal(R.loyaltyDrop(0.999999), 30);
for (let i = 0; i < 200; i++) { const d = R.loyaltyDrop(R.rng(i)()); assert.ok(d >= 15 && d <= 30); }
assert.equal(R.takeoverBlock(true, 3), 'capital'); assert.equal(R.takeoverBlock(false, 1), 'last_pop'); assert.equal(R.takeoverBlock(true, 1), 'last_pop'); assert.equal(R.takeoverBlock(false, 2), null);
assert.deepEqual(R.footprintGate(1, 499), { ok: false, need: 500, have: 499 }); assert.equal(R.footprintGate(2, 1741).ok, true); assert.equal(R.footprintGate(2, 1740).ok, false);
// scan: success needs more scanners than the defender; buildings at 2:1; failure loses everything
assert.deepEqual(R.resolveScan(5, 5), { success: false, detail: 'none', identityRevealed: true, lossFraction: 1 });
assert.equal(R.resolveScan(6, 5).detail, 'basic');
assert.equal(R.resolveScan(10, 5).detail, 'full');
assert.equal(R.resolveScan(3, 0).detail, 'full'); assert.equal(R.resolveScan(3, 0).lossFraction, 0);
assert.equal(R.resolveScan(6, 5).identityRevealed, false);
// incumbent: static, grows with age, varies per site, deterministic
assert.equal(R.incumbentDefence(1, 5, 5, 0), R.incumbentDefence(1, 5, 5, 0));
assert.ok(R.incumbentDefence(1, 5, 5, 100) > R.incumbentDefence(1, 5, 5, 0));
assert.notEqual(R.incumbentDefence(1, 5, 5, 0), R.incumbentDefence(1, 6, 5, 0));
// decommission: most expensive first, only as many as needed
assert.deepEqual(R.decommissionPlan({ botnet: 5, script_crew: 10 }, 8), { botnet: 5, script_crew: 2 });
assert.deepEqual(R.decommissionPlan({ botnet: 5, script_crew: 10 }, 100), {});
assert.deepEqual(R.decommissionPlan({ botnet: 5, soc_analyst: 3 }, -5), { botnet: 5, soc_analyst: 3 });
assert.equal(R.decommissionMs(1), 24 * H); assert.equal(R.decommissionMs(4), 6 * H);
// transport plan
const town = { speed: 1, updatedAt: 0, res: { fiber: 400, hardware: 400, capital: 400, battery: 0 }, footprint: 0, unitDraw: 0, bonus: {}, buildings: { internet_exchange: { type: 'internet_exchange', level: 2 }, rack_hall: { type: 'rack_hall', level: 5 } } };
assert.equal(R.transportPlan(town, { fiber: 100 }, 0, 0).ok, true);
assert.equal(R.transportPlan(town, { fiber: 100 }, 2, 0).code, 'no_transport_link');
assert.equal(R.transportPlan(town, { fiber: D.TRANSPORT.capacityPerLink + 1 }, 0, 0).code, 'capacity_exceeded');
assert.equal(R.transportPlan(town, { fiber: 450 }, 0, 0).code, 'not_enough_resources');
assert.equal(R.transportPlan(town, { gold: 5 }, 0, 0).code, 'validation_failed');
assert.equal(R.transportPlan(town, {}, 0, 0).code, 'validation_failed');
// settle checks and new-POP helpers
assert.equal(R.settleCheck({ tileType: 'land', occupied: false, nearestOwnDist: 10, ownedCount: 1, footprint: 600 }).ok, true);
assert.equal(R.settleCheck({ tileType: 'rural', occupied: false, nearestOwnDist: 10, ownedCount: 1, footprint: 600 }).code, 'invalid_target');
assert.equal(R.settleCheck({ tileType: 'land', occupied: true, nearestOwnDist: 10, ownedCount: 1, footprint: 600 }).code, 'invalid_target');
assert.equal(R.settleCheck({ tileType: 'land', occupied: false, nearestOwnDist: 15.01, ownedCount: 1, footprint: 600 }).code, 'out_of_range');
assert.equal(R.settleCheck({ tileType: 'land', occupied: false, nearestOwnDist: 15, ownedCount: 1, footprint: 400 }).code, 'footprint_too_low');
assert.deepEqual(R.cleanWild(['substation', 'bogus']), ['substation', D.START.wild[1]]);
const nb = R.newTownBuildings(['substation', 'sales_office']);
assert.equal(Object.keys(nb).length, 18); assert.ok(Object.values(nb).every((b) => b.level === 0));
assert.equal(nb.f17.type, 'substation');
});