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

@ -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,
};
}