Upstream/test/military-expansion.test.js
jvanvik 249818a7aa Stage 3-5 server (military, expansion, social), web client for stages 1-2, ops/deploy
Built: units/research/training, movements (scan, raid, attack, takeover, reinforce, settle, transport), deterministic
combat resolved in the event queue, reports, power/offline units, founding + conquest + incumbent sites; alliances,
roles, diplomacy (24h pact cancel via events), messages, rankings; vanilla-JS phone-first client (auth, POP, map,
alerts, settings, en/nb); systemd units, backup timer, DEPLOY.md, tools/admin.js.
Tested: npm test 96/96 (fake clock, in-memory db, a few real-HTTP tests); client checked with headless Chromium
screenshots only. NOT done: marketplace/transport trade, client screens for military/social, WebSocket push,
bots/balance, e2e suite. All unit stats and costs are unbalanced first guesses.

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

203 lines
14 KiB
JavaScript

'use strict';
const test = require('node:test');
const assert = require('node:assert');
const T = require('./military-helpers');
const { R, D, H } = T;
const { loadTown } = require('../server/state');
function sendTakeover(h, att, targetTownId, units) {
return h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'takeover', toTownId: targetTownId, units: units || { script_crew: 80, ma_team: 2 } });
}
test('takeover: loyalty drops by the seeded roll, the POP changes owner at zero, pending work stops', () => {
const h = T.setup();
const att = T.addOperator(h, 'buyer', { x: 5, y: 0, footprint: 5000, units: { script_crew: 80, ma_team: 2 } });
const def = T.addOperator(h, 'seller', { x: 10, y: 0 });
const extra = T.addTown(h, def, { x: 12, y: 2, infra: { noc: 2 } });
h.db.run('UPDATE towns SET loyalty = 40, loyalty_at = ? WHERE id = ?', h.clock.now(), extra.townId);
h.db.run('INSERT INTO town_units (town_id, unit, count) VALUES (?, ?, 4)', extra.townId, 'soc_analyst');
h.run('train', { userId: def.userId, townId: extra.townId, unit: 'soc_analyst', count: 5 }); // pending work that must be cancelled
let s = sendTakeover(h, att, extra.townId);
h.advanceTo(s.arriveAt);
let rep = T.reportsOf(h, att.userId)[0].data;
assert.equal(rep.outcome, 'attacker_won');
assert.equal(rep.takeover.attempted, true);
assert.ok(rep.takeover.drop >= 15 && rep.takeover.drop <= 30, 'drop in range');
assert.equal(rep.takeover.captured, false, '40 loyalty needs two hits');
assert.ok(Math.abs(T.town(h, extra.townId).loyalty - (rep.takeover.loyaltyBefore - rep.takeover.drop)) < 0.01);
assert.equal(T.town(h, extra.townId).owner_id, def.opId);
const retMv = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'");
assert.equal(JSON.parse(retMv.units).ma_team, 1, 'one M&A team was used up, the other comes home');
// second hit
h.advanceTo(retMv.arrive_at);
h.db.run('UPDATE towns SET loyalty = 10, loyalty_at = ? WHERE id = ?', h.clock.now(), extra.townId);
s = sendTakeover(h, att, extra.townId, { script_crew: 70, ma_team: 1 });
h.advanceTo(s.arriveAt);
rep = T.reportsOf(h, att.userId)[1].data;
assert.equal(rep.takeover.captured, true);
const taken = T.town(h, extra.townId);
assert.equal(taken.owner_id, att.opId);
assert.equal(taken.is_capital, 0);
assert.equal(taken.loyalty, D.EXPANSION.conqueredLoyalty);
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending'", extra.townId).n, 0, 'old owner training cancelled');
assert.deepEqual(T.units(h, extra.townId), {}, 'the defenders died with the loss');
assert.equal(T.notes(h, def.userId, 'town_lost').length, 1);
assert.equal(T.notes(h, att.userId, 'town_gained').length, 1);
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM towns WHERE owner_id = ?', def.opId).n, 1);
// loyalty then regenerates for the new owner (+1/h)
const t = loadTown(h.db, extra.townId);
assert.equal(R.loyaltyAt(t.loyalty, t.loyaltyAt, t.loyaltyAt + 10 * H, 1), D.EXPANSION.conqueredLoyalty + 10);
});
test('takeover protections: capital is only drained, last POP and low footprint are refused', () => {
const h = T.setup();
const att = T.addOperator(h, 'buyer', { x: 5, y: 0, footprint: 5000, units: { script_crew: 160, ma_team: 4 } });
const def = T.addOperator(h, 'seller', { x: 10, y: 0 });
const second = T.addTown(h, def, { x: 12, y: 2 });
const lone = T.addOperator(h, 'lone', { x: 20, y: 0 });
// last POP: refused at send
assert.throws(() => sendTakeover(h, att, lone.townId), (e) => e.code === 'cannot_takeover');
// capital: loyalty is dragged to zero, the owner stays
h.db.run('UPDATE towns SET loyalty = 5, loyalty_at = ? WHERE id = ?', h.clock.now(), def.townId);
const s = sendTakeover(h, att, def.townId, { script_crew: 80, ma_team: 2 });
h.advanceTo(s.arriveAt);
const rep = T.reportsOf(h, att.userId)[0].data;
assert.equal(rep.takeover.capital, true);
assert.equal(rep.takeover.captured, false);
assert.equal(T.town(h, def.townId).loyalty, 0);
assert.equal(T.town(h, def.townId).owner_id, def.opId);
// footprint gate
const poor = T.addOperator(h, 'poor', { x: 30, y: 0, footprint: 10, units: { script_crew: 80, ma_team: 1 } });
assert.throws(() => sendTakeover(h, poor, second.townId, { script_crew: 80, ma_team: 1 }), (e) => e.code === 'footprint_too_low' && e.details.need === R.footprintNeeded(1));
// a takeover needs an M&A team, which only goes on takeovers
assert.throws(() => h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'takeover', toTownId: second.townId, units: { script_crew: 5 } }), (e) => e.code === 'validation_failed');
assert.throws(() => h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'attack', toTownId: second.townId, units: { script_crew: 5, ma_team: 1 } }), (e) => e.code === 'validation_failed');
});
test('exploit kits damage the chosen building on a win; DDoS rigs lower the firewall in the battle', () => {
const h = T.setup();
const att = T.addOperator(h, 'siege', { x: 5, y: 0, units: { script_crew: 100, ddos_rig: 20, exploit_kit: 40 } });
const def = T.addOperator(h, 'wall', { x: 9, y: 0, units: { soc_analyst: 40 }, infra: { firewall: 10, noc: 7 } });
const s = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'attack', toTownId: def.townId, units: { script_crew: 100, ddos_rig: 20, exploit_kit: 40 }, target: 'noc' });
h.advanceTo(s.arriveAt);
const rep = T.reportsOf(h, att.userId)[0].data;
assert.equal(rep.outcome, 'attacker_won');
assert.equal(rep.power.effectiveFirewall, 8, '20 rigs lower a level-10 firewall by 2');
assert.equal(rep.siege.key, 'noc');
const kits = rep.attacker.units.survivors.exploit_kit;
assert.equal(rep.siege.to, 7 - R.siegeLevels(kits));
assert.equal(h.db.get('SELECT level FROM buildings WHERE town_id = ? AND key = ?', def.townId, 'noc').level, rep.siege.to);
// the lost units are gone for good
assert.deepEqual(T.units(h, def.townId), {});
});
test('protection: protected targets cannot be attacked, attacking ends your own protection, arrival re-checks', () => {
const h = T.setup();
const now = h.clock.now();
const newbie = T.addOperator(h, 'newbie', { x: 5, y: 0, protectedUntil: now + 72 * H, units: { script_crew: 20, port_scanner: 3 } });
const vet = T.addOperator(h, 'vet', { x: 9, y: 0, units: { script_crew: 40, port_scanner: 3 } });
// nobody may attack a protected operator ...
assert.throws(() => h.run('sendMovement', { userId: vet.userId, fromTownId: vet.townId, type: 'raid', toTownId: newbie.townId, units: { script_crew: 10 } }), (e) => e.code === 'target_protected');
// ... but scouting is allowed
h.run('sendMovement', { userId: vet.userId, fromTownId: vet.townId, type: 'scan', toTownId: newbie.townId, units: { port_scanner: 3 } });
// a protected operator must confirm to attack, which ends the protection at once
assert.throws(() => h.run('sendMovement', { userId: newbie.userId, fromTownId: newbie.townId, type: 'raid', toTownId: vet.townId, units: { script_crew: 10 } }), (e) => e.code === 'protection_active');
assert.ok(h.db.get('SELECT protection_until AS p FROM operators WHERE id = ?', newbie.opId).p > now, 'the refused send changed nothing');
const r = h.run('sendMovement', { userId: newbie.userId, fromTownId: newbie.townId, type: 'raid', toTownId: vet.townId, units: { script_crew: 10 }, confirmEndProtection: true });
assert.equal(r.protectionEnded, true);
assert.equal(h.db.get('SELECT protection_until AS p FROM operators WHERE id = ?', newbie.opId).p, now);
// protection that lasts past the arrival blocks the attack at arrival time (units turn around, report to the sender)
const h2 = T.setup();
const a2 = T.addOperator(h2, 'a', { x: 5, y: 0, units: { script_crew: 30 } });
const d2 = T.addOperator(h2, 'd', { x: 9, y: 0, units: { soc_analyst: 2 } });
const s2 = h2.run('sendMovement', { userId: a2.userId, fromTownId: a2.townId, type: 'raid', toTownId: d2.townId, units: { script_crew: 30 } });
h2.db.run('UPDATE operators SET protection_until = ? WHERE id = ?', s2.arriveAt + H, d2.opId); // e.g. an admin grants protection
h2.advanceTo(s2.arriveAt);
const rep = T.reportsOf(h2, a2.userId)[0];
assert.equal(rep.type, 'movement_failed');
assert.equal(rep.data.reason, 'protected');
assert.equal(T.reportsOf(h2, d2.userId).length, 0, 'the protected side is not bothered');
assert.deepEqual(T.units(h2, d2.townId), { soc_analyst: 2 });
h2.advance(10 * H);
assert.equal(T.units(h2, a2.townId).script_crew, 30, 'the units came back untouched');
});
test('expansion: three Rollout crews found a POP; wild slots, empty start, range, footprint, occupied tile', () => {
const h = T.setup();
const a = T.addOperator(h, 'founder', { x: 5, y: 0, footprint: 3000, units: { rollout_crew: 9 } });
const spot = T.landNear(h, 12, 3);
const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x, y: spot.y, units: { rollout_crew: 3 }, wild: ['substation', 'sales_office'] });
assert.equal(T.units(h, a.townId).rollout_crew, 6);
h.advanceTo(s.arriveAt);
const t = h.db.get('SELECT * FROM towns WHERE x = ? AND y = ?', spot.x, spot.y);
assert.ok(t, 'a new POP exists');
assert.equal(t.owner_id, a.opId); assert.equal(t.is_capital, 0);
const b = h.db.all('SELECT key, type, level FROM buildings WHERE town_id = ?', t.id);
assert.ok(b.every((x) => x.level === 0), 'everything at level 0');
assert.equal(b.length, D.FIELD_SLOTS, 'fields only, no infrastructure');
assert.equal(b.find((x) => x.key === 'f17').type, 'substation');
assert.equal(b.find((x) => x.key === 'f18').type, 'sales_office');
assert.equal(t.fiber, D.EXPANSION.startResources.fiber);
assert.equal(T.reportsOf(h, a.userId)[0].type, 'settle');
assert.equal(T.units(h, a.townId).rollout_crew, 6, 'the crews were consumed');
// the second extra POP needs more footprint (500 * 2^1.8 = 1741 for the 2nd extra; the operator has 3000 + ...)
h.db.run('UPDATE towns SET footprint = 700 WHERE id = ?', a.townId);
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x + 2, y: spot.y, units: { rollout_crew: 3 } }), (e) => e.code === 'footprint_too_low' && e.details.need === R.footprintNeeded(2));
// too far from every own POP
const far = T.landNear(h, 30, 0);
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: far.x, y: far.y, units: { rollout_crew: 3 } }), (e) => e.code === 'out_of_range');
// not exactly three crews
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x, y: spot.y + 3, units: { rollout_crew: 2 } }), (e) => e.code === 'validation_failed');
// an occupied tile
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: spot.x, y: spot.y, units: { rollout_crew: 3 } }), (e) => e.code === 'invalid_target');
// somebody else takes the tile while the crews are on the way: the crews come home with a report
h.db.run('UPDATE towns SET footprint = 99999 WHERE id = ?', a.townId);
const free = T.landNear(h, 10, -4);
const s2 = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'settle', x: free.x, y: free.y, units: { rollout_crew: 3 } });
const squatter = T.addOperator(h, 'squatter', { x: free.x, y: free.y }); // lands exactly on `free`
assert.equal(squatter.x, free.x);
h.advanceTo(s2.arriveAt);
const failed = T.reportsOf(h, a.userId).filter((r) => r.type === 'movement_failed');
assert.equal(failed.length, 1);
assert.equal(failed[0].data.reason, 'invalid_target');
h.advance(48 * H);
assert.equal(T.units(h, a.townId).rollout_crew, 6, 'crews returned');
});
test('incumbent site: static defence, one-time Hardware bonus per operator, research speed bonus', () => {
const h = T.setup({ seed: 99 });
let site = null;
for (let x = -20; x <= 20 && !site; x++) for (let y = -20; y <= 20 && !site; y++) if (R.tileAt(h.world.seed, 50, x, y).type === 'incumbent' && Math.abs(x) + Math.abs(y) > 6) site = { x, y };
assert.ok(site, 'the test world has an incumbent site');
const need = R.incumbentDefence(h.world.seed, site.x, site.y, 0);
const crews = Math.ceil(need / 40 * 1.6);
const a = T.addOperator(h, 'raider', { x: site.x - 3, y: site.y, res: 3000, units: { script_crew: crews } });
const hwBefore = T.town(h, a.townId).hardware;
const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'attack', x: site.x, y: site.y, units: { script_crew: crews } });
assert.equal(s.toTownId, null);
h.advanceTo(s.arriveAt);
const rep = T.reportsOf(h, a.userId)[0];
assert.equal(rep.type, 'incumbent');
assert.equal(rep.data.outcome, 'attacker_won');
assert.equal(rep.data.bonus.hardware, D.INCUMBENT.hardwareBonus);
assert.ok(rep.data.bonus.researchSpeedBonus > 0);
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM incumbent_takes WHERE operator_id = ?', a.opId).n, 1);
const ret = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'");
h.advanceTo(ret.arrive_at);
assert.ok(T.town(h, a.townId).hardware > hwBefore + 1000, 'the bonus arrived with the survivors');
// a second take gives no second bonus
const back = JSON.parse(ret.units);
const s2 = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'attack', x: site.x, y: site.y, units: back });
h.advanceTo(s2.arriveAt);
assert.equal(T.reportsOf(h, a.userId)[1].data.bonus, null);
// research gets faster
const plain = R.researchTimeMs('script_crew', 1, 8, 1, 0), fast = R.researchTimeMs('script_crew', 1, 8, 1, R.researchSpeedBonus(1));
assert.ok(fast < plain);
// incumbent sites accept only scans and attacks, and defence scales with world age
assert.throws(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'raid', x: site.x, y: site.y, units: { script_crew: 1 } }), (e) => e.code === 'invalid_target' || e.code === 'not_enough_units');
assert.ok(R.incumbentDefence(h.world.seed, site.x, site.y, 50) > need);
});