Phase 4: close loot/refund leaks, landing-site garrisons, speed-scaled shipping, update/offsite tooling, broad e2e

Built:
- Economy: raid loot capped to the room the raiders have at home (rest stays with the victim, "lootLeft" in the report); trade escrow reserves its room so refunds always fit; trade accept refuses with no_room_for_goods when the goods would not fit. Loot destroyed per 30-day run 31-61k -> ~1k, refunds clipped ~27k -> 0 (docs/BALANCE.md, 3 seeds).
- End game: members of the holding alliance garrison landing sites (migration 005_site_garrison.sql), garrison counts in site defence, 72 h capture shield, withdraw route, POP view lists garrisoned units. Shipping capacity scales with world speed (3x world: winner 76-98 -> ~30-36 days after sites open). Bot runs show real contests (84-194 attacks on held sites at 1x).
- Ops: deploy/update.sh (backup, stop, ff-merge, npm ci --ignore-scripts, health check, rollback), deploy/upstream-offsite (rsync only), admin end-world snapshots results, EPIPE fix, docs/workflows/ filled in.
- e2e 62 -> 163 checks: units, raids/reports, alliance+messages, trade, end game, nb, PWA, reconnect, slow polling fallback (opt-in). Two app bugs found: message push ignored, "New" button stayed English.

Tested: npm test 274/274, openapi check, npm run e2e 163/163 (137 s), bot runs 50x30d seeds 1-3 and 140-day/60-day speed-3 end-game runs INVARIANTS OK, adversarial review pass (findings fixed or documented).
NOT tested: update.sh on a real box (systemd, real npm, runuser; stubs only, shellcheck not installed), garrison card/loot text on a phone, Node 22.13, humans. Known leaks left open and documented (BALANCE S6): loot/shipments can still overflow when stock arrives in flight, bounced backbone shipments lose overflow (reported to the sender). Garrison numbers (heldDefenceMult 2, shield 72 h) are first guesses from 2 seeds. Not claimed: balanced.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
This commit is contained in:
jvanvik 2026-10-12 00:58:12 +02:00
parent 9104480463
commit 3c23c51902
92 changed files with 4887 additions and 300 deletions

125
test/admin-endworld.test.js Normal file
View file

@ -0,0 +1,125 @@
'use strict';
/* tools/admin.js end-world: it must end a world exactly like the natural end (worldEnd event handler): final ranking stored and
* served by /worlds/:id/results, trade escrow returned, pending events cancelled, notifications written, refusal without --yes.
* Also: a closed stdout pipe (`admin.js help | head`) is not an error. A file DB shared by the fixture and the CLI, fake clock. */
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawn } = require('child_process');
const admin = require('../tools/admin.js');
const T = require('./military-helpers');
const { createEndgameQueries } = require('../server/endgameQueries');
const { H } = T;
function cli(file, args, now) {
const out = [], err = [];
const code = admin.main(args.concat(['--db', file]), { out: (s) => out.push(s), err: (s) => err.push(s), env: {}, now: () => now });
const text = out.join('\n');
return { code, out: text, err: err.join('\n'), json: args.includes('--json') ? JSON.parse(text) : null };
}
// A world with two operators, an open trade offer (escrow), a pending build and one build that is already overdue.
function fixture() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'upstream-endworld-'));
const file = path.join(dir, 'game.db');
const h = T.setup({ file });
const a = T.addOperator(h, 'alice', { x: 5, y: 0 });
const b = T.addOperator(h, 'bob', { x: 9, y: 0 });
h.run('build', { userId: a.userId, townId: a.townId, key: 'f1' });
const offer = h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'fiber', giveAmount: 400, wantRes: 'hardware', wantAmount: 300, maxDistance: 30 }).offer;
return { h, file, a, b, offer, eg: createEndgameQueries(h) };
}
test('end-world refuses without --yes, says what it would do, and changes nothing', () => {
const { h, file, a, eg } = fixture();
const r = cli(file, ['end-world', String(h.worldId)], h.clock.now());
assert.equal(r.code, 2);
assert.match(r.err, /refusing without --yes/);
assert.match(r.err, /1 open trade offer/);
assert.equal(h.db.get('SELECT status FROM worlds').status, 'running');
assert.equal(eg.results(a.userId, h.worldId).available, false);
});
test('end-world --yes runs the real worldEnd: ranking snapshot, results available, escrow back, events cancelled, players notified', () => {
const { h, file, a, b, offer, eg } = fixture();
const fiberBefore = T.town(h, a.townId).fiber;
assert.ok(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'pending'").n >= 2);
const now = h.clock.now() + 60 * 1000; // the offer's expiry and the build are still in the future
const r = cli(file, ['end-world', String(h.worldId), '--yes', '--json'], now);
assert.equal(r.code, 0, r.err);
assert.equal(r.json.changed, true);
assert.equal(r.json.ranking, true);
assert.equal(r.json.operators, 2);
assert.equal(r.json.closedOffers, 1);
const w = h.db.get('SELECT * FROM worlds WHERE id = ?', h.worldId);
assert.equal(w.status, 'ended');
assert.equal(w.end_at, now);
// exactly what GET /worlds/:id/results serves after a natural end
const res = eg.results(b.userId, h.worldId);
assert.equal(res.available, true);
assert.equal(res.status, 'ended');
assert.equal(res.results.at, now);
assert.equal(res.results.operators.length, 2);
assert.deepEqual(res.results.operators.map((o) => o.rank), [1, 2]);
assert.equal(res.results.totals.operators, 2);
assert.equal(res.results.winner, null, 'nobody won the race: the admin ended it');
// the event row is the same shape the natural end leaves, and nothing is left pending
const ev = h.db.get("SELECT * FROM events WHERE type = 'worldEnd'");
assert.equal(ev.status, 'done');
assert.deepEqual(JSON.parse(ev.payload), { reason: 'admin' });
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'pending'").n, 0);
assert.ok(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'cancelled'").n >= 2);
// escrow went back to the POP, the offer is closed
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'expired');
assert.ok(T.town(h, a.townId).fiber >= fiberBefore + 400, 'the 400 are back in the POP (plus what it produced meanwhile)');
// every operator is told
for (const u of [a, b]) assert.equal(T.notes(h, u.userId, 'world_ended').length, 1);
// the world is frozen for commands
assert.throws(() => h.run('build', { userId: b.userId, townId: b.townId, key: 'f1' }), (e) => e.code === 'world_ended');
// second run: already ended, no change, exit 0, and no second ranking or notification
const again = cli(file, ['end-world', String(h.worldId), '--json'], now + 1000);
assert.equal(again.code, 0);
assert.equal(again.json.changed, false);
assert.equal(again.json.ranking, true);
assert.equal(T.notes(h, a.userId, 'world_ended').length, 1);
});
test('end-world processes events that were already due first, in order (a finished build is not lost)', () => {
const { h, file, a, eg } = fixture();
const q = h.db.get("SELECT due_at FROM events WHERE type = 'buildDone'");
assert.ok(q);
const now = q.due_at + 5000; // the server was stopped: the build fell due before the CLI ran
const r = cli(file, ['end-world', String(h.worldId), '--yes', '--json'], now);
assert.equal(r.code, 0, r.err);
assert.ok(r.json.caughtUpFirst >= 1);
assert.equal(h.db.get("SELECT status FROM events WHERE type = 'buildDone'").status, 'done');
assert.equal(h.db.get("SELECT level FROM buildings WHERE town_id = ? AND key = 'f1'", a.townId).level >= 1, true);
assert.equal(eg.results(a.userId, h.worldId).available, true);
});
test('end-world only touches the named world', () => {
const { h, file } = fixture();
const { createWorld } = require('../server/world');
const second = createWorld(h.db, h.clock.now(), { seed: 7, mapRadius: 20 });
h.db.run("INSERT INTO events (world_id, due_at, type, payload, status, created_at) VALUES (?, ?, 'reportCleanup', '{}', 'pending', ?)", second, h.clock.now() + 99 * H, h.clock.now());
assert.equal(cli(file, ['end-world', String(h.worldId), '--yes'], h.clock.now() + 1000).code, 0);
assert.equal(h.db.get('SELECT status FROM worlds WHERE id = ?', second).status, 'running');
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE world_id = ? AND status = 'pending'", second).n, 1);
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM world_rankings WHERE world_id = ?', second).n, 0);
});
test('a closed stdout pipe is quiet: `admin.js help | head` prints no EPIPE stack trace and keeps the exit code', async () => {
const child = spawn(process.execPath, [path.join(__dirname, '..', 'tools', 'admin.js'), 'help'], { stdio: ['ignore', 'pipe', 'pipe'] });
child.stdout.destroy(); // the reader goes away before the CLI has written anything
let err = '';
child.stderr.on('data', (d) => { err += d; });
const code = await new Promise((resolve) => child.on('close', resolve));
assert.equal(err, '');
assert.equal(code, 0);
});

View file

@ -39,10 +39,12 @@ const SAMPLES = {
trade_completed: { offerId: 3, give: T, want: W },
trade_expired: { offerId: 3, townId: 1, returned: T },
trade_void: { offerId: 3, townId: 1 },
trade_refund_clipped: { offerId: 3, townId: 1, resource: 'fiber', lost: 120, credited: 280 },
backbone_open: { sites: [{ siteId: 1, index: 0, x: 3, y: 4 }, { siteId: 2, index: 1, x: 5, y: 6 }] },
backbone_taken: { siteId: 1, index: 2, x: 10, y: -4, level: 12, by: { allianceId: 7, tag: 'NSP', name: 'North Sea Peering' }, from: { allianceId: 8, tag: 'FTC', name: 'Fjord' } },
backbone_lost: { siteId: 1, index: 2, x: 10, y: -4, level: 12, by: { allianceId: 8, tag: 'FTC', name: 'Fjord' }, from: { allianceId: 7, tag: 'NSP', name: 'North Sea Peering' } },
backbone_level: { siteId: 1, index: 2, level: 20 },
backbone_incoming: { siteId: 1, index: 2, x: 10, y: -4, arriveAt: 1767225600000 },
backbone_delivered: { movementId: 5, siteId: 1, cargo: { fiber: 500, hardware: 0, capital: 120 } },
backbone_ship_bounced: { movementId: 5, siteId: 1, cargo: { fiber: 500 } },
backbone_won: { allianceId: 7, name: 'North Sea Peering', tag: 'NSP', siteId: 1, endsAt: 1767225600000 },

View file

@ -0,0 +1,66 @@
'use strict';
/* Client side of the landing-site garrison (docs/DECISIONS.md E6): who may reinforce a site, how the manage sheet reads the server's
* garrison, strings in both languages. Pure logic and source checks, no browser. */
const test = require('node:test');
const assert = require('node:assert');
const fs = require('fs');
const path = require('path');
const Mil = require('../public/js/milcore.js');
const End = require('../public/js/endcore.js');
const I18n = require('../public/js/i18n.js');
const D = require('../public/js/data.js');
const ROOT = path.join(__dirname, '..', 'public', 'js');
for (const f of fs.readdirSync(path.join(ROOT, 'strings')).sort()) if (f.endsWith('.js')) require('../public/js/strings/' + f);
const tile = (mine) => ({ type: 'backbone', x: 10, y: 10, backbone: { index: 2, mine, holder: { allianceId: 7, tag: 'X', name: 'X' } } });
test('send dialog: members of the holding alliance can reinforce a site (and not attack it); everybody else attacks or scans', () => {
const home = { soc_analyst: 20, script_crew: 10, port_scanner: 3 };
const mine = Mil.moveOptions({ tile: tile(true), home, transport: { links: 0, active: 0 }, allianceId: 7 });
assert.deepEqual(mine.map((o) => [o.type, o.ok]), [['scan', true], ['attack', false], ['reinforce', true]]);
assert.equal(mine.find((o) => o.type === 'attack').reason, 'own_site');
const none = Mil.moveOptions({ tile: tile(true), home: { script_crew: 5 }, transport: {}, allianceId: 7 });
assert.equal(none.find((o) => o.type === 'reinforce').ok, true, 'attackers can garrison too');
const noUnits = Mil.moveOptions({ tile: tile(true), home: {}, transport: {}, allianceId: 7 });
assert.deepEqual(noUnits.find((o) => o.type === 'reinforce'), { type: 'reinforce', ok: false, reason: 'no_units' });
const rival = Mil.moveOptions({ tile: tile(false), home, transport: {}, allianceId: 8 });
assert.deepEqual(rival.map((o) => o.type), ['scan', 'attack'], 'a rival cannot reinforce');
const loner = Mil.moveOptions({ tile: tile(false), home, transport: {}, allianceId: null });
assert.deepEqual(loner.map((o) => o.type), ['scan', 'attack']);
assert.equal(loner.find((o) => o.type === 'attack').reason, 'no_alliance');
});
test('garrisonView: rows by defence, share of the whole defence, your own marked, offline groups count nothing', () => {
const data = {
defence: { static: 8000, garrison: 12000, total: 20000 },
garrison: [
{ ownerTownId: 5, townName: 'B POP', operator: { operatorId: 2, name: 'bea' }, units: { soc_analyst: 100 }, online: true, power: 2500, mine: false },
{ ownerTownId: 3, townName: 'A POP', operator: { operatorId: 1, name: 'ann' }, units: { blue_team: 120 }, online: true, power: 9600, mine: true },
{ ownerTownId: 9, townName: 'C POP', operator: null, units: { soc_analyst: 10 }, online: false, power: 250, mine: false },
],
};
const v = End.garrisonView(data);
assert.deepEqual(v.rows.map((r) => r.ownerTownId), [3, 5, 9]);
assert.equal(v.rows[0].mine, true);
assert.equal(v.rows[0].share, 9600 / 20000);
assert.equal(v.rows[2].share, 0, 'an offline group defends nothing');
assert.equal(v.rows[2].online, false);
assert.equal(v.rows[2].name, '');
assert.deepEqual([v.static, v.garrison, v.total], [8000, 12000, 20000]);
assert.deepEqual(End.garrisonView({}).rows, [], 'a missing block is an empty garrison');
assert.equal(End.garrisonView(null).total, 0);
});
test('every string the garrison UI uses exists in en and nb', () => {
const src = ['screens/world.js', 'screens/send.js', 'milstate.js', 'alertkinds.js'].map((f) => fs.readFileSync(path.join(ROOT, f), 'utf8')).join('\n');
const keys = new Set([...src.matchAll(/App\.t\('((?:wld\.gar|send\.landing|alerts\.garrison|alerts\.backbone_incoming)[a-zA-Z_.]*)'/g)].map((m) => m[1]).filter((k) => !k.endsWith('.')).concat(['send.invalid.not_holder', 'send.invalid.site_shielded', 'wld.shield', 'rep.landing.garrisonOf', 'alerts.garrison_released.alliance_dissolved', 'alerts.garrison_released.left_alliance', 'alerts.garrison_released.town_lost', 'alerts.garrison_released.other']));
assert.ok(keys.size >= 12, 'found the keys (' + keys.size + ')');
for (const l of ['en', 'nb']) for (const k of keys) assert.ok(I18n.strings[l][k], l + ' has ' + k);
});
test('nothing in the client reads TRANSPORT.capacityPerLink directly (a link carries capacityPerLink x world speed: rules.transportCapacity)', () => {
const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : e.name.endsWith('.js') ? [path.join(dir, e.name)] : []));
const hits = walk(ROOT).filter((f) => !/[\\/](data|rules)\.js$/.test(f) && /TRANSPORT\.capacityPerLink/.test(fs.readFileSync(f, 'utf8')));
assert.deepEqual(hits, []);
assert.ok(D.TRANSPORT.capacityPerLink > 0);
});

118
test/deploy-offsite.test.js Normal file
View file

@ -0,0 +1,118 @@
'use strict';
/* deploy/upstream-offsite: newest snapshot, verified first, copied (rsync to a local directory standing in for the far side),
* never overwritten, content compared. ssh itself is not exercised (no remote host here). */
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawnSync } = require('child_process');
const admin = require('../tools/admin.js');
const { openDb, migrate } = require('../server/db');
const SCRIPT = path.join(__dirname, '..', 'deploy', 'upstream-offsite');
const haveRsync = spawnSync('rsync', ['--version']).status === 0;
const opts = { skip: !haveRsync && 'rsync not installed' };
// the real tools/admin.js does the verification, exactly like on the server (upstream-admin wrapper replaced by a tiny sh)
function fixture() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'upstream-offsite-'));
const p = (...n) => path.join(root, ...n);
fs.mkdirSync(p('backups')); fs.mkdirSync(p('far'));
fs.writeFileSync(p('admin'), '#!/bin/sh\nexec node "' + path.join(__dirname, '..', 'tools', 'admin.js') + '" "$@"\n', { mode: 0o755 });
const dbFile = p('game.db');
const db = openDb(dbFile); migrate(db);
db.run("INSERT INTO worlds (name, seed, speed, map_radius, status, start_at, created_at) VALUES ('w', 1, 1, 10, 'running', 0, 0)");
db.close();
const snap = (name, ageSec) => {
const code = admin.main(['backup', p('backups'), '--db', dbFile], { out() {}, err() {}, env: {}, now: () => Date.UTC(2026, 9, 11, 4, 15, 0) + (snap.n = (snap.n || 0) + 1) * 1000 });
assert.equal(code, 0);
const made = fs.readdirSync(p('backups')).filter((f) => f.startsWith('upstream-')).sort().pop();
if (name) fs.renameSync(p('backups', made), p('backups', name));
const t = (Date.now() - ageSec * 1000) / 1000;
fs.utimesSync(p('backups', name || made), t, t);
return name || made;
};
const run = (args, env) => {
const r = spawnSync('sh', [SCRIPT].concat(args || []), { encoding: 'utf8', env: Object.assign({}, process.env, { BACKUP_DIR: p('backups'), UPSTREAM_ADMIN: p('admin'), OFFSITE_DEST: p('far'), OFFSITE_KNOWN_HOSTS: p('none') }, env || {}) });
return { code: r.status, out: r.stdout, err: r.stderr, all: r.stdout + r.stderr };
};
return { p, snap, run, far: () => fs.readdirSync(p('far')).sort() };
}
test('--check is the ExecCondition: unset destination = exit 1, set = 0', opts, () => {
const f = fixture();
assert.equal(f.run(['--check'], { OFFSITE_DEST: '' }).code, 1);
assert.equal(f.run(['--check']).code, 0);
const r = f.run([], { OFFSITE_DEST: '' });
assert.equal(r.code, 2);
assert.match(r.err, /not configured/);
});
test('copies the newest snapshot (by mtime, also against a same-second -1 name), verified, mode 0600, content identical', opts, () => {
const f = fixture();
f.snap('upstream-20261010T041500Z.db', 7200);
const newest = f.snap('upstream-20261011T041500Z-1.db', 60); // sorts BEFORE a plain ...Z.db by name, but is the newer one
f.snap('upstream-20261011T041500Z.db', 3600);
const r = f.run();
assert.equal(r.code, 0, r.all);
assert.deepEqual(f.far(), [newest]);
assert.deepEqual(fs.readFileSync(f.p('far', newest)), fs.readFileSync(f.p('backups', newest)));
assert.equal(fs.statSync(f.p('far', newest)).mode & 0o777, 0o600);
assert.match(r.out, /checksum compared/);
// the copy is a real snapshot
assert.equal(admin.verifySnapshot(f.p('far', newest)).integrity, 'ok');
// again: already there, still exit 0
assert.equal(f.run().code, 0);
assert.deepEqual(f.far(), [newest]);
});
test('a snapshot that does not verify is never copied', opts, () => {
const f = fixture();
const name = f.snap('upstream-20261011T041500Z.db', 60);
fs.writeFileSync(f.p('backups', name), 'not a database');
const r = f.run();
assert.equal(r.code, 1);
assert.match(r.err, /does not verify/);
assert.deepEqual(f.far(), []);
});
test('nothing to copy, and a different file of the same name on the far side, are failures (never overwritten)', opts, () => {
const f = fixture();
assert.equal(f.run().code, 1);
const name = f.snap('upstream-20261011T041500Z.db', 60);
fs.writeFileSync(f.p('far', name), 'someone else was here');
const r = f.run();
assert.equal(r.code, 1);
assert.match(r.err, /differs/);
assert.equal(fs.readFileSync(f.p('far', name), 'utf8'), 'someone else was here');
});
test('OFFSITE_METHOD=scp is refused (scp would overwrite), nothing is copied', () => {
const f = fixture();
f.snap('upstream-20261011T041500Z.db', 60);
const r = f.run([], { OFFSITE_METHOD: 'scp' });
assert.equal(r.code, 2);
assert.match(r.err, /scp is not supported|not supported any more/);
assert.deepEqual(f.far(), []);
});
test('an unwritable far side fails loudly', opts, () => {
const f = fixture();
f.snap('upstream-20261011T041500Z.db', 60);
const r = f.run([], { OFFSITE_DEST: f.p('nope', 'deeper', 'dir') });
assert.equal(r.code, 1);
assert.match(r.err, /failed/);
});
test('the unit files point at the script and gate on OFFSITE_DEST', () => {
const dir = path.join(__dirname, '..', 'deploy');
const svc = fs.readFileSync(path.join(dir, 'upstream-offsite.service'), 'utf8');
assert.match(svc, /^ExecCondition=\/opt\/upstream\/deploy\/upstream-offsite --check$/m);
assert.match(svc, /^ExecStart=\/opt\/upstream\/deploy\/upstream-offsite$/m);
assert.match(svc, /^Type=oneshot$/m);
const timer = fs.readFileSync(path.join(dir, 'upstream-offsite.timer'), 'utf8');
assert.match(timer, /^Unit=upstream-offsite\.service$/m);
assert.ok((fs.statSync(path.join(dir, 'upstream-offsite')).mode & 0o111) !== 0, 'executable bit (ExecStart needs it)');
assert.equal(spawnSync('sh', ['-n', SCRIPT]).status, 0);
});

