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 };
};