Upstream/server/military/combat.js
jvanvik 3c23c51902 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
2026-10-12 00:58:12 +02:00

314 lines
19 KiB
JavaScript

'use strict';
/*
* Arrival of scan / raid / attack / takeover. Everything here runs inside the `arrive` event's transaction at the
* event's own due time, after every earlier event, so combat order is exactly event order. Deterministic: the only
* dice (the loyalty roll) are seeded from (world seed, movement id).
*
* Steps: re-check the target (it may have changed since departure) -> settle the target to the due time -> gather
* defenders (home crews + reinforcements, only while online) -> rules.resolveBattle -> apply losses, loot, siege,
* takeover -> survivors drive home with the loot -> reports + battle points.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { loadTown, settle, loadWorld } = require('../state');
const U = require('./units');
const M = require('./movements');
const P = require('./power');
const { createReport } = require('./reports');
const { bounce, townBrief, opBrief } = require('./arrivals');
const DAY = 24 * D.HOUR_MS;
// All groups standing in the target: home crews then each reinforcing POP's units, with the research that applies.
function defenderGroups(db, target) {
const groups = [];
const home = U.homeUnits(db, target.id);
if (!U.isEmpty(home)) groups.push({ id: 'home', ownerTownId: target.id, ownerOpId: target.ownerId, units: home, research: U.researchLevels(db, target.id) });
for (const g of U.hostedGroups(db, target.id)) {
const ot = db.get('SELECT owner_id FROM towns WHERE id = ?', g.ownerTownId);
groups.push({ id: 'from:' + g.ownerTownId, ownerTownId: g.ownerTownId, ownerOpId: ot ? ot.owner_id : null, units: g.units, research: U.researchLevels(db, g.ownerTownId) });
}
return groups;
}
// Write a defending group's units back after the battle.
function writeGroup(db, hostTownId, group, units) {
const keys = new Set(Object.keys(group.units).concat(Object.keys(units)));
for (const k of keys) {
if (group.id === 'home') U.setHomeUnit(db, hostTownId, k, units[k] || 0);
else U.setStationed(db, hostTownId, group.ownerTownId, k, units[k] || 0);
}
}
function addPoints(db, operatorId, column, v) {
if (!operatorId || !(v > 0)) return;
db.run('INSERT INTO operator_stats (operator_id, attack_points, defense_points) VALUES (?, 0, 0) ON CONFLICT (operator_id) DO NOTHING', operatorId);
db.run('UPDATE operator_stats SET ' + (column === 'attack' ? 'attack_points' : 'defense_points') + ' = ' + (column === 'attack' ? 'attack_points' : 'defense_points') + ' + ? WHERE operator_id = ?', v, operatorId);
}
const sumValues = (list) => list.reduce((acc, u) => U.sumInto(acc, u), {});
// Survivors drive home (with loot). No survivors, no movement.
function sendHome(ctx, mv, survivors, cargo, extra) {
const { db } = ctx;
if (U.isEmpty(survivors)) return null;
const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
if (!dest) return null;
return M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: survivors, cargo: cargo || {}, parentId: mv.id, extra: extra || {} });
}
// What the raiders' home can bank per resource when they are back: Rack hall room minus the stock projected to that moment (pure
// projection, nothing is written). No home or no survivors to carry anything: no room at all (the loot would never be delivered).
function homeRoom(ctx, mv, survivors, now, world) {
const none = { fiber: 0, hardware: 0, capital: 0 };
const dest = U.homeTownFor(ctx.db, mv.ownerId, mv.fromTownId);
if (!dest || U.isEmpty(survivors)) return none;
const home = loadTown(ctx.db, dest.id);
const bankAt = now + R.movementMs(R.distance(mv.to.x, mv.to.y, dest.x, dest.y), survivors, world.speed);
const cur = R.resourcesAt(home, bankAt);
// Room already promised: cargo of other return legs still on the road to this POP (earlier raids, bounced shipments) will be banked
// too, so two raids that each see the same free room cannot both fill it (the later one is limited, not destroyed on landing).
// One-time bonus cargo (extra.bonus) is credited above the cap and holds no room.
const booked = { fiber: 0, hardware: 0, capital: 0 };
for (const row of ctx.db.all("SELECT cargo, extra FROM movements WHERE type = 'return' AND status = 'out' AND to_town_id = ? AND owner_id = ?", dest.id, mv.ownerId)) {
const c = JSON.parse(row.cargo || '{}'), bonus = (JSON.parse(row.extra || '{}').bonus) || {};
for (const r of D.RESOURCES) booked[r] += Math.max(0, (c[r] || 0) - (bonus[r] || 0));
}
const room = {};
for (const r of D.RESOURCES) room[r] = Math.max(0, Math.floor(cur.caps[r] - cur.amounts[r] - booked[r]));
return room;
}
function arrive(ctx, mv, ev) {
const { db } = ctx;
const now = ev.dueAt;
const world = loadWorld(db, mv.worldId);
if (!mv.toTownId) return arriveSite(ctx, mv, now, world);
const targetRow = db.get('SELECT * FROM towns WHERE id = ?', mv.toTownId);
if (!targetRow) return bounce(ctx, mv, now, 'target_gone');
const attackerOp = U.getOperator(db, mv.ownerId);
const defOp = U.getOperator(db, targetRow.owner_id);
if (defOp.id === attackerOp.id) return bounce(ctx, mv, now, 'own_town');
if (mv.type !== 'scan') {
if (R.isProtected(defOp.protection_until, now)) return bounce(ctx, mv, now, 'protected', { until: defOp.protection_until });
if (U.pactBlocks(db, attackerOp.id, defOp.id)) return bounce(ctx, mv, now, 'pact');
}
const target = loadTown(db, targetRow.id);
settle(db, target, now);
const online = P.online(target, now);
const groups = defenderGroups(db, target);
const active = online ? groups : [];
const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null;
if (mv.type === 'scan') return resolveScanOnTown(ctx, mv, now, { target, targetRow, defOp, attackerOp, origin, groups, active, online });
const kind = mv.type === 'raid' ? 'raid' : 'attack';
const fwLevel = target.buildings.firewall ? target.buildings.firewall.level : 0;
const b = R.resolveBattle({
kind, attackers: { units: mv.units, research: mv.extra.research || {} },
defenders: active.map((g) => ({ id: g.id, units: g.units, research: g.research })), firewall: fwLevel,
});
const win = b.attackerWins;
// ---- defenders: losses (a full attack lost by the defender wipes everything in the POP, offline units included)
const wipe = b.defenderLossFraction >= 1;
const groupReports = [];
let defenderLost = {};
for (const g of groups) {
const res = b.defenders.find((d) => d.id === g.id);
let survivors, lost;
if (wipe) { survivors = {}; lost = g.units; }
else if (res) { survivors = res.survivors; lost = res.lost; }
else { survivors = g.units; lost = {}; } // offline and not wiped: untouched
writeGroup(db, target.id, g, survivors);
U.sumInto(defenderLost, lost);
groupReports.push({ id: g.id, ownerTownId: g.ownerTownId, ownerOpId: g.ownerOpId, sent: g.units, lost, survivors, share: res ? res.share : 0, offline: !res });
}
const survivorsAtt = Object.assign({}, b.attacker.survivors);
// ---- loot
let loot = { fiber: 0, hardware: 0, capital: 0 };
const lootLeft = {}; // available and carried, but with no room to bank at home
let hidden = 0;
if (win) {
hidden = kind === 'raid' ? R.cacheFraction(target.buildings.rack_hall ? target.buildings.rack_hall.level : 0) : 0;
const avail = {};
for (const r of D.RESOURCES) avail[r] = target.res[r] * (1 - hidden);
// Only what the raiders' home Rack hall can bank when they arrive is taken; the rest stays with the victim and the report says so (S4).
const room = homeRoom(ctx, mv, survivorsAtt, now, world);
loot = R.lootSplit(R.carryOf(survivorsAtt), avail, room);
const wanted = R.lootSplit(R.carryOf(survivorsAtt), avail);
for (const r of D.RESOURCES) if (wanted[r] > loot[r]) lootLeft[r] = wanted[r] - loot[r];
for (const r of D.RESOURCES) target.res[r] -= loot[r];
db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', target.res.fiber, target.res.hardware, target.res.capital, target.id);
}
// ---- siege: exploit kits tear levels off the chosen building
let siege = null;
if (win && mv.type !== 'raid' && mv.extra.target) {
const levels = R.siegeLevels(survivorsAtt.exploit_kit || 0);
const cur = levels > 0 ? target.buildings[mv.extra.target] : null;
if (cur && cur.level > 0) {
const to = Math.max(0, cur.level - levels);
db.run('UPDATE buildings SET level = ? WHERE town_id = ? AND key = ?', to, target.id, mv.extra.target);
siege = { key: mv.extra.target, type: cur.type, from: cur.level, to };
}
}
// ---- takeover
let takeover = null;
let captured = false;
if (mv.type === 'takeover' && win && (survivorsAtt[D.EXPANSION.conquestUnit] || 0) > 0) {
const defTowns = db.get('SELECT COUNT(*) AS n FROM towns WHERE owner_id = ?', defOp.id).n;
const block = R.takeoverBlock(!!targetRow.is_capital, defTowns);
const gate = R.footprintGate(U.operatorTowns(db, attackerOp.id).length, U.operatorFootprint(db, attackerOp.id, now));
takeover = { attempted: true, blocked: block === 'last_pop' ? 'last_pop' : (gate.ok ? null : 'footprint'), capital: block === 'capital', loyaltyBefore: target.loyalty, loyaltyAfter: target.loyalty, drop: 0, captured: false };
if (takeover.blocked === null) {
const rand = R.rng(R.hash(world.seed, mv.id, 0x7a11))();
const drop = R.loyaltyDrop(rand);
const after = Math.max(0, target.loyalty - drop);
const left = survivorsAtt[D.EXPANSION.conquestUnit] - 1; // the M&A team that did the talking is used up
if (left > 0) survivorsAtt[D.EXPANSION.conquestUnit] = left; else delete survivorsAtt[D.EXPANSION.conquestUnit];
db.run('UPDATE towns SET loyalty = ?, loyalty_at = ? WHERE id = ?', after, now, target.id);
Object.assign(takeover, { drop, loyaltyAfter: after });
if (after <= 0 && block === null) { transferTown(ctx, target, attackerOp, defOp, now); captured = true; takeover.captured = true; }
}
}
// ---- battle points
const attLost = b.attacker.lost;
addPoints(db, attackerOp.id, 'attack', R.battlePoints(defenderLost));
const defPts = R.battlePoints(attLost);
for (const g of groupReports) addPoints(db, g.ownerOpId, 'defense', defPts * g.share);
P.reschedule(ctx, target.id, now);
const ret = sendHome(ctx, mv, survivorsAtt, loot);
// ---- reports
const data = {
type: mv.type, outcome: win ? 'attacker_won' : 'defender_won', arrivedAt: now,
attacker: { operator: opBrief(attackerOp), town: townBrief(origin), units: { sent: mv.units, lost: attLost, survivors: survivorsAtt } },
defender: { operator: opBrief(defOp), town: townBrief(target), online, groups: groupReports.map((g) => ({ ownerTownId: g.ownerTownId, sent: g.sent, lost: g.lost, survivors: g.survivors, offline: g.offline })) },
power: { attack: b.A, defence: b.D, defenceRaw: b.defenceRaw, firewallLevel: fwLevel, effectiveFirewall: b.effectiveFirewall },
loot, lootLeft, cacheHidden: hidden, siege, takeover, capturedTown: captured, returnMovementId: ret ? ret.id : null,
};
const summary = { type: mv.type, outcome: data.outcome, attacker: opBrief(attackerOp), defender: opBrief(defOp), target: townBrief(target), loot, captured };
const recipients = [{ userId: U.userOfOperator(db, attackerOp.id), role: 'attacker' }, { userId: U.userOfOperator(db, defOp.id), role: 'defender' }];
for (const g of groupReports) if (g.id !== 'home' && g.ownerOpId) recipients.push({ userId: U.userOfOperator(db, g.ownerOpId), role: 'reinforcer' });
createReport(ctx, { worldId: mv.worldId, type: mv.type, now, summary, data, recipients });
}
// ---- scans
function resolveScanOnTown(ctx, mv, now, s) {
const { db } = ctx;
const { target, defOp, attackerOp, origin, groups, active, online } = s;
const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research);
let sd = 0;
for (const g of active) sd += R.scanStrength(g.units.port_scanner || 0, g.research);
const res = R.resolveScan(sa, sd);
const loss = R.applyLoss(mv.units, res.lossFraction);
let intel = null;
if (res.success) {
intel = {
detail: res.detail, online,
units: { home: U.homeUnits(db, target.id), stationed: groups.filter((g) => g.id !== 'home').map((g) => ({ ownerTownId: g.ownerTownId, units: g.units })) },
resources: { fiber: target.res.fiber, hardware: target.res.hardware, capital: target.res.capital },
};
if (res.detail === 'full') {
intel.buildings = Object.keys(target.buildings).map((k) => ({ key: k, type: target.buildings[k].type, level: target.buildings[k].level }));
intel.loyalty = target.loyalty;
intel.outgoing = db.all("SELECT id, type, to_x, to_y, arrive_at FROM movements WHERE from_town_id = ? AND status = 'out' AND type != 'return' ORDER BY arrive_at, id", target.id)
.map((m) => ({ type: m.type, to: { x: m.to_x, y: m.to_y }, arriveAt: m.arrive_at }));
}
}
const aData = { success: res.success, detail: res.detail, scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, strength: { attacker: sa, defender: sd }, target: townBrief(target), operator: opBrief(defOp), intel };
createReport(ctx, {
worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, target: townBrief(target), operator: opBrief(defOp) },
data: aData, recipients: [{ userId: U.userOfOperator(db, attackerOp.id), role: 'attacker' }],
});
const dData = { identityRevealed: res.identityRevealed, target: townBrief(target), by: res.identityRevealed ? { operator: opBrief(attackerOp), town: townBrief(origin) } : null };
createReport(ctx, {
worldId: mv.worldId, type: 'scan_detected', now, summary: { identityRevealed: res.identityRevealed, target: townBrief(target), by: dData.by && dData.by.operator },
data: dData, recipients: [{ userId: U.userOfOperator(db, defOp.id), role: 'defender' }],
});
sendHome(ctx, mv, loss.survivors, {});
}
// ---- incumbent sites (NPC): static defence, no losses for the site, never attack
function arriveSite(ctx, mv, now, world) {
const { db } = ctx;
const { x, y } = mv.to;
const tile = R.tileAt(world.seed, world.map_radius, x, y, R.worldAgeDays(world.start_at, now, world.speed));
if (tile.type === 'backbone') return require('./landing')(ctx, mv, now, world, tile); // end game: backbone landing site
if (tile.type !== 'incumbent' || (mv.type !== 'scan' && mv.type !== 'attack')) return bounce(ctx, mv, now, 'invalid_target');
const attackerOp = U.getOperator(db, mv.ownerId);
const ageDays = Math.max(0, (now - world.start_at) / DAY * world.speed);
const staticDef = R.incumbentDefence(world.seed, x, y, ageDays);
const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null;
const site = { x, y, type: 'incumbent' };
const uid = U.userOfOperator(db, attackerOp.id);
if (mv.type === 'scan') {
const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research);
const res = R.resolveScan(sa, D.INCUMBENT.scanStrength);
const loss = R.applyLoss(mv.units, res.lossFraction);
const taken = !!db.get('SELECT 1 AS x FROM incumbent_takes WHERE world_id = ? AND x = ? AND y = ? AND operator_id = ?', world.id, x, y, attackerOp.id);
const intel = res.success ? { defence: staticDef, bonusAvailable: !taken, hardwareBonus: D.INCUMBENT.hardwareBonus } : null;
createReport(ctx, {
worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, site },
data: { success: res.success, detail: res.detail, site, scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, intel },
recipients: [{ userId: uid, role: 'attacker' }],
});
sendHome(ctx, mv, loss.survivors, {});
return;
}
const b = R.resolveBattle({ kind: 'attack', attackers: { units: mv.units, research: mv.extra.research || {} }, defenders: [], firewall: 0, staticDefence: staticDef });
const survivors = Object.assign({}, b.attacker.survivors);
let bonus = null;
const cargo = {};
if (b.attackerWins) {
const first = db.run('INSERT OR IGNORE INTO incumbent_takes (world_id, x, y, operator_id, taken_at) VALUES (?, ?, ?, ?, ?)', world.id, x, y, attackerOp.id, now);
if (first.changes) {
cargo.hardware = D.INCUMBENT.hardwareBonus;
bonus = { hardware: D.INCUMBENT.hardwareBonus, researchSpeedBonus: R.researchSpeedBonus(U.incumbentTakes(db, attackerOp.id)) };
}
}
// The once-only bonus is delivered in full even when the Rack hall is full (stock above the hall size is kept, it only stops growing): a reward
// that can never be earned again must not vanish at the door (S4, events/return.js reads extra.bonus).
const ret = sendHome(ctx, mv, survivors, cargo, bonus ? { bonus: { hardware: bonus.hardware } } : {});
createReport(ctx, {
worldId: mv.worldId, type: 'incumbent', now,
summary: { outcome: b.attackerWins ? 'attacker_won' : 'defender_won', site, bonus },
data: {
outcome: b.attackerWins ? 'attacker_won' : 'defender_won', arrivedAt: now, site, origin: townBrief(origin),
attacker: { operator: opBrief(attackerOp), units: { sent: mv.units, lost: b.attacker.lost, survivors } },
power: { attack: b.A, defence: b.D }, bonus, returnMovementId: ret ? ret.id : null,
},
recipients: [{ userId: uid, role: 'attacker' }],
});
}
// A takeover completed: the POP changes owner. Pending work of the old owner stops, reinforcements of the old owner
// standing elsewhere are re-homed, the new owner starts at conqueredLoyalty.
function transferTown(ctx, town, newOp, oldOp, now) {
const { db } = ctx;
require('./garrison').releaseTown(ctx, town.id, 'town_lost'); // what this POP had standing in a landing site goes home to its old owner (E6)
db.run('UPDATE towns SET owner_id = ?, is_capital = 0, loyalty = ?, loyalty_at = ? WHERE id = ?', newOp.id, D.EXPANSION.conqueredLoyalty, now, town.id);
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE town_id = ? AND type IN ('trainDone', 'researchDone') AND status = 'pending'", now, town.id);
db.run("UPDATE events SET payload = json_set(payload, '$.userId', ?) WHERE town_id = ? AND type = 'buildDone' AND status = 'pending'", U.userOfOperator(db, newOp.id), town.id);
// units of the old owner that were hosted here (should be dead already) or that belonged to this POP and stand elsewhere
const home = U.homeTownFor(db, oldOp.id);
for (const g of U.awayGroups(db, town.id)) {
db.run('DELETE FROM stationed WHERE host_town_id = ? AND owner_town_id = ?', g.hostTownId, town.id);
if (!home) continue;
if (home.id === g.hostTownId) U.addHome(db, home.id, g.units); else U.addStationed(db, g.hostTownId, home.id, g.units);
}
db.run('DELETE FROM town_power WHERE town_id = ?', town.id);
require('../trade').onTownTransferred(ctx, town.id, now); // open Internet exchange offers of the old owner end, the escrow stays in the POP
const oldUser = U.userOfOperator(db, oldOp.id), newUser = U.userOfOperator(db, newOp.id);
if (oldUser) ctx.notify(oldUser, town.worldId, 'town_lost', { townId: town.id, name: town.name, by: opBrief(newOp) });
if (newUser) ctx.notify(newUser, town.worldId, 'town_gained', { townId: town.id, name: town.name });
}
module.exports = { arrive, defenderGroups, transferTown };