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
This commit is contained in:
jvanvik 2026-10-12 00:58:12 +02:00
parent 9104480463
commit 3c23c51902
92 changed files with 4887 additions and 300 deletions

View file

@ -13,6 +13,7 @@ module.exports = function allianceKick(ctx, { userId, allianceId, operatorId })
if (!R.outranks(member.role, t.role)) throw new GameError('forbidden', { need: 'outrank', role: member.role, targetRole: t.role });
const target = db.get('SELECT id, name FROM operators WHERE id = ?', operatorId);
A.removeMember(db, operatorId);
require('../military/garrison').releaseOperator(require('../military/ctx')(ctx), operatorId, 'left_alliance'); // its units standing in the alliance's landing sites go home
A.notifyOperator(ctx, operatorId, 'alliance_kicked', { allianceId: alliance.id, tag: alliance.tag, name: alliance.name });
A.notifyAlliance(ctx, alliance.id, 'alliance_member_left', { allianceId: alliance.id, operatorId, name: target.name, kicked: true });
return { changed: true };

View file

@ -18,6 +18,7 @@ module.exports = function allianceLeave(ctx, { userId, allianceId }) {
return { changed: true, disbanded: true };
}
A.removeMember(db, op.id);
require('../military/garrison').releaseOperator(require('../military/ctx')(ctx), op.id, 'left_alliance'); // its units standing in the alliance's landing sites go home
A.notifyAlliance(ctx, alliance.id, 'alliance_member_left', { allianceId: alliance.id, operatorId: op.id, name: op.name, kicked: false });
return { changed: true, disbanded: false };
};

View file

