#!/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-contest end game: no garrisons (holders do not station defenders at their site) and no coordinated waves (one striker * per site, as before E6); pair with --set ENDGAME.heldDefenceMult=12 to get the pre-E6 world back * --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 '--no-contest': o.contest = 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();