Upstream/CLAUDE.md
2026-10-11 15:53:05 +00:00

199 lines
14 KiB
Markdown

# CLAUDE.md
Persistent, multiplayer browser strategy game (towns, resources, build queues, troops, map, alliances) in the genre of
long-running "build and conquer" worlds. Original game: own theme, names, art, text and numbers. Do not copy names,
assets, UI layouts, unit rosters or balance tables from Travian, Ikariam or any other existing game.
Built on the same stack and conventions as NETWALL (`jvanvik/towerdef`): vanilla JS, no build step, no framework,
one small Node process behind nginx Proxy Manager, systemd in a Debian LXC. Where this file is silent, do what
NETWALL does.
**Name:** UPSTREAM (working title).
**Theme:** rival regional network operators. Players build POPs, connect the region, steal each other's customers
and race to finish a backbone. Fictional only: no real companies, products or AS numbers. Tone matches NETWALL
(light, nerdy, accurate jargon). All player-facing names live in `data.js`/`i18n.js`, never hard-coded in logic;
code uses the generic genre terms in the left column.
| Genre concept | In game |
| -------------------- | ----------------------------------------------------------------------------------------- |
| Player | Operator (has an AS number, generated, from a private range) |
| Town | POP |
| Resources | Fiber, Hardware, Capital, Power. Power is the upkeep resource: buildings and units draw it; negative net power takes units offline |
| Resource fields | Cable yards, supply depots, sales offices, substations |
| Main building | Core router (faster builds) |
| Storage / upkeep cap | Rack hall / battery bank |
| Wall | Firewall (defence bonus; nod to NETWALL) |
| Barracks etc. | NOC (defensive crews), Ops lab (offensive tools), Research lab (upgrades) |
| Marketplace | Internet exchange: trade resources between POPs/players over transport links |
| Embassy | Peering office (alliances) |
| Offensive units | Script crews, botnets, DDoS rigs (vs firewall), exploit kits (target buildings), port scanners (scouts) |
| Defensive units | SOC analysts, blue team, honeypots |
| Raid / attack | Phishing raid (loot Capital) / takedown |
| Reinforce | Peering support |
| Settler | Rollout crew (founds a new POP) |
| Loyalty / conquest | Customer loyalty / hostile takeover by an M&A team |
| Travel time | Latency (distance / slowest unit) |
| Oases | Unconnected rural areas: production bonus while held |
| NPC faction | Legacy incumbent telco: neutral strongholds |
| End game | First alliance to complete the Tier-1 backbone wins the world |
## The one big difference from NETWALL
NETWALL is real-time and stores nothing. This game runs for weeks, and a restart must lose nothing.
- State lives in **SQLite** (WAL mode), one file, owned by the one Node process. Use the built-in `node:sqlite`
(target Node 22 LTS or newer; verify on the deploy Node version in stage 0). If that turns out to be a problem, the
fallback is `better-sqlite3`. All DB access goes through `server/db.js` so the driver can be swapped.
- There is **no tick loop**. Time is handled by lazy evaluation plus a persistent event queue (see Time model).
- Backups: `VACUUM INTO` snapshot from a systemd timer, documented in `docs/DEPLOY.md`.
## Layout
```text
public/ static client (web root), no build step
index.html, css/ phone-first layout (portrait, landscape, desktop), PWA manifest
js/data.js ALL content and balance: resources, buildings, units, costs, times, world presets
js/rules.js ALL game rules: pure, deterministic, no DOM, no I/O, no Date.now(). Loads in browser AND Node
js/api.js client for the REST API + WebSocket push (token, retries, serverTime offset)
js/render.js canvas map: camera, pan/zoom, pinch, tile culling
js/main.js screens, HUD, input
js/i18n.js strings, en + nb
server/
index.js boot: config, db, migrations, scheduler catch-up, http + ws
net.js, static.js taken from NETWALL (proxy trust, origin check, per-IP limits, dual stack, static files)
http.js tiny router on node:http, JSON in/out, error envelope, auth middleware, rate limits
db.js driver wrapper, transactions, prepared statements
migrations/ numbered SQL files, applied in order at boot, never edited after merge
clock.js injectable clock (real or fake) — the only place server code reads time
scheduler.js persistent event queue: one timer to the next due event, catch-up after restart
commands/ one file per player command (build, train, send, trade, ...): validate + apply in one tx
events/ one file per event type (buildDone, arrive, return, ...): apply in one tx
routes/ REST handlers, thin: parse, auth, call command/query, serialize
push.js WebSocket push to connected sessions
docs/
DESIGN.md game design: theme, loop, formulas in words
API.md the API contract (humans) + openapi.json (machines, for mobile client generation)
PROTOCOL.md WebSocket push messages
DEPLOY.md LXC + NPM + systemd + backups, same style as NETWALL
NEXT.md honest status and next steps, updated at the end of every stage
DECISIONS.md short log of non-obvious decisions and why
workflows/ planned stage workflows, same style as NETWALL's docs/workflows/
test/ node:test (rules, commands, events, scheduler, API, security)
e2e/ Playwright, same setup as NETWALL
tools/
bot.js headless players driving the real server/rules with a fake clock (balance, load)
admin.js CLI: create world, reset, ban, inspect town, replay events
deploy/ systemd units (service + backup timer)
```
Dependencies: `ws` only (plus the SQLite driver if `node:sqlite` is not used). Playwright as devDependency. Adding
anything else needs a line in `docs/DECISIONS.md`.
## Time model (core invariant)
- Every stored quantity that grows is stored as `(amount, rate, updatedAt)`. Current value =
`rules.resourcesAt(town, now)`, capped by storage. Never persist a "current" value without its timestamp.
- Every future thing (build done, troops arrive, troops return, trade arrives, training batch done) is a row in
`events(id, world_id, due_at, type, payload, status)`.
- `scheduler.js` processes due events strictly in `(due_at, id)` order. Each event: bring affected towns up to
`due_at` via rules, apply, enqueue follow-ups, mark done — all in ONE transaction. Handlers must be idempotent.
- Before any command or read touches a town, process all events due up to `now` that affect it. Event order is
what makes combat and conquest fair; never resolve something out of order.
- After a restart, catch up all overdue events in order before accepting traffic.
- All times are integer ms since epoch, UTC, server clock only. Clients get `serverTime` in every response and
compute countdowns from the offset; nothing trusts the client's clock.
- World speed is a multiplier in the world config, applied in rules, never sprinkled through code.
## Rules and data
- `rules.js` is the single source of truth for formulas: production, costs, build/train times, travel time
(distance, slowest unit, speed), combat, loot, upkeep, loyalty/conquest. Inputs in, outputs out; `now` and any
randomness (seeded RNG) are arguments.
- The client uses the same `rules.js` for previews (cost, time, travel ETA, combat estimate) but the server
recomputes everything. The client never sends computed amounts, only intents.
- Balance lives in `data.js` only. Changing balance must not require touching `rules.js`.
- Same dual-load pattern as NETWALL's `sim.js` (works as a browser script and as a Node module).
## API (built for web now, mobile later)
- REST JSON under `/api/v1/`. Resource-oriented: `/me`, `/towns/:id`, `/towns/:id/build`, `/map?x&y&r`,
`/movements`, `/reports`, `/messages`, `/alliances/...`.
- Error envelope: `{ "error": { "code": "not_enough_resources", "message": "...", "details": {} } }`. Codes are
stable and documented; clients switch on `code`, never on `message`.
- Every response includes `serverTime`. Lists are cursor-paginated.
- Mutating POSTs accept an `Idempotency-Key` header (mobile retries on flaky networks must not double-build).
- Auth: username + password (scrypt via `node:crypto`), opaque bearer tokens per device (random 32 bytes, stored
hashed), listable and revocable. No cookies; same scheme for web and mobile. Strict CSP, no external requests.
- WebSocket `/ws`: authenticate with the token in the first message (not the URL, keeps it out of proxy logs).
Push is a hint ("town X changed", "attack incoming at T"); clients refetch over REST. The game must be fully
playable with push disconnected.
- Keep a `notifications` table written by event handlers so APNs/FCM push can be added later without touching
game logic.
- `docs/API.md` + `docs/openapi.json` are updated in the same commit as any route change. A test fails if a route
exists that `openapi.json` does not describe, or vice versa.
## Security and abuse
- Server-authoritative for everything. Validate ownership, ranges, queue limits and resources on every command.
- Reuse NETWALL's net hardening and env vars: `PORT`, `HOST` (`::`), `TRUST_PROXY`, `TRUSTED_PROXIES`,
`ALLOWED_ORIGINS`, `MAX_CONN_PER_IP`. `/healthz` returns `ok`.
- Rate limits per token and per IP (login stricter). Log refusals with the reason, like NETWALL does.
- Never log passwords or tokens. Parameterised SQL only.
## Multi-world from day one
Every game row carries `world_id`. Start with one world, but world config (speed, map size, start/end, rules
preset) is data in the `worlds` table, so parallel or successive worlds need no code change.
## Testing
- `npm test`: node:test. Rules are tested as pure functions. Server tests use a temp DB file and the fake clock:
advance time, assert events fired in order with the right results.
- Every bug fix comes with a test that failed before it.
- `tools/bot.js` runs N bot players for X simulated days in seconds (fake clock) and prints economy/combat stats.
Balance claims in commit messages or NEXT.md must cite a bot run.
- `npm run e2e`: Playwright, same approach as NETWALL (desktop, phone touch, layout matrix). Run a smoke e2e at
the end of each stage; run the full suite only when asked.
## Client
- Phone-first, touch-first, same standards as NETWALL: act on finger lift, pinch never acts, thumb-reach controls,
portrait and landscape, "Add to Home Screen" works.
- The client is a thin view over the API. No game logic beyond previews from `rules.js`.
- Countdown timers are computed locally from `serverTime` offset and refetched on expiry.
## Working in stages
Work one stage at a time. A stage is done when: `npm test` passes, the smoke e2e passes, docs (API, PROTOCOL,
DESIGN, NEXT) match the code, and the commit message states honestly what was built, what was tested, and what was
NOT (same style as NETWALL commits). Don't claim "balanced" or "QA'd" without evidence. If a stage reveals that an
earlier decision was wrong, stop and write it in `docs/DECISIONS.md` before changing direction.
Planned stages (details in `docs/workflows/`):
0. **Skeleton:** repo layout, net/static from NETWALL, router, db + migrations, clock, scheduler with catch-up,
auth + tokens, error envelope, openapi test, `/healthz`, systemd unit, backup timer, DEPLOY.md.
1. **Economy:** one town per player, resources (lazy), buildings and levels, build queue, storage caps; API +
minimal client (town view, build menu, countdowns).
2. **World:** map generation (seeded), spawn placement, neutral tiles, map API with viewport queries, canvas map.
3. **Military:** unit training queue, movements (attack, raid, reinforce, scout, return), combat at arrival,
loot, reports, incoming warnings.
4. **Expansion:** founding new towns, conquest mechanic, multi-town UI.
5. **Social:** alliances, roles, messaging, diplomacy, marketplace and resource transport.
6. **Push and polish:** WebSocket push, notifications table, PWA, layout matrix, i18n nb/en.
7. **Ops and balance:** bot-driven balance passes, admin CLI, world lifecycle (start, end condition, reset),
load test with bots, full e2e.
## Commands
```bash
npm install # ws (+ driver if needed)
npm start # http://localhost:8080, prints LAN URLs, creates ./data/game.db if missing
npm test # unit + server tests
npm run e2e # Playwright
node tools/bot.js --players 50 --days 14 --speed 1 # headless balance run
node tools/admin.js help
```
Env vars beyond NETWALL's: `DB_PATH` (default `./data/game.db`), `WORLD_SPEED` (only used when creating a world).