@ -14,8 +14,8 @@ module.exports = function cancelBuild(ctx, { userId, townId, eventId }) {
if (!ev) throw new GameError('not_found', { what: 'queue entry' });
settle(db, town, now);
const cost = JSON.parse(ev.payload).cost || {};
const cap = require('../../public/js/rules.js').storageCap(town);
for (const r of D.RESOURCES) town.res[r] = Math.min(Math.max(cap, town.res[r]), town.res[r] + Math.floor((cost[r] || 0) * REFUND));
const R = require('../../public/js/rules.js');
for (const r of D.RESOURCES) town.res[r] = Math.min(Math.max(R.storageCapOf(town, r), town.res[r]), town.res[r] + Math.floor((cost[r] || 0) * REFUND));
db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', town.res.fiber, town.res.hardware, town.res.capital, town.id);
db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ?", now, ev.id);
return { cancelled: ev.id };

View file

@ -48,6 +48,7 @@ const handlers = {
tradeAccept: require('./tradeAccept'),
backboneBuild: require('./backboneBuild'),
backboneShip: require('./backboneShip'),
withdrawGarrison: require('./withdrawGarrison'),
};
function createCommands({ db, clock, scheduler }) {

View file

@ -95,9 +95,13 @@ module.exports = function sendMovement(ctx0, args) {
extra.target = t;
}
} else if (type === 'reinforce') {
if (!tgt.town) throw new GameError('invalid_target', { reason: 'no_town' });
if (!U.mayReinforce(db, op.id, tgt.town.owner_id)) throw new GameError('invalid_target', { reason: 'not_allied' });
defOp = U.getOperator(db, tgt.town.owner_id);
if (!tgt.town && tgt.tile.type === 'backbone') {
require('../endgame').checkLandingReinforce(db, world, op, tgt, now, ctx); // the garrison of a landing site: members of the holder only
} else {
if (!tgt.town) throw new GameError('invalid_target', { reason: 'no_town' });
if (!U.mayReinforce(db, op.id, tgt.town.owner_id)) throw new GameError('invalid_target', { reason: 'not_allied' });
defOp = U.getOperator(db, tgt.town.owner_id);
}
} else if (type === 'settle') {
const own = U.operatorTowns(db, op.id);
let nearest = Infinity;
@ -119,6 +123,7 @@ module.exports = function sendMovement(ctx0, args) {
const uid = U.userOfOperator(db, defOp.id);
if (uid) ctx.notify(uid, from.worldId, 'incoming', { movementId: mv.id, toTownId: tgt.town.id, fromTownId: from.id, arriveAt }); // type hidden
}
if (!tgt.town && tgt.tile.type === 'backbone' && (type === 'attack' || type === 'scan')) require('../endgame').notifyLandingIncoming(ctx, world, tgt, op, mv);
return { movementId: mv.id, type, fromTownId: from.id, toTownId: tgt.town ? tgt.town.id : null, to: { x: tgt.x, y: tgt.y }, units, departAt: now, arriveAt, protectionEnded: endProtection };
};
module.exports.resolveTarget = resolveTarget;

View file

@ -5,12 +5,14 @@
* the usual transport rules: capacity, resources),
* - the poster's escrow leaves as a transport to the acceptor's POP (on the link the open offer held in reserve),
* - the offer becomes `accepted`; it is `completed` when both transports have been delivered (see server/trade.js).
* Any failure rolls everything back. Not your own offer; the acceptor's POP needs an Internet exchange and must be in range
* Any failure rolls everything back. Not your own offer; the acceptor's Rack hall must have room for the goods when they arrive
* (projected: stock after paying, plus production, minus other cargo already on its way to this POP), else `no_room_for_goods`
* (goods that do not fit on arrival are destroyed, so the trade is refused up front; economics are otherwise unchanged); the acceptor's POP needs an Internet exchange and must be in range
* (the offer's max distance and the exchange's reach).
*/
const R = require('../../public/js/rules.js');
const { GameError } = require('../errors');
const { settle, loadWorld } = require('../state');
const { settle, loadWorld, loadTown } = require('../state');
const { ownedTown } = require('./build');
const { launchTransport } = require('./sendTransport');
const ctxOf = require('../military/ctx');
@ -32,15 +34,22 @@ module.exports = function tradeAccept(ctx0, { userId, offerId, townId }) {
if (level < 1) throw new GameError('no_transport_link', { links: 0, active: 0 });
if (!R.tradeInRange(dist, o.max_distance, level)) throw new GameError('trade_out_of_range', { distance: dist, maxDistance: o.max_distance, reach: R.tradeReach(level) });
settle(db, mine, now);
settle(db, loadTown(db, poster.id), now); // the escrow leaves the poster's Rack hall now: settle under the cap it shaped (rules.storageCapOf)
// acceptor -> poster: the wanted resource (validates links, capacity and resources, deducts, inserts the movement)
const pay = launchTransport(ctx, mine, poster, { [o.want_res]: o.want_amount }, { tradeId: o.id, role: 'payment' });
// poster -> acceptor: the escrow
const world = loadWorld(db, o.world_id);
const arriveAt = now + R.transportMs(dist, world.speed);
const room = R.resourcesAt(mine, arriveAt); // `mine` is settled and already paid; production until arrival is projected
let booked = 0; // cargo of this resource already on its way here will take room first
for (const row of db.all("SELECT cargo FROM movements WHERE status = 'out' AND to_town_id = ? AND type IN ('transport', 'return')", mine.id)) booked += JSON.parse(row.cargo || '{}')[o.give_res] || 0;
const free = Math.floor(room.caps[o.give_res] - room.amounts[o.give_res] - booked);
if (free < o.give_amount) throw new GameError('no_room_for_goods', { resource: o.give_res, amount: o.give_amount, room: Math.max(0, free) });
const goods = M.insertMovement(ctx, {
worldId: o.world_id, ownerId: o.operator_id, type: 'transport', fromTownId: poster.id, toTownId: mine.id,
from: { x: poster.x, y: poster.y }, to: { x: mine.x, y: mine.y }, units: {}, cargo: { [o.give_res]: o.give_amount },
departAt: now, arriveAt: now + R.transportMs(dist, world.speed), extra: { tradeId: o.id, role: 'goods' },
departAt: now, arriveAt, extra: { tradeId: o.id, role: 'goods' },
});
db.run("UPDATE trade_offers SET status = 'accepted', accepted_by_operator = ?, accepted_town_id = ?, accepted_at = ?, goods_movement_id = ?, payment_movement_id = ? WHERE id = ?",
mine.ownerId, mine.id, now, goods.id, pay.id, o.id);

View file

@ -10,6 +10,6 @@ module.exports = function tradeCancel(ctx0, { userId, offerId }) {
const o = T.getOffer(db, offerId);
if (!o || T.userOfOperator(db, o.operator_id) !== userId) throw new GameError('not_found', { what: 'offer' });
if (o.status !== 'open') throw new GameError('offer_closed', { status: o.status });
T.closeOffer(ctx, o, 'cancelled', now);
return { offerId: o.id, status: 'cancelled', returned: { resource: o.give_res, amount: o.give_amount } };
const back = T.closeOffer(ctx, o, 'cancelled', now);
return { offerId: o.id, status: 'cancelled', returned: { resource: o.give_res, amount: Math.round(back.credited) } };
};

View file

@ -15,7 +15,7 @@ const T = require('../trade');
module.exports = function tradeOffer(ctx, { userId, townId, giveRes, giveAmount, wantRes, wantAmount, maxDistance }) {
const { db, now, scheduler } = ctx;
const town = ownedTown(db, userId, townId);
const terms = R.tradeTermsCheck({ giveRes, giveAmount, wantRes, wantAmount, maxDistance });
const terms = R.tradeTermsCheck({ giveRes, giveAmount, wantRes, wantAmount, maxDistance }, town.speed);
if (!terms.ok) throw new GameError(terms.code, terms);
const links = R.transportLinks(town);
const inUse = M.activeLinks(db, town.id);

View file

@ -0,0 +1,30 @@
'use strict';
/*
* POST /backbone/:id/withdraw {fromTownId, units?}: units of one of YOUR POPs that stand in a landing site go home. Only their owner can
* call them back (the holding alliance has no way to send somebody else's units away; leaving the alliance does it automatically).
* `units` defaults to the whole group. They stop defending the site and stop drawing the owner's power at once, and drive home as a
* return movement (so they are in no battle on the way). Works whoever holds the site now, also after it changed hands.
*/
const { GameError } = require('../errors');
const { ownedTown } = require('./build');
const ctxOf = require('../military/ctx');
const U = require('../military/units');
const G = require('../military/garrison');
const E = require('../endgame');
module.exports = function withdrawGarrison(ctx0, { userId, siteId, fromTownId, units }) {
const ctx = ctxOf(ctx0);
const { db } = ctx;
const site = E.siteRow(db, siteId);
if (!site) throw new GameError('not_found', { what: 'landing site' });
const owner = ownedTown(db, userId, fromTownId);
if (owner.worldId !== site.world_id) throw new GameError('not_found', { what: 'town' });
const have = G.ownedAt(db, site.id, owner.id);
let take = units && Object.keys(units).length ? U.cleanUnits(units) : have;
take = Object.fromEntries(Object.entries(take).filter(([, n]) => n > 0));
if (U.isEmpty(take)) throw new GameError('not_enough_units', { reason: 'nothing stationed' });
for (const k of Object.keys(take)) if ((have[k] || 0) < take[k]) throw new GameError('not_enough_units', { unit: k, have: have[k] || 0, want: take[k] });
const mv = G.sendHome(ctx, site, owner.id, take, { withdrawn: true });
if (!mv) throw new GameError('conflict', { what: 'no POP to return to' });
return { movementId: mv.id, siteId: site.id, fromTownId: owner.id, units: take, arriveAt: mv.arriveAt };
};

View file

@ -5,8 +5,9 @@
* Representation (DECISIONS.md E1): a landing site is NOT a POP. It is a row of `landing_sites` (position from the world seed,
* holder alliance, node level, stockpile, build in progress). The tile reads 'backbone' (rules.tileAt with the world age) from
* D.ENDGAME.openDay on; before that it is plain land that nobody may settle or spawn on. A site is defended by a static value
* only (rules.backboneDefence: incumbent defence x defenceMult, + a bonus per node level), so there are no reinforcements at a
* site. Holders keep the level when the site is taken; the stockpile and a running build stay with the site as well.
* (rules.backboneDefence: incumbent defence x defenceMult while nobody holds it, x heldDefenceMult once an alliance does, + a bonus per node
* level) PLUS the garrison its holders station there (server/military/garrison.js, DECISIONS E6). The level stays with the site when it is
* taken; the stockpile and a running build stay with the site as well.
*
* Time: world age is in world days (real days x speed). Everything here takes `now` (ms) from the caller.
*/
@ -61,7 +62,7 @@ function siteView(db, world, s, row) {
id: row ? row.id : null, index: s.index, x: s.x, y: s.y,
holder: row ? allianceInfo(db, row.holder_alliance_id) : null,
takenBy: row ? opBrief(db, row.holder_operator_id) : null, takenAt: row ? row.taken_at : null,
level, maxLevel: E.maxLevel, progress: level / E.maxLevel, pool, build,
level, maxLevel: E.maxLevel, progress: level / E.maxLevel, pool, build, shieldUntil: row && shieldUntil(row, world) || null,
next: level < E.maxLevel ? { toLevel: level + 1, cost: R.backboneCost(level + 1), durationMs: R.backboneTimeMs(level + 1, world.speed) } : null,
};
}
@ -121,14 +122,31 @@ function notifyWorld(ctx, worldId, type, payload) {
// ---------------------------------------------------------------- taking a site, winning, the end
// Sending checks (sendMovement): landing sites can be scanned and attacked, nothing else. Attacking needs an alliance; you cannot
// attack a site your own alliance or a pact partner holds.
// Sending checks (sendMovement): landing sites can be scanned and attacked, and reinforced by members of the alliance that holds them;
// nothing else. Attacking needs an alliance; you cannot attack a site your own alliance or a pact partner holds.
function checkLandingTarget(db, world, op, tgt, type, now, ctx) {
if (type !== 'scan' && type !== 'attack') throw new GameError('invalid_target', { reason: 'landing_scan_or_attack_only' });
if (type !== 'attack') return;
if (!op.alliance_id) throw new GameError('invalid_target', { reason: 'no_alliance' });
const row = ensureSites(db, world, now, ctx).find((r) => r.idx === tgt.tile.site);
denyIfFriendly(db, op, row);
const until = shieldUntil(row, world);
if (until > now) throw new GameError('invalid_target', { reason: 'site_shielded', until });
}
// A site that changed hands is shielded for D.ENDGAME.captureShieldHours (E6): its new holders need time to garrison it. 0 = not shielded (unheld sites never are).
function shieldUntil(row, world) {
return row && row.holder_alliance_id && row.taken_at ? R.siteShieldUntil(row.taken_at, world.speed) : 0;
}
// Reinforcing a landing site (the garrison, E6): members of the holding alliance only. Checked again when the units arrive.
function checkLandingReinforce(db, world, op, tgt, now, ctx) {
const row = ensureSites(db, world, now, ctx).find((r) => r.idx === tgt.tile.site);
if (!op.alliance_id || !row || !row.holder_alliance_id || row.holder_alliance_id !== op.alliance_id) throw new GameError('invalid_target', { reason: 'not_holder' });
}
// Tell the holders that something is on its way to their site (the type is hidden, like `incoming` for a POP). Nothing for an unheld site.
function notifyLandingIncoming(ctx, world, tgt, op, mv) {
const row = siteAt(ctx.db, world.id, tgt.tile.site);
if (!row || !row.holder_alliance_id || row.holder_alliance_id === op.alliance_id) return;
notifyAlliance(ctx, row.holder_alliance_id, 'backbone_incoming', { siteId: row.id, index: row.idx, x: row.x, y: row.y, arriveAt: mv.arriveAt });
}
function denyIfFriendly(db, op, row) {
if (!row || !row.holder_alliance_id) return;
@ -163,7 +181,10 @@ function maybeWin(ctx, site, now) {
}
// An alliance is gone: its sites are the incumbent's again (the level stays with the site).
function onAllianceDissolved(ctx, allianceId) {
function onAllianceDissolved(ctx0, allianceId) {
const ctx = require('./military/ctx')(ctx0);
const G = require('./military/garrison');
for (const s of ctx.db.all('SELECT * FROM landing_sites WHERE holder_alliance_id = ?', allianceId)) G.releaseSite(ctx, s, 'alliance_dissolved'); // the garrison goes home
ctx.db.run('UPDATE landing_sites SET holder_alliance_id = NULL WHERE holder_alliance_id = ?', allianceId);
}
@ -188,5 +209,5 @@ function deliverShipment(ctx, mv, now) {
module.exports = {
DAY, ageDays, phase, isOpen, ensureSites, siteRow, siteAt, siteStates, siteView, allianceInfo, opBrief, winnerView, statusView,
guard, worldOfCommand, notifyAlliance, notifyWorld, checkLandingTarget, denyIfFriendly, transferSite, maybeWin, onAllianceDissolved, deliverShipment,
guard, worldOfCommand, notifyAlliance, notifyWorld, checkLandingTarget, shieldUntil, checkLandingReinforce, notifyLandingIncoming, denyIfFriendly, transferSite, maybeWin, onAllianceDissolved, deliverShipment,
};

View file

@ -7,6 +7,7 @@ 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(); };
@ -35,8 +36,14 @@ function createEndgameQueries({ db, clock, scheduler }) {
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) } };
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 }));