416
test/deploy-update.test.js Normal file
View file

@ -0,0 +1,416 @@
'use strict';
/* deploy/update.sh against a scratch "server": a bare origin, a checkout standing in for /opt/upstream, and stub
* systemctl / curl / npm / upstream-admin / sleep on the PATH. Nothing real is touched. It checks the script's logic
* (order of steps, refusals, rollback, exit codes), not systemd, a real Node or a real network. */
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { spawnSync } = require('child_process');
const SCRIPT = path.join(__dirname, '..', 'deploy', 'update.sh');
const haveGit = spawnSync('git', ['--version']).status === 0;
const opts = { skip: !haveGit && 'git not installed' };
const STUBS = {
systemctl: `echo "systemctl $* [tree=$(git -C "$UPSTREAM_DIR" rev-parse HEAD)]" >> "$STUB_DIR/calls.log"
[ "$1" = start ] && [ -e "$STUB_DIR/restart_fail" ] && exit 1
[ "$1" = stop ] && [ -e "$STUB_DIR/stop_fail" ] && exit 1
if [ "$1" = start ] && [ -e "$STUB_DIR/kill_once" ]; then rm -f "$STUB_DIR/kill_once"; kill -TERM $PPID; fi
exit 0`,
curl: `echo "curl $*" >> "$STUB_DIR/calls.log"
[ -e "$UPSTREAM_DIR/BROKEN" ] && exit 22
exit 0`,
sleep: 'exit 0',
npm: `echo "npm $* [cwd=$PWD]" >> "$STUB_DIR/calls.log"
case $1 in
ci) [ -e "$STUB_DIR/npm_fail" ] && exit 1 ;;
test) [ -e "$PWD/TESTFAIL" ] && exit 1 ;;
esac
exit 0`,
'upstream-admin': `echo "upstream-admin $*" >> "$STUB_DIR/calls.log"
case $1 in
backup) [ -e "$STUB_DIR/backup_fail" ] && { echo "error: disk full" >&2; exit 1; }
mkdir -p "$2"; f="$2/upstream-20261011T041500Z.db"; echo snap > "$f"
echo "backup written: $f (5 bytes, verified)" ;;
verify-backup) [ -e "$STUB_DIR/verify_fail" ] && exit 1; [ -f "$2" ] || exit 3 ;;
esac
exit 0`,
};
const GIT_ENV = { GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null', GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@example.com', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@example.com' };
function git(cwd, ...args) {
const r = spawnSync('git', args, { cwd, encoding: 'utf8', env: Object.assign({}, process.env, GIT_ENV) });
assert.equal(r.status, 0, 'git ' + args.join(' ') + ': ' + r.stderr);
return r.stdout.trim();
}
// origin (bare) + a working clone `dev` to push from + `app` = the checkout on the "server"
function fixture() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'upstream-update-'));
const p = (n) => path.join(root, n);
for (const d of ['origin.git', 'dev', 'app', 'bin', 'stub']) fs.mkdirSync(p(d));
git(p('origin.git'), 'init', '--bare', '-b', 'main', '-q');
git(p('dev'), 'init', '-b', 'main', '-q');
git(p('dev'), 'remote', 'add', 'origin', p('origin.git'));
fs.writeFileSync(p('dev/package.json'), '{"name":"x"}\n');
fs.writeFileSync(p('dev/package-lock.json'), '{"v":1}\n');
fs.writeFileSync(p('dev/.gitignore'), 'node_modules/\n');
fs.writeFileSync(p('dev/server.js'), '// v1\n');
git(p('dev'), 'add', '-A'); git(p('dev'), 'commit', '-q', '-m', 'v1');
git(p('dev'), 'push', '-q', 'origin', 'main');
git(root, 'clone', '-q', p('origin.git'), p('app'));
fs.mkdirSync(p('app/node_modules'));
for (const [name, body] of Object.entries(STUBS)) { fs.writeFileSync(p('bin/' + name), '#!/bin/sh\n' + body + '\n', { mode: 0o755 }); }
const f = {
root, app: p('app'), dev: p('dev'), stub: p('stub'), backups: p('backups'),
old: git(p('app'), 'rev-parse', 'HEAD'),
head: () => git(p('app'), 'rev-parse', 'HEAD'),
calls: () => (fs.existsSync(p('stub/calls.log')) ? fs.readFileSync(p('stub/calls.log'), 'utf8').split('\n').filter(Boolean) : []),
// a new commit on origin; files = { path: content | null }
publish(files, msg) {
for (const [n, c] of Object.entries(files)) {
if (c === null) fs.rmSync(path.join(p('dev'), n), { force: true });
else { fs.mkdirSync(path.dirname(path.join(p('dev'), n)), { recursive: true }); fs.writeFileSync(path.join(p('dev'), n), c); }
}
git(p('dev'), 'add', '-A'); git(p('dev'), 'commit', '-q', '-m', msg || 'next');
git(p('dev'), 'push', '-q', 'origin', 'main');
return git(p('dev'), 'rev-parse', 'HEAD');
},
run(args, env) {
const r = spawnSync('sh', [SCRIPT].concat(args || []), {
encoding: 'utf8',
env: Object.assign({}, process.env, GIT_ENV, {
PATH: p('bin') + path.delimiter + process.env.PATH, STUB_DIR: p('stub'), UPSTREAM_DIR: p('app'), UPSTREAM_ADMIN: p('bin/upstream-admin'),
UPSTREAM_ALLOW_NONROOT: '1', BACKUP_DIR: p('backups'), LOCK_DIR: p('lock'), UPSTREAM_ENV_FILE: p('none.env'), HEALTH_TIMEOUT: '2',
}, env || {}),
});
return { code: r.status, out: r.stdout, err: r.stderr, all: r.stdout + r.stderr };
},
};
return f;
}
const idx = (calls, prefix) => calls.findIndex((c) => c.startsWith(prefix));
test('already up to date: exit 0, no backup, no restart', opts, () => {
const f = fixture();
const r = f.run();
assert.equal(r.code, 0, r.all);
assert.match(r.out, /already up to date/);
assert.deepEqual(f.calls(), []);
assert.equal(fs.existsSync(path.join(f.root, 'lock')), false, 'lock released');
});
test('update: snapshot first, fast-forward, no npm ci when the lock is unchanged, restart, health check, old -> new printed', opts, () => {
const f = fixture();
const next = f.publish({ 'server.js': '// v2\n' }, 'second');
const r = f.run();
assert.equal(r.code, 0, r.all);
assert.equal(f.head(), next);
assert.match(r.out, new RegExp(f.old.slice(0, 9) + ' -> ' + next.slice(0, 9)));
assert.match(r.out, /second/, 'the commit subjects that went out are listed');
const c = f.calls();
assert.ok(idx(c, 'systemctl stop upstream') >= 0 && idx(c, 'upstream-admin backup') > idx(c, 'systemctl stop'), 'the snapshot comes from the stopped database');
assert.ok(idx(c, 'upstream-admin verify-backup') > idx(c, 'upstream-admin backup'));
assert.ok(idx(c, 'systemctl start upstream') > idx(c, 'upstream-admin verify-backup'), 'start only after the snapshot');
assert.ok(idx(c, 'curl') > idx(c, 'systemctl start'));
assert.match(c[idx(c, 'systemctl stop')], new RegExp('tree=' + f.old), 'mixed-code window: the service is stopped while the tree is still the OLD one');
assert.match(c[idx(c, 'systemctl start')], new RegExp('tree=' + next), '... and started only when the tree is the NEW one');
assert.equal(c.filter((x) => x.startsWith('systemctl')).length, 2, 'one stop, one start');
assert.equal(c.some((x) => x.startsWith('npm')), false, 'no npm ci, no npm test');
assert.match(c.find((x) => x.startsWith('upstream-admin backup')), new RegExp('backup ' + f.backups.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ' --keep 14'));
});
test('npm ci --omit=dev only when package-lock changed; npm test only with --test', opts, () => {
const f = fixture();
f.publish({ 'package-lock.json': '{"v":2}\n' });
let r = f.run();
assert.equal(r.code, 0, r.all);
assert.ok(f.calls().some((x) => x.startsWith('npm ci --omit=dev --ignore-scripts')), 'no install scripts as root');
assert.ok(idx(f.calls(), 'npm ci') > idx(f.calls(), 'systemctl stop') && idx(f.calls(), 'npm ci') < idx(f.calls(), 'systemctl start'), 'deps change only while the service is stopped');
assert.equal(f.calls().some((x) => x.startsWith('npm test')), false);
const g = fixture();
g.publish({ 'server.js': '// v2\n' });
r = g.run(['--test']);
assert.equal(r.code, 0, r.all);
const c = g.calls();
assert.ok(idx(c, 'npm test') >= 0 && idx(c, 'npm test') < idx(c, 'systemctl stop'), 'tests run before the service is touched');
const cwd = (/\[cwd=(.*)\]$/.exec(c[idx(c, 'npm test')]) || [])[1];
assert.ok(cwd && !cwd.startsWith(g.app), 'tests run in an isolated copy, never in the live tree: ' + cwd);
assert.equal(fs.existsSync(cwd), false, 'the copy is removed again');
assert.deepEqual(c.filter((x) => x.startsWith('npm ci')).length, 1, 'only the isolated copy got an npm ci (lock unchanged)');
assert.match(c[idx(c, 'npm ci')], /--ignore-scripts/);
});
test('a dirty tree is refused before anything happens (tracked change and untracked file)', opts, () => {
for (const dirty of [(f) => fs.writeFileSync(path.join(f.app, 'server.js'), '// hotfix\n'), (f) => fs.writeFileSync(path.join(f.app, 'stray.txt'), 'x')]) {
const f = fixture();
f.publish({ 'server.js': '// v2\n' });
dirty(f);
const r = f.run();
assert.equal(r.code, 2);
assert.match(r.err, /dirty/);
assert.equal(f.head(), f.old);
assert.deepEqual(f.calls(), []);
}
// ignored files (node_modules, data) are not dirt
const g = fixture();
g.publish({ 'server.js': '// v2\n' });
fs.writeFileSync(path.join(g.app, 'node_modules', 'x.js'), '1');
assert.equal(g.run().code, 0);
});
test('refuses: credentials in the origin URL, detached HEAD, a rewritten history, a second run at the same time', opts, () => {
let f = fixture();
git(f.app, 'remote', 'set-url', 'origin', 'https://jvanvik:glpat-secret@git.example.com/jvanvik/Upstream.git');
let r = f.run();
assert.equal(r.code, 2);
assert.match(r.err, /credentials/);
assert.ok(!r.all.includes('glpat-secret'), 'the token is never echoed');
assert.deepEqual(f.calls(), []);
f = fixture();
git(f.app, 'checkout', '-q', '--detach');
r = f.run();
assert.equal(r.code, 2);
assert.match(r.err, /detached HEAD/);
f = fixture(); // origin gets a different history (force push)
git(f.dev, 'reset', '-q', '--hard', 'HEAD');
fs.writeFileSync(path.join(f.dev, 'server.js'), '// other\n');
git(f.dev, 'commit', '-q', '--amend', '-a', '-m', 'rewritten');
git(f.dev, 'push', '-q', '-f', 'origin', 'main');
r = f.run();
assert.equal(r.code, 2);
assert.match(r.err, /not a fast-forward/);
assert.equal(f.head(), f.old);
assert.deepEqual(f.calls(), []);
f = fixture();
f.publish({ 'server.js': '// v2\n' });
fs.mkdirSync(path.join(f.root, 'lock'));
r = f.run();
assert.equal(r.code, 2);
assert.match(r.err, /another update/);
assert.equal(f.head(), f.old);
});
test('--dry-run fetches and reports, changes nothing', opts, () => {
const f = fixture();
f.publish({ 'server.js': '// v2\n', 'server/migrations/005_x.sql': 'select 1;\n' }, 'with a migration');
const r = f.run(['--dry-run']);
assert.equal(r.code, 0, r.all);
assert.match(r.out, /NEW MIGRATIONS.*005_x\.sql/);
assert.match(r.out, /dry run/);
assert.equal(f.head(), f.old);
assert.deepEqual(f.calls(), []);
});
test('no verified snapshot, no update', opts, () => {
let f = fixture();
f.publish({ 'server.js': '// v2\n' });
fs.writeFileSync(path.join(f.stub, 'backup_fail'), '');
let r = f.run();
assert.equal(r.code, 2);
assert.match(r.out, /no verified snapshot/);
assert.equal(f.head(), f.old);
assert.equal(f.calls().filter((x) => x.startsWith('systemctl')).map((x) => x.split(' ')[1]).join(), 'stop,start', 'stopped for the snapshot, started again when there is none');
assert.equal(f.calls().some((x) => x.startsWith('npm')), false);
f = fixture();
f.publish({ 'server.js': '// v2\n' });
fs.writeFileSync(path.join(f.stub, 'verify_fail'), '');
r = f.run();
assert.equal(r.code, 2);
assert.match(r.out, /no verified snapshot/);
assert.equal(f.head(), f.old);
});
test('new version does not answer /healthz: rolled back to the old rev, restarted, exit 1; migrations are called out with the snapshot', opts, () => {
const f = fixture();
f.publish({ BROKEN: 'x', 'server/migrations/005_x.sql': 'select 1;\n' }, 'bad release');
const r = f.run();
assert.equal(r.code, 1, r.all);
assert.match(r.out, /FAILED: no 200 from/);
assert.match(r.out, /rolled back: .* answers \/healthz again/);
assert.match(r.out, /migrations \(005_x\.sql \).*restore the snapshot .*upstream-20261011T041500Z\.db/);
assert.equal(f.head(), f.old);
assert.equal(fs.existsSync(path.join(f.app, 'BROKEN')), false, 'the tree is the old one again');
assert.equal(f.calls().filter((x) => x.startsWith('systemctl start')).length, 2, 'start for the new code, start for the old');
assert.equal(f.calls().filter((x) => x.startsWith('systemctl stop')).length, 2, 'the broken new process is stopped before the tree is put back');
assert.match(r.out, /005_x\.sql/);
});
test('rollback across migration 005_site_garrison.sql warns about stranded garrisons', opts, () => {
const f = fixture();
f.publish({ BROKEN: 'x', 'server/migrations/005_site_garrison.sql': 'select 1;\n' }, 'garrison');
const dry = f.run(['--dry-run']);
assert.match(dry.out, /005_site_garrison\.sql adds garrisons in landing sites/);
const r = f.run();
assert.equal(r.code, 1, r.all);
assert.match(r.out, /site_stationed.*neither shows, nor powers, nor sends home/);
});
test('rollback restores dependencies when the lock file had changed', opts, () => {
const f = fixture();
f.publish({ BROKEN: 'x', 'package-lock.json': '{"v":2}\n' });
const r = f.run();
assert.equal(r.code, 1, r.all);
assert.equal(f.calls().filter((x) => x.startsWith('npm ci --omit=dev')).length, 2, 'ci for the new lock, ci again for the old one');
assert.equal(f.head(), f.old);
});
test('a failing npm ci or a red --test rolls back; a red suite never restarts the service for the new code', opts, () => {
let f = fixture();
f.publish({ 'package-lock.json': '{"v":2}\n' });
fs.writeFileSync(path.join(f.stub, 'npm_fail'), '');
let r = f.run();
// npm ci fails for the new AND the old lock (the stub fails always), so the rollback itself cannot recover
assert.equal(r.code, 3, r.all);
assert.equal(f.calls().filter((x) => x.startsWith('systemctl start')).length, 0, 'no start on top of a failed recovery');
assert.match(r.out, /npm ci for the old code failed/);
f = fixture();
f.publish({ TESTFAIL: 'x' }, 'red');
r = f.run(['--test']);
assert.equal(r.code, 1, r.all);
assert.match(r.err, /test suite .*failed/);
assert.equal(f.head(), f.old);
assert.equal(f.calls().some((x) => x.startsWith('systemctl')), false, 'the live service was not even stopped');
});
test('rollback that does not recover: exit 3 with the snapshot named', opts, () => {
const f = fixture();
f.publish({ 'server.js': '// v2\n' });
fs.writeFileSync(path.join(f.stub, 'restart_fail'), '');
const r = f.run();
assert.equal(r.code, 3, r.all);
assert.match(r.out, /ROLLBACK DID NOT RECOVER/);
assert.match(r.out, /upstream-20261011T041500Z\.db/);
assert.equal(f.head(), f.old);
});
test('a SIGTERM after the merge puts the old rev back and restarts (the next run must not say "up to date" with the old process running)', opts, () => {
const f = fixture();
f.publish({ 'server.js': '// v2\n' });
fs.writeFileSync(path.join(f.stub, 'kill_once'), ''); // the first systemctl restart sends TERM to the script
const r = f.run();
assert.equal(r.code, 1, r.all);
assert.match(r.out, /FAILED: interrupted by a signal/);
assert.equal(f.head(), f.old);
assert.equal(fs.existsSync(path.join(f.root, 'lock')), false, 'lock released');
assert.equal(f.calls().filter((x) => x.startsWith('systemctl start')).length, 2);
});
test('PORT comes from the env file for the health check; the script is plain POSIX sh syntax', opts, () => {
const f = fixture();
f.publish({ 'server.js': '// v2\n' });
fs.writeFileSync(path.join(f.root, 'none.env'), 'SIGNUP_CODE=x\nPORT="9090"\n');
assert.equal(f.run().code, 0);
assert.ok(f.calls().some((x) => x.startsWith('curl') && x.includes('http://127.0.0.1:9090/healthz')));
assert.equal(spawnSync('sh', ['-n', SCRIPT]).status, 0);
assert.equal(/^\s*(local|source|declare|typeset)\s|\[\[(?!:)|\[ [^\]]*==|<\(|\$\{[A-Za-z_]+(\/|,,|\^\^)/m.test(fs.readFileSync(SCRIPT, 'utf8').replace(/^\s*#.*$/gm, '')), false, 'no bashisms the usual way');
});
// ---------------------------------------------------------------------------------------------------------------------------
// review fixes: tools up front, credentials check, mixed-code window, tests as the service user in an isolated copy
const SYS_TOOLS = ['git', 'sh', 'sed', 'tr', 'head', 'tail', 'id', 'rm', 'rmdir', 'mkdir', 'env', 'tar', 'mktemp', 'cat', 'basename', 'dirname', 'ls', 'chmod', 'date', 'uname', 'grep', 'awk', 'mv', 'cp', 'ln', 'readlink', 'sort', 'cut', 'wc', 'xargs', 'true', 'false', 'test', 'expr', 'printf', 'ssh'];
// a PATH holding the stubs plus a few real tools, and NOT curl (or whatever is left out)
function restrictedPath(f, leaveOut) {
const sys = path.join(f.root, 'sys');
fs.mkdirSync(sys, { recursive: true });
for (const t of SYS_TOOLS) {
if (leaveOut.includes(t)) continue;
const r = spawnSync('sh', ['-c', 'command -v ' + t], { encoding: 'utf8' });
const real = r.stdout.trim();
if (real && real.startsWith('/') && !fs.existsSync(path.join(sys, t))) fs.symlinkSync(real, path.join(sys, t));
}
return path.join(f.root, 'bin') + path.delimiter + sys;
}
test('a missing tool (curl, npm, systemctl, the admin wrapper) is refused up front: exit 2, nothing stopped, no misleading rollback', opts, () => {
for (const tool of ['curl', 'npm', 'systemctl', 'upstream-admin']) {
const f = fixture();
f.publish({ 'server.js': '// v2\n' });
fs.rmSync(path.join(f.root, 'bin', tool));
const r = f.run([], { PATH: restrictedPath(f, []), UPSTREAM_ADMIN: tool === 'upstream-admin' ? 'no-such-admin' : path.join(f.root, 'bin', 'upstream-admin') });
assert.equal(r.code, 2, tool + ': ' + r.all);
assert.match(r.err, new RegExp('missing on the PATH:.* ' + (tool === 'upstream-admin' ? 'no-such-admin' : tool)), tool);
assert.ok(!/ROLLBACK DID NOT RECOVER|rolling back/.test(r.all), tool + ': no rollback story');
assert.equal(f.head(), f.old);
assert.deepEqual(f.calls(), [], tool + ': nothing ran');
}
});
test('the credential check only refuses user:password@ / token@ in an http(s) authority, not ssh:// logins or an @ in a path', opts, () => {
const refused = ['https://jvanvik:glpat-secret@git.example.com/x.git', 'https://glpat-secret@git.example.com/x.git', 'http://u:p@127.0.0.1:1/x.git'];
for (const url of refused) {
const f = fixture();
git(f.app, 'remote', 'set-url', 'origin', url);
const r = f.run();
assert.equal(r.code, 2, url);
assert.match(r.err, /credentials/, url);
assert.ok(!r.all.includes('secret'), 'never echoed');
}
// allowed: the script gets past the check and only then fails on the (unreachable) network, never with "credentials"
for (const url of ['ssh://git@127.0.0.1:1/jvanvik/Upstream.git', 'git@127.0.0.1:jvanvik/Upstream.git', 'https://127.0.0.1:1/a@b/c.git', 'https://127.0.0.1:1/jvanvik/Upstream.git']) {
const f = fixture();
git(f.app, 'remote', 'set-url', 'origin', url);
const r = f.run([], { GIT_SSH_COMMAND: 'false' });
assert.ok(!/credentials/.test(r.all), url + ': ' + r.all);
assert.match(r.err, /git fetch origin main failed/, url);
assert.equal(r.code, 1);
}
});
test('a SIGTERM while the service is stopped but before the merge starts it again on the untouched tree', opts, () => {
const f = fixture();
f.publish({ 'server.js': '// v2\n' });
// the admin wrapper (runs between stop and merge) sends TERM to the script
fs.writeFileSync(path.join(f.root, 'bin', 'upstream-admin'), '#!/bin/sh\necho "upstream-admin $*" >> "$STUB_DIR/calls.log"\nkill -TERM $PPID\nsleep 0\nexit 1\n', { mode: 0o755 });
const r = f.run();
assert.equal(r.code, 1, r.all);
assert.equal(f.head(), f.old, 'tree untouched');
const sys = f.calls().filter((x) => x.startsWith('systemctl')).map((x) => x.split(' ')[1]);
assert.equal(sys.join(), 'stop,start', 'stopped, then started again: never left down');
assert.equal(fs.existsSync(path.join(f.root, 'lock')), false);
});
test('a stop that fails refuses before anything is changed', opts, () => {
const f = fixture();
f.publish({ 'server.js': '// v2\n' });
fs.writeFileSync(path.join(f.stub, 'stop_fail'), '');
const r = f.run();
assert.equal(r.code, 1, r.all);
assert.match(r.err, /systemctl stop upstream failed/);
assert.equal(f.head(), f.old);
assert.equal(f.calls().some((x) => x.startsWith('upstream-admin') || x.startsWith('npm')), false);
});
test('--test as root runs npm ci / npm test as the service user (runuser) and never as root', opts, () => {
const f = fixture();
f.publish({ 'server.js': '// v2\n' });
// pretend to be root: id -u answers 0, and runuser is a stub that records who it switches to and then runs the command
fs.writeFileSync(path.join(f.root, 'bin', 'id'), '#!/bin/sh\n[ "$1" = "-u" ] && { echo 0; exit 0; }\nexec /usr/bin/id "$@"\n', { mode: 0o755 });
fs.writeFileSync(path.join(f.root, 'bin', 'runuser'), '#!/bin/sh\necho "runuser $*" >> "$STUB_DIR/calls.log"\n[ "$1" = "-u" ] || exit 9\nshift 2\n[ "$1" = "--" ] && shift\nexec "$@"\n', { mode: 0o755 });
fs.writeFileSync(path.join(f.root, 'bin', 'chown'), '#!/bin/sh\necho "chown $*" >> "$STUB_DIR/calls.log"\n', { mode: 0o755 });
const r = f.run(['--test'], { UPSTREAM_ALLOW_NONROOT: '0', UPSTREAM_SERVICE_USER: 'svcuser' });
assert.equal(r.code, 0, r.all);
const c = f.calls();
assert.match(c[idx(c, 'runuser')], /^runuser -u svcuser -- env /);
assert.ok(idx(c, 'chown') >= 0 && idx(c, 'chown') < idx(c, 'runuser'), 'the copy is handed to the service user first');
assert.ok(idx(c, 'runuser') < idx(c, 'systemctl stop'), 'before the service is touched');
assert.equal(c.filter((x) => x.startsWith('runuser')).length, 1);
});
test('a red --test in the isolated copy leaves the live tree, the service and the snapshot dir alone', opts, () => {
const f = fixture();
f.publish({ TESTFAIL: 'x' }, 'red');
const r = f.run(['--test']);
assert.equal(r.code, 1, r.all);
assert.equal(f.head(), f.old);
assert.equal(fs.existsSync(path.join(f.app, 'TESTFAIL')), false);
assert.equal(fs.existsSync(f.backups), false, 'no snapshot was needed');
});

173
test/economy-leaks.test.js Normal file
View file

@ -0,0 +1,173 @@
'use strict';
/* docs/BALANCE.md S2 (trade escrow refunds were clipped silently) and S4 (raid loot and the incumbent bonus were destroyed on
* arrival when the raiders' home Rack hall was full). Each test below fails on the code before the fix. Fake clock, in-memory db. */
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');
const capOf = (h, townId) => R.storageCap(loadTown(h.db, townId));
const fieldsOff = (h, townId) => h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%'", townId);
// ---------------------------------------------------------------- S4: loot
test('rules.lootSplit: a resource with no room at home is not taken and its share goes to the others', () => {
const rich = { fiber: 1000, hardware: 1000, capital: 1000 };
assert.deepEqual(R.lootSplit(300, rich, { fiber: Infinity, hardware: Infinity, capital: Infinity }), { fiber: 100, hardware: 100, capital: 100 });
assert.deepEqual(R.lootSplit(300, rich, { fiber: 1000, hardware: 0, capital: 1000 }), { fiber: 150, hardware: 0, capital: 150 });
assert.deepEqual(R.lootSplit(300, rich, { fiber: 20, hardware: 0, capital: 0 }), { fiber: 20, hardware: 0, capital: 0 }, 'no more than the room, even if the raiders could carry more');
assert.deepEqual(R.lootSplit(300, rich, { fiber: 50 }), { fiber: 50, hardware: 125, capital: 125 }, 'a missing key means no limit');
assert.deepEqual(R.lootSplit(300, rich), { fiber: 100, hardware: 100, capital: 100 }, 'room is optional');
});
function raid(homeStock) {
const h = T.setup();
const att = T.addOperator(h, 'raider', { x: 5, y: 0, units: { script_crew: 40 } });
const def = T.addOperator(h, 'target', { x: 9, y: 0, units: { soc_analyst: 20 }, infra: { rack_hall: 2 } });
fieldsOff(h, att.townId); fieldsOff(h, def.townId);
h.db.run('UPDATE towns SET fiber = 600, hardware = 600, capital = 600 WHERE id = ?', def.townId);
h.db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', homeStock.fiber, homeStock.hardware, homeStock.capital, att.townId);
const sent = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'raid', toTownId: def.townId, units: { script_crew: 40 } });
return { h, att, def, sent };
}
test('raid: loot is limited to what the home Rack hall can bank; the rest stays with the victim and the report says so (S4)', () => {
const probe = T.setup(); const cap = capOf(probe, T.addOperator(probe, 'p', { x: 5, y: 0 }).townId);
const { h, att, def, sent } = raid({ fiber: 100, hardware: cap, capital: cap - 30 }); // no room for Hardware, 30 for Capital
const defBefore = T.town(h, def.townId);
h.advanceTo(sent.arriveAt);
const rep = T.reportsOf(h, att.userId)[0].data;
assert.equal(rep.outcome, 'attacker_won');
assert.equal(rep.loot.hardware, 0, 'nothing is taken that cannot be banked');
assert.ok(rep.loot.capital <= 30 + 1e-9, 'Capital is limited to the 30 of room');
assert.ok(rep.loot.fiber > 0, 'the carry goes to the resource that has room');
assert.ok(rep.lootLeft.hardware > 0, 'the report says what was left behind for lack of room');
const defAfter = T.town(h, def.townId);
assert.equal(defAfter.hardware, defBefore.hardware, 'the victim keeps what was not taken');
const ret = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'");
assert.deepEqual(JSON.parse(ret.cargo), rep.loot);
h.advanceTo(ret.arrive_at);
const back = T.notes(h, att.userId, 'movement_returned')[0];
assert.ok(!back.cargoLost || Object.values(back.cargoLost).every((v) => v === 0), 'nothing is destroyed on arrival: ' + JSON.stringify(back.cargoLost));
assert.ok(Math.abs(T.town(h, att.townId).hardware - cap) < 1e-6, 'hardware stays at the hall size');
});
test('raid: two raids from one home that each see the same free room cannot both fill it; the later one is limited, nothing is destroyed on landing', () => {
const h = T.setup();
const att = T.addOperator(h, 'raider', { x: 5, y: 0, units: { script_crew: 80 } });
const def = T.addOperator(h, 'target', { x: 9, y: 0, units: { soc_analyst: 10 }, infra: { rack_hall: 2 } });
fieldsOff(h, att.townId); fieldsOff(h, def.townId);
const cap = capOf(h, att.townId), room = 600, carry = room;
h.db.run('UPDATE towns SET fiber = 2000, hardware = 2000, capital = 2000 WHERE id = ?', def.townId);
h.db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', cap, cap, cap - room, att.townId); // room for ONE raid's worth, in Capital only (each raid alone could fill it)
const s1 = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'raid', toTownId: def.townId, units: { script_crew: 40 } });
const s2 = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'raid', toTownId: def.townId, units: { script_crew: 40 } });
h.advanceTo(Math.max(s1.arriveAt, s2.arriveAt));
const reps = T.reportsOf(h, att.userId).map((r) => r.data).filter((d) => d.type === 'raid');
assert.equal(reps.length, 2);
assert.ok(reps.every((r) => r.outcome === 'attacker_won'), 'both raids won (the test is about room, not combat)');
const total = reps.reduce((a, r) => a + r.loot.capital, 0);
assert.ok(total <= carry + 1e-6, 'together they take no more than the home can bank: ' + total + ' vs ' + carry);
assert.ok(reps.some((r) => r.lootLeft && (r.lootLeft.fiber > 0 || r.lootLeft.hardware > 0)), 'the reports say what stayed with the victim');
h.advance(2 * H);
assert.equal(T.notes(h, att.userId, 'movement_returned').length, 2);
for (const n of T.notes(h, att.userId, 'movement_returned')) assert.ok(!n.cargoLost || Object.values(n.cargoLost).every((v) => v === 0), 'nothing destroyed: ' + JSON.stringify(n.cargoLost));
});
test('raid: with room everywhere the loot is the same even split as before and lootLeft is empty', () => {
const { h, att, sent } = raid({ fiber: 100, hardware: 100, capital: 100 });
h.advanceTo(sent.arriveAt);
const rep = T.reportsOf(h, att.userId)[0].data;
assert.ok(rep.loot.fiber > 0 && rep.loot.fiber === rep.loot.hardware);
assert.deepEqual(rep.lootLeft, {});
});
test('incumbent bonus is delivered in full even when the Hardware store is full (a one-time reward must not vanish at the door)', () => {
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 };
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, units: { script_crew: crews } });
fieldsOff(h, a.townId);
const cap = capOf(h, a.townId);
h.db.run('UPDATE towns SET fiber = 100, hardware = ?, capital = 100 WHERE id = ?', cap, a.townId);
const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'attack', x: site.x, y: site.y, units: { script_crew: crews } });
h.advanceTo(s.arriveAt);
const ret = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'");
h.advanceTo(ret.arrive_at);
assert.equal(T.town(h, a.townId).hardware, cap + D.INCUMBENT.hardwareBonus, 'the bonus sits on top of the full store (kept, it only stops growing)');
const back = T.notes(h, a.userId, 'movement_returned')[0];
assert.ok(!back.cargoLost || !back.cargoLost.hardware, 'and is not reported lost');
});
// ---------------------------------------------------------------- S2: trade escrow
function poster(o) {
const h = T.setup();
const a = T.addOperator(h, 'alice', { x: 5, y: 0, res: 100 });
const b = T.addOperator(h, 'bob', { x: 9, y: 0 });
const cap = capOf(h, a.townId);
h.db.run('UPDATE towns SET fiber = ?, hardware = 0, capital = 0 WHERE id = ?', o && o.fiber !== undefined ? o.fiber : cap - 420, a.townId);
return { h, a, b, cap };
}
const offerOf = (h, a, amount) => h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'fiber', giveAmount: amount || 400, wantRes: 'hardware', wantAmount: 300, maxDistance: 30 }).offer;
const fiberNow = (h, townId) => R.resourcesAt(loadTown(h.db, townId), h.clock.now()).amounts.fiber;
test('trade (S2): escrow keeps its room in the Rack hall, so a refund after the store refilled loses nothing and stores nothing extra', () => {
for (const how of ['cancel', 'expire']) {
const { h, a, cap } = poster();
const offer = offerOf(h, a);
h.advance(30 * H); // production refills everything it may (the offer lives 48 h)
const before = fiberNow(h, a.townId);
assert.ok(Math.abs(before - (cap - 400)) < 1e-6, how + ': the stock stops 400 below the hall size while 400 are escrowed, got ' + before);
if (how === 'cancel') h.run('tradeCancel', { userId: a.userId, offerId: offer.id });
else h.advanceTo(offer.expiresAt);
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, how === 'cancel' ? 'cancelled' : 'expired');
const after = fiberNow(h, a.townId);
assert.ok(Math.abs(after - (before + 400)) < 1e-6 && Math.abs(after - cap) < 1e-6, how + ': the whole escrow came back and exactly fills the hall: ' + after + ' / ' + cap);
assert.equal(T.notes(h, a.userId, 'trade_refund_clipped').length, 0, 'nothing was lost, so nothing is reported');
}
});
test('trade (S2): several offers and other resources - the room is per resource and per open offer', () => {
const { h, a, cap } = poster({ fiber: 0 });
h.db.run('UPDATE towns SET fiber = ?, hardware = ? WHERE id = ?', cap - 300, cap - 100, a.townId);
const o1 = offerOf(h, a, 400), o2 = offerOf(h, a, 300);
h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'hardware', giveAmount: 250, wantRes: 'fiber', wantAmount: 300, maxDistance: 30 });
h.advance(30 * H);
const t = loadTown(h.db, a.townId);
assert.deepEqual(t.escrow, { fiber: 700, hardware: 250, capital: 0 });
assert.equal(R.resourcesAt(t, h.clock.now()).caps.fiber, cap - 700);
h.run('tradeCancel', { userId: a.userId, offerId: o1.id });
assert.ok(Math.abs(fiberNow(h, a.townId) - (cap - 300)) < 1e-6, 'the other offer still holds its 300');
h.run('tradeCancel', { userId: a.userId, offerId: o2.id });
assert.ok(Math.abs(fiberNow(h, a.townId) - cap) < 1e-6);
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM notifications WHERE type = 'trade_refund_clipped'").n, 0);
});
test('trade (S2): accepting settles the poster under the reserved room; afterwards the room is free again', () => {
const { h, a, b, cap } = poster({ fiber: 0 });
h.db.run('UPDATE towns SET fiber = ? WHERE id = ?', cap - 420, a.townId);
const offer = offerOf(h, a, 400);
h.advance(30 * H);
assert.ok(Math.abs(fiberNow(h, a.townId) - (cap - 400)) < 1e-6);
const acc = h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId });
const stored = h.db.get('SELECT fiber FROM towns WHERE id = ?', a.townId).fiber;
assert.ok(Math.abs(stored - (cap - 400)) < 1e-6, 'the poster was settled at the moment the escrow left, under the reserved cap: ' + stored);
h.advanceTo(acc.arriveAt + 100 * H);
assert.ok(Math.abs(fiberNow(h, a.townId) - cap) < 1e-6, 'the hall fills up again once the escrow is gone');
});
test('trade (S2): what cannot be refunded (Rack hall shot down meanwhile) is reported, never silent', () => {
const { h, a } = poster({ fiber: 3000 });
const offer = offerOf(h, a, 400);
const total = () => h.db.get('SELECT fiber FROM towns WHERE id = ?', a.townId).fiber;
const before = total();
T.setBuildings(h, a.townId, { rack_hall: 1 }); // cap 1000 << stock 2600
const r = h.run('tradeCancel', { userId: a.userId, offerId: offer.id });
assert.equal(r.returned.amount, 0, 'stock above the hall size is kept but a refund does not lift it further');
assert.ok(Math.abs(total() - before) < 1e-6);
const note = T.notes(h, a.userId, 'trade_refund_clipped');
assert.equal(note.length, 1);
assert.deepEqual([note[0].resource, note[0].lost, note[0].credited], ['fiber', 400, 0]);
});

