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

@ -204,7 +204,7 @@
body.push(h('p', { class: 'detail-desc', text: App.t('map.info.land') }));
}
body.push(row('', App.t('map.info.coords', { x, y })));
if (App.openSend && App.state.towns.length && (town || (special && (special.type === 'incumbent' || (special.type === 'backbone' && !(special.site && special.site.holder && special.site.holder.allianceId === (App.state.operator && App.state.operator.allianceId))))) || (!special && known))) {
if (App.openSend && App.state.towns.length && (town || (special && (special.type === 'incumbent' || special.type === 'backbone')) || (!special && known))) {
body.push(h('button', { class: 'btn wide' + (town && town.owner.id === ownOperatorId() ? '' : ' primary'), type: 'button', onclick: () => App.openSend({ x, y }) }, icon('target'), App.t('send.open')));
}
if (cap && !(town && town.id === cap.id)) body.push(row('', App.t('map.info.distance', { d: App.fmt.dec(R.distance(cap.x, cap.y, x, y)) })));

View file

@ -25,16 +25,25 @@
const urls = { inbox: '/messages/inbox', sent: '/messages/outbox', alliance: '/messages/alliance' };
// ------------------------------------------------------------------ unread badge (works without the screen being open)
const badge = { n: 0, polling: false };
const badge = { n: 0, polling: false, again: false };
async function pollUnread() {
if (!App.state.user || badge.polling || document.hidden) return;
if (!App.state.user || document.hidden) return;
if (badge.polling) { badge.again = true; return; } // a message that lands while a poll is in flight: ask once more
badge.polling = true;
try { const r = await App.api.get('/messages/inbox', { limit: 1 }); setUnread(r.unread || 0); } catch (e) { /* a badge is a convenience */ } finally { badge.polling = false; }
try { const r = await App.api.get('/messages/inbox', { limit: 1 }); setUnread(r.unread || 0); } catch (e) { /* a badge is a convenience */ } finally { badge.polling = false; if (badge.again) { badge.again = false; pollUnread(); } }
}
// App.setBadge (main.js) shows it on this screen's nav button, or summed on the "More" button when the screen lives there.
function setUnread(n) { badge.n = n; App.state.unreadMsgs = n; App.setBadge('messages', n, 'info'); }
setInterval(pollUnread, 60000);
document.addEventListener('visibilitychange', () => { if (!document.hidden) pollUnread(); });
// WebSocket hint {type:'message'} (ws.js forwards every push through api.emit): the unread count is stale, and so is the list on screen.
let shown = false;
App.api.on('push', (msg) => {
if (!msg || msg.type !== 'message' || !App.state.user) return;
pollUnread();
if (!shown) return;
if (thread) fetchThread(false); else if (tab === 'inbox' || tab === 'alliance') loadFeed(tab);
});
App.on('session', () => { setUnread(0); for (const k of Object.keys(feeds)) feeds[k] = blank(); blocks = { items: null, err: null }; thread = null; setTimeout(pollUnread, 800); });
// ------------------------------------------------------------------ loading
@ -314,12 +323,13 @@
h('div', { class: 'card-head page-head' }, h('h1', { id: 'soc-msg-h', text: App.t('screen.messages') }),
h('div', { class: 'soc-head-actions' },
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('common.retry'), onclick: () => { if (thread) fetchThread(false); else if (tab === 'blocked') loadBlocks(); else { feeds[tab] = blank(); loadFeed(tab); } } }, icon('refresh')),
h('button', { class: 'btn small primary', type: 'button', onclick: () => openNew() }, icon('pencil'), App.t('soc.msg.new.go')))),
h('button', { class: 'btn small primary soc-new-btn', type: 'button', onclick: () => openNew() }, icon('pencil'), App.t('soc.msg.new.go')))),
tabsEl, listBox));
},
onShow(params) {
gen++;
gen++; shown = true;
box.querySelector('#soc-msg-h').textContent = App.t('screen.messages');
box.querySelector('.soc-new-btn').lastChild.textContent = App.t('soc.msg.new.go'); // built once in render(): follow a language switch
const labels = { inbox: 'soc.msg.tab.inbox', sent: 'soc.msg.tab.sent', alliance: 'soc.msg.tab.alliance', blocked: 'soc.msg.tab.blocked' };
for (const b of tabsEl.children) b.querySelector('.soc-tabt').textContent = App.t(labels[b.dataset.tab]);
bc = null;
@ -329,6 +339,6 @@
startTick();
pollUnread();
},
onHide() { if (offTick) { offTick(); offTick = null; } gen++; },
onHide() { shown = false; if (offTick) { offTick(); offTick = null; } gen++; },
});
}());

