From b5ac3df495ad50439a236d274703f5970509d98b Mon Sep 17 00:00:00 2001 From: jvanvik Date: Sun, 11 Oct 2026 15:53:05 +0000 Subject: [PATCH] Upload files to "/" --- CLAUDE.md | 199 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ DESIGN.md | 193 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 392 insertions(+) create mode 100644 CLAUDE.md create mode 100644 DESIGN.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..2246d66 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,199 @@ +# 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). diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 0000000..bdf9bf3 --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,193 @@ +# DESIGN.md + +Working title: **UPSTREAM**. First-pass design. Every number here is a starting point for the bot balance +passes in stage 7, not a promise. Formulas are the contract; constants live in `public/js/data.js`. + +## Pitch + +You are a regional network operator with one POP on a map full of rivals. Build out the POP, connect the countryside, +peer with friends, raid and take over competitors, and be in the alliance that finishes the Tier-1 backbone first. +Slow by design: a world runs for months, and a session is a few minutes a few times a day. Everything that takes +time can be queued, and nothing happens that you weren't warned about. + +Tone: light and nerdy, like NETWALL. Jargon is used correctly and never explained in the UI beyond a tooltip. +No real companies, products, people or AS numbers. + +## Core loop + +1. Resources accrue while you're away (capped by storage). +2. Spend them on building levels (one build queue, slow) and units (training queue). +3. Send units somewhere: scout, raid, attack, reinforce, settle, take over. Travel time ("latency") is the pacing + mechanic: a raid across the map takes hours, and the target is warned. +4. Reports tell you what happened. Repeat. + +Mid game adds more POPs, alliances and trade. Late game is the backbone race. + +## World + +- Square tile map, default 301 x 301 (coordinates -150..150), one tile = one site. World config sets size, + speed (1x, 2x, 3x), start time and a planned end. +- Tile types: empty land, **rural area** (bonus tile), **incumbent site** (NPC), **backbone landing site** + (appears late, see End game), player POP. +- Spawn: new operators get a POP placed randomly in an expanding ring around the centre so early joiners are + central and the map fills outward. Minimum spacing 3 tiles from any other POP. +- Each operator gets a fictional AS number from a reserved range on signup; it's a display name, nothing more. +- Beginner protection: 72 h (divided by world speed), no attacks in or out. Ends early if you attack. + +## Resources + +Four resources, all per POP: + +| Resource | Produced by | Used for | +| ------------ | -------------------- | -------------------------------------------- | +| **Fiber** | Cable yard | Most buildings, cheap units | +| **Hardware** | Supply depot | Advanced buildings, strong units | +| **Capital** | Sales office | Everything a bit; the raid currency | +| **Power** | Substation | Upkeep: every building level and unit draws it | + +Fiber, Hardware and Capital accumulate and are capped by the **Rack hall**. Power does not accumulate: it is a +rate. Net power = substation output − building draw − unit draw. A **Battery bank** holds a buffer that drains +while net power is negative and refills while positive. When the buffer hits zero, units go **offline** (no +attack or defence value, cannot move) starting with the most expensive; after 24 h offline they are decommissioned. +Nothing else breaks: buildings keep working. This replaces "starvation" with something you can see coming. + +Each POP has 18 resource slots around it: 4 fixed to each production type plus 2 wild slots the player assigns at +founding. Rural areas held nearby add a +25% bonus to one resource type each (max 3 per POP). + +### Production + +`output(L) = base * growth^(L-1) * speed * bonuses`, per hour, with `base = 6`, `growth = 1.25` (level 1 → 6, +level 10 → 44, level 20 → 420). Substation uses the same curve for power output in watts-as-points. + +Current amount is always computed, never stored as "now": `amount = min(cap, stored + rate * (now − updatedAt))`. + +## Buildings + +One build queue per POP. The **Core router** level shortens all build times. Level cap 20 for most buildings. + +| Building | Role | +| --------------- | --------------------------------------------------------------------------------------------- | +| Core router | Required for everything. Build time ÷ (1 + 0.04·L). Unlocks the second queue slot at 10. | +| Rack hall | Storage cap for Fiber/Hardware/Capital: `cap(L) = 1000 * 1.22^(L-1)`. | +| Battery bank | Power buffer: `buf(L) = 200 * 1.22^(L-1)` points. | +| Firewall | Defence multiplier `1 + 0.03·L`. DDoS rigs reduce it during attacks. | +| NOC | Trains defensive units. Training time ÷ (1 + 0.03·L). | +| Ops lab | Trains offensive units and siege. Requires Research lab 3. | +| Research lab | Unlocks unit types and upgrades (each upgrade: +5% attack or defence for one unit type). | +| Internet exchange | Trade: list offers, accept offers, send resources. Level sets number of transport links. | +| Peering office | Create/join an alliance. Level sets alliance size you can found (10 + 2·L). | +| Rollout depot | Trains Rollout crews (settlers) and M&A teams. Requires Core router 10. | +| Backbone node | Only on backbone landing sites. The end-game building (see below). | + +Costs: `cost(L) = base_cost * 1.28^(L-1)` per resource. Times: `time(L) = base_time * 1.16^(L-1) / corerouter / +speed`. Base costs/times per building in `data.js`. Every building level adds 1 power draw per level +(resource producers 0, so expansion is never power-negative on its own). + +**Footprint:** every building level produces footprint points per day (1 + L/5). Founding or taking over a POP +requires a footprint threshold that grows with POP count: `need(n) = 500 * n^1.8` for the n-th extra POP. + +## Units + +Stats per unit: attack, defence, speed (tiles/hour at 1x), carry (loot), power draw, cost, training time, +required research. Two defence values would add depth (vs crews / vs automated); start with one and revisit. + +| Unit | Trained in | Role | +| --------------- | ---------- | ----------------------------------------------------------------- | +| Port scanner | NOC | Scout. Fast, no carry. Scanner vs scanner decides if the scan succeeds and whether the target learns who scanned. | +| SOC analyst | NOC | Cheap defender, weak attacker. | +| Blue team | NOC | Strong defender, slow. | +| Honeypot | NOC | Defender that cannot move. High defence, cheap upkeep. | +| Script crew | Ops lab | Cheap attacker, good carry. The raid unit. | +| Botnet | Ops lab | Fast attacker, big carry, high power draw. | +| DDoS rig | Ops lab | Siege vs Firewall: each rig lowers the effective firewall level during that battle. | +| Exploit kit | Ops lab | Siege vs buildings: damages a chosen building level on a win. | +| Rollout crew | Rollout depot | Three found a new POP on an empty tile. Consumed. | +| M&A team | Rollout depot | Lowers customer loyalty on a winning attack. Max one per attack. | + +Upkeep is power draw per unit, counted at the POP the unit is stationed in (reinforcements draw from the host). + +## Movements + +Movement types: scan, raid, attack, reinforce, settle, takeover, transport (resources), return. + +`latency = distance / (slowest speed * world speed)` with Euclidean distance in tiles; minimum 10 min. The +target sees an incoming movement with ETA and origin (type is hidden; a successful scan reveals it). Movements +can be recalled within the first 90 s. + +Returning units carry loot and come back at the same speed. Units cannot be re-routed while out. + +## Combat + +Resolved at arrival, in the event queue, in order. Deterministic given the inputs and the world seed. + +- `A = Σ attack(units) * research`, `D = (Σ defence(units in POP, incl. reinforcements) * research + 10) * + firewall(L_eff)` where `L_eff = max(0, L − rigs/10)`. +- Full attack: the losing side loses everything; the winning side loses `(loser/winner)^1.5` of its strength, + spread proportionally across unit types. On a win with exploit kits, one chosen building loses + `floor(kits/20)` levels (min 1 if kits ≥ 5). +- Raid: both sides lose a fraction only: `losses = ratio^1.5 * 0.5`, so raids are for loot, not for killing. +- Loot: winner takes `min(carry, available)` from Fiber/Hardware/Capital evenly, never from Power. Rack hall + hides 10% per level up to 50% from raids (the "cold spare" cache). +- Takeover: on a winning full attack with an M&A team present, loyalty drops by `rand(15, 30)` points. At ≤ 0 the + POP changes owner, loyalty resets to 25 and grows +1/h. Capital POP (the player's chosen one) cannot be taken + over; it can be destroyed to zero loyalty and left. A player's last POP cannot be taken over either. +- Scan: `scanners_att` vs `scanners_def`; if attackers outnumber, report shows units and resources (buildings at + 2:1). Defender always gets a report that a scan happened; identity only if their scanners win. + +Reports: every participant gets one. Reports are stored for 14 days, can be shared to the alliance. + +## Expansion and footprint + +Three Rollout crews plus footprint threshold found a new POP on an empty tile; distance from an own POP ≤ 15. +A new POP starts at level 0 everything and 1 h of resources. Takeover requires the same footprint threshold. + +## Alliances and diplomacy + +- Alliance: name, tag, up to size cap. Roles: leader, diplomat, officer, member. Shared report folder, pinned + notes, member list with last online and POP count. +- Diplomacy states between alliances: war, neutral, non-aggression pact, confederation (can reinforce each other, + see each other's incoming). Pacts take 24 h to cancel. +- Messages: player-to-player and alliance broadcast, plain text, 2000 chars, basic rate limit. + +## Trade + +The Internet exchange lists offers "give X of A for Y of B, max distance Z". Ratio bounded 1:2 to stop +pump-feeding. Accepting an offer spawns two transport movements. Direct transports to own POPs or to any player +(e.g. alliance support) use the same links. Transport links: level of the exchange, capacity 500 each. + +## Incumbent (NPC) + +The legacy telco. Holds incumbent sites spread over the map with large static defences that scale with world age. +They never attack. Taking one gives a one-time Hardware bonus and a permanent +10% research speed. In the end game +they hold the backbone landing sites. + +## End game + +At day 100 (÷ speed), 7 **backbone landing sites** appear at fixed positions, held by the incumbent with heavy +defence. Taking one lets the owning alliance build the **Backbone node** there, levels 1–100, each level costing +far more than anything else and requiring resources shipped in from members (transport). Level 100 = that alliance +wins and the world ends two days later with a final ranking. Backbone nodes can be attacked and taken; the level +stays with the site. Landing sites cannot be settled, only taken. + +Rankings throughout: operators by footprint, alliances by sum, attackers/defenders by points from battles. + +## Fairness and anti-frustration + +- Multi-accounting: one account per person; sitter feature (give a friend read/limited-write access) instead. +- No real-money anything. No speed-ups for sale. The game is a hobby project. +- Night: no night protection in v1; revisit after the first world. +- New players in a running world spawn in the outer ring with protection; worlds are expected to be re-run. + +## Client views (web, same for mobile) + +POP view (buildings + queue), Resource view (slots), Map (pan/zoom, tile info, send dialog), Units (train, +station, movements list), Reports, Messages, Alliance, Exchange, Rankings, Profile/settings. Every countdown is +computed from `serverTime`. + +## Open questions + +- One or two defence stats per unit? +- Research as a tree or a flat list of upgrades? +- Should rural areas be contested (takeable from each other) or just held? +- Night protection and holiday mode. +- World size vs expected players (301² tiles is a lot for 50 players; shrink for the first world).