View file

@ -0,0 +1,508 @@
'use strict';
/* Garrisons at backbone landing sites (docs/DECISIONS.md E6): members of the holding alliance station units in a site, the units defend it on top
* of its static defence, attacks resolve in arrival order (a lost wave kills a share of the garrison, the next wave faces less), a won attack
* wipes it and takes the site. Plus the edges: nobody but the holder can reinforce, units are never in two places, withdraw/recall while under
* attack, leaving the alliance, power. Fake clock, in-memory db; the world is moved to day 100 by advancing the clock. */
const test = require('node:test');
const assert = require('node:assert');
const T = require('./military-helpers');
const A = require('../server/alliances');
const E = require('../server/endgame');
const G = require('../server/military/garrison');
const { createEndgameQueries } = require('../server/endgameQueries');
const { loadTown } = require('../server/state');
const { R, D, H } = T;
const DAY = 24 * H;
function alliance(h, name, leader, members) {
const id = Number(h.db.run('INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, ?, ?, 10, ?, ?)', h.worldId, name, name.slice(0, 3).toUpperCase(), leader.opId, h.clock.now()).lastInsertRowid);
A.addMember(h.db, id, leader.opId, 'leader', h.clock.now());
for (const m of members || []) A.addMember(h.db, id, m.opId, 'member', h.clock.now());
return id;
}
const err = (fn) => { try { fn(); } catch (e) { return e; } assert.fail('expected an error'); };
function world(day, o) {
const h = T.setup(Object.assign({ seed: 4242, radius: 50 }, o));
h.advanceTo(h.world.start_at + Math.round(day * DAY / (h.world.speed || 1)));
h.eg = createEndgameQueries(h);
h.sites = R.backboneSites(h.world.seed, h.world.map_radius);
return h;
}
// An operator next to site `i` with plenty of power so that its units stay online; no production unless asked.
function near(h, name, i, o) {
const s = h.sites[i];
const op = T.addOperator(h, name, Object.assign({ x: s.x - 4, y: s.y, power: 25 }, o || {}));
if (!(o && o.produce)) h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%' AND key NOT IN ('f13','f14','f15','f16')", op.townId);
return op;
}
const siteOf = (h, i) => h.db.get('SELECT * FROM landing_sites WHERE world_id = ? AND idx = ?', h.worldId, i);
function hold(h, i, allianceId, opId) {
E.ensureSites(h.db, h.world, h.clock.now());
h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ? WHERE idx = ?', allianceId, opId, i);
}
const sendTo = (h, who, i, type, units) => h.run('sendMovement', { userId: who.userId, fromTownId: who.townId, type, x: h.sites[i].x, y: h.sites[i].y, units });
const staticHeld = (h, i, level, held) => R.backboneDefence(h.world.seed, h.sites[i].x, h.sites[i].y, R.worldAgeDays(h.world.start_at, h.clock.now(), h.world.speed), level || 0, held !== false);
const garrisonAt = (h, i) => { const s = siteOf(h, i); const out = {}; for (const g of G.groups(h.db, s.id)) for (const k of Object.keys(g.units)) out[k] = (out[k] || 0) + g.units[k]; return out; };
// Every unit in the world, wherever it is: home, stationed in a POP, in a garrison, in a movement that has not arrived.
function totals(h) {
const out = {};
const add = (u, n) => { out[u] = (out[u] || 0) + n; };
for (const r of h.db.all('SELECT unit, SUM(count) AS n FROM town_units GROUP BY unit')) add(r.unit, r.n);
for (const r of h.db.all('SELECT unit, SUM(count) AS n FROM stationed GROUP BY unit')) add(r.unit, r.n);
for (const r of h.db.all('SELECT unit, SUM(count) AS n FROM site_stationed GROUP BY unit')) add(r.unit, r.n);
for (const m of h.db.all("SELECT units FROM movements WHERE status = 'out'")) { const u = JSON.parse(m.units); for (const k of Object.keys(u)) add(k, u[k]); }
return out;
}
const draw = (h, who) => loadTown(h.db, who.townId).unitDraw;
const lastReport = (h, who, type) => T.reportsOf(h, who.userId).filter((r) => r.type === type).pop();
// alice (leader) + alice2 (member) hold site 0 for ALP; bob + bob2 are BRA; 'loner' has no alliance
function scene(o) {
const h = world(100, o);
const s0 = h.sites[0];
const a = near(h, 'alice', 0, { units: { soc_analyst: 600 } });
const a2 = near(h, 'alice2', 0, { x: s0.x - 4, y: s0.y + 3, units: { blue_team: 100 } });
const b = near(h, 'bob', 0, { x: s0.x + 4, y: s0.y });
const b2 = near(h, 'bob2', 0, { x: s0.x + 4, y: s0.y + 3 });
const loner = near(h, 'loner', 0, { x: s0.x, y: s0.y - 5, units: { soc_analyst: 10 } });
const A1 = alliance(h, 'Alpha', a, [a2]), B1 = alliance(h, 'Bravo', b, [b2]);
hold(h, 0, A1, a.opId);
return Object.assign(h, { a, a2, b, b2, loner, A1, B1 });
}
// ---------------------------------------------------------------- pure rules
test('rules: a held site is much weaker than an unheld one; battle = static + garrison; the static part never loses anything; transport capacity scales with speed', () => {
const seed = 4242, x = 10, y = 10;
const open = R.backboneDefence(seed, x, y, 100, 0, false), heldD = R.backboneDefence(seed, x, y, 100, 0, true);
assert.equal(R.backboneDefence(seed, x, y, 100, 0), open, 'unheld is the default (the opening scramble)');
assert.ok(open > 5 * heldD && heldD > 0, 'held = ' + heldD + ', unheld = ' + open);
assert.ok(R.backboneDefence(seed, x, y, 100, 50, true) > heldD, 'node levels still raise it');
const grp = (n) => ({ id: 'g', units: { soc_analyst: n }, research: {} });
const none = R.resolveBattle({ kind: 'attack', attackers: { units: { script_crew: 100 }, research: {} }, defenders: [], firewall: 0, staticDefence: 3000 });
assert.equal(none.D, 3000);
assert.equal(none.defenderLossFraction, 0, 'no garrison, nothing to lose');
assert.equal(none.attackerWins, true);
const b = R.resolveBattle({ kind: 'attack', attackers: { units: { script_crew: 100 }, research: {} }, defenders: [grp(100)], firewall: 0, staticDefence: 3000 });
assert.equal(b.D, 3000 + 100 * 25, 'static + raw defence, no firewall, no base defence');
assert.equal(b.attackerWins, false);
assert.ok(b.defenderLossFraction > 0 && b.defenderLossFraction < 1);
assert.equal(b.defenders[0].lost.soc_analyst, Math.round(100 * Math.pow(4000 / 5500, 1.5)));
const win = R.resolveBattle({ kind: 'attack', attackers: { units: { script_crew: 200 }, research: {} }, defenders: [grp(100)], firewall: 0, staticDefence: 3000 });
assert.equal(win.attackerWins, true);
assert.equal(win.defenders[0].lost.soc_analyst, 100, 'a won attack wipes the garrison');
// a POP battle is untouched by the new mode
const pop = R.resolveBattle({ kind: 'attack', attackers: { units: { script_crew: 100 }, research: {} }, defenders: [grp(100)], firewall: 0 });
assert.equal(pop.D, (100 * 25 + D.MILITARY.defenceBase) * R.firewallMult(0));
assert.equal(R.transportCapacity(1), D.TRANSPORT.capacityPerLink);
assert.equal(R.transportCapacity(3), 3 * D.TRANSPORT.capacityPerLink);
assert.equal(R.transportCapacity(undefined), D.TRANSPORT.capacityPerLink);
});
// ---------------------------------------------------------------- stationing
test('reinforce a site: only members of the holding alliance; the units leave home, join the garrison on arrival and draw their owner\'s power', () => {
const h = scene();
const { a, a2, b, loner } = h;
T.giveUnits(h, b.townId, { soc_analyst: 20 });
assert.equal(err(() => sendTo(h, b, 0, 'reinforce', { soc_analyst: 10 })).details.reason, 'not_holder', 'a rival cannot');
assert.equal(err(() => sendTo(h, loner, 0, 'reinforce', { soc_analyst: 10 })).details.reason, 'not_holder', 'no alliance cannot');
assert.equal(err(() => sendTo(h, a, 1, 'reinforce', { soc_analyst: 10 })).details.reason, 'not_holder', 'not a site your alliance holds');
assert.equal(err(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'reinforce', x: h.sites[0].x + 1, y: h.sites[0].y, units: { soc_analyst: 1 } })).code, 'invalid_target');
const before = totals(h);
const d0 = draw(h, a);
assert.equal(d0, 600);
const mv = sendTo(h, a, 0, 'reinforce', { soc_analyst: 400 });
assert.equal(draw(h, a), 200, 'units on the road draw nothing');
assert.equal(T.units(h, a.townId).soc_analyst, 200);
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM site_stationed').n, 0);
assert.deepEqual(totals(h), before, 'in a movement, counted once');
assert.equal(T.notes(h, a2.userId, 'backbone_incoming').length, 0, 'own members are not warned about the own reinforcement');
h.advanceTo(mv.arriveAt);
assert.deepEqual(garrisonAt(h, 0), { soc_analyst: 400 });
assert.equal(draw(h, a), 600, 'the owner pays for them again, nobody else');
assert.equal(draw(h, a2), 100 * D.UNITS.blue_team.draw);
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM stationed').n, 0, 'not a POP reinforcement');
assert.deepEqual(totals(h), Object.assign({}, before), 'counted once');
assert.equal(T.notes(h, a.userId, 'garrison_arrived').length, 1);
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0);
// the POP view lists them (they draw this POP's power, so they must not just vanish from it)
const mu = h.queries.town(a.userId, a.townId).town.military.units;
assert.deepEqual(mu.garrisoned, [{ siteId: siteOf(h, 0).id, x: h.sites[0].x, y: h.sites[0].y, units: { soc_analyst: 400 } }]);
assert.equal(T.units(h, a.townId).soc_analyst, 200);
assert.deepEqual(h.queries.town(b.userId, b.townId).town.military.units.garrisoned, []);
// a second member adds to the same site; groups are per owner POP
const mv2 = sendTo(h, a2, 0, 'reinforce', { blue_team: 100 });
h.advanceTo(mv2.arriveAt);
assert.equal(G.groups(h.db, siteOf(h, 0).id).length, 2);
const view = h.eg.site(a.userId, siteOf(h, 0).id);
assert.equal(view.you.canReinforce, true);
assert.equal(view.garrison.length, 2);
assert.deepEqual(view.garrison.map((g) => g.mine), [true, false]);
assert.equal(view.defence.static, staticHeld(h, 0, 0));
assert.equal(view.defence.garrison, 400 * 25 + 100 * 80);
assert.equal(view.defence.total, view.defence.static + view.defence.garrison);
assert.equal(h.eg.site(b.userId, siteOf(h, 0).id).garrison, undefined, 'the garrison is the holders\' business (a scan shows it)');
assert.equal(h.eg.site(b.userId, siteOf(h, 0).id).you.canReinforce, false);
});
test('a scan of a held site shows the garrison once: defence = static + garrison, units not doubled', () => {
const h = scene();
const { a, b } = h;
const mv = sendTo(h, a, 0, 'reinforce', { soc_analyst: 300 });
h.advanceTo(mv.arriveAt);
T.giveUnits(h, b.townId, { port_scanner: 200 });
const sc = sendTo(h, b, 0, 'scan', { port_scanner: 200 });
assert.equal(T.notes(h, a.userId, 'backbone_incoming').length, 1, 'the holders are told something is coming (no type, no sender)');
assert.deepEqual(Object.keys(T.notes(h, a.userId, 'backbone_incoming')[0]).sort(), ['arriveAt', 'index', 'siteId', 'x', 'y']);
h.advanceTo(sc.arriveAt);
const rep = lastReport(h, b, 'scan').data;
assert.equal(rep.success, true);
assert.deepEqual(rep.intel.garrison.units, { soc_analyst: 300 });
assert.equal(rep.intel.garrison.power, 300 * 25);
assert.equal(rep.intel.static, staticHeld(h, 0, 0));
assert.equal(rep.intel.defence, staticHeld(h, 0, 0) + 300 * 25);
assert.equal(rep.intel.holder.allianceId, h.A1);
});
// ---------------------------------------------------------------- the fight
test('waves: a lost wave kills part of the garrison and nothing else, the next wave faces less and takes the site; the garrison is wiped, the site changes hands', () => {
const h = scene();
const { a, b, b2 } = h;
const mv = sendTo(h, a, 0, 'reinforce', { soc_analyst: 400 });
h.advanceTo(mv.arriveAt);
const S = staticHeld(h, 0, 0), G0 = 400 * 25;
// wave 1: more than the static part, less than static + garrison
const n1 = Math.ceil((S + 0.8 * G0) / 40);
assert.ok(n1 * 40 > S && n1 * 40 < S + G0);
T.giveUnits(h, b.townId, { script_crew: n1 });
// wave 2 is sized for what is LEFT after wave 1 (computed from the rules), and must be smaller than the whole defence
const f1 = Math.pow((n1 * 40) / (S + G0), 1.5);
const left = 400 - Math.round(400 * f1);
const n2 = Math.ceil((S + left * 25) * 1.02 / 40);
assert.ok(n2 * 40 < S + G0, 'the second wave alone could not have taken the site');
T.giveUnits(h, b2.townId, { script_crew: n2 });
const w1 = sendTo(h, b, 0, 'attack', { script_crew: n1 });
const w2 = sendTo(h, b2, 0, 'attack', { script_crew: n2 });
assert.ok(w1.arriveAt <= w2.arriveAt, 'bob first (the same distance, lower id first)');
assert.equal(T.notes(h, a.userId, 'backbone_incoming').length, 2);
const unitsBefore = totals(h);
h.advanceTo(w1.arriveAt);
assert.equal(siteOf(h, 0).holder_alliance_id, h.A1, 'wave 1 lost');
assert.deepEqual(garrisonAt(h, 0), { soc_analyst: left }, 'the garrison lost ratio^1.5 of its units');
const r1 = lastReport(h, b, 'landing').data;
assert.equal(r1.outcome, 'defender_won');
assert.equal(r1.power.static, S);
assert.equal(r1.power.garrison, G0);
assert.equal(r1.defender.garrison[0].lost.soc_analyst, 400 - left);
assert.equal(T.units(h, b.townId).script_crew, undefined, 'a lost attack loses everything');
assert.equal(lastReport(h, a, 'landing').role, 'defender', 'the garrison owner gets the report');
assert.equal(h.db.get('SELECT defense_points FROM operator_stats WHERE operator_id = ?', a.opId).defense_points > 0, true);
assert.equal(h.db.get('SELECT attack_points FROM operator_stats WHERE operator_id = ?', b.opId).attack_points > 0, true);
assert.equal(draw(h, a), 200 + left, 'the dead no longer draw power');
h.advanceTo(w2.arriveAt);
const site = siteOf(h, 0);
assert.equal(site.holder_alliance_id, h.B1, 'wave 2 took it');
assert.equal(site.holder_operator_id, b2.opId);
assert.deepEqual(garrisonAt(h, 0), {}, 'a won attack wipes the garrison');
const r2 = lastReport(h, b2, 'landing').data;
assert.equal(r2.outcome, 'attacker_won');
assert.equal(r2.power.defence, S + left * 25);
assert.equal(T.notes(h, a.userId, 'backbone_lost').length, 1);
assert.equal(draw(h, a), 200, 'and the wiped ones neither');
// nothing was created: units before = units after + the dead (units of the survivors are in movements)
const after = totals(h);
const dead = { soc_analyst: 400 - 0, script_crew: n1 + n2 };
assert.equal(unitsBefore.soc_analyst - after.soc_analyst, 400, 'all 400 analysts are gone (lost in the two battles), none duplicated');
assert.ok(unitsBefore.script_crew - after.script_crew <= dead.script_crew && unitsBefore.script_crew - after.script_crew >= n1, 'wave 1 died, wave 2 lost part of its crews');
// the new holder can now garrison, the old one cannot
T.giveUnits(h, b.townId, { soc_analyst: 5 });
assert.equal(err(() => sendTo(h, a, 0, 'reinforce', { soc_analyst: 1 })).details.reason, 'not_holder');
assert.ok(sendTo(h, b, 0, 'reinforce', { soc_analyst: 5 }).movementId);
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0);
});
test('an attack that beats the static part but not the garrison loses; without the garrison the same attack wins (withdraw at T-1)', () => {
const h = scene();
const { a, b } = h;
const mv = sendTo(h, a, 0, 'reinforce', { soc_analyst: 400 });
h.advanceTo(mv.arriveAt);
const S = staticHeld(h, 0, 0);
const n = Math.ceil(1.3 * S / 40);
assert.ok(n * 40 > S && n * 40 < S + 400 * 25);
T.giveUnits(h, b.townId, { script_crew: 2 * n });
const atk = sendTo(h, b, 0, 'attack', { script_crew: n });
const before = totals(h);
// alice calls the garrison home one millisecond before the attack arrives: the attack meets the static part only
h.advanceTo(atk.arriveAt - 1);
const wd = h.run('withdrawGarrison', { userId: a.userId, siteId: siteOf(h, 0).id, fromTownId: a.townId });
assert.deepEqual(wd.units, { soc_analyst: 400 });
assert.deepEqual(garrisonAt(h, 0), {});
assert.equal(draw(h, a), 200, 'they stopped drawing at once');
assert.deepEqual(totals(h), before, 'in the return movement, counted once');
h.advanceTo(atk.arriveAt);
assert.equal(siteOf(h, 0).holder_alliance_id, h.B1, 'the same attack that would have lost took the site');
assert.equal(lastReport(h, b, 'landing').data.defender.garrison.length, 0);
// the return leg survives the change of hands and brings every unit home
assert.equal(h.db.get("SELECT status FROM movements WHERE id = ?", wd.movementId).status, 'out');
h.advanceTo(wd.arriveAt);
assert.equal(T.units(h, a.townId).soc_analyst, 600, 'nothing lost on the way home');
assert.equal(draw(h, a), 600);
assert.equal(T.notes(h, a.userId, 'movement_returned').length, 1);
});
test('the other order: the attack arrives first, then a withdraw only gets the survivors, and after a wipe there is nothing to withdraw', () => {
const h = scene();
const { a, a2, b, b2 } = h;
const mv = sendTo(h, a, 0, 'reinforce', { soc_analyst: 400 });
h.advanceTo(mv.arriveAt);
const S = staticHeld(h, 0, 0);
const n = Math.ceil((S + 0.5 * 400 * 25) / 40);
T.giveUnits(h, b.townId, { script_crew: n });
const atk = sendTo(h, b, 0, 'attack', { script_crew: n });
h.advanceTo(atk.arriveAt);
const left = garrisonAt(h, 0).soc_analyst;
assert.ok(left > 0 && left < 400);
const siteId = siteOf(h, 0).id;
assert.equal(err(() => h.run('withdrawGarrison', { userId: a.userId, siteId, fromTownId: a.townId, units: { soc_analyst: 400 } })).code, 'not_enough_units', 'cannot call home more than there is');
assert.equal(err(() => h.run('withdrawGarrison', { userId: a2.userId, siteId, fromTownId: a.townId })).code, 'not_found', 'only the owner can');
assert.equal(err(() => h.run('withdrawGarrison', { userId: b.userId, siteId, fromTownId: b.townId })).code, 'not_enough_units', 'a POP with nothing there');
const part = h.run('withdrawGarrison', { userId: a.userId, siteId, fromTownId: a.townId, units: { soc_analyst: 5 } });
assert.deepEqual(part.units, { soc_analyst: 5 });
assert.equal(garrisonAt(h, 0).soc_analyst, left - 5);
// the site is wiped by the next wave: a late withdraw finds nothing
const S1 = staticHeld(h, 0, 0);
const n2 = Math.ceil((S1 + (left - 5) * 25) * 1.05 / 40);
T.giveUnits(h, b2.townId, { script_crew: n2 });
const atk2 = sendTo(h, b2, 0, 'attack', { script_crew: n2 });
h.advanceTo(atk2.arriveAt);
assert.equal(siteOf(h, 0).holder_alliance_id, h.B1);
assert.equal(err(() => h.run('withdrawGarrison', { userId: a.userId, siteId, fromTownId: a.townId })).details.reason, 'nothing stationed');
h.advance(DAY);
assert.equal(T.units(h, a.townId).soc_analyst, 200 + 5, 'only the withdrawn 5 came back; the rest died in the two battles');
});
test('recall of a reinforcement within the window: nothing ever arrives in the garrison; a reinforcement that arrives after the site changed hands is turned back', () => {
const h = scene();
const { a, a2, b } = h;
const before = totals(h);
const mv = sendTo(h, a, 0, 'reinforce', { soc_analyst: 100 });
const rc = h.run('recallMovement', { userId: a.userId, movementId: mv.movementId });
h.advanceTo(rc.arriveAt + 1);
assert.deepEqual(garrisonAt(h, 0), {});
assert.deepEqual(totals(h), before);
assert.equal(T.units(h, a.townId).soc_analyst, 600);
// alice2 lives further away: bob takes the site while her units are on the road
h.db.run("UPDATE operators SET alliance_id = alliance_id WHERE id = ?", a2.opId);
const late = sendTo(h, a2, 0, 'reinforce', { blue_team: 50 });
T.giveUnits(h, b.townId, { script_crew: Math.ceil(staticHeld(h, 0, 0) * 1.2 / 40) });
const atk = sendTo(h, b, 0, 'attack', { script_crew: Math.ceil(staticHeld(h, 0, 0) * 1.2 / 40) });
assert.ok(atk.arriveAt < late.arriveAt, 'the attack gets there first');
h.advanceTo(late.arriveAt);
assert.equal(siteOf(h, 0).holder_alliance_id, h.B1);
assert.deepEqual(garrisonAt(h, 0), {}, 'an ex-holder\'s units do not join the new holder\'s garrison');
assert.equal(lastReport(h, a2, 'movement_failed').data.reason, 'not_holder');
h.advance(DAY);
assert.equal(T.units(h, a2.townId).blue_team, 100, 'they came home');
});
// ---------------------------------------------------------------- membership edges
test('leaving or being kicked from the alliance, or the alliance disbanding, sends the garrison home; so does losing the POP it belongs to', () => {
const h = scene();
const { a, a2, b } = h;
const m1 = sendTo(h, a, 0, 'reinforce', { soc_analyst: 300 });
const m2 = sendTo(h, a2, 0, 'reinforce', { blue_team: 60 });
h.advanceTo(Math.max(m1.arriveAt, m2.arriveAt));
const before = totals(h);
assert.deepEqual(garrisonAt(h, 0), { soc_analyst: 300, blue_team: 60 });
// a2 leaves: only her units go home
h.run('allianceLeave', { userId: a2.userId, allianceId: h.A1 });
assert.deepEqual(garrisonAt(h, 0), { soc_analyst: 300 });
assert.deepEqual(totals(h), before, 'in a return movement');
const rel = T.notes(h, a2.userId, 'garrison_released');
assert.equal(rel.length, 1);
assert.equal(rel[0].reason, 'left_alliance');
assert.deepEqual(rel[0].units, { blue_team: 60 });
h.advance(DAY);
assert.equal(T.units(h, a2.townId).blue_team, 100);
// a POP that changes hands: what it had in a site goes home to its OLD owner's other POP
const a3 = T.addTown(h, a, { n: 2 });
const ctx = h.ctx();
const m3 = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'reinforce', x: h.sites[0].x, y: h.sites[0].y, units: { soc_analyst: 50 } });
h.advanceTo(m3.arriveAt);
assert.equal(G.ownedAt(h.db, siteOf(h, 0).id, a.townId).soc_analyst, 350);
const combat = require('../server/military/combat');
const tb = loadTown(h.db, a.townId);
assert.ok(a3.townId);
combat.transferTown(h.ctx(), tb, { id: b.opId }, { id: a.opId }, h.clock.now());
assert.deepEqual(garrisonAt(h, 0), {}, 'nothing is left standing for a POP that no longer belongs to its owner');
const rel2 = T.notes(h, a.userId, 'garrison_released').pop();
assert.equal(rel2.reason, 'town_lost');
h.advance(DAY);
assert.equal(T.units(h, a3.townId).soc_analyst, 350, 'home to the old owner\'s remaining POP');
});
test('disbanding the holding alliance sends every garrison home and leaves the level with the site', () => {
const h = scene();
const { a, a2 } = h;
const m1 = sendTo(h, a, 0, 'reinforce', { soc_analyst: 300 });
const m2 = sendTo(h, a2, 0, 'reinforce', { blue_team: 60 });
h.advanceTo(Math.max(m1.arriveAt, m2.arriveAt));
h.db.run('UPDATE landing_sites SET level = 7 WHERE idx = 0');
const before = totals(h);
h.run('allianceDisband', { userId: a.userId, allianceId: h.A1 });
assert.deepEqual(garrisonAt(h, 0), {});
assert.equal(siteOf(h, 0).holder_alliance_id, null);
assert.equal(siteOf(h, 0).level, 7);
assert.deepEqual(totals(h), before);
assert.equal(T.notes(h, a.userId, 'garrison_released')[0].reason, 'alliance_dissolved');
h.advance(DAY);
assert.equal(T.units(h, a.townId).soc_analyst, 600);
assert.equal(T.units(h, a2.townId).blue_team, 100);
assert.equal(h.db.get('SELECT COUNT(*) AS n FROM site_stationed').n, 0);
});
// ---------------------------------------------------------------- power
test('power: garrison units draw their owner\'s power; with the owner POP out of power the group stops defending, and a won attack still wipes it', () => {
const h = scene();
const { b } = h;
const s0 = h.sites[0];
const weak = near(h, 'weak', 0, { x: s0.x - 6, y: s0.y - 3, power: 5, battery: 40, infra: { battery_bank: 1 }, units: { soc_analyst: 60 } });
A.addMember(h.db, h.A1, weak.opId, 'member', h.clock.now());
const mv = sendTo(h, weak, 0, 'reinforce', { soc_analyst: 60 });
h.advanceTo(mv.arriveAt);
const town = loadTown(h.db, weak.townId);
assert.equal(town.unitDraw, 60, 'the garrison is the owner\'s draw');
assert.ok(R.ratesPerHour(town).powerNet < 0, 'net power is negative: ' + JSON.stringify(R.ratesPerHour(town)));
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'powerCheck' AND status = 'pending' AND town_id = ?", weak.townId).n, 1, 'a power check is scheduled for the owner');
const emptyAt = R.batteryEmptyAt(town, h.clock.now());
assert.ok(emptyAt > h.clock.now());
const S = staticHeld(h, 0, 0);
// online: the group defends
assert.equal(G.defenders(h.db, siteOf(h, 0).id, emptyAt - 1000).groups[0].online, true);
assert.equal(G.defenders(h.db, siteOf(h, 0).id, emptyAt - 1000).power, 60 * 25);
// dry: offline, no defence value, and an attack that beats the static part takes the site although the group is there
h.advanceTo(emptyAt + 5000);
assert.equal(T.notes(h, weak.userId, 'units_offline').length, 1);
const d = G.defenders(h.db, siteOf(h, 0).id, h.clock.now());
assert.equal(d.groups[0].online, false);
assert.equal(d.power, 0);
const n = Math.ceil(1.1 * S / 40);
T.giveUnits(h, b.townId, { script_crew: n });
const atk = sendTo(h, b, 0, 'attack', { script_crew: n });
h.advanceTo(atk.arriveAt);
assert.equal(siteOf(h, 0).holder_alliance_id, h.B1, 'an attack that beats the static part only takes a site whose garrison is offline');
const rep = lastReport(h, b, 'landing').data;
assert.equal(rep.power.garrison, 0);
assert.equal(rep.defender.garrison[0].offline, true);
assert.equal(G.ownedAt(h.db, siteOf(h, 0).id, weak.townId).soc_analyst || 0, 0, 'a won attack wipes offline units too');
});
// ---------------------------------------------------------------- the opening scramble is unchanged
test('an unheld site keeps its heavy static defence (the opening scramble), a held one drops to heldDefenceMult', () => {
const h = scene();
const open = staticHeld(h, 1, 0, false), held = staticHeld(h, 1, 0, true);
assert.equal(open, R.backboneDefence(h.world.seed, h.sites[1].x, h.sites[1].y, 100, 0));
assert.ok(open / held >= D.ENDGAME.defenceMult / D.ENDGAME.heldDefenceMult - 0.01);
// a scan of the unheld site 1 shows the heavy number, a scan of the held site 0 the light one
const c = near(h, 'scout', 1, { units: { port_scanner: 300 } });
const mv = sendTo(h, c, 1, 'scan', { port_scanner: 300 });
h.advanceTo(mv.arriveAt);
assert.equal(lastReport(h, c, 'scan').data.intel.defence, open);
});
test('power: decommission takes units out of the garrison, partly, until the draw fits the output', () => {
const h = scene();
const s0 = h.sites[0];
const weak = near(h, 'weak', 0, { x: s0.x - 6, y: s0.y - 3, power: 5, battery: 40, infra: { battery_bank: 1 }, units: { soc_analyst: 60 } });
A.addMember(h.db, h.A1, weak.opId, 'member', h.clock.now());
const mv = sendTo(h, weak, 0, 'reinforce', { soc_analyst: 60 });
h.advanceTo(mv.arriveAt);
const emptyAt = R.batteryEmptyAt(loadTown(h.db, weak.townId), h.clock.now());
h.advanceTo(emptyAt + 5000);
const since = h.db.get('SELECT offline_since FROM town_power WHERE town_id = ?', weak.townId).offline_since;
h.advanceTo(since + R.decommissionMs(1) + 1000);
const left = G.ownedAt(h.db, siteOf(h, 0).id, weak.townId).soc_analyst || 0;
assert.ok(left > 0 && left < 60, 'partly decommissioned: ' + left);
const t1 = loadTown(h.db, weak.townId);
const base = R.ratesPerHour(Object.assign({}, t1, { unitDraw: 0 }));
assert.ok(t1.unitDraw <= base.powerOut - base.powerDraw + 1e-9, 'the draw fits the output again');
assert.equal(T.units(h, weak.townId).soc_analyst, undefined, 'it was the garrison that was decommissioned, nothing at home to take');
assert.equal(T.notes(h, weak.userId, 'units_decommissioned').length, 1);
});
test('kicking a member sends her units home from the site', () => {
const h = scene();
const { a, a2 } = h;
const m = sendTo(h, a2, 0, 'reinforce', { blue_team: 40 });
h.advanceTo(m.arriveAt);
assert.deepEqual(garrisonAt(h, 0), { blue_team: 40 });
h.run('allianceKick', { userId: a.userId, allianceId: h.A1, operatorId: a2.opId });
assert.deepEqual(garrisonAt(h, 0), {});
assert.equal(T.notes(h, a2.userId, 'garrison_released')[0].reason, 'left_alliance');
h.advance(DAY);
assert.equal(T.units(h, a2.townId).blue_team, 100);
});
// ---------------------------------------------------------------- the capture shield
test('a site that changed hands is shielded for captureShieldHours (world hours / speed): attacks are refused or turned back, scans and garrisons are not', () => {
const h = scene();
const { a, b } = h;
const s0 = h.sites[0];
const S = staticHeld(h, 0, 0);
const n = Math.ceil(1.3 * S / 40);
const c = near(h, 'charlie', 0, { x: s0.x, y: s0.y + 6, units: { script_crew: 4 * n, port_scanner: 5 } });
alliance(h, 'Charlie', c);
T.giveUnits(h, b.townId, { script_crew: n });
// charlie's strike is on the road when bob takes the site (she lives further away)
const early = sendTo(h, c, 0, 'attack', { script_crew: 2 * n });
const atk = sendTo(h, b, 0, 'attack', { script_crew: n });
assert.ok(atk.arriveAt < early.arriveAt);
h.advanceTo(atk.arriveAt);
const site = siteOf(h, 0);
assert.equal(site.holder_alliance_id, h.B1);
const until = R.siteShieldUntil(site.taken_at, 1);
assert.equal(until, site.taken_at + D.ENDGAME.captureShieldHours * H);
assert.equal(h.eg.status(a.userId, h.worldId).sites[0].shieldUntil, until);
// refused at the door ...
const e = err(() => sendTo(h, c, 0, 'attack', { script_crew: n }));
assert.equal(e.code, 'invalid_target');
assert.equal(e.details.reason, 'site_shielded');
assert.equal(e.details.until, until);
// ... and one already on the road is turned back (its units come home)
h.advanceTo(early.arriveAt);
assert.equal(siteOf(h, 0).holder_alliance_id, h.B1, 'the strike bounced');
assert.equal(lastReport(h, c, 'movement_failed').data.reason, 'site_shielded');
// scanning and garrisoning are fine during the shield
assert.ok(sendTo(h, c, 0, 'scan', { port_scanner: 5 }).movementId);
T.giveUnits(h, b.townId, { soc_analyst: 5 });
assert.ok(sendTo(h, b, 0, 'reinforce', { soc_analyst: 5 }).movementId);
// the shield ends on time, to the millisecond
h.advanceTo(until - 1);
assert.equal(err(() => sendTo(h, c, 0, 'attack', { script_crew: n })).details.reason, 'site_shielded');
h.advanceTo(until);
assert.ok(sendTo(h, c, 0, 'attack', { script_crew: n }).movementId);
// unheld sites never have one: the opening scramble is first come, first served
assert.ok(sendTo(h, c, 1, 'attack', { script_crew: n }).movementId);
});
test('the shield is world time: at speed 2 it lasts half as long', () => {
assert.equal(R.siteShieldUntil(1000, 1) - 1000, D.ENDGAME.captureShieldHours * H);
assert.equal(R.siteShieldUntil(1000, 2) - 1000, D.ENDGAME.captureShieldHours * H / 2);
assert.equal(R.siteShieldUntil(null, 1), 0);
});