View file

@ -185,6 +185,7 @@
if (d.loot && D.RESOURCES.some((x) => d.loot[x])) {
out.push(sec(App.t('rep.loot'), mil().resChips(d.loot, true), d.cacheHidden ? h('p', { class: 'row-sub', text: App.t('rep.cache', { p: Math.round(d.cacheHidden * 100) }) }) : null));
}
if (d.lootLeft && D.RESOURCES.some((x) => d.lootLeft[x])) out.push(sec(App.t('rep.lootLeft'), mil().resChips(d.lootLeft, true), h('p', { class: 'row-sub', text: App.t('rep.lootLeft.why') })));
if (d.siege) out.push(sec(App.t('rep.siege'), h('p', { text: App.t('rep.siege.line', { name: App.buildingName(d.siege.type), a: d.siege.from, b: d.siege.to }) })));
if (d.takeover) {
const t = d.takeover;
@ -212,6 +213,8 @@
if (d.site && d.site.type === 'backbone') { // end game landing site: the static defence is the number to beat
out.push(sec(App.t('rep.intel'),
kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(intel.defence) })),
Number.isFinite(intel.static) ? kv(App.t('wld.gar.static'), h('span', { class: 'mono', text: num(intel.static) })) : null,
intel.garrison && intel.garrison.power > 0 ? kv(App.t('wld.gar.units'), h('span', { text: mil().unitsText(intel.garrison.units) + ' (' + num(intel.garrison.power) + ')' })) : null,
kv(App.t('wld.levelShort'), h('b', { class: 'mono', text: App.t('wld.level', { n: intel.level || 0, max: D.ENDGAME.maxLevel }) })),
kv(App.t('rep.landing.holder'), h('span', { text: intel.holder ? '[' + intel.holder.tag + '] ' + intel.holder.name : App.t('wld.incumbent') })),
intel.build ? kv(App.t('wld.building', { n: intel.build.toLevel }), h('span', { text: mil().dayTime(intel.build.dueAt) })) : null));
@ -272,6 +275,9 @@
const p = d.power || {};
out.push(sec(App.t('rep.power'), kv(App.t('rep.power.attack'), h('b', { class: 'mono', text: num(p.attack || 0) })), kv(App.t('rep.power.defence'), h('b', { class: 'mono', text: num(p.defence || 0) }))));
out.push(sec(App.t('rep.attackerUnits'), unitsTable(d.attacker.units.sent, d.attacker.units.lost, d.attacker.units.survivors)));
for (const g of (d.defender && d.defender.garrison) || []) { // the garrison (E6): one table per owner POP
out.push(sec(App.t('rep.landing.garrisonOf', { name: g.operator ? g.operator.name : '?' }) + (g.offline ? ' (' + App.t('wld.gar.offline') + ')' : ''), unitsTable(g.sent, g.lost, g.survivors)));
}
out.push(h('button', { class: 'btn wide', type: 'button', 'data-keep': '', onclick: () => { UI.closeSheet(); App.go('world', Number.isInteger(site.index) ? { site: site.index } : null); } }, icon('b-backbone_node'), App.t('map.info.openWorld')));
return out;
}

View file

@ -289,6 +289,7 @@
h('span', { class: 'field-hint', text: App.t('send.siege.hint', { n: D.MILITARY.kitsMin }) })));
}
if (type === 'takeover') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.takeover.hint') }));
if (st.tile.type === 'backbone' && type === 'reinforce') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.landing.reinforce') }));
if (st.tile.type === 'backbone' && (type === 'attack' || type === 'scan')) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.landing.hint', { mult: D.ENDGAME.defenceMult }) }));
if (type === 'transport' && st.tile.town && !st.tile.town.mine) items.push(h('p', { class: 'row-sub wrap', text: App.t('send.transport.rival') }));
if (type === 'raid') items.push(h('p', { class: 'row-sub wrap', text: App.t('send.raid.hint') }));