View file

@ -61,6 +61,7 @@ const CODES = {
offer_closed: [409, 'That offer is not open any more.'],
own_offer: [409, 'You cannot accept your own offer.'],
trade_out_of_range: [409, 'That POP is too far from the offer (its max distance or your Internet exchange reach).'],
no_room_for_goods: [409, 'Your Rack hall will not have room for the goods when they arrive; make room (spend, or raise the hall) and accept again.'],
world_ended: [409, 'This world has ended: it can still be read, but nothing can be changed.'],
backbone_closed: [409, 'The backbone landing sites have not appeared yet.'],
};

View file

@ -22,7 +22,7 @@ module.exports = function ret(ctx, ev) {
const town = loadTown(db, dest.id);
settle(db, town, ev.dueAt);
U.addHome(db, town.id, mv.units);
const lost = addCargo(db, town, mv.cargo);
const lost = addCargo(db, town, mv.cargo, mv.extra && mv.extra.bonus);
P.reschedule(ctx, town.id, ev.dueAt);
// Empty carriers coming home (extra.link) are silent; a bounced shipment that carries cargo is not: its overflow is reported.
const carrying = D.RESOURCES.some((r) => mv.cargo && mv.cargo[r] > 0);

View file

@ -6,7 +6,7 @@ const T = require('../trade');
module.exports = function tradeExpire(ctx, ev) {
const o = T.getOffer(ctx.db, ev.payload.offerId);
if (!o || o.status !== 'open') return;
T.closeOffer(ctx, o, 'expired', ev.dueAt);
const back = T.closeOffer(ctx, o, 'expired', ev.dueAt);
const uid = T.userOfOperator(ctx.db, o.operator_id);
if (uid) ctx.notify(uid, o.world_id, 'trade_expired', { offerId: o.id, townId: o.town_id, returned: { resource: o.give_res, amount: o.give_amount } });
if (uid) ctx.notify(uid, o.world_id, 'trade_expired', { offerId: o.id, townId: o.town_id, returned: { resource: o.give_res, amount: Math.round(back.credited) } });
};

View file

@ -0,0 +1,12 @@
-- Garrisons at backbone landing sites (docs/DECISIONS.md E6). Units of owner_town_id's operator standing in a landing site that the
-- operator's alliance holds. They defend the site (on top of its static defence) and draw the OWNER's power (state.unitDraw), because
-- a site has no power budget of its own. Same shape as `stationed`, whose host is a POP; a site is not a POP (E1), hence a table of its own.
-- Written only by commands/events inside their transaction; the bot ledger counts these units as alive.
CREATE TABLE site_stationed (
site_id INTEGER NOT NULL REFERENCES landing_sites(id),
owner_town_id INTEGER NOT NULL REFERENCES towns(id),
unit TEXT NOT NULL,
count INTEGER NOT NULL CHECK (count > 0),
PRIMARY KEY (site_id, owner_town_id, unit)
);
CREATE INDEX site_stationed_owner ON site_stationed(owner_town_id);

View file

@ -17,14 +17,15 @@ const townBrief = (t) => t ? { id: t.id, name: t.name, x: t.x, y: t.y } : null;
const opBrief = (o) => o ? { id: o.id, name: o.name, asNumber: o.as_number } : null;
// Add resources to a SETTLED town, capped at its storage (an amount already above the cap is kept). -> what was lost
function addCargo(db, town, cargo) {
const cap = R.storageCap(town);
// `bonus` (optional, per resource) is part of the cargo that is credited even above the Rack hall size (one-time rewards).
function addCargo(db, town, cargo, bonus) {
const lost = {};
for (const r of D.RESOURCES) {
const add = (cargo && cargo[r]) || 0;
if (!add) continue;
const cur = town.res[r];
const next = Math.min(Math.max(cap, cur), cur + add);
const free = Math.max(0, add - ((bonus && bonus[r]) || 0));
const next = Math.min(Math.max(R.storageCapOf(town, r), cur), cur + free) + (add - free); // escrowed goods of open offers keep their room (storageCapOf)
lost[r] = Math.max(0, Math.round(cur + add - next));
town.res[r] = next;
}
@ -50,6 +51,7 @@ function bounce(ctx, mv, now, reason, details) {
function arriveReinforce(ctx, mv, ev) {
const { db } = ctx;
const now = ev.dueAt;
if (!mv.toTownId) return require('./landing').reinforce(ctx, mv, ev); // a backbone landing site: the garrison (E6)
const target = mv.toTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.toTownId) : null;
if (!target || !U.mayReinforce(db, mv.ownerId, target.owner_id)) return bounce(ctx, mv, now, 'not_allied');
const ownerTown = U.homeTownFor(db, mv.ownerId, mv.fromTownId);

View file

@ -49,12 +49,34 @@ function addPoints(db, operatorId, column, v) {
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) {
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: {} });
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) {
@ -106,12 +128,17 @@ function arrive(ctx, mv, ev) {
// ---- 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);
loot = R.lootSplit(R.carryOf(survivorsAtt), avail);
// 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);
}
@ -163,7 +190,7 @@ function arrive(ctx, mv, ev) {
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, cacheHidden: hidden, siege, takeover, capturedTown: captured, returnMovementId: ret ? ret.id : null,
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' }];
@ -247,7 +274,9 @@ function arriveSite(ctx, mv, now, world) {
bonus = { hardware: D.INCUMBENT.hardwareBonus, researchSpeedBonus: R.researchSpeedBonus(U.incumbentTakes(db, attackerOp.id)) };
}
}
const ret = sendHome(ctx, mv, survivors, cargo);
// 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 },
@ -264,6 +293,7 @@ function arriveSite(ctx, mv, now, world) {
// 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);

139
server/military/garrison.js Normal file
View file

@ -0,0 +1,139 @@
'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 };

View file

@ -1,9 +1,14 @@
'use strict';
/*
* Arrival of a scan or an attack at a backbone landing site (hooked from combat.arriveSite, runs inside the `arrive` event).
* A site is defended by a static value only: rules.backboneDefence(seed, x, y, world age, node level). Beating it as a member
* of an alliance makes that alliance the holder (level, stockpile and a running build stay with the site). The site never
* loses anything, so there is no loot and no raid; survivors drive home. Re-validates at arrival like every movement.
* 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');
@ -11,10 +16,21 @@ 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);
@ -22,7 +38,27 @@ function sendHome(ctx, mv, survivors) {
return M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: null, at: mv.to, to: dest, units: survivors, cargo: {}, parentId: mv.id, extra: {} });
}
module.exports = function arriveLanding(ctx, mv, now, world, tile) {
// 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);
@ -31,13 +67,24 @@ module.exports = function arriveLanding(ctx, mv, now, world, tile) {
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 staticDef = R.backboneDefence(world.seed, site.x, site.y, E.ageDays(world, now), site.level);
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);
const res = R.resolveScan(sa, SCAN_STRENGTH);
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 intel = res.success ? { defence: staticDef, level: site.level, holder: where.holder, build: site.build_to ? { toLevel: site.build_to, dueAt: site.build_due_at } : null } : null;
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 },
@ -50,18 +97,50 @@ module.exports = function arriveLanding(ctx, mv, now, world, tile) {
// 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: [], firewall: 0, staticDefence: staticDef });
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 } },
power: { attack: b.A, defence: b.D }, taken: b.attackerWins, returnMovementId: ret ? ret.id : null,
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;

View file

@ -14,6 +14,7 @@ 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;
@ -23,10 +24,12 @@ function online(town, now) {
return !(c.amounts.battery <= EPS && c.rates.powerNet < 0);
}
// Every unit drawing power in the POP: home + reinforcements hosted here, as { unit: count }.
// 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;
}
@ -52,7 +55,7 @@ function reschedule(ctx, townId, 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) until the draw fits. The town is settled.
// 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);
@ -77,6 +80,14 @@ function decommission(ctx, town, now) {
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 });

View file

@ -6,7 +6,7 @@
const R = require('../../public/js/rules.js');
const D = require('../../public/js/data.js');
const { GameError } = require('../errors');
const { loadWorld } = require('../state');
const { loadWorld, hasTable } = require('../state');
const U = require('./units');
const P = require('./power');
@ -78,6 +78,16 @@ function movementLists(db, operatorId, townId) {
return out;
}
// [{ siteId, x, y, units }] of one owner POP's units standing in landing sites (the `site_stationed` rows), ordered by site.
function garrisonGroups(db, townId) {
const by = new Map();
for (const r of db.all('SELECT s.site_id AS sid, l.x AS x, l.y AS y, s.unit AS unit, s.count AS count FROM site_stationed s JOIN landing_sites l ON l.id = s.site_id WHERE s.owner_town_id = ? ORDER BY s.site_id, s.unit', townId)) {
if (!by.has(r.sid)) by.set(r.sid, { siteId: r.sid, x: r.x, y: r.y, units: {} });
by.get(r.sid).units[r.unit] = r.count;
}
return Array.from(by.values());
}
// The military part of GET /towns/:id (the town object is already loaded and belongs to the caller).
function townMilitary(db, t, now, world) {
const home = U.homeUnits(db, t.id);
@ -85,6 +95,8 @@ function townMilitary(db, t, now, world) {
const names = townNames(db, U.hostedGroups(db, t.id).map((g) => g.ownerTownId).concat(U.awayGroups(db, t.id).map((g) => g.hostTownId)));
const hosted = U.hostedGroups(db, t.id).map((g) => ({ ownerTownId: g.ownerTownId, ownerTownName: names.get(g.ownerTownId) ? names.get(g.ownerTownId).name : null, owner: names.get(g.ownerTownId) ? names.get(g.ownerTownId).owner : null, units: g.units }));
const away = U.awayGroups(db, t.id).map((g) => ({ hostTownId: g.hostTownId, hostTownName: names.get(g.hostTownId) ? names.get(g.hostTownId).name : null, units: g.units }));
// Units of this POP standing in backbone landing sites its alliance holds: they draw THIS POP's power (state.unitDraw), so they belong here.
const garrisoned = hasTable(db, 'site_stationed') ? garrisonGroups(db, t.id) : [];
const training = db.all("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending' ORDER BY due_at, id", t.id)
.map((e) => { const p = JSON.parse(e.payload); return { id: e.id, unit: p.unit, count: p.count, building: p.building, startAt: p.startAt, dueAt: e.due_at }; });
const rq = db.get("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'researchDone' AND status = 'pending' ORDER BY due_at, id LIMIT 1", t.id);
@ -99,10 +111,10 @@ function townMilitary(db, t, now, world) {
const op = U.getOperator(db, t.ownerId);
const links = R.transportLinks(t);
return {
units: { home, online, offlineSince: offline ? offline.offline_since : null, stationedHere: hosted, stationedAway: away },
units: { home, online, offlineSince: offline ? offline.offline_since : null, stationedHere: hosted, stationedAway: away, garrisoned },
training, trainable,
research: { levels: U.researchLevels(db, t.id), queue: rq ? { id: rq.id, unit: rp.unit, stat: rp.stat, toLevel: rp.toLevel, startedAt: rp.startedAt, dueAt: rq.due_at } : null, speedBonus: bonus, maxLevel: D.RESEARCH.maxLevel },
transport: { links, active: require('./movements').activeLinks(db, t.id), capacityPerLink: D.TRANSPORT.capacityPerLink },
transport: { links, active: require('./movements').activeLinks(db, t.id), capacityPerLink: R.transportCapacity(world.speed) },
movements: movementLists(db, t.ownerId, t.id),
protectionUntil: op.protection_until,
};

View file

@ -24,6 +24,7 @@ const TOWN_KINDS = {
town_lost: 'townId', town_gained: 'townId',
transport_arrived: 'townId', transport_delivered: 'toTownId',
movement_returned: 'townId', reinforcements_sent_home: 'ownerTownId',
garrison_arrived: 'ownerTownId', garrison_released: 'ownerTownId', // units of that POP joined / left a landing site garrison: its power draw changed
};
// Command args that name a POP the command changed (the receiving POP of a movement is NOT listed: the defender gets

View file

@ -68,7 +68,7 @@ function createQueries({ db, clock, scheduler }) {
id: t.id, name: t.name, x: t.x, y: t.y, isCapital: t.isCapital, ownerId: t.ownerId, worldId: t.worldId,
loyalty, footprint: R.footprintAt(t, now), footprintPerDay: R.footprintPerDay(t),
resources, power, buildings, queue, queueSlots: R.queueSlots(t),
bonus: t.bonus,
bonus: t.bonus, escrow: t.escrow,
military: require('./military/views').townMilitary(db, t, now, world),
},
};

View file

@ -29,6 +29,7 @@ const schemas = {
power: obj({ out: num, draw: num, net: num, buffer: num, bufferCap: num, bufferRate: num, online: bool }),
buildings: arr({ $ref: 'BuildingView' }), queue: arr({ $ref: 'QueueEntry' }), queueSlots: int,
bonus: obj({ fiber: num, hardware: num, capital: num }),
escrow: obj({ fiber: num, hardware: num, capital: num }), // goods in open Internet exchange offers: they still occupy the Rack hall (resources[r].cap already excludes them)
}),
TownResponse: obj({ serverTime: int, town: { $ref: 'Town' } }),
MapTown: obj({ id: int, name: str, x: int, y: int, isCapital: bool, owner: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, alliance: { type: ['object', 'null'], properties: { id: int, tag: str, name: str }, additionalProperties: true }, protected: bool }) }),

View file

@ -21,7 +21,7 @@ module.exports = function addEndgameSchemas(schemas, { int, num, str, bool, obj,
// ---- end game
LandingSite: obj({
id: nint, index: int, x: int, y: int, holder: { type: ['object', 'null'], properties: { allianceId: int, tag: str, name: str }, additionalProperties: true },
takenBy: { type: ['object', 'null'], additionalProperties: true }, takenAt: nint, level: int, maxLevel: int, progress: num, pool: Cost,
takenBy: { type: ['object', 'null'], additionalProperties: true }, takenAt: nint, shieldUntil: nint, level: int, maxLevel: int, progress: num, pool: Cost,
build: { type: ['object', 'null'], properties: { toLevel: int, startedAt: int, dueAt: int }, additionalProperties: true },
next: { type: ['object', 'null'], properties: { toLevel: int, cost: Cost, durationMs: int }, additionalProperties: true },
}),
@ -31,9 +31,13 @@ module.exports = function addEndgameSchemas(schemas, { int, num, str, bool, obj,
}),
WorldResults: obj({ serverTime: int, available: bool, status: str, winner: { type: ['object', 'null'], additionalProperties: true }, endsAt: nint, results: { type: ['object', 'null'], additionalProperties: true } }),
LandingSiteResponse: obj({
serverTime: int, site: { $ref: 'LandingSite' }, you: obj({ holder: bool, canBuild: bool, canShip: bool, canAttack: bool }),
serverTime: int, site: { $ref: 'LandingSite' }, you: obj({ holder: bool, canBuild: bool, canShip: bool, canAttack: bool, canReinforce: bool }),
contributions: arr(obj({ operatorId: int, name: str, fiber: int, hardware: int, capital: int })),
// holders only: what defends the site now (static part + the units members station there) and who owns the units
defence: obj({ static: num, garrison: num, total: num }),
garrison: arr(obj({ ownerTownId: int, townName: nstr, operator: { type: ['object', 'null'], additionalProperties: true }, units: { type: 'object', additionalProperties: true }, online: bool, power: num, mine: bool })),
}, ['serverTime', 'site', 'you']),
GarrisonWithdrawn: obj({ serverTime: int, movementId: int, siteId: int, fromTownId: int, units: { type: 'object', additionalProperties: true }, arriveAt: int }),
BackboneBuildStarted: obj({ serverTime: int, siteId: int, eventId: int, toLevel: int, startedAt: int, dueAt: int, cost: Cost }),
// ---- shared reports
ReportShared: obj({ serverTime: int, changed: bool, reportId: int, allianceId: int }),

View file

@ -29,7 +29,7 @@ module.exports = function addMilitarySchemas(schemas, { int, num, str, bool, obj
settle: obj({ possible: bool, code: { type: ['string', 'null'] }, footprint: num, footprintNeeded: num, maxDistance: int }),
}, ['serverTime', 'x', 'y', 'type', 'distances', 'settle']),
TownMilitary: obj({
units: obj({ home: Units, online: bool, offlineSince: nint, stationedHere: arr(free), stationedAway: arr(free) }),
units: obj({ home: Units, online: bool, offlineSince: nint, stationedHere: arr(free), stationedAway: arr(free), garrisoned: arr(obj({ siteId: int, x: int, y: int, units: Units })) }),
training: arr(obj({ id: int, unit: str, count: int, building: str, startAt: int, dueAt: int })),
trainable: arr(obj({ unit: str, building: str, role: str, cost: Cost, timeMs: int, missing: arr(free), locked: bool })),
research: obj({ levels: free, queue: { type: ['object', 'null'], additionalProperties: true }, speedBonus: num, maxLevel: int }),

View file

@ -47,7 +47,7 @@ function register(router, services) {
summary: 'Take an open offer with one of your POPs: two transports leave at once (your payment, their goods) and the offer is settled when both arrive', tag: 'trade', status: 201,
body: { type: 'object', required: ['townId'], properties: { townId: int1 } },
response: { $ref: 'TradeAccepted' },
errors: errs.concat(['offer_closed', 'own_offer', 'trade_out_of_range', 'no_transport_link', 'capacity_exceeded', 'not_enough_resources', 'world_ended']),
errors: errs.concat(['offer_closed', 'own_offer', 'trade_out_of_range', 'no_room_for_goods', 'no_transport_link', 'capacity_exceeded', 'not_enough_resources', 'world_ended']),
}, ({ user, params, body }) => reply(201, commands.run('tradeAccept', { userId: user.id, offerId: params.id, townId: body.townId })));
}
module.exports = { register };

View file

@ -26,12 +26,18 @@ function register(router, services) {
}, ({ user, params }) => eg.site(user.id, params.id));
router.post('/backbone/:id/ship', {
summary: 'Send resources from one of your POPs to a landing site your alliance holds (a transport: Internet exchange links, 500 each)', tag: 'world', status: 201,
summary: 'Send resources from one of your POPs to a landing site your alliance holds (a transport: Internet exchange links, 1000 each at world speed 1, times the world speed)', tag: 'world', status: 201,
body: { type: 'object', required: ['fromTownId', 'cargo'], properties: { fromTownId: { type: 'integer', minimum: 1 }, cargo: { type: 'object', additionalProperties: true, description: 'fiber/hardware/capital -> amount' } } },
response: { $ref: 'MovementSent' },
errors: errs.concat(['forbidden', 'backbone_closed', 'capacity_exceeded', 'no_transport_link', 'not_enough_resources', 'world_ended']),
}, ({ user, params, body }) => reply(201, commands.run('backboneShip', { userId: user.id, siteId: params.id, fromTownId: body.fromTownId, cargo: body.cargo })));
router.post('/backbone/:id/withdraw', {
summary: 'Call units of one of your POPs home from a landing site\'s garrison (default: all of them). Only their owner can; works whoever holds the site now. Station units with POST /movements type reinforce at the site\'s x,y (members of the holding alliance only)', tag: 'world', status: 201,
body: { type: 'object', required: ['fromTownId'], properties: { fromTownId: { type: 'integer', minimum: 1 }, units: { type: 'object', additionalProperties: true, description: 'defaults to the whole group' } } },
response: { $ref: 'GarrisonWithdrawn' }, errors: errs.concat(['not_enough_units', 'unknown_unit', 'conflict', 'world_ended']),
}, ({ user, params, body }) => reply(201, commands.run('withdrawGarrison', { userId: user.id, siteId: params.id, fromTownId: body.fromTownId, units: body.units })));
router.post('/backbone/:id/build', {
summary: 'Start the next Backbone node level on a landing site your alliance holds (paid from the site\'s stockpile; one level at a time, up to level ' + D.ENDGAME.maxLevel + ')', tag: 'world', status: 201,
response: { $ref: 'BackboneBuildStarted' },

View file

@ -25,6 +25,7 @@ function townFromRow(db, row, world) {
loyalty: row.loyalty, loyaltyAt: row.loyalty_at,
buildings,
unitDraw: unitDraw(db, row.id),
escrow: escrowOf(db, row.id),
bonus: R.ruralBonus(world.seed, world.map_radius, row.x, row.y),
};
}
@ -39,9 +40,20 @@ function unitDraw(db, townId) {
if (hasTable(db, 'stationed')) {
for (const r of db.all('SELECT unit, count FROM stationed WHERE host_town_id = ?', townId)) if (D.UNITS && D.UNITS[r.unit]) draw += D.UNITS[r.unit].draw * r.count;
}
// Units of this POP standing in backbone landing sites (garrisons, E6) draw from their OWNER: a site has no power budget.
if (hasTable(db, 'site_stationed')) {
for (const r of db.all('SELECT unit, SUM(count) AS count FROM site_stationed WHERE owner_town_id = ? GROUP BY unit', townId)) if (D.UNITS && D.UNITS[r.unit]) draw += D.UNITS[r.unit].draw * r.count;
}
return draw;
}
// Goods this POP has escrowed in open Internet exchange offers, per resource: they still occupy the Rack hall (rules.storageCapOf).
function escrowOf(db, townId) {
const out = { fiber: 0, hardware: 0, capital: 0 };
for (const r of db.all("SELECT give_res, SUM(give_amount) AS n FROM trade_offers WHERE town_id = ? AND status = 'open' GROUP BY give_res", townId)) out[r.give_res] = r.n;
return out;
}
const tableCache = new Map();
function hasTable(db, name) {
if (!tableCache.has(db)) tableCache.set(db, new Map());
@ -79,4 +91,4 @@ function pendingBuilds(db, townId) {
.map((e) => Object.assign({ id: e.id, dueAt: e.due_at }, JSON.parse(e.payload)));
}
module.exports = { loadWorld, loadTown, townFromRow, settle, spend, pendingBuilds, hasTable };
module.exports = { loadWorld, loadTown, townFromRow, escrowOf, settle, spend, pendingBuilds, hasTable };

View file

@ -10,8 +10,12 @@
* cancelled the poster took it back: the escrow is credited to the POP again
* expired ttl ran out (event `tradeExpire`): same
* void the poster's POP changed hands while the offer was open: the escrow stays in that POP (it goes with the POP)
* Nothing is created or lost: escrow is returned WITHOUT the Rack hall cap (an amount above the cap is kept, it only stops
* growing); the only loss anywhere is what a delivery cannot store (the existing cargoLost rule of transports).
* Escrowed goods keep occupying the POP's Rack hall (S2 in docs/BALANCE.md, rules.storageCapOf): while an offer is open the stock
* of that resource stops growing at hall size minus escrow, so the refund always fits. Nothing is lost and the escrow is no extra
* storage (decision R1). The one case that can still clip a refund is a Rack hall that was shot down below stock + escrow in the
* meantime; that loss is reported (`trade_refund_clipped`). Every way out of `open` must settle the POP first (the cap changes
* there): closeOffer does, and so does tradeAccept for the poster's POP. The only other loss anywhere in trade is what a delivery
* cannot store (the existing cargoLost rule of transports).
*/
const R = require('../public/js/rules.js');
const D = require('../public/js/data.js');
@ -20,15 +24,17 @@ const M = require('./military/movements');
const COL = { fiber: 'fiber', hardware: 'hardware', capital: 'capital' };
// Credit `amount` of `res` to a POP (settled first, capped by the Rack hall: escrow cannot be used to store past it).
// Credit `amount` of `res` back to a POP that is still carrying the escrow in its Rack hall (the offer is still `open` when this
// runs, so the town's escrow includes it). Settled first. -> the part that did not fit (only after a lowered Rack hall), else 0
function refund(db, townId, res, amount, at) {
const town = loadTown(db, townId);
if (!town) return;
if (!town) return 0;
settle(db, town, at);
// Capped like cancelBuild: stock already above the Rack hall cap stays, but a refund never lifts it further.
const cap = Math.max(R.storageCap(town), town.res[res]);
const next = Math.min(cap, town.res[res] + amount);
// The hall's room once this offer is gone is storageCapOf + amount. Stock already above it stays (like cancelBuild), a refund never lifts it further.
const room = Math.max(R.storageCapOf(town, res) + amount, town.res[res]);
const next = Math.min(room, town.res[res] + amount);
db.run('UPDATE towns SET ' + COL[res] + ' = ? WHERE id = ?', next, townId);
return Math.max(0, town.res[res] + amount - next);
}
const getOffer = (db, id) => db.get('SELECT * FROM trade_offers WHERE id = ?', id) || null;
@ -37,13 +43,18 @@ function expiryMs(speed) { return Math.round(D.TRADE.ttlHours * D.HOUR_MS / (spe
function userOfOperator(db, operatorId) { const o = db.get('SELECT user_id FROM operators WHERE id = ?', operatorId); return o ? o.user_id : null; }
// Close an open offer and give the escrow back to its POP. `status`: cancelled | expired | void. -> the offer row (before)
// Close an open offer and give the escrow back to its POP. `status`: cancelled | expired | void. -> { credited, lost }
function closeOffer(ctx, offer, status, at) {
const { db } = ctx;
const lost = refund(db, offer.town_id, offer.give_res, offer.give_amount, at); // BEFORE the status changes: the open escrow shaped the settle
db.run('UPDATE trade_offers SET status = ?, closed_at = ? WHERE id = ?', status, at, offer.id);
if (offer.expire_event_id) db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", at, offer.expire_event_id);
refund(db, offer.town_id, offer.give_res, offer.give_amount, at);
return offer;
const lostWhole = Math.round(lost);
if (lostWhole > 0) {
const uid = userOfOperator(db, offer.operator_id);
if (uid) ctx.notify(uid, offer.world_id, 'trade_refund_clipped', { offerId: offer.id, townId: offer.town_id, resource: offer.give_res, lost: lostWhole, credited: offer.give_amount - lostWhole });
}
return { credited: offer.give_amount - lost, lost };
}
// A POP changed hands (takeover): its open offers end and the escrow stays with the POP. Called from combat.transferTown.