# DECISIONS Short log of non-obvious decisions and why. Newest at the bottom. ## D1 — `node:sqlite` as the driver Dev machine runs Node 24; the deploy target (Debian 13 LXC) ships Node 22+. `node:sqlite` is used through `server/db.js` only, so `better-sqlite3` is a one-file swap if it ever misbehaves. Parameters are always positional. ## D2 — Scheduler processes ALL due events before any command or read `scheduler.runDue()` runs every pending event with `due_at <= now` globally, in `(due_at, id)` order, not just the ones touching the town in question. It is simpler and makes fairness trivial (nothing resolves out of order). Cost is nil in practice because the timer processes events within milliseconds of their due time; it only matters after a restart (catch-up). ## D3 — One `towns.res_at` for all lazily-grown values Fiber, hardware, capital, power battery, footprint and loyalty are all settled together at `res_at` (`state.settle`). Any change that alters a rate (building finished, unit trained or lost) settles first. `rules.resourcesAt` is therefore exact between settles. ## D4 — Power battery uses the same lazy model Battery = (amount, rate = net power x world speed, cap = Battery bank). Units are offline while battery = 0 and net < 0 (`rules.unitsOnline`). The 24 h decommission countdown is an event scheduled from `rules.batteryEmptyAt`. ## D5 — Rural areas are held by proximity in v1 DESIGN.md leaves "contested or just held" open. v1: a POP within `ruralReach` (2) tiles of a rural tile gets its +25% (max 3, nearest first). Computed from the seed, no state. Revisit after the first world. ## D6 — First world is 101 x 101, not 301 x 301 DESIGN.md's own open question. `mapRadius` is world data (`worlds.map_radius`), default 50. ## D7 — `docs/openapi.json` is generated `tools/gen-openapi.js` builds it from the route table (schemas live in route meta + `server/routes/schemas.js`). `npm test` fails when the committed file is stale, which satisfies "updated in the same commit as any route change" mechanically. ## D8 — Resource fields are slot-keyed Buildings table key: `f1..f18` for resource fields (type fixed at founding, 4 per type + 2 wild), the building type for infrastructure. Build "slots": 1 concurrent build, 2 from Core router 10 (queue = pending `buildDone` events). ## S5-1 — Alliance size cap is stored, only ever raised DESIGN says the Peering office level sets the size you can found. The cap is stored at founding (`10 + 2 * best level`). A lost or downgraded building must never kick anyone, so the cap is monotonic: commands that depend on it (invite, accept, transfer) raise it if the CURRENT leader's best office would give more; reads show `max(stored, formula)` without writing. The floor is therefore 10 even for a leader without an office after a transfer. The office requirement (>= 1) is checked when founding and when accepting an invite, not afterwards. ## S5-2 — Diplomacy move table is data, three kinds of change `SOCIAL.diplomacyMoves` (data.js) says for each (from, to) whether it is `immediate`, a `proposal` or `delayed`. War from neutral is immediate (no consent needed). Anything that leaves a pact (nap/confed -> neutral/war, confed -> nap) is `delayed`: 24 h / world speed via a `diploChange` event, so you cannot betray a partner without warning. Pacts and peace need acceptance. While a delayed change is pending the pair is locked (`diplomacy_pending`); only the starter can revoke. A pair at `neutral` with nothing pending has no row in `alliance_relations`. Acceptance re-validates against the current state, because the relation may have moved since the proposal. `war -> confed` is not allowed (go through a pact first). ## S5-3 — Membership lives in two tables, one writer `operators.alliance_id` (from 001, cheap joins in /map, /me) and `alliance_members` (role, joined_at, one leader per alliance by a partial unique index). `alliances.js` addMember/removeMember are the only writers. Alliance rows are hard-deleted on disband; messages keep a `alliance_tag` snapshot and carry no foreign key to alliances so broadcasts survive. ## S5-4 — Last online comes from tokens No new column: `lastOnline` = newest `tokens.last_used_at` of the member's user, which auth.js refreshes at most once a minute. So it is accurate to about a minute and includes revoked tokens (a logout still counts as having been online). ## S5-5 — Message rate limit is DB-backed, not the in-memory Limiter `server/http.js` Limiter keys on monotonic real time and forgets on restart; message limits are a product rule that should follow the (fake) clock and survive restarts, so the sender's recent rows in `messages` are counted (`SOCIAL.messageLimits`, indexed by `messages_sender`). The per-token/IP limiters still apply on top. ## S5-6 — Messages: per-recipient rows, sanitising on write One `messages` row plus one `message_recipients` row per recipient (broadcast fan-out at send time: members who join later do not see old broadcasts; members who leave keep what they received). Read/delete state is per recipient; the sender's copy is hidden with `sender_deleted_at`; the row is purged when nobody has a copy. A blocked sender is silently not delivered to (no row), so blocking does not leak. Text is sanitised once on write (`server/text.js`): C0/C1 controls, bidi overrides and isolates, zero-width and invisible tag characters are stripped, NFC, `\r\n` -> `\n`; ZWJ/ZWNJ are kept for emoji. Clients render with `textContent` only. ## S5-7 — Rankings are computed per request, no cache Footprint for a whole world comes from two queries (towns, buildings) and `rules.footprintAt`; fine for the expected 50-300 operators. If it ever shows up in a profile, cache per (world, minute). Cursor is a rank offset because rankings are a computed snapshot, not rows. ## S5-8 — Route params and list order `inviteId`, `noteId`, `proposalId`, `otherId`, `operatorId` were added to `INT_PARAMS` in http.js. Lists that are newest-first (messages) use the last id as the `after` cursor and return older items; this is the one place `after` does not mean "newer than". ## S3-1 — Online/offline is computed lazily; `powerCheck` only does the side effects Units are offline while the battery is empty and net power is negative. That is derived from the lazy battery value (`power.online`) at the moment it matters (sending, combat, the town view), never from an event having run. The `powerCheck` event (one pending per POP, re-armed by `power.reschedule` after anything that changes unit draw or building levels, including `buildDone`) only writes the "units offline" notification and does the decommission after 24 h / world speed. Offline is all-or-nothing per POP (the contract of `rules.unitsOnline`); the decommission then removes the most expensive units (home first, then reinforcements) until the draw fits the output, not everything. Offline units are neither counted in defence nor hurt by a raid, but a full attack lost by the defender still wipes them. Reinforcements draw from the host (`state.unitDraw` reads `stationed`); units in transit draw from nobody. ## S3-2 — Research is per POP, speed bonus per operator `town_research(town_id, unit, stat, level)`; level n needs a Research lab of level n + 2, one research at a time per POP. An attack uses a snapshot of the origin POP's research taken at departure (`movements.extra.research`); defenders use the research of the POP each group belongs to. Incumbent sites: +10% research speed per distinct site taken (cap +50%), and a one-time +2500 Hardware per site and operator. Taking a site does not remove it: it stays a static fortress for everybody else. ## S3-3 — One report row, many recipients; cleanup armed at the earliest expiry A battle is one `reports` row shared through `report_recipients(report_id, user_id, role, read_at)`, so both sides see the same data (a scan is two separate rows: intel for the scanner, "a scan happened" for the target, with the scanner's identity only if the target's scanners won). `reportCleanup` is armed at the earliest `expires_at` (14 days, real time, not divided by world speed) and re-arms itself only while reports remain: at most one pending cleanup per world, none on a quiet world. ## S3-4 — Arrival re-validates everything and bounces A movement is validated when it is sent and again when it arrives (the target may have changed owner, got protection, joined a pact, the tile may have been taken). If it no longer holds, the units turn around with the loot they carry and the sender gets a `movement_failed` report. Return legs whose origin POP changed hands go to the operator's capital (or oldest POP). ## S3-5 — Takeover details Only `takeover` movements (with an M&A team) can lower loyalty; one team per attack counts and is used up when it does. `takeoverBlock`: a player's last POP wins over "capital" (refused at send); a capital with siblings is only dragged to loyalty 0. Loot is taken in the same arrival, before the POP changes hands. On transfer the old owner's pending training/research is cancelled, pending builds are re-keyed to the new owner's user, and that POP's units standing elsewhere are re-homed to the old owner's capital. A captured POP keeps its footprint. ## S3-6 — Transport links `links` = Internet exchange level, each carries 500 (`D.TRANSPORT`). A link is busy while the transport is out and while its empty carriers drive back (a `return` movement with `extra.link`). Cargo above the receiver's Rack hall cap is lost (the notification says how much). `transport` movements keep arbitrary `extra` and `movements.hooks.transportArrived` is called on delivery, so the trade stage needs no change in the movement code. ## S3-7 — Protection Beginner protection blocks raid/attack/takeover in both directions. Sending one from a protected operator needs `confirmEndProtection` and ends it at once; attacking an incumbent site does not end it; scans never do. The target's protection is compared with the ARRIVAL time at send, and re-checked at arrival. ## S3-8 — Footprint gate counts the operator's total `footprintNeeded(n)` with n = POPs owned now (second POP: n = 1). Founding and takeover both need `sum(footprint of own POPs) >= need`, nothing is spent. New POPs start with every field at level 0, no infrastructure, 250 of each resource and loyalty 100. ## S3-9 — Moving units between your own POPs `reinforce` to an own POP puts the units into `town_units` of the target (they live there now). Only units of OTHER operators are `stationed` rows.