View file

@ -45,7 +45,7 @@
const d = e.details || {};
if (e.code === 'trade_out_of_range') return App.t('trd.err.range', { d: App.fmt.dec(d.distance || 0), max: d.maxDistance || 0, reach: d.reach || 0 });
if (e.code === 'trade_ratio') return App.t('trd.err.ratio', { n: T.ratioMax });
if (e.code === 'capacity_exceeded') return App.t('trd.err.cap', { n: D.TRANSPORT.capacityPerLink });
if (e.code === 'capacity_exceeded') return App.t('trd.err.cap', { n: R.transportCapacity(speed()) });
return App.errMsg(e);
}
@ -117,7 +117,7 @@
const req = (D.BUILDINGS[EXCH].requires || []).map((r) => App.t('trd.need.req', { building: App.buildingName(r.type), level: r.level })).join(' ');
return h('section', { class: 'card trd-need' },
h('div', { class: 'card-head' }, h('h2', null, icon('b-' + EXCH), App.t('trd.need.title'))),
h('p', { class: 'detail-desc', text: App.t('trd.need.body', { n: T.reachPerLevel, cap: D.TRANSPORT.capacityPerLink }) }),
h('p', { class: 'detail-desc', text: App.t('trd.need.body', { n: T.reachPerLevel, cap: R.transportCapacity(speed()) }) }),
h('p', { class: 'row-sub wrap', text: req }),
h('button', { class: 'btn primary wide', type: 'button', onclick: () => App.go('pop') }, icon('pop'), App.t('trd.need.go')));
}
@ -253,18 +253,18 @@
input.addEventListener('input', () => { F[key] = input.value === '' ? 0 : Math.floor(Number(input.value)) || 0; if (key === 'maxDistance') F.touchedDist = true; refresh(); });
return input;
};
const giveIn = numField('giveAmount', App.t('trd.new.giveAmount'), 1, D.TRANSPORT.capacityPerLink);
const wantIn = numField('wantAmount', App.t('trd.new.wantAmount'), 1, D.TRANSPORT.capacityPerLink);
const giveIn = numField('giveAmount', App.t('trd.new.giveAmount'), 1, R.transportCapacity(speed()));
const wantIn = numField('wantAmount', App.t('trd.new.wantAmount'), 1, R.transportCapacity(speed()));
const distIn = numField('maxDistance', App.t('trd.new.maxDist'), 1, T.maxDistance);
const maxBtn = h('button', { class: 'btn small', type: 'button', onclick: () => { const have = rec ? Math.floor(stock(rec)[F.giveRes]) : 0; F.giveAmount = Math.max(1, Math.min(D.TRANSPORT.capacityPerLink, have)); giveIn.value = String(F.giveAmount); refresh(); } }, App.t('send.all'));
const maxBtn = h('button', { class: 'btn small', type: 'button', onclick: () => { const have = rec ? Math.floor(stock(rec)[F.giveRes]) : 0; F.giveAmount = Math.max(1, Math.min(R.transportCapacity(speed()), have)); giveIn.value = String(F.giveAmount); refresh(); } }, App.t('send.all'));
const matchBtn = h('button', { class: 'btn small', type: 'button', onclick: () => { F.wantAmount = F.giveAmount; wantIn.value = String(F.wantAmount); refresh(); } }, App.t('trd.new.match'));
function validate() {
const out = [];
const chk = R.tradeTermsCheck({ giveRes: F.giveRes, giveAmount: F.giveAmount, wantRes: F.wantRes, wantAmount: F.wantAmount, maxDistance: F.maxDistance });
const chk = R.tradeTermsCheck({ giveRes: F.giveRes, giveAmount: F.giveAmount, wantRes: F.wantRes, wantAmount: F.wantAmount, maxDistance: F.maxDistance }, speed());
if (!chk.ok) {
if (chk.code === 'trade_ratio') out.push(App.t('trd.err.ratio', { n: T.ratioMax }));
else if (chk.code === 'capacity_exceeded') out.push(App.t('trd.err.cap', { n: D.TRANSPORT.capacityPerLink }));
else if (chk.code === 'capacity_exceeded') out.push(App.t('trd.err.cap', { n: R.transportCapacity(speed()) }));
else out.push(App.t('trd.v.' + ((chk.errors && chk.errors[0] && chk.errors[0].path) || 'terms')));
}
if (rec) {
@ -282,14 +282,14 @@
for (const p of problems) msgs.appendChild(h('p', { class: 'reason', text: p }));
submit.disabled = problems.length > 0 || !rec;
if (F.giveAmount >= 1) {
const lo = Math.max(1, Math.ceil(F.giveAmount / T.ratioMax)), hi = Math.min(D.TRANSPORT.capacityPerLink, F.giveAmount * T.ratioMax);
const lo = Math.max(1, Math.ceil(F.giveAmount / T.ratioMax)), hi = Math.min(R.transportCapacity(speed()), F.giveAmount * T.ratioMax);
bandEl.textContent = App.t('trd.new.band', { lo: num(lo), hi: num(hi) });
} else bandEl.textContent = '';
stockEl.textContent = rec ? App.t('trd.have', { n: num(stock(rec)[F.giveRes]), res: App.resName(F.giveRes) }) : '';
clear(note);
const need = Math.max(1, Math.ceil((F.maxDistance || 1) / T.reachPerLevel));
note.appendChild(h('p', { class: 'row-sub wrap', text: App.t('trd.new.level', { lv, reach, need, d: F.maxDistance || 0 }) }));
note.appendChild(h('p', { class: 'row-sub wrap', text: App.t('trd.new.rules', { cap: D.TRANSPORT.capacityPerLink, n: T.ratioMax, ttl: App.fmt.dur(T.ttlHours * D.HOUR_MS / speed()) }) }));
note.appendChild(h('p', { class: 'row-sub wrap', text: App.t('trd.new.rules', { cap: R.transportCapacity(speed()), n: T.ratioMax, ttl: App.fmt.dur(T.ttlHours * D.HOUR_MS / speed()) }) }));
if (rec) { const ls = linkState(rec); note.appendChild(h('p', { class: 'row-sub wrap', text: App.t('trd.new.links', { free: ls.free, links: ls.links }) })); }
}
@ -396,7 +396,7 @@
const lookup = () => { if (xin.value === '' || yin.value === '') return; open(Math.round(Number(xin.value)), Math.round(Number(yin.value))); };
into.appendChild(h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', null, icon('box'), App.t('trd.send.head'))),
h('p', { class: 'detail-desc', text: App.t('trd.send.body', { n: D.TRANSPORT.capacityPerLink }) }),
h('p', { class: 'detail-desc', text: App.t('trd.send.body', { n: R.transportCapacity(speed()) }) }),
S.levels.length > 1 ? h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('send.from') }),
sel(S.levels.map((l) => ({ value: l.townId, text: townName(l.townId) })), sd.fromId, (v) => { sd.fromId = Number(v); }, App.t('send.from'))) : h('p', { class: 'row-sub', text: App.t('send.from') + ': ' + townName(sd.fromId) }),
h('h3', { class: 'sub', text: App.t('trd.send.own') }),

