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
122 lines
6.4 KiB
JavaScript
122 lines
6.4 KiB
JavaScript
'use strict';
|
|
/*
|
|
* Unit power: while the battery is empty and net power is negative, the units in a POP are offline (no attack or
|
|
* defence value, cannot move). After MILITARY.decommissionHours (divided by world speed) offline, the most expensive
|
|
* units are decommissioned until the draw fits the output again.
|
|
*
|
|
* Whether units are online right now is always computed from the lazy battery value (`online`), so reads and combat
|
|
* never depend on an event having run. The `powerCheck` event exists for the side effects: the "units offline"
|
|
* notification and the decommission. `reschedule` is idempotent: it cancels the pending check of the POP and enqueues
|
|
* the one that is correct for the current rates. Call it after ANYTHING that changes unit draw or building levels of a
|
|
* POP (units arriving or leaving, losses, buildings finishing or being damaged).
|
|
*/
|
|
const R = require('../../public/js/rules.js');
|
|
const D = require('../../public/js/data.js');
|
|
const { loadTown, settle } = require('../state');
|
|
const U = require('./units');
|
|
const garrison = () => require('./garrison'); // lazy: garrison.js needs this module
|
|
|
|
const EPS = D.MILITARY.batteryEpsilon;
|
|
|
|
// Are the units in this town online at `now`? (the town object may be unsettled: resourcesAt projects it)
|
|
function online(town, now) {
|
|
const c = R.resourcesAt(town, now);
|
|
return !(c.amounts.battery <= EPS && c.rates.powerNet < 0);
|
|
}
|
|
|
|
// Every unit drawing power in the POP: home + reinforcements hosted here + its own units standing in backbone landing sites (they draw
|
|
// their owner's power, E6), as { unit: count }.
|
|
function drawingUnits(db, townId) {
|
|
const out = U.homeUnits(db, townId);
|
|
for (const g of U.hostedGroups(db, townId)) U.sumInto(out, g.units);
|
|
U.sumInto(out, garrison().ofTown(db, townId));
|
|
return out;
|
|
}
|
|
|
|
function reschedule(ctx, townId, now) {
|
|
const { db } = ctx;
|
|
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE town_id = ? AND type = 'powerCheck' AND status = 'pending'", now, townId);
|
|
const town = loadTown(db, townId);
|
|
if (!town) return;
|
|
if (!(town.unitDraw > 0)) { db.run('DELETE FROM town_power WHERE town_id = ?', townId); return; }
|
|
if (online(town, now)) {
|
|
db.run('DELETE FROM town_power WHERE town_id = ?', townId);
|
|
const at = R.batteryEmptyAt(town, now);
|
|
if (at !== null) ctx.enqueue({ worldId: town.worldId, dueAt: at + 1, type: 'powerCheck', townId, payload: { townId } });
|
|
return;
|
|
}
|
|
let row = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', townId);
|
|
if (!row || row.offline_since === null) {
|
|
db.run('INSERT INTO town_power (town_id, offline_since) VALUES (?, ?) ON CONFLICT (town_id) DO UPDATE SET offline_since = excluded.offline_since', townId, now);
|
|
row = { offline_since: now };
|
|
const uid = U.userOfOperator(db, town.ownerId);
|
|
if (uid) ctx.notify(uid, town.worldId, 'units_offline', { townId, since: now });
|
|
}
|
|
ctx.enqueue({ worldId: town.worldId, dueAt: Math.max(now, row.offline_since + R.decommissionMs(town.speed)), type: 'powerCheck', townId, payload: { townId } });
|
|
}
|
|
|
|
// Decommission the most expensive units (home first, then reinforcements, then its own garrison units) until the draw fits. The town is settled.
|
|
function decommission(ctx, town, now) {
|
|
const { db } = ctx;
|
|
const units = drawingUnits(db, town.id);
|
|
const rates = R.ratesPerHour(Object.assign({}, town, { unitDraw: 0 }));
|
|
const plan = R.decommissionPlan(units, rates.powerOut - rates.powerDraw);
|
|
const removed = {};
|
|
const byOwner = new Map(); // userId -> { unit: n }, who lost units
|
|
const note = (userId, unit, n) => { if (!byOwner.has(userId)) byOwner.set(userId, {}); const o = byOwner.get(userId); o[unit] = (o[unit] || 0) + n; };
|
|
const ownerUser = U.userOfOperator(db, town.ownerId);
|
|
for (const unit of Object.keys(plan)) {
|
|
let left = plan[unit];
|
|
const home = U.homeUnits(db, town.id)[unit] || 0;
|
|
const fromHome = Math.min(home, left);
|
|
if (fromHome > 0) { U.setHomeUnit(db, town.id, unit, home - fromHome); left -= fromHome; note(ownerUser, unit, fromHome); }
|
|
for (const g of U.hostedGroups(db, town.id)) {
|
|
if (left <= 0) break;
|
|
const have = g.units[unit] || 0;
|
|
const n = Math.min(have, left);
|
|
if (n > 0) {
|
|
U.setStationed(db, town.id, g.ownerTownId, unit, have - n); left -= n;
|
|
const ot = db.get('SELECT t.owner_id AS oid FROM towns t WHERE t.id = ?', g.ownerTownId);
|
|
note(ot ? U.userOfOperator(db, ot.oid) : null, unit, n);
|
|
}
|
|
}
|
|
if (left > 0) { // its own units standing in landing sites
|
|
const G = garrison();
|
|
for (const r of db.all('SELECT site_id, count FROM site_stationed WHERE owner_town_id = ? AND unit = ? ORDER BY site_id', town.id, unit)) {
|
|
if (left <= 0) break;
|
|
const n = Math.min(r.count, left);
|
|
G.setUnit(db, r.site_id, town.id, unit, r.count - n); left -= n; note(ownerUser, unit, n);
|
|
}
|
|
}
|
|
removed[unit] = plan[unit] - left;
|
|
}
|
|
for (const [userId, lost] of byOwner) if (userId) ctx.notify(userId, town.worldId, 'units_decommissioned', { townId: town.id, units: lost });
|
|
return removed;
|
|
}
|
|
|
|
// Event handler: payload { townId }. Settles the POP to the due time and acts on what it finds.
|
|
function powerCheck(ctx, ev) {
|
|
const { db } = ctx;
|
|
const town = loadTown(db, ev.townId);
|
|
if (!town) return;
|
|
settle(db, town, ev.dueAt);
|
|
if (town.unitDraw > 0 && !online(town, ev.dueAt)) {
|
|
let row = db.get('SELECT offline_since FROM town_power WHERE town_id = ?', town.id);
|
|
if (!row || row.offline_since === null) {
|
|
db.run('INSERT INTO town_power (town_id, offline_since) VALUES (?, ?) ON CONFLICT (town_id) DO UPDATE SET offline_since = excluded.offline_since', town.id, ev.dueAt);
|
|
row = { offline_since: ev.dueAt };
|
|
const uid = U.userOfOperator(db, town.ownerId);
|
|
if (uid) ctx.notify(uid, town.worldId, 'units_offline', { townId: town.id, since: ev.dueAt });
|
|
}
|
|
if (ev.dueAt >= row.offline_since + R.decommissionMs(town.speed)) {
|
|
const removed = decommission(ctx, town, ev.dueAt);
|
|
if (!Object.keys(removed).some((k) => removed[k] > 0)) { // rounding noise, nothing to remove: stand down, never loop
|
|
db.run('DELETE FROM town_power WHERE town_id = ?', town.id);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
reschedule(ctx, town.id, ev.dueAt);
|
|
}
|
|
|
|
module.exports = { online, drawingUnits, reschedule, decommission, powerCheck };
|