Upstream/server/military/landing.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

146 lines
9.5 KiB
JavaScript

'use strict';
/*
* Arrival of a scan, an attack or a reinforcement at a backbone landing site (scan/attack hooked from combat.arriveSite, reinforce from
* arrivals.arriveReinforce; all run inside the `arrive` event, at its due time, so waves resolve strictly in arrival order).
*
* Defence of a site = static value (rules.backboneDefence: heavy while nobody holds it, a modest `heldDefenceMult` once an alliance does,
* both growing with the node level) + the garrison: units that members of the holding alliance stationed there (server/military/garrison.js,
* DECISIONS E6), counted with their owner's defence research while their owner POP is online. A lost attack kills the same share of the
* garrison as it would in a POP (ratio^1.5 of its units), so the next wave faces less; a won attack wipes it and the attacker's alliance
* holds the site (level, stockpile and a running build stay with the site). The static part loses nothing; survivors drive home.
* Re-validates at arrival like every movement.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const U = require('./units');
const M = require('./movements');
const E = require('../endgame');
const { createReport } = require('./reports');
const G = require('./garrison');
const P = require('./power');
const { loadTown, loadWorld, settle } = require('../state');
const { bounce, townBrief, opBrief } = require('./arrivals');
const SCAN_STRENGTH = D.ENDGAME.scanStrength; // a landing site counts as this many defending scanners
// Battle points (the same bookkeeping as POP combat; combat.js keeps its own copy of this helper private).
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);
const col = column === 'attack' ? 'attack_points' : 'defense_points';
db.run('UPDATE operator_stats SET ' + col + ' = ' + col + ' + ? WHERE operator_id = ?', v, operatorId);
}
function sendHome(ctx, mv, survivors) {
if (U.isEmpty(survivors)) return null;
const dest = U.homeTownFor(ctx.db, mv.ownerId, mv.fromTownId);
if (!dest) return null;
return M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: null, at: mv.to, to: dest, units: survivors, cargo: {}, parentId: mv.id, extra: {} });
}
// A member of the holding alliance's units reach the site: they join its garrison. Anybody else, or a site that changed hands on the road, bounces them.
function reinforce(ctx, mv, ev) {
const { db } = ctx;
const now = ev.dueAt;
const world = loadWorld(db, mv.worldId);
const tile = R.tileAt(world.seed, world.map_radius, mv.to.x, mv.to.y, E.ageDays(world, now));
if (tile.type !== 'backbone') return bounce(ctx, mv, now, 'invalid_target');
const site = E.ensureSites(db, world, now, ctx).find((r) => r.idx === tile.site);
const op = U.getOperator(db, mv.ownerId);
if (!op.alliance_id || !site.holder_alliance_id || site.holder_alliance_id !== op.alliance_id) return bounce(ctx, mv, now, 'not_holder');
const ownerTown = U.homeTownFor(db, mv.ownerId, mv.fromTownId);
if (!ownerTown) return; // the sender lost every POP meanwhile: nothing to belong to
const town = loadTown(db, ownerTown.id);
settle(db, town, now); // the owner's draw is the same as before the trip, but only from this moment
G.add(db, site.id, ownerTown.id, mv.units);
P.reschedule(ctx, town.id, now);
const uid = U.userOfOperator(db, op.id);
if (uid) ctx.notify(uid, mv.worldId, 'garrison_arrived', { siteId: site.id, index: site.idx, ownerTownId: ownerTown.id, units: mv.units });
}
function arriveLanding(ctx, mv, now, world, tile) {
const { db } = ctx;
if (mv.type !== 'scan' && mv.type !== 'attack') return bounce(ctx, mv, now, 'invalid_target');
const rows = E.ensureSites(db, world, now, ctx);
const site = rows.find((r) => r.idx === tile.site);
const attackerOp = U.getOperator(db, mv.ownerId);
const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null;
const uid = U.userOfOperator(db, attackerOp.id);
const where = { x: site.x, y: site.y, index: site.idx, siteId: site.id, level: site.level, holder: E.allianceInfo(db, site.holder_alliance_id) };
const held = !!site.holder_alliance_id;
const staticDef = R.backboneDefence(world.seed, site.x, site.y, E.ageDays(world, now), site.level, held);
const def = G.defenders(db, site.id, now); // the garrison (read only: nothing changes until the battle is resolved)
const active = def.groups.filter((g) => g.online);
where.held = held;
if (mv.type === 'scan') {
const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research);
let sd = SCAN_STRENGTH;
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);
const garrisonUnits = {};
for (const g of def.groups) U.sumInto(garrisonUnits, g.units);
const intel = res.success ? {
defence: staticDef + def.power, static: staticDef, level: site.level, holder: where.holder, build: site.build_to ? { toLevel: site.build_to, dueAt: site.build_due_at } : null,
garrison: { units: garrisonUnits, power: def.power, offline: def.groups.filter((g) => !g.online).map((g) => g.ownerTownId) },
} : null;
createReport(ctx, {
worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, site: Object.assign({ type: 'backbone' }, where) },
data: { success: res.success, detail: res.detail, site: Object.assign({ type: 'backbone' }, where), scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, intel },
recipients: [{ userId: uid, role: 'attacker' }],
});
sendHome(ctx, mv, loss.survivors);
return;
}
// attack: alliance members only, and not against the own alliance or a pact partner (the world may have changed since it left)
if (!attackerOp.alliance_id) return bounce(ctx, mv, now, 'no_alliance');
try { E.denyIfFriendly(db, attackerOp, site); } catch (e) { return bounce(ctx, mv, now, e.details.reason || 'invalid_target'); }
const shield = E.shieldUntil(site, world);
if (shield > now) return bounce(ctx, mv, now, 'site_shielded', { until: shield }); // it changed hands while the attack was on the road
const b = R.resolveBattle({
kind: 'attack', attackers: { units: mv.units, research: mv.extra.research || {} },
defenders: active.map((g) => ({ id: g.id, units: g.units, research: g.research })), firewall: 0, staticDefence: staticDef,
});
const survivors = Object.assign({}, b.attacker.survivors);
const oldHolder = site.holder_alliance_id;
// ---- the garrison: losses (a won attack wipes every group, offline ones included), written after settling each owner POP (its draw changes)
const wipe = b.attackerWins || b.defenderLossFraction >= 1; // (the offline groups are not in the battle, but a lost site takes them with it)
const garrisonReport = [];
let defenderLost = {};
for (const g of def.groups) {
const res = b.defenders.find((d) => d.id === g.id);
let left, lost;
if (wipe) { left = {}; lost = g.units; } else if (res) { left = res.survivors; lost = res.lost; } else { left = g.units; lost = {}; }
if (!U.isEmpty(lost)) {
const town = loadTown(db, g.ownerTownId);
if (town) settle(db, town, now);
for (const k of Object.keys(g.units)) G.setUnit(db, site.id, g.ownerTownId, k, left[k] || 0);
if (town) P.reschedule(ctx, town.id, now);
}
U.sumInto(defenderLost, lost);
garrisonReport.push({ ownerTownId: g.ownerTownId, ownerOpId: g.ownerOpId, sent: g.units, lost, survivors: left, share: res ? res.share : 0, offline: !res });
}
const attLost = b.attacker.lost;
addPoints(db, attackerOp.id, 'attack', R.battlePoints(defenderLost));
const defPts = R.battlePoints(attLost);
for (const g of garrisonReport) addPoints(db, g.ownerOpId, 'defense', defPts * g.share);
if (b.attackerWins) E.transferSite(ctx, site, attackerOp, now);
const ret = sendHome(ctx, mv, survivors);
const data = {
outcome: b.attackerWins ? 'attacker_won' : 'defender_won', arrivedAt: now, site: Object.assign({ type: 'backbone' }, where), origin: townBrief(origin),
attacker: { operator: opBrief({ id: attackerOp.id, name: attackerOp.name, as_number: attackerOp.as_number }), alliance: E.allianceInfo(db, attackerOp.alliance_id), units: { sent: mv.units, lost: b.attacker.lost, survivors } },
defender: { staticDefence: staticDef, garrison: garrisonReport.map((g) => ({ ownerTownId: g.ownerTownId, operator: g.ownerOpId ? opBrief(U.getOperator(db, g.ownerOpId)) : null, sent: g.sent, lost: g.lost, survivors: g.survivors, offline: g.offline })) },
power: { attack: b.A, defence: b.D, static: staticDef, garrison: b.defenceRaw }, taken: b.attackerWins, returnMovementId: ret ? ret.id : null,
};
const recipients = [{ userId: uid, role: 'attacker' }];
if (oldHolder) for (const m of db.all('SELECT o.user_id AS uid FROM alliance_members am JOIN operators o ON o.id = am.operator_id WHERE am.alliance_id = ?', oldHolder)) recipients.push({ userId: m.uid, role: 'defender' });
createReport(ctx, { worldId: mv.worldId, type: 'landing', now, summary: { outcome: data.outcome, site: data.site, attacker: data.attacker.operator, taken: b.attackerWins }, data, recipients });
}
module.exports = arriveLanding;
module.exports.reinforce = reinforce;