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

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

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

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

126 lines
8.2 KiB
JavaScript

#!/usr/bin/env node
'use strict';
/*
* UPSTREAM bot harness: N headless players against the REAL server code, in-process, on a fake clock.
*
* node tools/bot.js --players 50 --days 14 --speed 1 [--seed 1] [--strategy-mix builder:12,raider:8,...] [--json out.json]
*
* Options
* --players N bots (default 50) --days N simulated days (default 14)
* --speed X world speed (default 1) --seed N world + bot seed (default 1)
* --radius N map radius in tiles (default: data.js WORLD_DEFAULTS.mapRadius)
* --strategy-mix M e.g. builder:12,raider:8,conqueror:3,turtle:6,expander:8,trader:6,alliancer:7 (default: a mix of all)
* --sessions-per-day N every bot plays N short sessions a day (default: per archetype, 3-5)
* --always-on every bot acts every --step-min minutes (upper bound of what attention could do)
* --step-min N tick of --always-on (default 10) --join-days N joining spread over the first N days (default 2)
* --session-min N length of a sitting in minutes (default 5; the first one 20, --first-session-min): a bot whose build
* finishes inside its sitting starts the next one, so cheap early builds chain, long ones do not
* --endgame-step-min N once the landing sites are open, members of alliances that chase the backbone also act every N minutes
* (a final push with high attention; default 0 = off, normal sessions only) --endgame-min-members N (default 3)
* --field-policy P marginal (default: keep the production mix at the ratio the player spends, upgrade whatever lags) or balanced
* (all fields level up together; a lower bound of player skill)
* --no-adapt bots do not answer raids with more defence (default: after being hit a bot trains defence up to 1.25 x the
* strongest attack it saw, for 5 days; an upper bound of how defenders react)
* --sample-min N economy sampling interval (default 120)
* --set A.B.c=V override a data.js value for this run (repeatable, value is JSON), e.g. --set FORMULAS.costGrowth=1.25
* Only values the code reads at call time are reached; a constant copied at require time (e.g.
* ENDGAME.scanStrength in military/landing.js) is silently not overridden.
* --json FILE write the full stats as JSON --quiet print only the verdict line --progress progress dots
* --exit-0 never exit non-zero (default: exit 1 when an invariant breaks, 2 on usage errors)
*
* How it drives the server: srv.commands.run(name, args) - the function every REST route calls - so validation, transactions,
* events and notifications are the real ones; HTTP, JSON and scrypt are skipped to keep 50 players x 30 days in well under a
* minute. Bots read state through the server's own modules and use rules.js previews; they cannot change anything except by
* command. Determinism: every choice comes from a generator seeded with (seed, bot, purpose); the same options give the same stats
* (wall-clock numbers under `perf` excepted).
*/
const path = require('path');
const D = require('../public/js/data.js');
function parseArgs(argv) {
const o = { players: 50, days: 14, speed: 1, seed: 1, radius: D.WORLD_DEFAULTS.mapRadius, mix: '', sessionsPerDay: 0, alwaysOn: false, stepMin: 10, joinDays: 2, sampleMin: 120, sessionMin: 5, firstSessionMin: 20, endgameMinMembers: 3, endgameStepMin: 0, adapt: true, fieldPolicy: 'marginal', set: [], json: null, quiet: false, progress: false, exit0: false };
const need = (i, k) => { if (i + 1 >= argv.length) throw new Error('missing value for ' + k); return argv[i + 1]; };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
const num = (k) => { const v = Number(need(i, k)); if (!Number.isFinite(v)) throw new Error(k + ' needs a number'); i++; return v; };
switch (a) {
case '--players': o.players = num(a); break;
case '--days': o.days = num(a); break;
case '--speed': o.speed = num(a); break;
case '--seed': o.seed = num(a); break;
case '--radius': o.radius = num(a); break;
case '--strategy-mix': o.mix = need(i, a); i++; break;
case '--sessions-per-day': o.sessionsPerDay = num(a); break;
case '--always-on': o.alwaysOn = true; break;
case '--step-min': o.stepMin = num(a); break;
case '--join-days': o.joinDays = num(a); break;
case '--sample-min': o.sampleMin = num(a); break;
case '--session-min': o.sessionMin = num(a); break;
case '--first-session-min': o.firstSessionMin = num(a); break;
case '--endgame-min-members': o.endgameMinMembers = num(a); break;
case '--endgame-step-min': o.endgameStepMin = num(a); break;
case '--no-adapt': o.adapt = false; break;
case '--field-policy': o.fieldPolicy = need(i, a); i++; if (['marginal', 'balanced'].indexOf(o.fieldPolicy) < 0) throw new Error('--field-policy is marginal or balanced'); break;
case '--set': o.set.push(need(i, a)); i++; break;
case '--json': o.json = need(i, a); i++; break;
case '--quiet': o.quiet = true; break;
case '--progress': o.progress = true; break;
case '--exit-0': o.exit0 = true; break;
case '-h': case '--help': o.help = true; break;
default: throw new Error('unknown option ' + a);
}
}
if (!(o.players >= 1) || !(o.days > 0) || !(o.speed > 0)) throw new Error('players, days and speed must be positive');
return o;
}
// "FORMULAS.costGrowth=1.25" -> mutate the shared data module in place; returns a function that puts everything back.
function applyOverrides(list) {
const undo = [];
for (const spec of list || []) {
const eq = spec.indexOf('=');
if (eq < 0) throw new Error('--set needs PATH=VALUE: ' + spec);
const keys = spec.slice(0, eq).split('.');
let value;
try { value = JSON.parse(spec.slice(eq + 1)); } catch (e) { throw new Error('--set value must be JSON: ' + spec); }
let node = D;
for (let i = 0; i < keys.length - 1; i++) {
if (!node || typeof node[keys[i]] !== 'object') throw new Error('--set: no such path ' + spec.slice(0, eq));
node = node[keys[i]];
}
const last = keys[keys.length - 1];
if (!node || !(last in node)) throw new Error('--set: no such path ' + spec.slice(0, eq));
const old = node[last];
node[last] = value;
undo.push(() => { node[last] = old; });
}
return () => { for (let i = undo.length - 1; i >= 0; i--) undo[i](); };
}
// Library entry (used by the test): runBot({players, days, speed, seed, ...}) -> stats. Overrides are undone afterwards.
async function runBot(opts) {
const o = Object.assign({ players: 50, days: 14, speed: 1, seed: 1, radius: D.WORLD_DEFAULTS.mapRadius, mix: '', sessionsPerDay: 0, alwaysOn: false, stepMin: 10, joinDays: 2, sampleMin: 120, sessionMin: 5, firstSessionMin: 20, endgameMinMembers: 3, endgameStepMin: 0, adapt: true, fieldPolicy: 'marginal', set: [] }, opts || {});
const restore = applyOverrides(o.set);
try {
const { runSim } = require('./bot/sim');
return await runSim(o);
} finally { restore(); }
}
async function main() {
let o;
try { o = parseArgs(process.argv.slice(2)); } catch (e) { console.error('tools/bot.js: ' + e.message + ' (see --help)'); process.exit(2); }
if (o.help) { console.log(require('fs').readFileSync(__filename, 'utf8').split('*/')[0].replace(/^#!.*\n/, '').replace(/^'use strict';\n/, '').replace(/^\/\*\n?/, '')); return; }
if (o.progress) o.progress = (d, n) => process.stderr.write(d % 10 === 0 ? ' ' + d + '/' + n + '\n' : '.');
let stats;
try { stats = await runBot(o); } catch (e) { console.error('bot run failed: ' + (e && e.stack || e)); process.exit(2); }
if (o.json) { require('fs').writeFileSync(path.resolve(o.json), JSON.stringify(stats, null, 1)); }
const verdict = stats.invariants.ok ? 'INVARIANTS OK' : 'INVARIANTS BROKEN';
if (o.quiet) console.log(verdict + ' (' + stats.perf.wallSeconds + ' s, ' + stats.perf.commands + ' commands)');
else { console.log(require('./bot/report').render(stats)); console.log('\n' + verdict); }
if (!stats.invariants.ok && !o.exit0) process.exit(1);
}
module.exports = { runBot, parseArgs, applyOverrides };
if (require.main === module) main();