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

139 lines
8.3 KiB
JavaScript

'use strict';
/*
* Garrisons at backbone landing sites (docs/DECISIONS.md E6): units of an operator whose alliance holds the site, standing in the
* site and defending it on top of its static defence. Table `site_stationed(site_id, owner_town_id, unit, count)`.
*
* Rules in one place:
* - Only members of the HOLDING alliance may station units (checked when sending and again when the units arrive).
* - The units draw the power of their OWNER's POP (state.unitDraw), so garrisoning moves no power around; they are online
* exactly when that POP's units are. Always loadTown + settle the owner BEFORE changing its garrison (the draw is part of its rates).
* - A unit lives in exactly one place: home (town_units), stationed in a POP, in a garrison, or in a movement. Every function here
* moves units, none creates or deletes them except through a battle report (losses) or `lost` below (no POP to go home to).
* - Units leave a garrison only by (a) the owner withdrawing them, (b) the owner leaving/being kicked from the alliance or the alliance
* dissolving, (c) the owner's POP changing hands, (d) dying in a battle, (e) decommission when the owner's POP has no power.
* (a) to (c) are return movements to the owner's home, so nothing is ever lost on the way.
*/
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { GameError } = require('../errors');
const { loadTown, settle } = require('../state');
const U = require('./units');
const M = require('./movements');
const P = require('./power');
// Units of one owner POP in a site as { unit: count }.
function ownedAt(db, siteId, ownerTownId) {
const out = {};
for (const r of db.all('SELECT unit, count FROM site_stationed WHERE site_id = ? AND owner_town_id = ?', siteId, ownerTownId)) out[r.unit] = r.count;
return out;
}
// Everything standing in a site, grouped by owner POP: [{ ownerTownId, ownerOpId, units }] (ordered by owner POP id: a stable battle order).
function groups(db, siteId) {
const by = new Map();
for (const r of db.all('SELECT s.owner_town_id AS tid, s.unit AS unit, s.count AS count, t.owner_id AS oid FROM site_stationed s LEFT JOIN towns t ON t.id = s.owner_town_id WHERE s.site_id = ? ORDER BY s.owner_town_id, s.unit', siteId)) {
if (!by.has(r.tid)) by.set(r.tid, { ownerTownId: r.tid, ownerOpId: r.oid, units: {} });
by.get(r.tid).units[r.unit] = r.count;
}
return Array.from(by.values());
}
// All units an owner POP has standing in sites (its draw): { unit: count }.
function ofTown(db, ownerTownId) {
const out = {};
for (const r of db.all('SELECT unit, SUM(count) AS n FROM site_stationed WHERE owner_town_id = ? GROUP BY unit', ownerTownId)) out[r.unit] = r.n;
return out;
}
function setUnit(db, siteId, ownerTownId, unit, count) {
if (count > 0) db.run('INSERT INTO site_stationed (site_id, owner_town_id, unit, count) VALUES (?, ?, ?, ?) ON CONFLICT (site_id, owner_town_id, unit) DO UPDATE SET count = excluded.count', siteId, ownerTownId, unit, count);
else db.run('DELETE FROM site_stationed WHERE site_id = ? AND owner_town_id = ? AND unit = ?', siteId, ownerTownId, unit);
}
function add(db, siteId, ownerTownId, units) {
const cur = ownedAt(db, siteId, ownerTownId);
for (const k of Object.keys(units || {})) if (units[k] > 0) setUnit(db, siteId, ownerTownId, k, (cur[k] || 0) + units[k]);
}
function remove(db, siteId, ownerTownId, units) {
const cur = ownedAt(db, siteId, ownerTownId);
for (const k of Object.keys(units || {})) if (units[k] > 0 && (cur[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: cur[k] || 0, want: units[k] });
for (const k of Object.keys(units || {})) if (units[k] > 0) setUnit(db, siteId, ownerTownId, k, cur[k] - units[k]);
}
// Defence figures of a site's garrison at `now`: only groups whose owner POP is online defend (like units at home). Reads only (online is projected).
// -> { groups: [{ id, ownerTownId, ownerOpId, units, research, online }], power: raw defence of the online groups }
function defenders(db, siteId, now) {
const out = [];
let power = 0;
for (const g of groups(db, siteId)) {
const town = loadTown(db, g.ownerTownId);
const online = !town || P.online(town, now);
const research = U.researchLevels(db, g.ownerTownId);
out.push({ id: 'from:' + g.ownerTownId, ownerTownId: g.ownerTownId, ownerOpId: g.ownerOpId, units: g.units, research, online });
if (online) power += R.defencePower(g.units, research);
}
return { groups: out, power };
}
// Take `units` out of the site and send them home to their owner (the owner POP, or the operator's capital/oldest POP when that POP has changed
// hands). The owner POP is settled first and its power rescheduled. -> the return movement, or null when the owner has no POP left (units gone).
function sendHome(ctx, site, ownerTownId, units, extra) {
const { db, now } = ctx;
units = Object.fromEntries(Object.entries(units).filter(([, n]) => n > 0));
if (U.isEmpty(units)) return null;
const ownerTown = db.get('SELECT * FROM towns WHERE id = ?', ownerTownId);
const town = ownerTown ? loadTown(db, ownerTownId) : null;
if (town) settle(db, town, now); // the draw of the owner changes now
remove(db, site.id, ownerTownId, units);
if (town) P.reschedule(ctx, town.id, now);
const opId = ownerTown ? ownerTown.owner_id : null;
const dest = opId ? U.homeTownFor(db, opId, ownerTownId) : null;
if (!dest) return null;
return M.launchReturn(ctx, { worldId: site.world_id, ownerId: dest.owner_id, fromTownId: null, at: { x: site.x, y: site.y }, to: dest, units, cargo: {}, extra: Object.assign({ garrison: true }, extra || {}) });
}
// Everything of one owner POP in one site goes home. -> units sent
function releaseGroup(ctx, site, ownerTownId, reason) {
const units = ownedAt(ctx.db, site.id, ownerTownId);
if (U.isEmpty(units)) return {};
const mv = sendHome(ctx, site, ownerTownId, units, { released: reason });
const t = ctx.db.get('SELECT owner_id AS oid, world_id AS wid FROM towns WHERE id = ?', ownerTownId);
const uid = t ? U.userOfOperator(ctx.db, t.oid) : null;
if (uid) ctx.notify(uid, site.world_id, 'garrison_released', { siteId: site.id, index: site.idx, ownerTownId, reason, units, movementId: mv ? mv.id : null });
return units;
}
// The whole garrison of a site goes home (the holding alliance is gone).
function releaseSite(ctx, site, reason) {
for (const g of groups(ctx.db, site.id)) releaseGroup(ctx, site, g.ownerTownId, reason);
}
// Everything an operator has standing in sites goes home (it left or was kicked from the holding alliance). Only sites of its OLD alliance
// can hold its units, so this takes no alliance argument.
function releaseOperator(ctx, operatorId, reason) {
const { db } = ctx;
const rows = db.all(`SELECT DISTINCT s.site_id AS sid, s.owner_town_id AS tid FROM site_stationed s JOIN towns t ON t.id = s.owner_town_id WHERE t.owner_id = ? ORDER BY s.site_id, s.owner_town_id`, operatorId);
for (const r of rows) releaseGroup(ctx, db.get('SELECT * FROM landing_sites WHERE id = ?', r.sid), r.tid, reason);
}
// A POP changed hands (takeover): whatever it had standing in sites goes home to its OLD owner (like units it had in other POPs).
function releaseTown(ctx, ownerTownId, reason) {
const { db } = ctx;
for (const r of db.all('SELECT DISTINCT site_id AS sid FROM site_stationed WHERE owner_town_id = ? ORDER BY site_id', ownerTownId)) {
releaseGroup(ctx, db.get('SELECT * FROM landing_sites WHERE id = ?', r.sid), ownerTownId, reason);
}
}
// Read model for a site: groups with owner and units, total raw defence (online groups only) and the static part.
function view(db, siteId, now) {
const d = defenders(db, siteId, now);
return {
power: d.power,
groups: d.groups.map((g) => {
const op = g.ownerOpId ? db.get('SELECT id, name FROM operators WHERE id = ?', g.ownerOpId) : null;
const t = db.get('SELECT id, name, x, y FROM towns WHERE id = ?', g.ownerTownId);
return { ownerTownId: g.ownerTownId, townName: t ? t.name : null, operator: op ? { operatorId: op.id, name: op.name } : null, units: g.units, online: g.online, power: R.defencePower(g.units, g.research) };
}),
};
}
module.exports = { ownedAt, groups, ofTown, add, remove, setUnit, defenders, sendHome, releaseGroup, releaseSite, releaseOperator, releaseTown, view };