View file

@ -97,6 +97,14 @@
h('button', { class: 'btn small', type: 'button', onclick: (ev) => withdraw(g.hostTownId, td().id, ev.currentTarget) }, icon('return'), App.t('units.callBack'))),
h('p', { class: 'row-sub wrap', text: mil().unitsText(g.units) }))))));
}
const gar = m.units.garrisoned || [];
if (gar.length) { // standing in a landing site: they still draw this POP's power
out.push(h('section', { class: 'card' },
h('div', { class: 'card-head' }, h('h2', null, icon('flag'), App.t('units.garrisoned'))),
h('ul', { class: 'mil-list' }, gar.map((g) => h('li', { class: 'mil-group' },
h('div', { class: 'row' }, h('span', null, h('b', { text: App.t('units.garrisoned.site', { x: g.x, y: g.y }) }))),
h('p', { class: 'row-sub wrap', text: mil().unitsText(g.units) }))))));
}
return out;
}

View file

@ -185,6 +185,7 @@
kids.push(h('div', { class: 'wld-building' }, h('span', { class: 'row-sub wrap' }, App.t('wld.building', { n: s.build.toLevel }) + ' ', cd(s.build.dueAt)), b));
}
if (s.holder && s.id) kids.push(h('div', { class: 'row-sub wrap' }, App.t('wld.stock') + ' ', mil().resChips(s.pool)));
if (s.shieldUntil && s.shieldUntil > now && !ended) kids.push(h('div', { class: 'row-sub wrap' }, h('span', { class: 'pill amber' }, icon('shield'), App.t('wld.shield', { t: mil().dayTime(s.shieldUntil) }))));
const acts = [];
if (kind === 'mine' && s.id) acts.push(h('button', { class: 'btn small primary', type: 'button', disabled: ended, onclick: () => openManage(s) }, icon('up'), App.t('wld.manage')));
if (kind !== 'mine' && App.openSend && App.state.towns.length) acts.push(h('button', { class: 'btn small primary', type: 'button', disabled: ended, onclick: () => App.openSend({ x: s.x, y: s.y }) }, icon('target'), App.t('wld.attack')));
@ -308,6 +309,35 @@
sec.appendChild(btn);
body.appendChild(sec);
// ---- garrison: what defends the site on top of its static part (units of the holders' POPs); call your own home, station more
const gv = E.garrisonView(data);
const gar = h('section', { class: 'wld-sec' }, h('h3', { class: 'sub', text: App.t('wld.gar.head') }));
const garErr = h('p', { class: 'form-error', role: 'alert', hidden: true });
gar.appendChild(h('div', null,
kv(App.t('wld.gar.static'), h('b', { class: 'mono', text: num(gv.static) })),
kv(App.t('wld.gar.units'), h('b', { class: 'mono', text: num(gv.garrison) })),
kv(App.t('wld.gar.total'), h('b', { class: 'mono', text: num(gv.total) }))));
if (!gv.rows.length) gar.appendChild(h('p', { class: 'row-sub wrap', text: App.t('wld.gar.empty') }));
else {
gar.appendChild(h('ul', { class: 'mil-list' }, gv.rows.map((r) => h('li', { class: 'mil-row' },
h('span', { class: 'row-main' },
h('b', { text: r.name + (r.mine ? ' · ' + App.t('wld.gar.mine') : '') }),
h('span', { class: 'row-sub wrap', text: [r.townName, mil().unitsText(r.units), r.online ? App.t('wld.gar.share', { p: Math.round(r.share * 100) }) : App.t('wld.gar.offline')].filter(Boolean).join(' · ') })),
r.mine ? h('button', { class: 'btn small', type: 'button', disabled: App.worldEnded(), onclick: async (ev) => {
const b = ev.currentTarget; b.disabled = true; garErr.hidden = true;
try {
await App.api.post('/backbone/' + s.id + '/withdraw', { fromTownId: r.ownerTownId }, { intent: 'bb-wd:' + s.id + ':' + r.ownerTownId + ':' + nonce() });
toast(App.t('wld.gar.withdrawn'), 'ok');
App.refreshTown().catch(() => {}); App.refreshMovements().catch(() => {});
await load();
} catch (e) { garErr.textContent = App.errMsg(e); garErr.hidden = false; b.disabled = false; load(); }
} }, icon('return'), App.t('wld.gar.withdraw')) : null))));
}
gar.appendChild(garErr);
gar.appendChild(h('p', { class: 'row-sub wrap', text: App.t('wld.gar.hint') }));
if (you.canReinforce && App.openSend && App.state.towns.length) gar.appendChild(h('button', { class: 'btn wide', type: 'button', disabled: App.worldEnded(), onclick: () => App.openSend({ x: s.x, y: s.y, type: 'reinforce' }) }, icon('shield'), App.t('wld.gar.station')));
body.appendChild(gar);
// ---- ship resources
const ship = h('section', { class: 'wld-sec' }, h('h3', { class: 'sub', text: App.t('wld.ship.head') }));
const cur = pops.find((q) => q.id === sh.fromId);