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

View file

@ -28,6 +28,8 @@ const { FakeClock } = require(path.join(ROOT, 'server', 'clock.js'));
const HOUR = 3600 * 1000;
const DAY = 24 * HOUR;
let stdoutClosed = false; // set when stdout was a pipe that went away (EPIPE)
class AdminError extends Error {
constructor(message, code) { super(message); this.exitCode = code || 1; }
}
@ -358,14 +360,64 @@ commands['create-world'] = (args, ctx) => {
return { data: { world: w }, lines: ['created world ' + id + ' "' + w.name + '" speed ' + w.speed + ', radius ' + w.map_radius + ', seed ' + w.seed + (endAt ? ', planned end ' + iso(endAt) : '')] };
};
// End a world the way the natural end does: the real `worldEnd` event handler (server/events/worldEnd.js) runs, so the final ranking
// snapshot is written (GET /worlds/:id/results becomes available:true), open trade offers are closed with their escrow returned,
// every other pending event of the world is cancelled, status becomes 'ended' and every operator gets a `world_ended` notification.
// Events of this world that were already due are processed first, in order (like the server's catch-up), so nothing that had
// happened by now is lost; handlers run through a guard that skips an event another process has finished meanwhile.
function endWorldNow(db, ctx, world) {
const { Scheduler } = require(path.join(ROOT, 'server', 'scheduler.js'));
const handlers = require(path.join(ROOT, 'server', 'events'));
const guarded = {};
for (const type of Object.keys(handlers)) {
guarded[type] = (c, ev) => {
const cur = c.db.get('SELECT status FROM events WHERE id = ?', ev.id);
if (cur && cur.status !== 'pending') return; // the running server got there first (we are inside BEGIN IMMEDIATE: no race)
return handlers[type](c, ev);
};
}
const now = ctx.now();
const logs = [];
const sched = new Scheduler({ db, clock: { now: () => now }, handlers: guarded, log: (m) => logs.push(String(m).split('\n')[0]), autoArm: false });
let caughtUp = 0;
for (;;) {
const ev = db.get("SELECT * FROM events WHERE world_id = ? AND status = 'pending' AND due_at <= ? AND type != 'worldEnd' ORDER BY due_at, id LIMIT 1", world.id, now);
if (!ev) break;
sched.process(ev);
caughtUp++;
}
const evId = db.tx(() => sched.enqueue({ worldId: world.id, dueAt: now, type: 'worldEnd', payload: { reason: 'admin' } }));
sched.process(db.get('SELECT * FROM events WHERE id = ?', evId));
const ev = db.get('SELECT status, error FROM events WHERE id = ?', evId);
if (ev.status !== 'done') throw new AdminError('the worldEnd event failed (' + (ev.error || ev.status) + '); nothing was ended. Handler log: ' + logs.join(' | '));
return { caughtUp, logs };
}
commands['end-world'] = (args, ctx) => {
const id = idArg(args, 'world-id');
const db = openDatabase(ctx);
const w = worldOrThrow(db, id);
if (w.status === 'ended') return { data: { id, status: 'ended', changed: false }, lines: ['world ' + id + ' is already ended'] };
requireFlag(args, 'yes', 'ending world ' + id + ' ("' + w.name + '") stops signups and new joins');
db.tx(() => db.run("UPDATE worlds SET status = 'ended', end_at = ? WHERE id = ?", ctx.now(), id));
return { data: { id, status: 'ended', changed: true }, lines: ['world ' + id + ' ended'] };
if (w.status === 'ended') {
const ranked = !!(tableExists(db, 'world_rankings') && db.get('SELECT 1 AS x FROM world_rankings WHERE world_id = ?', id));
return { data: { id, status: 'ended', changed: false, ranking: ranked }, lines: ['world ' + id + ' is already ended' + (ranked ? '' : ' (no final ranking snapshot: it was ended by an older version of this command; /results stays unavailable)')] };
}
const pending = db.get("SELECT COUNT(*) AS n FROM events WHERE world_id = ? AND status = 'pending'", id).n;
const offers = tableExists(db, 'trade_offers') ? db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE world_id = ? AND status = 'open'", id).n : 0;
requireFlag(args, 'yes', 'ending world ' + id + ' ("' + w.name + '") freezes it for good: it writes the final ranking, closes ' + offers + ' open trade offer(s), ' +
'cancels the world\'s ' + pending + ' pending event(s) (movements, training, builds still in progress stop) and every game command then answers world_ended');
const before = { pending, offers };
const { caughtUp } = endWorldNow(db, ctx, w);
const after = worldOrThrow(db, id);
const snap = db.get('SELECT data FROM world_rankings WHERE world_id = ?', id);
const top = snap ? JSON.parse(snap.data) : null;
const cancelled = Number(db.get("SELECT COUNT(*) AS n FROM events WHERE world_id = ? AND status = 'cancelled' AND done_at = ?", id, after.end_at).n);
const data = { id, status: after.status, changed: true, endedAt: after.end_at, caughtUpFirst: caughtUp, cancelledEvents: cancelled, closedOffers: before.offers,
ranking: !!top, operators: top ? top.totals.operators : 0, alliances: top ? top.totals.alliances : 0 };
const lines = ['world ' + id + ' ended at ' + iso(after.end_at) + ' (event worldEnd, reason admin)',
'final ranking stored: ' + (top ? top.totals.operators + ' operator(s), ' + top.totals.alliances + ' alliance(s); GET /worlds/' + id + '/results is available' : 'NO'),
'processed ' + caughtUp + ' overdue event(s) first, cancelled ' + cancelled + ' pending event(s), closed ' + before.offers + ' open trade offer(s)',
'players are told through their notifications (a running server pushes nothing for rows written by the CLI: clients see world_ended on their next request)'];
return { data, lines };
};
commands.users = (args, ctx) => {
@ -655,7 +707,7 @@ const HELP_CMDS = {
migrate: 'apply pending migrations (the server does this at boot too; creates the file if missing)',
worlds: 'list worlds',
'create-world': '[--name N] [--speed X] [--radius R] [--seed S] [--end-in 90d] new world (a second one runs in parallel)',
'end-world': '<world-id> --yes mark a world ended (no new signups/joins)',
'end-world': '<world-id> --yes end a world like the natural end: final ranking, trade escrow back, pending events cancelled',
users: '[--banned] list accounts (no hashes, no tokens)',
operators: '[--world ID] list operators (a user in a world)',
ban: '<username> ban and revoke all tokens; login answers 403',
@ -689,7 +741,7 @@ function helpText() {
// main(argv, io) -> exit code. io = { out, err, env, cwd, now } (all optional, for tests).
function main(argv, io) {
io = io || {};
const out = io.out || ((s) => process.stdout.write(s + '\n'));
const out = io.out || ((s) => { if (!stdoutClosed) process.stdout.write(s + '\n'); });
const err = io.err || ((s) => process.stderr.write(s + '\n'));
const env = io.env || process.env;
const ctx = { opened: [], cwd: io.cwd || process.cwd(), now: io.now || (() => Date.now()), dbPath: null };
@ -716,4 +768,9 @@ function main(argv, io) {
module.exports = { main, commands, parseArgs, parseTime, parseDuration, listBackups, pruneSet, backupStamp, verifySnapshot, doBackup, resetPlan, table, AdminError };
if (require.main === module) process.exitCode = main(process.argv.slice(2));
if (require.main === module) {
// `admin.js events | head`: a closed pipe is not an error worth a stack trace. The error event is swallowed (the process finishes
// normally and keeps its exit code); `stdoutClosed` stops later writes when the event arrives before the output is done.
process.stdout.on('error', (e) => { if (e && e.code === 'EPIPE') stdoutClosed = true; else throw e; });
process.exitCode = main(process.argv.slice(2));
}

View file

@ -19,6 +19,8 @@
* (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)
@ -60,6 +62,7 @@ function parseArgs(argv) {
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;

View file

@ -93,7 +93,7 @@ class Bot {
this.firstAllianceTry = 0;
this.incCache = null;
this.takeoverTargets = new Map();
this.armyOverride = 0; this.egForce = null;
this.armyOverride = 0; this.egForce = null; this.egDefTarget = 0;
}
// ------------------------------------------------------------------ session schedule (human cadence)
@ -164,7 +164,7 @@ class Bot {
if (!sec && this.egForce) for (const type of Object.keys(this.egForce)) if (view.level(t, type) < this.egForce[type]) out.push({ key: type, type });
// a store that keeps hitting its cap is the first thing a player fixes
const cur = R.resourcesAt(t, now);
if (RES.every((r) => cur.amounts[r] >= 0.8 * cur.caps.fiber) && !busy.has('rack_hall') && view.level(t, 'rack_hall') < Math.min(20, Math.max(2, F + 1))) out.push({ key: 'rack_hall', type: 'rack_hall' });
if (RES.every((r) => cur.amounts[r] >= 0.8 * R.storageCap(t)) && !busy.has('rack_hall') && view.level(t, 'rack_hall') < Math.min(20, Math.max(2, F + 1))) out.push({ key: 'rack_hall', type: 'rack_hall' });
const order = sec ? ['core_router', 'rack_hall', 'battery_bank'] : this.arch.order;
for (const type of order) {
const tgt = sec ? Math.min(this.target(type, F), 6) : this.target(type, F);
@ -186,7 +186,7 @@ class Bot {
// level the other fields are at; substations only when power is short (or units are wanted).
pickFieldMarginal(t, fields, now) {
const rates = R.ratesPerHour(t);
const unitsWanted = this.arch.armyDays > 0 || this.arch.defDays > 0.5 || !!this.armyOverride;
const unitsWanted = this.arch.armyDays > 0 || this.arch.defDays > 0.5 || !!this.armyOverride || !!this.egDefTarget;
const lowest = (type) => fields.filter((f) => f.type === type && f.level < 20).sort((a, b) => a.level - b.level || (a.key < b.key ? -1 : 1))[0];
if (rates.powerNet < 4 + 0.04 * rates.powerOut && (unitsWanted || rates.powerNet < 2)) {
const s = lowest('substation');
@ -209,7 +209,7 @@ class Bot {
const w = this.arch.weights;
const rates = R.ratesPerHour(t);
const power = rates.powerNet;
const unitsWanted = this.arch.armyDays > 0 || this.arch.defDays > 0.5 || !!this.armyOverride;
const unitsWanted = this.arch.armyDays > 0 || this.arch.defDays > 0.5 || !!this.armyOverride || !!this.egDefTarget;
const lag = fields.filter((f) => f.level === F);
if (!lag.length) return null;
// power first when it is short and units are on the way
@ -248,7 +248,7 @@ class Bot {
const pending = view.pendingBuilds(t.id);
if (pending.length >= R.queueSlots(t)) break;
const cur = R.resourcesAt(t, now);
const cap = cur.caps.fiber;
const cap = R.storageCap(t);
const overflow = RES.some((r) => cur.amounts[r] >= 0.9 * cap);
let acted = false;
const list = this.wishes(t, now, new Set(pending.map((p) => p.key)));
@ -615,7 +615,7 @@ class Bot {
if (lvl < 1) continue;
let t = t0;
const cur = R.resourcesAt(t, now);
const cap = cur.caps.fiber;
const cap = R.storageCap(t);
const fill = {}; for (const r of RES) fill[r] = cur.amounts[r] / cap;
const sorted = RES.slice().sort((a, b) => fill[b] - fill[a]);
const surplus = sorted[0], deficit = sorted[2];
@ -638,9 +638,9 @@ class Bot {
// post one of our own (one open offer per POP at a time)
const open = db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE town_id = ? AND status = 'open'", t.id).n;
if (open >= 1) continue;
const give = Math.min(D.TRANSPORT.capacityPerLink, Math.floor((cur.amounts[surplus] - 0.4 * cap) * 0.6));
const give = Math.min(R.transportCapacity(this.sim.world.speed), Math.floor((cur.amounts[surplus] - 0.4 * cap) * 0.6));
if (give < 100) continue;
const want = Math.min(D.TRANSPORT.capacityPerLink, Math.max(50, Math.floor(give * (0.9 + this.rng() * 0.2))));
const want = Math.min(R.transportCapacity(this.sim.world.speed), Math.max(50, Math.floor(give * (0.9 + this.rng() * 0.2))));
const r = this.call('tradeOffer', { townId: t.id, giveRes: surplus, giveAmount: give, wantRes: deficit, wantAmount: want, maxDistance: Math.max(10, Math.min(reach, 40)) });
if (r.ok) this.log.offers += 1;
}

View file

@ -24,12 +24,12 @@ class Collector {
this.unitsLost = {}; // unit -> count, every way of losing units that the ledger knows about
this.unitsConsumed = {}; // crews/teams used up (not battle losses)
this.byType = {}; // report type -> count
this.battles = { raid: { n: 0, att: 0, loot: 0, lootRes: { fiber: 0, hardware: 0, capital: 0 }, attLost: 0, defLost: 0 }, attack: { n: 0, att: 0, loot: 0, attLost: 0, defLost: 0 }, takeover: { n: 0, att: 0, loot: 0, attLost: 0, defLost: 0 } };
this.battles = { raid: { n: 0, att: 0, loot: 0, lootRes: { fiber: 0, hardware: 0, capital: 0 }, lootLeft: { fiber: 0, hardware: 0, capital: 0 }, emptyWins: 0, attLost: 0, defLost: 0 }, attack: { n: 0, att: 0, loot: 0, attLost: 0, defLost: 0 }, takeover: { n: 0, att: 0, loot: 0, attLost: 0, defLost: 0 } };
this.raidSamples = []; // { loot, attLostValue, defLostValue, A, D, win, targetAgeDays, undefended }
this.takeovers = { attempted: 0, dropped: 0, blocked: {}, captured: 0, loyaltyDropped: 0 };
this.scans = { n: 0, ok: 0, failed: 0, detected: 0, revealed: 0 };
this.incumbent = { n: 0, wins: 0, hardware: 0, attLostValue: 0 };
this.landing = { n: 0, taken: 0, attLostValue: 0 };
this.landing = { n: 0, taken: 0, attLostValue: 0, vsHeld: 0, vsHeldTaken: 0, vsGarrison: 0, garrisonLostValue: 0, garrisonLost: {}, attackPower: 0, defencePower: 0 };
this.movementFailed = {};
this.settles = { ok: 0 };
this.siege = { n: 0, levels: 0 };
@ -37,6 +37,7 @@ class Collector {
this.notes = {}; // notification type -> count
this.cargoLostTotal = { fiber: 0, hardware: 0, capital: 0 };
this.cargoLostEvents = 0;
this.cargoLostBy = {}; // where the overflow happened: transport_arrived | raid_return | link_return -> { fiber, hardware, capital, n }
this.decommissioned = {};
this.unitsOfflineNotes = 0;
this.opCreated = new Map();
@ -68,17 +69,25 @@ class Collector {
default: break;
}
}
const rows = db.all("SELECT id, type, payload FROM notifications WHERE id > ? AND type IN ('transport_arrived','movement_returned','units_decommissioned','units_offline') ORDER BY id", this.noteCursor);
const rows = db.all("SELECT id, type, payload FROM notifications WHERE id > ? AND type IN ('transport_arrived','movement_returned','units_decommissioned','units_offline','trade_refund_clipped') ORDER BY id", this.noteCursor);
for (const n of rows) {
this.noteCursor = n.id;
const p = JSON.parse(n.payload);
bump(this.notes, n.type);
if (n.type === 'units_decommissioned') { addInto(this.decommissioned, p.units); addInto(this.unitsLost, p.units); }
else if (n.type === 'units_offline') this.unitsOfflineNotes += 1;
else if (n.type === 'trade_refund_clipped') { ledger.sinkClip[p.resource] += p.lost; ledger.clipEvents += 1; }
else if (p.cargoLost) {
let any = false;
for (const r of RES) if (p.cargoLost[r]) { this.cargoLostTotal[r] += p.cargoLost[r]; ledger.sinkLost[r] += p.cargoLost[r]; any = true; }
if (any) { ledger.lostEvents += 1; this.cargoLostEvents += 1; }
if (any) {
ledger.lostEvents += 1; this.cargoLostEvents += 1;
let where = n.type;
if (n.type === 'movement_returned') { const m = db.get('SELECT m.extra, pm.type AS ptype, pm.to_town_id AS ptown FROM movements m LEFT JOIN movements pm ON pm.id = m.parent_id WHERE m.id = ?', p.movementId); where = m && JSON.parse(m.extra || '{}').link ? 'link_return' : (m && m.ptype && !m.ptown ? 'site_return' : 'raid_return'); }
const by = this.cargoLostBy[where] || (this.cargoLostBy[where] = { fiber: 0, hardware: 0, capital: 0, n: 0 });
for (const r of RES) by[r] += p.cargoLost[r] || 0;
by.n += 1;
}
}
}
// notifications are numbered independently of the filter above: move the cursor past rows we skipped
@ -100,7 +109,7 @@ class Collector {
const loot = lootValue(d.loot);
if (win) b.att += 1;
b.loot += loot; b.attLost += attLostVal; b.defLost += defLostVal;
if (kind === 'raid') addInto(b.lootRes, d.loot);
if (kind === 'raid') { addInto(b.lootRes, d.loot); addInto(b.lootLeft, d.lootLeft || {}); if (win && !loot) b.emptyWins += 1; }
const aId = d.attacker.operator.id, dId = d.defender.operator.id;
const a = this.op(aId), df = this.op(dId);
if (kind === 'raid') { a.raids += 1; if (win) a.raidWins += 1; a.raidLoot += loot; a.raidLostValue += attLostVal; }
@ -144,6 +153,12 @@ class Collector {
const lost = (d.attacker.units && d.attacker.units.lost) || {};
this.landing.attLostValue += unitsValue(lost);
addInto(this.unitsLost, lost);
// contests (E6): attacks on a HELD site, those that met a garrison, and what the garrison lost (units stationed at a site die in these reports)
if (d.site && d.site.holder) { this.landing.vsHeld += 1; if (d.taken) this.landing.vsHeldTaken += 1; this.landing.firstVsHeldAt = this.landing.firstVsHeldAt || d.arrivedAt; this.landing.lastVsHeldAt = d.arrivedAt; }
const gar = (d.defender && d.defender.garrison) || [];
if (gar.some((g) => Object.keys(g.sent || {}).length)) this.landing.vsGarrison += 1;
for (const g of gar) { addInto(this.unitsLost, g.lost || {}); addInto(this.landing.garrisonLost, g.lost || {}); this.landing.garrisonLostValue += unitsValue(g.lost || {}); }
if (d.power) { this.landing.attackPower += d.power.attack || 0; this.landing.defencePower += d.power.defence || 0; }
}
}

View file

@ -4,16 +4,24 @@
* backbone, coordinated through a plan kept in memory (what an alliance would agree in its chat):
*
* 1. site the site that is cheapest to take for the alliance (static defence, a little distance weight)
* 2. striker ONE member with an Ops lab trains an army whose attack beats the site's defence on its own (every attack is
* resolved separately against the full static defence, so attacks cannot be added up) and attacks
* 3. holders once the alliance holds a site every member ships its spare Fiber/Hardware/Capital to it (transport links, 500
* each), anyone starts the next Backbone node level when the stockpile pays for it
* 2. striker a site with NO garrison has only a static defence that waves cannot wear down (nothing to kill), so ONE member
* with an Ops lab trains an army whose attack beats it on its own and attacks
* assault a site WITH a garrison (E6) is worn down by waves: every member with an Ops lab trains crews towards a share of
* what the alliance needs (about 1.15 x static + 2.2 x garrison), and once a war game over the members' real armies
* (rules.resolveBattle, wave by wave, the garrison shrinking by the real loss law) says the last wave takes the site,
* the plan says GO and every member with an army sends it at its next sitting (arrival order is the real one)
* 3. holders once the alliance holds a site every member ships its spare Fiber/Hardware/Capital to it (transport links,
* rules.transportCapacity each), anyone starts the next Backbone node level when the stockpile pays for it, and
* (contest, unless --no-contest) members station their defenders in the site and train more, towards what the
* strongest rival alliance could throw at it (the holders scout their rivals; bots read it from the db)
*
* Everything goes through the normal commands; the plan only decides who does what.
*/
const D = require('../../public/js/data.js');
const R = require('../../public/js/rules.js');
const { DAY, HOUR } = require('./util');
const ATTACK_UNITS = ['script_crew', 'botnet'];
const DEFENDERS = ['blue_team', 'soc_analyst']; // movable defenders (honeypots are fixed)
const RES = D.RESOURCES;
const EG = D.ENDGAME;
@ -22,7 +30,9 @@ function createEndgame(sim) {
const E = require('../../server/endgame');
const A = require('../../server/alliances');
const M = require('../../server/military/movements');
const log = { opened: null, plans: 0, strikes: 0, strikeWins: 0, shipments: 0, shipped: { fiber: 0, hardware: 0, capital: 0 }, builds: 0, buildErrors: {}, strikeSkips: {}, firstCapture: null, shipLinks: 0, wins: null };
const G = require('../../server/military/garrison');
const contest = sim.opts.contest !== false;
const log = { assaults: 0, assaultGo: 0, assaultSkips: {}, garrisoned: 0, garrisonSends: 0, garrisonPeak: 0, garrisonTrained: 0, opened: null, plans: 0, strikes: 0, strikeWins: 0, shipments: 0, shipped: { fiber: 0, hardware: 0, capital: 0 }, builds: 0, buildErrors: {}, strikeSkips: {}, firstCapture: null, shipLinks: 0, wins: null };
const plans = sim.alliancePlans;
const bump = (o, k) => { o[k] = (o[k] || 0) + 1; };
@ -44,7 +54,14 @@ function createEndgame(sim) {
return E.siteStates(sim.db, sim.world, now).map(({ site, row }) => row || { id: null, idx: site.index, x: site.x, y: site.y, holder_alliance_id: null, level: 0, build_to: null, fiber: 0, hardware: 0, capital: 0 });
}
const defenceAt = (s, at) => R.backboneDefence(sim.world.seed, s.x, s.y, E.ageDays(sim.world, at), s.level);
// What a site is worth at `at`: its static defence (heavy while nobody holds it, light once an alliance does) and its garrison.
function siteDefence(s, at) {
const held = !!s.holder_alliance_id;
const staticDef = R.backboneDefence(sim.world.seed, s.x, s.y, E.ageDays(sim.world, at), s.level || 0, held);
const g = s.id ? G.defenders(sim.db, s.id, at) : { groups: [], power: 0 };
return { staticDef, garrison: g.power, groups: g.groups, total: staticDef + g.power };
}
const defenceAt = (s, at) => siteDefence(s, at).total;
function choose(plan, allianceId, now) {
const c = centroid(allianceId);
@ -106,18 +123,106 @@ function createEndgame(sim) {
const row = siteRows(now).find((r) => r.idx === plan.site.idx);
plan.siteHeld = !!(row && row.holder_alliance_id === allianceId);
if (plan.siteHeld) { hold(bot, towns, row, now); return; }
// not ours yet: the striker prepares and attacks, the others carry on with their economy
bot.egForce = null;
if (plan.striker === bot.idx) strike(bot, main, plan, row, now);
if (plan.siteHeld) { bot.armyOverride = 0; hold(bot, towns, row, now); return; }
// not ours yet. A site with a garrison is worn down by waves (assault), one without has a static defence that only a single
// army can beat (striker); the other members carry on with their economy
bot.egForce = null; bot.egDefTarget = 0;
const site = row || { id: null, idx: plan.site.idx, x: plan.site.x, y: plan.site.y, level: 0, holder_alliance_id: null };
const flight = R.movementMs(R.distance(main.x, main.y, site.x, site.y), { script_crew: 1 }, sim.world.speed);
const d = siteDefence(site, now + flight);
const shielded = E.shieldUntil(site, sim.world) > now + flight; // just taken: nothing can be attacked until the shield is down
if (contest && d.garrison > 0) { assault(bot, towns, plan, site, d, allianceId, now, shielded); return; }
bot.armyOverride = 0;
if (plan.striker === bot.idx) strike(bot, main, plan, row, now, shielded);
}
// ---- assault: every member trains towards a share, the plan says GO when the war game over the real armies says the site falls
const sumRes = (u) => ATTACK_UNITS.reduce((a, k) => a + (u[k] || 0), 0);
// Production share of one member inside its alliance (what it can carry of the army the alliance needs).
function shareOf(bot, allianceId) {
let mine = 0, all = 0;
for (const m of members(allianceId)) {
const t = sim.view.towns(m.operatorId)[0];
if (!t) continue;
const r = R.ratesPerHour(t);
const v = (m.archetype === 'turtle' ? 0.3 : 1) * (r.fiber + r.hardware + r.capital);
all += v; if (m === bot) mine = v;
}
return all > 0 ? mine / all : 0;
}
// Every POP of the alliance with attackers at home, as armies { townId, opId, bot, units, research, flightMs, attack }, nearest first.
function armies(allianceId, site, now) {
const out = [];
for (const m of members(allianceId)) {
for (const t of sim.view.towns(m.operatorId)) {
if (!R.unitsOnline(t, now)) continue;
const home = sim.view.home(t.id);
const units = {};
for (const u of ATTACK_UNITS) if (home[u] > 0) units[u] = home[u];
if (!sumRes(units)) continue;
const research = sim.view.researchLevels(t.id);
const attack = R.attackPower(units, research);
if (attack < 400) continue;
out.push({ townId: t.id, opId: m.operatorId, units, research, attack, flightMs: R.movementMs(R.distance(t.x, t.y, site.x, site.y), units, sim.world.speed) });
}
}
return out.sort((a, b) => a.flightMs - b.flightMs || a.townId - b.townId);
}
// The war game: the armies arrive in this order, one battle each, against the static part (x margin) and the garrison, which shrinks
// by the real loss law. -> number of waves it takes, or 0 when the last wave still loses.
function wargame(list, d, margin) {
let groups = d.groups.filter((g) => g.online).map((g) => ({ id: g.id, units: Object.assign({}, g.units), research: g.research }));
for (let i = 0; i < list.length; i++) {
const b = R.resolveBattle({ kind: 'attack', attackers: { units: list[i].units, research: list[i].research }, defenders: groups, firewall: 0, staticDefence: d.staticDef * margin });
if (b.attackerWins) return i + 1;
groups = groups.map((g) => { const r = b.defenders.find((x) => x.id === g.id); return { id: g.id, units: r ? r.survivors : g.units, research: g.research }; });
}
return 0;
}
function assault(bot, towns, plan, site, d, allianceId, now, shielded) {
const view = sim.view;
const main = towns[0];
// training: this member's share of ~1.15 x static + 2.2 x garrison (a lost wave only kills ratio^1.5 of the garrison)
const need = 1.15 * d.staticDef + 2.2 * d.garrison;
const research = view.researchLevels(main.id);
const mult = R.researchMult(R.researchLevel(research, 'script_crew', 'attack'));
bot.egForce = { ops_lab: 6, research_lab: 5, noc: 1 };
bot.armyOverride = Math.ceil(need * shareOf(bot, allianceId) / (R.unitDef('script_crew').attack * mult));
if (shielded) { bump(log.assaultSkips, 'shielded'); return; }
// GO? evaluated at most every 3 hours per alliance
if (!plan.go || now > plan.go.until) {
plan.go = null;
if (!plan.checkedAt || now - plan.checkedAt >= 3 * HOUR) {
plan.checkedAt = now;
const list = armies(allianceId, site, now);
const waves = list.length ? wargame(list, d, 1.15) : 0;
if (waves) { plan.go = { until: now + 30 * HOUR, towns: new Set(list.map((a) => a.townId)), waves, planned: list.length }; log.assaultGo += 1; }
else bump(log.assaultSkips, list.length ? 'army_short' : 'no_army');
}
}
if (!plan.go) return;
for (const t of towns) {
if (!plan.go.towns.has(t.id)) continue;
plan.go.towns.delete(t.id);
const home = view.home(t.id);
const units = {};
for (const u of ATTACK_UNITS) if (home[u] > 0) units[u] = home[u];
if (!sumRes(units)) continue;
const r = bot.call('sendMovement', { fromTownId: t.id, type: 'attack', x: site.x, y: site.y, units });
if (r.ok) { log.assaults += 1; log.strikes += 1; } else bump(log.strikeSkips, r.code);
}
}
// ---- striker
function strike(bot, main, plan, row, now) {
function strike(bot, main, plan, row, now, shielded) {
const view = sim.view;
const site = row || { x: plan.site.x, y: plan.site.y, level: 0 };
const flight = R.movementMs(R.distance(main.x, main.y, site.x, site.y), { script_crew: 1 }, sim.world.speed);
const dv = defenceAt({ x: site.x, y: site.y, level: site.level || 0 }, now + flight);
const dv = siteDefence({ x: site.x, y: site.y, level: site.level || 0, id: site.id, holder_alliance_id: site.holder_alliance_id }, now + flight).total;
const research = view.researchLevels(main.id);
const mult = R.researchMult(R.researchLevel(research, 'script_crew', 'attack'));
const need = Math.ceil(1.12 * dv / (R.unitDef('script_crew').attack * mult));
@ -125,7 +230,8 @@ function createEndgame(sim) {
bot.armyOverride = need;
const home = view.home(main.id);
const attack = armyAttack(main, home, research);
if (attack >= 1.08 * dv) {
if (shielded) bump(log.strikeSkips, 'shielded');
else if (attack >= 1.08 * dv) {
const units = {};
for (const u of ['script_crew', 'botnet']) if (home[u]) units[u] = home[u];
const r = bot.call('sendMovement', { fromTownId: main.id, type: 'attack', x: site.x, y: site.y, units });
@ -133,9 +239,70 @@ function createEndgame(sim) {
} else bump(log.strikeSkips, 'army_short');
}
// ---- garrison (holders): what could the strongest rival throw, keep that much defence in the site
function rivalThreat(allianceId, now) {
const plan = plans.get(allianceId);
if (plan.threatAt && now - plan.threatAt < 4 * HOUR) return plan.threat;
let best = 0;
const byAlliance = new Map();
for (const b of sim.bots) {
const op = sim.view.operator(b.operatorId);
if (!op || !op.alliance_id || op.alliance_id === allianceId) continue;
let v = 0;
for (const t of sim.view.towns(b.operatorId)) {
const home = sim.view.home(t.id);
const units = {};
for (const u of ATTACK_UNITS) if (home[u] > 0) units[u] = home[u];
v += R.attackPower(units, sim.view.researchLevels(t.id));
}
for (const m of sim.view.outgoing(b.operatorId)) { const u = JSON.parse(m.units || '{}'); v += R.attackPower({ script_crew: u.script_crew || 0, botnet: u.botnet || 0 }, {}); }
byAlliance.set(op.alliance_id, (byAlliance.get(op.alliance_id) || 0) + v);
}
for (const [aid, v] of byAlliance) {
if (A.memberCount(sim.db, aid) < sim.opts.endgameMinMembers) continue;
const rel = A.relationBetween(sim.db, allianceId, aid);
if (rel === 'nap' || rel === 'confed') continue;
best = Math.max(best, v);
}
plan.threatAt = now; plan.threat = best;
return best;
}
function garrison(bot, towns, row, now, allianceId) {
const view = sim.view;
const d = siteDefence(row, now);
const threat = rivalThreat(allianceId, now);
const goal = Math.max(1.1 * threat, 1.5 * d.staticDef); // total defence in the site the alliance wants (static + garrison)
const share = shareOf(bot, allianceId);
const mine = G.ofTown(sim.db, towns[0].id);
const main = towns[0];
// the garrison this member should keep: its share of (goal - static)
const want = Math.max(0, (goal - d.staticDef) * share);
bot.egDefTarget = want;
bot.egForce = { noc: 5, research_lab: 3 }; // blue teams need them
const have = R.defencePower(mine, {}) + R.defencePower(view.home(main.id), {}) + bot.queuedDefence(main);
if (have < want) {
const unit = R.unitMissing(main, 'blue_team').length === 0 ? 'blue_team' : 'soc_analyst';
const n = bot.trainSome(main, unit, Math.ceil((want - have) / R.unitDef(unit).defence), now, false);
log.garrisonTrained += n || 0;
}
// send every movable defender at home into the site (the member keeps none at home for the site)
for (const t of towns) {
const home = view.home(t.id);
const units = {};
for (const u of DEFENDERS) if (home[u] > 0) units[u] = home[u];
if (!Object.keys(units).length) continue;
if (!R.unitsOnline(t, now)) continue;
const r = bot.call('sendMovement', { fromTownId: t.id, type: 'reinforce', x: row.x, y: row.y, units });
if (r.ok) { log.garrisonSends += 1; log.garrisoned += Object.keys(units).reduce((a, k) => a + units[k], 0); } else bump(log.assaultSkips, 'garrison_' + r.code);
}
log.garrisonPeak = Math.max(log.garrisonPeak, siteDefence(row, now).garrison);
}
// ---- holders: ship and build
function hold(bot, towns, row, now) {
const view = sim.view;
if (contest) garrison(bot, towns, row, now, row.holder_alliance_id);
// start the next level when the stockpile pays for it
if (!row.build_to && row.level < EG.maxLevel) {
const cost = R.backboneCost(row.level + 1);
@ -157,9 +324,9 @@ function createEndgame(sim) {
for (let i = 0; i < lvl; i++) {
if (M.activeLinks(sim.db, t.id) >= lvl) break;
const cur = R.resourcesAt(t, now);
const cap = cur.caps.fiber;
const cap = R.storageCap(t);
const cargo = {};
let room = D.TRANSPORT.capacityPerLink;
let room = R.transportCapacity(sim.world.speed);
const order = RES.slice().sort((a, b) => want[b] - want[a]);
for (const r of order) {
const spare = Math.max(0, cur.amounts[r] - 0.12 * cap);
@ -206,7 +373,7 @@ function createEndgame(sim) {
for (const r of sim.db.all('SELECT town_id, unit, count FROM town_units')) { (perTown[r.town_id] = perTown[r.town_id] || {})[r.unit] = r.count; }
let maxPopAttack = 0;
for (const id of Object.keys(perTown)) maxPopAttack = Math.max(maxPopAttack, R.attackPower(perTown[id], {}));
const bestDefence = sites.filter((x) => x.level > 0).reduce((m, x) => Math.max(m, R.backboneDefence(sim.world.seed, x0(x).x, x0(x).y, E.ageDays(world, now), x.level)), 0);
const bestDefence = sim.db.all('SELECT * FROM landing_sites WHERE world_id = ? AND level > 0', sim.world.id).reduce((m, r) => Math.max(m, siteDefence(r, now).total), 0);
const daysSinceOpen = Math.max(1e-9, (now - sim.t0) / DAY - (log.opened || 0));
const shippedTotal = RES.reduce((s, r) => s + log.shipped[r], 0);
const perDay = shippedTotal / daysSinceOpen;
@ -216,6 +383,12 @@ function createEndgame(sim) {
open: true, ageDays: age, openedAtSimDay: log.opened, plans: log.plans, strikes: log.strikes, strikeSkips: log.strikeSkips, landingReports: sim.col.landing, shipments: log.shipments, shippedTotal, shipped: log.shipped,
maxPopAttackNoResearch: Math.round(maxPopAttack), bestHeldSiteDefenceNow: bestDefence, shippedPerSimDay: Math.round(perDay), buildsStarted: log.builds, buildErrors: log.buildErrors, sites, bestLevel,
remainingToLevel100: remaining, remainingTotal: remainTotal, simDaysToFinishAtThisRate: perDay > 0 ? Math.round(remainTotal / perDay) : null,
contest: {
enabled: contest, assaultGo: log.assaultGo, assaultsSent: log.assaults, assaultSkips: log.assaultSkips, garrisonSends: log.garrisonSends, garrisonedUnits: log.garrisoned, garrisonTrained: log.garrisonTrained,
garrisonPeakPower: Math.round(log.garrisonPeak), garrisonNow: sites.map((x) => { const row = sim.db.get('SELECT id FROM landing_sites WHERE world_id = ? AND idx = ?', sim.world.id, x.idx); return row ? Math.round(G.defenders(sim.db, row.id, now).power) : 0; }),
attacksOnHeld: sim.col.landing.vsHeld, heldTaken: sim.col.landing.vsHeldTaken, metGarrison: sim.col.landing.vsGarrison, garrisonLostValue: Math.round(sim.col.landing.garrisonLostValue),
firstAttackOnHeldDay: sim.col.landing.firstVsHeldAt ? Math.round((sim.col.landing.firstVsHeldAt - sim.t0) / DAY * 10) / 10 : null, lastAttackOnHeldDay: sim.col.landing.lastVsHeldAt ? Math.round((sim.col.landing.lastVsHeldAt - sim.t0) / DAY * 10) / 10 : null,
},
winner: world.winner_alliance_id ? { allianceId: world.winner_alliance_id, tag: world.winner_tag, wonAtSimDay: (world.won_at - sim.t0) / DAY } : null, worldStatus: world.status, towns: links,
};
}

View file

@ -13,7 +13,8 @@
* bookings (db.tx is tapped too), so only committed settles count. Caps are already inside the stored numbers.
* sinks build/train/research costs (from the command results), Backbone node levels (from landing_sites), cargo that
* did not fit the Rack hall (`cargoLost` in notifications), trade escrow refunds clipped by the Rack hall cap
* (tap on the refund statement)
* (booked from `trade_refund_clipped` notifications: with escrow reserving its room in the Rack hall this is only a hall that was
* shot down below stock + escrow in the meantime, so it is 0 in normal runs)
*
* Anything else is DRIFT: a leak or a duplication in the server (or a missing sink here). Drift is printed and fails the run.
*
@ -28,8 +29,6 @@ const zero = () => ({ fiber: 0, hardware: 0, capital: 0 });
const addRes = (a, b) => { for (const r of RES) a[r] += (b && b[r]) || 0; return a; };
const SETTLE_SQL = 'UPDATE towns SET fiber = ?, hardware = ?, capital = ?, battery = ?, footprint = ?, res_at = ?, loyalty = ?, loyalty_at = ? WHERE id = ?';
const REFUND_RE = /^UPDATE towns SET (fiber|hardware|capital) = \? WHERE id = \?$/;
const CLOSE_PREFIX = 'UPDATE trade_offers SET status = ?, closed_at = ? WHERE id = ?';
class Ledger {
constructor(db) {
@ -38,11 +37,10 @@ class Ledger {
this.sinkCosts = zero(); // build / train / research (command results)
this.sinkLost = zero(); // cargoLost notifications
this.lostEvents = 0;
this.sinkClip = zero(); // trade refund clipped by the Rack hall cap
this.sinkClip = zero(); // trade refund that did not fit (trade_refund_clipped notifications)
this.clipEvents = 0;
this.sourceStart = zero(); // operators' start stock
this.stack = [];
this.closing = null;
this.t = { settles: 0 };
this.installed = false;
}
@ -63,20 +61,6 @@ class Ledger {
if (sql === SETTLE_SQL) {
const prev = db.get('SELECT fiber, hardware, capital FROM towns WHERE id = ?', p[8]);
if (prev) self.book({ fiber: p[0] - prev.fiber, hardware: p[1] - prev.hardware, capital: p[2] - prev.capital }, zero(), 0);
} else if (sql === CLOSE_PREFIX) {
self.closing = p[2];
} else {
const m = REFUND_RE.exec(sql);
if (m && self.closing !== null) {
const prev = db.get('SELECT ' + m[1] + ' AS v FROM towns WHERE id = ?', p[1]);
const off = db.get('SELECT give_amount, give_res FROM trade_offers WHERE id = ?', self.closing);
if (prev && off && off.give_res === m[1]) {
const credit = p[0] - prev.v;
const clip = Math.max(0, off.give_amount - credit);
if (clip > 1e-9) { const c = zero(); c[m[1]] = clip; self.book(zero(), c, 1); }
}
self.closing = null;
}
}
return run(sql, ...p);
};
@ -157,6 +141,7 @@ function aliveUnits(db) {
const add = (k, n) => { out[k] = (out[k] || 0) + n; };
for (const r of db.all('SELECT unit, SUM(count) AS n FROM town_units GROUP BY unit')) add(r.unit, r.n);
for (const r of db.all('SELECT unit, SUM(count) AS n FROM stationed GROUP BY unit')) add(r.unit, r.n);
for (const r of db.all('SELECT unit, SUM(count) AS n FROM site_stationed GROUP BY unit')) add(r.unit, r.n); // garrisons at landing sites (E6)
for (const m of db.all("SELECT units FROM movements WHERE status = 'out' AND units != '{}'")) { const u = JSON.parse(m.units); for (const k of Object.keys(u)) add(k, u[k]); }
return out;
}

View file

@ -79,6 +79,7 @@ function render(s, opts) {
const t = s.trade;
out.push('offers by status: ' + Object.entries(t.byStatus).map(([k, v]) => k + ':' + v.n).join(' ') + ', completed volume ' + fmt(t.volumeCompleted) + ', completed give/want ratio p10/50/90 ' + pc(t.ratio, 'p10') + '/' + pc(t.ratio, 'p50') + '/' + pc(t.ratio, 'p90'));
out.push('transport overflow lost (' + t.cargoLostEvents + ' deliveries): ' + JSON.stringify(t.cargoLost) + ', trade refunds clipped by the Rack hall cap (' + t.clipEvents + '): ' + JSON.stringify(t.refundClipped));
out.push(' overflow by place: ' + Object.entries(t.cargoLostBy || {}).map(([k, v]) => k + ' ' + v.n + 'x (' + fmt(v.fiber) + '/' + fmt(v.hardware) + '/' + fmt(v.capital) + ')').join(', '));
const a = s.alliances;
out.push('alliances ' + a.count + ', members p10/50/90 ' + pc(a.members, 'p10') + '/' + pc(a.members, 'p50') + '/' + pc(a.members, 'p90') + ' (max ' + a.membersMax + '), operators in an alliance ' + a.inAlliance + '/' + a.operators + ', relations ' + JSON.stringify(a.relations) + ', proposals ' + JSON.stringify(a.proposals));
@ -90,7 +91,8 @@ function render(s, opts) {
out.push('opened at simulated day ' + fmt(e.openedAtSimDay, 1) + ' (world age now ' + fmt(e.ageDays, 0) + '), alliance plans ' + e.plans + ', strikes sent ' + e.strikes + ' (landing reports ' + e.landingReports.n + ', taken ' + e.landingReports.taken + ', units lost value ' + fmt(e.landingReports.attLostValue) + '), strike blockers ' + JSON.stringify(e.strikeSkips));
out.push('shipments ' + e.shipments + ' carrying ' + fmt(e.shippedTotal) + ' (F ' + fmt(e.shipped.fiber) + ' H ' + fmt(e.shipped.hardware) + ' C ' + fmt(e.shipped.capital) + '), ' + fmt(e.shippedPerSimDay) + ' per simulated day; node levels started ' + e.buildsStarted + ' ' + JSON.stringify(e.buildErrors));
out.push(table(e.sites.map((x) => [x.idx, x.holder || '-', x.level, x.takenAt === null ? '-' : fmt(x.takenAt, 1), x.contributors, fmt(x.shippedIn.fiber + x.shippedIn.hardware + x.shippedIn.capital), fmt(x.shippedPerDay), x.daysToLevel100 === null ? '-' : x.daysToLevel100, fmt(x.stock.fiber + x.stock.hardware + x.stock.capital)]), ['site', 'holder', 'node level', 'taken (day)', 'contributors', 'shipped in', 'shipped/day', 'days to lvl 100 at that rate', 'stockpile now']));
out.push('largest army (attack, before research) any single POP holds: ' + fmt(e.maxPopAttackNoResearch) + ' against the defence of the best built-up site now: ' + fmt(e.bestHeldSiteDefenceNow) + ' (one attack is one movement from one POP, so attacks cannot be added up)');
if (e.contest) out.push('contest (E6, garrisons) ' + (e.contest.enabled ? 'on' : 'OFF') + ': attacks on HELD sites ' + e.contest.attacksOnHeld + ' (taken ' + e.contest.heldTaken + ', met a garrison ' + e.contest.metGarrison + '), first/last on day ' + e.contest.firstAttackOnHeldDay + '/' + e.contest.lastAttackOnHeldDay + '; assaults GO ' + e.contest.assaultGo + ', armies sent ' + e.contest.assaultsSent + ' ' + JSON.stringify(e.contest.assaultSkips) + '; garrison sends ' + e.contest.garrisonSends + ' (' + e.contest.garrisonedUnits + ' units), trained ' + e.contest.garrisonTrained + ', peak power ' + fmt(e.contest.garrisonPeakPower) + ', now per site ' + JSON.stringify(e.contest.garrisonNow) + ', garrison units lost (value) ' + fmt(e.contest.garrisonLostValue));
out.push('largest army (attack, before research) any single POP holds: ' + fmt(e.maxPopAttackNoResearch) + ' against the whole defence (static + garrison) of the best built-up site now: ' + fmt(e.bestHeldSiteDefenceNow) + ' (one attack is one movement from one POP; a garrison is worn down by several waves, a static defence only by one army that beats it)');
out.push('best node level ' + e.bestLevel + '; still to ship for level 100 from there (per resource) ' + fmt(e.remainingToLevel100.fiber) + '; world ' + e.worldStatus + (e.winner ? ', WINNER ' + e.winner.tag + ' on day ' + fmt(e.winner.wonAtSimDay, 1) : ', no winner'));
}
}

View file

@ -148,7 +148,7 @@ async function runSim(o) {
for (const row of db.all('SELECT * FROM towns ORDER BY id')) {
const t = S.townFromRow(db, row, world);
const cur = R.resourcesAt(t, now);
const cap = cur.caps.fiber;
const cap = R.storageCap(t);
acc.towns += 1;
for (const r of RES) { acc.stock[r] += cur.amounts[r]; acc.prod[r] += cur.rates[r]; }
const fills = RES.map((r) => cur.amounts[r] / cap);

View file

@ -106,7 +106,7 @@ function build(x) {
const undefended = samples.filter((s) => s.undefended);
const combat = {
reports: col.byType,
raids: { n: raid.n, wins: raid.att, winRate: raid.n ? raid.att / raid.n : null, lootTotal: round(raid.loot, 0), lootRes: raid.lootRes, lootPerRaid: percentiles(lootPerRaid, [10, 50, 90]), attackerLostValue: round(raid.attLost, 0), defenderLostValue: round(raid.defLost, 0),
raids: { n: raid.n, wins: raid.att, winRate: raid.n ? raid.att / raid.n : null, lootTotal: round(raid.loot, 0), lootRes: raid.lootRes, lootLeft: raid.lootLeft, emptyWins: raid.emptyWins, lootPerRaid: percentiles(lootPerRaid, [10, 50, 90]), attackerLostValue: round(raid.attLost, 0), defenderLostValue: round(raid.defLost, 0),
lootPerLostValue: raid.attLost > 0 ? round(raid.loot / raid.attLost, 2) : null, undefendedShare: samples.length ? round(undefended.length / samples.length, 3) : null, undefendedLoot: round(sum(undefended.map((s) => s.loot)), 0),
lootOverLossValue: percentiles(ratio, [10, 50, 90]), targetAge: ageBuckets, attackOverDefence: percentiles(samples.filter((s) => s.D > 0).map((s) => s.A / s.D), [10, 50, 90]) },
attacks: col.battles.attack, takeoverBattles: col.battles.takeover, takeovers: col.takeovers, siege: col.siege,
@ -117,7 +117,7 @@ function build(x) {
// ---- trade, alliances
const tradeRows = db.all('SELECT status, COUNT(*) AS n, SUM(give_amount) AS give, SUM(want_amount) AS want FROM trade_offers GROUP BY status');
const trade = { byStatus: Object.fromEntries(tradeRows.map((r) => [r.status, { n: r.n, give: r.give, want: r.want }])), refundClipped: ledger.sinkClip, clipEvents: ledger.clipEvents,
cargoLost: col.cargoLostTotal, cargoLostEvents: col.cargoLostEvents };
cargoLost: col.cargoLostTotal, cargoLostEvents: col.cargoLostEvents, cargoLostBy: col.cargoLostBy };
const completed = db.all("SELECT give_res, give_amount, want_res, want_amount FROM trade_offers WHERE status = 'completed'");
trade.volumeCompleted = sum(completed.map((r) => r.give_amount + r.want_amount));
trade.ratio = percentiles(completed.map((r) => r.give_amount / r.want_amount), [10, 50, 90]);