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:
parent
9104480463
commit
3c23c51902
92 changed files with 4887 additions and 300 deletions
|
|
@ -28,6 +28,8 @@ const { FakeClock } = require(path.join(ROOT, 'server', 'clock.js'));
|
|||
const HOUR = 3600 * 1000;
|
||||
const DAY = 24 * HOUR;
|
||||
|
||||
let stdoutClosed = false; // set when stdout was a pipe that went away (EPIPE)
|
||||
|
||||
class AdminError extends Error {
|
||||
constructor(message, code) { super(message); this.exitCode = code || 1; }
|
||||
}
|
||||
|
|
@ -358,14 +360,64 @@ commands['create-world'] = (args, ctx) => {
|
|||
return { data: { world: w }, lines: ['created world ' + id + ' "' + w.name + '" speed ' + w.speed + ', radius ' + w.map_radius + ', seed ' + w.seed + (endAt ? ', planned end ' + iso(endAt) : '')] };
|
||||
};
|
||||
|
||||
// End a world the way the natural end does: the real `worldEnd` event handler (server/events/worldEnd.js) runs, so the final ranking
|
||||
// snapshot is written (GET /worlds/:id/results becomes available:true), open trade offers are closed with their escrow returned,
|
||||
// every other pending event of the world is cancelled, status becomes 'ended' and every operator gets a `world_ended` notification.
|
||||
// Events of this world that were already due are processed first, in order (like the server's catch-up), so nothing that had
|
||||
// happened by now is lost; handlers run through a guard that skips an event another process has finished meanwhile.
|
||||
function endWorldNow(db, ctx, world) {
|
||||
const { Scheduler } = require(path.join(ROOT, 'server', 'scheduler.js'));
|
||||
const handlers = require(path.join(ROOT, 'server', 'events'));
|
||||
const guarded = {};
|
||||
for (const type of Object.keys(handlers)) {
|
||||
guarded[type] = (c, ev) => {
|
||||
const cur = c.db.get('SELECT status FROM events WHERE id = ?', ev.id);
|
||||
if (cur && cur.status !== 'pending') return; // the running server got there first (we are inside BEGIN IMMEDIATE: no race)
|
||||
return handlers[type](c, ev);
|
||||
};
|
||||
}
|
||||
const now = ctx.now();
|
||||
const logs = [];
|
||||
const sched = new Scheduler({ db, clock: { now: () => now }, handlers: guarded, log: (m) => logs.push(String(m).split('\n')[0]), autoArm: false });
|
||||
let caughtUp = 0;
|
||||
for (;;) {
|
||||
const ev = db.get("SELECT * FROM events WHERE world_id = ? AND status = 'pending' AND due_at <= ? AND type != 'worldEnd' ORDER BY due_at, id LIMIT 1", world.id, now);
|
||||
if (!ev) break;
|
||||
sched.process(ev);
|
||||
caughtUp++;
|
||||
}
|
||||
const evId = db.tx(() => sched.enqueue({ worldId: world.id, dueAt: now, type: 'worldEnd', payload: { reason: 'admin' } }));
|
||||
sched.process(db.get('SELECT * FROM events WHERE id = ?', evId));
|
||||
const ev = db.get('SELECT status, error FROM events WHERE id = ?', evId);
|
||||
if (ev.status !== 'done') throw new AdminError('the worldEnd event failed (' + (ev.error || ev.status) + '); nothing was ended. Handler log: ' + logs.join(' | '));
|
||||
return { caughtUp, logs };
|
||||
}
|
||||
|
||||
commands['end-world'] = (args, ctx) => {
|
||||
const id = idArg(args, 'world-id');
|
||||
const db = openDatabase(ctx);
|
||||
const w = worldOrThrow(db, id);
|
||||
if (w.status === 'ended') return { data: { id, status: 'ended', changed: false }, lines: ['world ' + id + ' is already ended'] };
|
||||
requireFlag(args, 'yes', 'ending world ' + id + ' ("' + w.name + '") stops signups and new joins');
|
||||
db.tx(() => db.run("UPDATE worlds SET status = 'ended', end_at = ? WHERE id = ?", ctx.now(), id));
|
||||
return { data: { id, status: 'ended', changed: true }, lines: ['world ' + id + ' ended'] };
|
||||
if (w.status === 'ended') {
|
||||
const ranked = !!(tableExists(db, 'world_rankings') && db.get('SELECT 1 AS x FROM world_rankings WHERE world_id = ?', id));
|
||||
return { data: { id, status: 'ended', changed: false, ranking: ranked }, lines: ['world ' + id + ' is already ended' + (ranked ? '' : ' (no final ranking snapshot: it was ended by an older version of this command; /results stays unavailable)')] };
|
||||
}
|
||||
const pending = db.get("SELECT COUNT(*) AS n FROM events WHERE world_id = ? AND status = 'pending'", id).n;
|
||||
const offers = tableExists(db, 'trade_offers') ? db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE world_id = ? AND status = 'open'", id).n : 0;
|
||||
requireFlag(args, 'yes', 'ending world ' + id + ' ("' + w.name + '") freezes it for good: it writes the final ranking, closes ' + offers + ' open trade offer(s), ' +
|
||||
'cancels the world\'s ' + pending + ' pending event(s) (movements, training, builds still in progress stop) and every game command then answers world_ended');
|
||||
const before = { pending, offers };
|
||||
const { caughtUp } = endWorldNow(db, ctx, w);
|
||||
const after = worldOrThrow(db, id);
|
||||
const snap = db.get('SELECT data FROM world_rankings WHERE world_id = ?', id);
|
||||
const top = snap ? JSON.parse(snap.data) : null;
|
||||
const cancelled = Number(db.get("SELECT COUNT(*) AS n FROM events WHERE world_id = ? AND status = 'cancelled' AND done_at = ?", id, after.end_at).n);
|
||||
const data = { id, status: after.status, changed: true, endedAt: after.end_at, caughtUpFirst: caughtUp, cancelledEvents: cancelled, closedOffers: before.offers,
|
||||
ranking: !!top, operators: top ? top.totals.operators : 0, alliances: top ? top.totals.alliances : 0 };
|
||||
const lines = ['world ' + id + ' ended at ' + iso(after.end_at) + ' (event worldEnd, reason admin)',
|
||||
'final ranking stored: ' + (top ? top.totals.operators + ' operator(s), ' + top.totals.alliances + ' alliance(s); GET /worlds/' + id + '/results is available' : 'NO'),
|
||||
'processed ' + caughtUp + ' overdue event(s) first, cancelled ' + cancelled + ' pending event(s), closed ' + before.offers + ' open trade offer(s)',
|
||||
'players are told through their notifications (a running server pushes nothing for rows written by the CLI: clients see world_ended on their next request)'];
|
||||
return { data, lines };
|
||||
};
|
||||
|
||||
commands.users = (args, ctx) => {
|
||||
|
|
@ -655,7 +707,7 @@ const HELP_CMDS = {
|
|||
migrate: 'apply pending migrations (the server does this at boot too; creates the file if missing)',
|
||||
worlds: 'list worlds',
|
||||
'create-world': '[--name N] [--speed X] [--radius R] [--seed S] [--end-in 90d] new world (a second one runs in parallel)',
|
||||
'end-world': '<world-id> --yes mark a world ended (no new signups/joins)',
|
||||
'end-world': '<world-id> --yes end a world like the natural end: final ranking, trade escrow back, pending events cancelled',
|
||||
users: '[--banned] list accounts (no hashes, no tokens)',
|
||||
operators: '[--world ID] list operators (a user in a world)',
|
||||
ban: '<username> ban and revoke all tokens; login answers 403',
|
||||
|
|
@ -689,7 +741,7 @@ function helpText() {
|
|||
// main(argv, io) -> exit code. io = { out, err, env, cwd, now } (all optional, for tests).
|
||||
function main(argv, io) {
|
||||
io = io || {};
|
||||
const out = io.out || ((s) => process.stdout.write(s + '\n'));
|
||||
const out = io.out || ((s) => { if (!stdoutClosed) process.stdout.write(s + '\n'); });
|
||||
const err = io.err || ((s) => process.stderr.write(s + '\n'));
|
||||
const env = io.env || process.env;
|
||||
const ctx = { opened: [], cwd: io.cwd || process.cwd(), now: io.now || (() => Date.now()), dbPath: null };
|
||||
|
|
@ -716,4 +768,9 @@ function main(argv, io) {
|
|||
|
||||
module.exports = { main, commands, parseArgs, parseTime, parseDuration, listBackups, pruneSet, backupStamp, verifySnapshot, doBackup, resetPlan, table, AdminError };
|
||||
|
||||
if (require.main === module) process.exitCode = main(process.argv.slice(2));
|
||||
if (require.main === module) {
|
||||
// `admin.js events | head`: a closed pipe is not an error worth a stack trace. The error event is swallowed (the process finishes
|
||||
// normally and keeps its exit code); `stdoutClosed` stops later writes when the event arrives before the output is done.
|
||||
process.stdout.on('error', (e) => { if (e && e.code === 'EPIPE') stdoutClosed = true; else throw e; });
|
||||
process.exitCode = main(process.argv.slice(2));
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue