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

@ -228,6 +228,12 @@
return Math.round(F.storageBase * Math.pow(F.storageGrowth, r.level - 1));
}
// Room the Rack hall has for ONE resource: goods escrowed in open Internet exchange offers (town.escrow, per resource) still occupy
// the hall, so the stock stops growing at the hall's size minus the escrow and a refund always fits (nothing is lost, nothing is stored extra).
function storageCapOf(town, res) {
return Math.max(0, storageCap(town) - ((town.escrow && town.escrow[res]) || 0));
}
function batteryCap(town) {
const b = town.buildings.battery_bank;
return b && b.level > 0 ? Math.round(F.batteryBase * Math.pow(F.batteryGrowth, b.level - 1)) : 0;
@ -266,16 +272,17 @@
function resourcesAt(town, now) {
const dtH = Math.max(0, now - town.updatedAt) / HOUR;
const rates = ratesPerHour(town);
const cap = storageCap(town);
const bcap = batteryCap(town);
const speed = town.speed || 1;
const out = {};
const out = {}, caps = {};
for (const r of D.RESOURCES) {
// An amount already above the cap (the rack hall was lowered) is kept, it just stops growing.
out[r] = Math.max(0, Math.min(Math.max(cap, town.res[r]), town.res[r] + rates[r] * dtH));
caps[r] = storageCapOf(town, r);
out[r] = Math.max(0, Math.min(Math.max(caps[r], town.res[r]), town.res[r] + rates[r] * dtH));
}
out.battery = Math.max(0, Math.min(bcap, town.res.battery + rates.powerNet * speed * dtH));
return { amounts: out, caps: { fiber: cap, hardware: cap, capital: cap, battery: bcap }, rates };
caps.battery = bcap;
return { amounts: out, caps, rates };
}
// When will the battery hit zero (ms epoch)? null if it never does at the current rates. Units go offline then.
@ -569,7 +576,9 @@
// o.kind: 'attack' (full) | 'raid'
// o.attackers: { units, research }
// o.defenders: [{ id, units, research }] everything defending the POP (home crews first, then each reinforcement)
// o.firewall: Firewall level of the target; o.staticDefence: a number for an incumbent site (no groups, no losses)
// o.firewall: Firewall level of the target; o.staticDefence: a number for an incumbent site (no groups, no losses). A held backbone
// landing site passes BOTH: the static number plus the garrison groups; then D = static + the groups' raw defence (no firewall, no
// base defence) and the groups lose units by the same loss law as in a POP (the static part never loses anything).
// Full attack: the loser loses everything, the winner loses (loser/winner)^1.5 of its units.
// Raid: both sides lose 0.5 * (weaker/stronger)^1.5, whoever wins. Ties go to the defender.
function resolveBattle(o) {
@ -581,7 +590,7 @@
const raw = groups.map((g) => defencePower(g.units, g.research));
const rawTotal = raw.reduce((s, v) => s + v, 0);
const isStatic = o.staticDefence !== undefined && o.staticDefence !== null;
const Dv = isStatic ? o.staticDefence : (rawTotal + MIL.defenceBase) * firewallMult(effFw);
const Dv = isStatic ? o.staticDefence + rawTotal : (rawTotal + MIL.defenceBase) * firewallMult(effFw);
const attackerWins = A > Dv;
const hi = Math.max(A, Dv), lo = Math.min(A, Dv);
const ratio = hi > 0 ? lo / hi : 0;
@ -593,7 +602,7 @@
} else {
attF = 1; defF = Math.min(1, Math.pow(ratio, MIL.lossExponent));
}
if (isStatic) defF = 0;
if (isStatic && !groups.length) defF = 0;
const a = applyLoss(att, attF);
const defenders = groups.map((g, i) => {
const r = applyLoss(g.units, defF);
@ -615,15 +624,19 @@
// Loot: `carry` is split evenly over Fiber/Hardware/Capital; what one resource cannot give is shared by the others.
// avail = what can be taken. -> whole-number { fiber, hardware, capital }.
function lootSplit(carry, avail) {
// `room` (optional, per resource) = what the raiders' home Rack hall can still bank: a resource with no room is not taken at all
// and the carry goes to the others, so loot is never destroyed on arrival (default: no limit).
function lootSplit(carry, avail, room) {
const take = { fiber: 0, hardware: 0, capital: 0 };
const lim = {};
for (const r of D.RESOURCES) lim[r] = Math.min(avail[r], room && room[r] !== undefined ? room[r] : Infinity);
let left = Math.max(0, carry);
for (let pass = 0; pass < 4 && left > 1e-9; pass++) {
const open = D.RESOURCES.filter((r) => avail[r] - take[r] > 1e-9);
const open = D.RESOURCES.filter((r) => lim[r] - take[r] > 1e-9);
if (!open.length) break;
const share = left / open.length;
for (const r of open) {
const t = Math.min(share, avail[r] - take[r]);
const t = Math.min(share, lim[r] - take[r]);
take[r] += t; left -= t;
}
}
@ -716,6 +729,9 @@
// ---- transport (trade is built on it): concurrent links = Internet exchange level, each carries up to capacityPerLink
const transportLinks = (town) => buildingLevel(town, D.TRANSPORT.building);
// What one link carries in a world of this speed: capacityPerLink x speed (trips are per sitting, not per hour, so a faster world must carry
// more per trip or its end game stays as slow as a 1x world's, BALANCE.md B7). The ONLY place that reads D.TRANSPORT.capacityPerLink.
const transportCapacity = (speed) => Math.max(1, Math.round(D.TRANSPORT.capacityPerLink * (speed > 0 ? speed : 1)));
// Codes: validation_failed, capacity_exceeded, no_transport_link, not_enough_resources.
function transportPlan(town, cargo, activeLinks, now) {
let total = 0;
@ -725,7 +741,8 @@
}
if (total < 1) return { ok: false, code: 'validation_failed' };
if (activeLinks >= transportLinks(town)) return { ok: false, code: 'no_transport_link', links: transportLinks(town), active: activeLinks };
if (total > D.TRANSPORT.capacityPerLink) return { ok: false, code: 'capacity_exceeded', capacity: D.TRANSPORT.capacityPerLink, total };
const capacity = transportCapacity(town.speed);
if (total > capacity) return { ok: false, code: 'capacity_exceeded', capacity, total };
const have = resourcesAt(town, now).amounts;
for (const r of D.RESOURCES) if (have[r] + 1e-6 < (cargo[r] || 0)) return { ok: false, code: 'not_enough_resources' };
return { ok: true, total };
@ -737,8 +754,8 @@
// Is the exchange rate within the 1:ratioMax band (give/want in [1/ratioMax, ratioMax])?
const tradeRatioOk = (give, want) => give > 0 && want > 0 && give <= want * D.TRADE.ratioMax && want <= give * D.TRADE.ratioMax;
// Validate the terms of a new offer. `o` = { giveRes, giveAmount, wantRes, wantAmount, maxDistance }. Codes: validation_failed,
// trade_ratio, capacity_exceeded. Does not look at the town (resources, links) - the command does.
function tradeTermsCheck(o) {
// trade_ratio, capacity_exceeded (one transport at the world's `speed`). Does not look at the town (resources, links) - the command does.
function tradeTermsCheck(o, speed) {
const bad = (path, message) => ({ ok: false, code: 'validation_failed', errors: [{ path, message }] });
if (D.RESOURCES.indexOf(o.giveRes) < 0) return bad('giveRes', 'must be one of ' + D.RESOURCES.join(', '));
if (D.RESOURCES.indexOf(o.wantRes) < 0) return bad('wantRes', 'must be one of ' + D.RESOURCES.join(', '));
@ -746,7 +763,7 @@
if (!Number.isInteger(o.giveAmount) || o.giveAmount < 1) return bad('giveAmount', 'must be a whole number >= 1');
if (!Number.isInteger(o.wantAmount) || o.wantAmount < 1) return bad('wantAmount', 'must be a whole number >= 1');
if (!Number.isInteger(o.maxDistance) || o.maxDistance < 1 || o.maxDistance > D.TRADE.maxDistance) return bad('maxDistance', 'must be a whole number of tiles 1..' + D.TRADE.maxDistance);
const cap = D.TRANSPORT.capacityPerLink;
const cap = transportCapacity(speed);
if (o.giveAmount > cap || o.wantAmount > cap) return { ok: false, code: 'capacity_exceeded', capacity: cap };
if (!tradeRatioOk(o.giveAmount, o.wantAmount)) return { ok: false, code: 'trade_ratio', max: D.TRADE.ratioMax };
return { ok: true };
@ -756,9 +773,15 @@
const tradeInRange = (dist, maxDistance, level) => level >= 1 && dist <= maxDistance && dist <= tradeReach(level);
// ---- end game: backbone landing sites
// Heavy static defence of a landing site: the incumbent's site defence x defenceMult, plus defencePerLevel per node level.
function backboneDefence(seed, x, y, ageDays, level) {
return Math.round(incumbentDefence(seed, x, y, ageDays) * D.ENDGAME.defenceMult * (1 + D.ENDGAME.defencePerLevel * Math.max(0, level || 0)));
// Static defence of a landing site: the incumbent's site defence x a multiplier, plus defencePerLevel per node level. Nobody holds it:
// defenceMult (heavy, the opening scramble). An alliance holds it (`held`): heldDefenceMult, and its garrison comes on top (E6).
function backboneDefence(seed, x, y, ageDays, level, held) {
const mult = held ? D.ENDGAME.heldDefenceMult : D.ENDGAME.defenceMult;
return Math.round(incumbentDefence(seed, x, y, ageDays) * mult * (1 + D.ENDGAME.defencePerLevel * Math.max(0, level || 0)));
}
// Until when a landing site that changed hands at `takenAt` cannot be attacked (0 = no shield). Only a HELD site has one: the caller checks that.
function siteShieldUntil(takenAt, speed) {
return takenAt ? takenAt + Math.round(D.ENDGAME.captureShieldHours * HOUR / (speed || 1)) : 0;
}
// Cost to build the Backbone node UP TO `level` (1..maxLevel), per resource.
function backboneCost(level) {
@ -784,10 +807,10 @@
}
return {
unitDef, unitCount, costValue, unitValue, researchKey, researchLevel, researchMult, unitStat, unitCost, trainTimeMs, unitMissing, trainPlan, researchCost, researchTimeMs, researchSpeedBonus, researchPlan, slowestSpeed, movementMs, transportMs, checkUnitsForType, isProtected, firewallMult, effectiveFirewall, attackPower, defencePower, applyLoss, resolveBattle, battlePoints, cacheFraction, lootSplit, carryOf, siegeLevels, loyaltyDrop, takeoverBlock, footprintGate, settleCheck, cleanWild, newTownBuildings, scanStrength, resolveScan, incumbentDefence, decommissionMs, decommissionPlan, transportLinks, transportPlan, rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn,
unitDef, unitCount, costValue, unitValue, researchKey, researchLevel, researchMult, unitStat, unitCost, trainTimeMs, unitMissing, trainPlan, researchCost, researchTimeMs, researchSpeedBonus, researchPlan, slowestSpeed, movementMs, transportMs, checkUnitsForType, isProtected, firewallMult, effectiveFirewall, attackPower, defencePower, applyLoss, resolveBattle, battlePoints, cacheFraction, lootSplit, carryOf, siegeLevels, loyaltyDrop, takeoverBlock, footprintGate, settleCheck, cleanWild, newTownBuildings, scanStrength, resolveScan, incumbentDefence, decommissionMs, decommissionPlan, transportLinks, transportCapacity, transportPlan, rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn,
terrainAt, backboneSites, backboneSiteAt, isBackboneSite, worldAgeDays, worldPhase, tradeReach, tradeRatioOk, tradeTermsCheck, tradeInRange,
backboneDefence, backboneCost, backboneTimeMs, backbonePlan,
buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, earlyTimeFactor, queueSlots, storageCap, batteryCap,
backboneDefence, siteShieldUntil, backboneCost, backboneTimeMs, backbonePlan,
buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, earlyTimeFactor, queueSlots, storageCap, storageCapOf, batteryCap,
fieldOutputPerHour, ratesPerHour, resourcesAt, batteryEmptyAt, unitsOnline, footprintPerDay, footprintAt,
allianceCap, allianceCan, roleRank, outranks, diplomacyMove, pactCancelMs,
footprintNeeded, loyaltyAt, buildPlan, initialBuildings, latencyMs,