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

57 lines
3.3 KiB
JavaScript

'use strict';
/* Read models of the end game: world status (the race), the final results, one landing site. Reads catch the event queue up first
* and never write (an untouched site has no row yet and shows as the incumbent's, level 0). */
const R = require('../public/js/rules.js');
const D = require('../public/js/data.js');
const { GameError } = require('./errors');
const { loadWorld } = require('./state');
const A = require('./alliances');
const E = require('./endgame');
const Garrison = require('./military/garrison');
function createEndgameQueries({ db, clock, scheduler }) {
const fresh = () => { scheduler.runDue(); return clock.now(); };
const world = (id) => { const w = loadWorld(db, id); if (!w) throw new GameError('not_found', { what: 'world' }); return w; };
function status(userId, worldId) {
const now = fresh();
return Object.assign({ serverTime: now }, E.statusView(db, world(worldId), now));
}
function results(userId, worldId) {
const now = fresh();
const w = world(worldId);
const row = db.get('SELECT created_at, data FROM world_rankings WHERE world_id = ?', w.id);
if (!row) return { serverTime: now, available: false, status: w.status, winner: E.winnerView(w), endsAt: w.won_at ? w.end_at : null, results: null };
return { serverTime: now, available: true, status: w.status, winner: E.winnerView(w), endsAt: w.end_at, results: JSON.parse(row.data) };
}
// One site. Holders (members of the holding alliance) also get the contribution ledger and what they may do.
function site(userId, siteId) {
const now = fresh();
const row = E.siteRow(db, siteId);
const w = row ? world(row.world_id) : null;
const op = w ? db.get('SELECT * FROM operators WHERE user_id = ? AND world_id = ?', userId, w.id) : null;
if (!row || !op || !E.isOpen(w, now)) throw new GameError('not_found', { what: 'landing site' });
const s = R.backboneSites(w.seed, w.map_radius).find((x) => x.index === row.idx);
const m = A.membership(db, op.id);
const holder = !!(m && row.holder_alliance_id && m.alliance_id === row.holder_alliance_id);
const out = { serverTime: now, site: E.siteView(db, w, s, row), you: { holder, canBuild: holder && R.allianceCan(m.role, 'backboneBuild'), canShip: holder, canAttack: !!op.alliance_id && !(holder), canReinforce: holder } };
if (holder) {
// what defends the site: the static part + the garrison (online groups only), and who owns the units (E6)
const gv = Garrison.view(db, row.id, now);
const mineTowns = new Set(db.all('SELECT id FROM towns WHERE owner_id = ?', op.id).map((t) => t.id));
const st = R.backboneDefence(w.seed, row.x, row.y, E.ageDays(w, now), row.level, true);
out.defence = { static: st, garrison: gv.power, total: st + gv.power };
out.garrison = gv.groups.map((g) => Object.assign({}, g, { mine: mineTowns.has(g.ownerTownId) }));
out.contributions = db.all(`SELECT c.operator_id AS oid, o.name AS name, c.fiber, c.hardware, c.capital FROM landing_contributions c JOIN operators o ON o.id = c.operator_id
WHERE c.site_id = ? ORDER BY (c.fiber + c.hardware + c.capital) DESC, c.operator_id`, row.id)
.map((c) => ({ operatorId: c.oid, name: c.name, fiber: c.fiber, hardware: c.hardware, capital: c.capital }));
}
return out;
}
return { status, results, site };
}
module.exports = { createEndgameQueries };