View file

@ -31,6 +31,7 @@ test('trade legs cannot be recalled (either side could otherwise keep both halve
for (const u of [a, b]) t.setBuilding(u.townId, 'internet_exchange', 3);
const made = await t.api('/trade/offers', { method: 'POST', body: { townId: a.townId, giveRes: 'fiber', giveAmount: 400, wantRes: 'hardware', wantAmount: 300, maxDistance: 60 } }, a.token);
assert.equal(made.status, 201, JSON.stringify(made.body));
t.srv.db.run('UPDATE towns SET fiber = 0 WHERE id = ?', b.townId); // room for the goods (accept refuses a full hall)
const acc = await t.api('/trade/offers/' + made.body.offer.id + '/accept', { method: 'POST', body: { townId: b.townId } }, b.token);
assert.equal(acc.status, 201, JSON.stringify(acc.body));
const legs = t.srv.db.all("SELECT id, owner_id FROM movements WHERE type = 'transport' AND status = 'out'");

View file

@ -43,6 +43,12 @@ test('trade API: post, list, take, mine, detail, cancel, errors', async () => {
const one = await t.api('/trade/offers/' + id, {}, c.token);
assert.equal(one.body.offer.status, 'open', 'open offers are public inside the world');
// a full Rack hall cannot take the goods: refused up front instead of destroying them on arrival
t.srv.db.run('UPDATE towns SET fiber = 1000000 WHERE id = ?', b.townId);
const full = await t.api('/trade/offers/' + id + '/accept', { method: 'POST', body: { townId: b.townId } }, b.token);
assert.equal(full.status, 409); assert.equal(full.body.error.code, 'no_room_for_goods');
assert.equal(t.srv.db.get('SELECT status FROM trade_offers WHERE id = ?', id).status, 'open', 'nothing happened');
t.srv.db.run('UPDATE towns SET fiber = 0 WHERE id = ?', b.townId);
const acc = await t.api('/trade/offers/' + id + '/accept', { method: 'POST', body: { townId: b.townId } }, b.token);
assert.equal(acc.status, 201);
assert.equal(acc.body.status, 'accepted');

View file

@ -174,10 +174,11 @@ test('trade: an offer expires after its ttl (divided by world speed) and returns
test('trade: a delivery above the receiver\'s storage cap loses exactly the overflow (and says so); the rest is conserved', () => {
const { h, a, b } = traders({ bInfra: { rack_hall: 1 } }); // cap 1000
h.db.run('UPDATE towns SET fiber = 900 WHERE id = ?', b.townId);
const before = total(h);
h.db.run('UPDATE towns SET fiber = 500 WHERE id = ?', b.townId);
const offer = post(h, a, a.townId);
const acc = h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId });
const acc = h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId }); // room for the 400 at accept time ...
h.db.run('UPDATE towns SET fiber = 900 WHERE id = ?', b.townId); // ... but the hall fills up on the road
const before = total(h);
h.advanceTo(acc.arriveAt);
assert.equal(stock(h, b.townId).fiber, 1000);
const arrived = T.notes(h, b.userId, 'transport_arrived')[0];
@ -186,6 +187,22 @@ test('trade: a delivery above the receiver\'s storage cap loses exactly the over
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'completed');
});
test('trade: accepting into a hall with no room for the goods is refused up front (no_room_for_goods); cargo already on its way counts', () => {
const { h, a, b } = traders({ bInfra: { rack_hall: 1 } }); // cap 1000
h.db.run('UPDATE towns SET fiber = 900 WHERE id = ?', b.townId);
const offer = post(h, a, a.townId); // gives 400 fiber
const before = total(h);
const e = err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId }));
assert.equal(e.code, 'no_room_for_goods');
assert.equal(e.details.room, 100);
assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'open');
assert.equal(h.db.get("SELECT COUNT(*) AS n FROM movements WHERE status = 'out'").n, 0, 'rolled back: no payment left either');
assert.equal(total(h), before);
h.db.run('UPDATE towns SET fiber = 500 WHERE id = ?', b.townId);
h.db.run("INSERT INTO movements (world_id, owner_id, type, from_town_id, to_town_id, from_x, from_y, to_x, to_y, units, cargo, depart_at, arrive_at, status, extra, created_at) SELECT world_id, owner_id, 'transport', id, id, x, y, x, y, '{}', '{\"fiber\":200}', 0, 9e15, 'out', '{}', 0 FROM towns WHERE id = ?", b.townId);
assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })).code, 'no_room_for_goods', '500 + 200 on its way + 400 > 1000');
});
test('trade: a POP that changes hands voids its open offers; the escrow stays in the POP', () => {
const { h, a, b } = traders();
const offer = post(h, a, a.townId);

View file

@ -0,0 +1,72 @@
'use strict';
/* Transport capacity scales with world speed (docs/BALANCE.md B7): trips are per sitting, not per hour, so a link carries
* capacityPerLink x speed. One function (rules.transportCapacity) is the only reader of the constant; commands, trade terms and the
* client's numbers (the `transport` block of a POP view) all go through it. Fake clock, in-memory db. */
const test = require('node:test');
const assert = require('node:assert');
const T = require('./military-helpers');
const { R, D } = T;
const err = (fn) => { try { fn(); } catch (e) { return e; } assert.fail('expected an error'); };
const CAP = D.TRANSPORT.capacityPerLink;
test('transportCapacity: capacityPerLink x speed, read at call time', () => {
assert.equal(R.transportCapacity(1), CAP);
assert.equal(R.transportCapacity(3), 3 * CAP);
assert.equal(R.transportCapacity(0.5), Math.round(CAP / 2));
assert.equal(R.transportCapacity(10), 10 * CAP);
assert.equal(R.transportCapacity(), CAP, 'no speed = 1x');
const keep = D.TRANSPORT.capacityPerLink;
D.TRANSPORT.capacityPerLink = 250;
try { assert.equal(R.transportCapacity(4), 1000); } finally { D.TRANSPORT.capacityPerLink = keep; }
});
test('transportPlan and tradeTermsCheck use the world speed', () => {
const town = { speed: 3, buildings: { internet_exchange: { type: 'internet_exchange', level: 2 } }, res: { fiber: 9000, hardware: 9000, capital: 9000, battery: 0 }, updatedAt: 0, unitDraw: 0, footprint: 0 };
town.buildings.rack_hall = { type: 'rack_hall', level: 20 };
const plan = (n, speed) => R.transportPlan(Object.assign({}, town, { speed }), { fiber: n }, 0, 0);
assert.notEqual(plan(3 * CAP, 3).code, 'capacity_exceeded');
assert.equal(plan(3 * CAP + 1, 3).code, 'capacity_exceeded');
assert.equal(plan(3 * CAP + 1, 3).capacity, 3 * CAP);
assert.equal(plan(CAP + 1, 1).code, 'capacity_exceeded', 'a 1x world is as before');
const terms = (n, speed) => R.tradeTermsCheck({ giveRes: 'fiber', giveAmount: n, wantRes: 'hardware', wantAmount: n, maxDistance: 10 }, speed);
assert.equal(terms(3 * CAP, 3).ok, true);
assert.equal(terms(3 * CAP + 1, 3).code, 'capacity_exceeded');
assert.equal(terms(3 * CAP, 1).code, 'capacity_exceeded');
assert.equal(terms(CAP).ok, true, 'speed defaults to 1');
});
test('server: a 3x world sends, ships and trades up to three times the 1x capacity; the POP view reports the real number', () => {
const h = T.setup({ speed: 3 });
const a = T.addOperator(h, 'sender', { x: 5, y: 0, infra: { internet_exchange: 2, rack_hall: 20 }, res: 20000 });
const b = T.addOperator(h, 'receiver', { x: 9, y: 0, infra: { rack_hall: 20 } });
const send = (n) => h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo: { fiber: n } });
assert.equal(err(() => send(3 * CAP + 1)).code, 'capacity_exceeded');
assert.equal(h.queries.town(a.userId, a.townId).town.military.transport.capacityPerLink, 3 * CAP);
const mv = send(3 * CAP);
assert.equal(mv.cargo.fiber, 3 * CAP);
const offer = h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'hardware', giveAmount: 2 * CAP, wantRes: 'capital', wantAmount: 2 * CAP, maxDistance: 30 }).offer;
assert.equal(offer.give.amount, 2 * CAP, 'an offer may fill a whole 3x transport');
assert.equal(err(() => h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'hardware', giveAmount: 3 * CAP + 1, wantRes: 'capital', wantAmount: 3 * CAP + 1, maxDistance: 30 })).code, 'capacity_exceeded');
// the same send in a 1x world is refused
const h1 = T.setup({ speed: 1 });
const a1 = T.addOperator(h1, 'sender', { x: 5, y: 0, infra: { internet_exchange: 2, rack_hall: 20 }, res: 20000 });
const b1 = T.addOperator(h1, 'receiver', { x: 9, y: 0 });
assert.equal(err(() => h1.run('sendTransport', { userId: a1.userId, fromTownId: a1.townId, toTownId: b1.townId, cargo: { fiber: 3 * CAP } })).code, 'capacity_exceeded');
});
test('no file outside rules.js and data.js reads TRANSPORT.capacityPerLink directly (a constant read bypasses the world speed)', () => {
const fs = require('fs'), path = require('path');
const root = path.join(__dirname, '..');
const hits = [];
const walk = (dir) => {
for (const f of fs.readdirSync(dir, { withFileTypes: true })) {
if (f.name === 'node_modules' || f.name === '.git' || f.name === 'test' || f.name === 'e2e' || f.name === 'docs') continue;
const p = path.join(dir, f.name);
if (f.isDirectory()) walk(p);
else if (/\.js$/.test(f.name) && /TRANSPORT\.capacityPerLink/.test(fs.readFileSync(p, 'utf8'))) hits.push(path.relative(root, p));
}
};
walk(root);
assert.deepEqual(hits.filter((p) => !/^public\/js\/(rules|data)\.js$/.test(p)), []);
});