From 3c23c5190204940bd100dddcbfdb32cab4b3489a Mon Sep 17 00:00:00 2001 From: jvanvik Date: Mon, 12 Oct 2026 00:58:12 +0200 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14 --- deploy/update.sh | 292 ++++++++ deploy/upstream-offsite | 69 ++ deploy/upstream-offsite.service | 43 ++ deploy/upstream-offsite.timer | 15 + docs/API.md | 78 +- docs/BALANCE.md | 164 ++++- docs/DECISIONS.md | 114 ++- docs/DEPLOY.md | 155 +++- docs/DESIGN.md | 52 +- docs/NEXT.md | 88 ++- docs/PROTOCOL.md | 4 +- docs/openapi.json | 282 +++++++- docs/workflows/README.md | 23 + docs/workflows/stage-0-skeleton.md | 22 + docs/workflows/stage-1-economy.md | 21 + docs/workflows/stage-2-world.md | 18 + docs/workflows/stage-3-military.md | 22 + docs/workflows/stage-4-expansion.md | 19 + docs/workflows/stage-5-social.md | 21 + docs/workflows/stage-6-push-polish.md | 21 + docs/workflows/stage-7-ops-balance.md | 24 + e2e/flows.js | 911 ++++++++++++++++++++++++ e2e/lib.js | 41 +- e2e/run.js | 65 +- public/js/alertkinds.js | 2 + public/js/data.js | 7 +- public/js/endcore.js | 13 +- public/js/main.js | 2 +- public/js/milcore.js | 2 +- public/js/milstate.js | 10 +- public/js/rules.js | 63 +- public/js/screens/map.js | 2 +- public/js/screens/messages.js | 22 +- public/js/screens/reports.js | 6 + public/js/screens/send.js | 1 + public/js/screens/trade.js | 20 +- public/js/screens/units.js | 8 + public/js/screens/world.js | 30 + public/js/strings/alerts.js | 6 + public/js/strings/military.js | 20 +- public/js/strings/trade.js | 6 +- public/js/strings/world.js | 18 +- server/commands/allianceKick.js | 1 + server/commands/allianceLeave.js | 1 + server/commands/cancelBuild.js | 4 +- server/commands/index.js | 1 + server/commands/sendMovement.js | 11 +- server/commands/tradeAccept.js | 15 +- server/commands/tradeCancel.js | 4 +- server/commands/tradeOffer.js | 2 +- server/commands/withdrawGarrison.js | 30 + server/endgame.js | 35 +- server/endgameQueries.js | 9 +- server/errors.js | 1 + server/events/return.js | 2 +- server/events/tradeExpire.js | 4 +- server/migrations/005_site_garrison.sql | 12 + server/military/arrivals.js | 8 +- server/military/combat.js | 40 +- server/military/garrison.js | 139 ++++ server/military/landing.js | 101 ++- server/military/power.js | 15 +- server/military/views.js | 18 +- server/pushHooks.js | 1 + server/queries.js | 2 +- server/routes/schemas.js | 1 + server/routes/schemasEndgame.js | 8 +- server/routes/schemasMilitary.js | 2 +- server/routes/trade.js | 2 +- server/routes/world.js | 8 +- server/state.js | 14 +- server/trade.js | 31 +- test/admin-endworld.test.js | 125 ++++ test/client-alerts.test.js | 2 + test/client-garrison.test.js | 66 ++ test/deploy-offsite.test.js | 118 +++ test/deploy-update.test.js | 416 +++++++++++ test/economy-leaks.test.js | 173 +++++ test/endgame-garrison.test.js | 508 +++++++++++++ test/review-fixes.test.js | 1 + test/trade-api.test.js | 6 + test/trade-flow.test.js | 23 +- test/transport-speed.test.js | 72 ++ tools/admin.js | 71 +- tools/bot.js | 3 + tools/bot/bots.js | 16 +- tools/bot/collector.js | 25 +- tools/bot/endgame.js | 205 +++++- tools/bot/ledger.js | 23 +- tools/bot/report.js | 4 +- tools/bot/sim.js | 2 +- tools/bot/stats.js | 4 +- 92 files changed, 4887 insertions(+), 300 deletions(-) create mode 100755 deploy/update.sh create mode 100755 deploy/upstream-offsite create mode 100644 deploy/upstream-offsite.service create mode 100644 deploy/upstream-offsite.timer create mode 100644 docs/workflows/README.md create mode 100644 docs/workflows/stage-0-skeleton.md create mode 100644 docs/workflows/stage-1-economy.md create mode 100644 docs/workflows/stage-2-world.md create mode 100644 docs/workflows/stage-3-military.md create mode 100644 docs/workflows/stage-4-expansion.md create mode 100644 docs/workflows/stage-5-social.md create mode 100644 docs/workflows/stage-6-push-polish.md create mode 100644 docs/workflows/stage-7-ops-balance.md create mode 100644 e2e/flows.js create mode 100644 server/commands/withdrawGarrison.js create mode 100644 server/migrations/005_site_garrison.sql create mode 100644 server/military/garrison.js create mode 100644 test/admin-endworld.test.js create mode 100644 test/client-garrison.test.js create mode 100644 test/deploy-offsite.test.js create mode 100644 test/deploy-update.test.js create mode 100644 test/economy-leaks.test.js create mode 100644 test/endgame-garrison.test.js create mode 100644 test/transport-speed.test.js diff --git a/deploy/update.sh b/deploy/update.sh new file mode 100755 index 0000000..28d3585 --- /dev/null +++ b/deploy/update.sh @@ -0,0 +1,292 @@ +#!/bin/sh +# Update the running game from git, safely. Runs ON THE SERVER as root (or via sudo); see docs/DEPLOY.md section 8. +# +# sudo sh /opt/upstream/deploy/update.sh # fetch origin/main, back up, stop, fast-forward, start, health check +# sudo sh /opt/upstream/deploy/update.sh --dry-run # fetch and show what would change, touch nothing else +# sudo sh /opt/upstream/deploy/update.sh --test # also run `npm test` on the new code (isolated copy, service user) before stopping +# +# What it does, in this order (it stops at the first failure; once the service is stopped it always puts it back): +# 0. needs git, curl, npm, systemctl and the admin wrapper on the PATH (plus runuser and tar with --test): missing = exit 2, nothing touched +# 1. refuses on a dirty tree (any change to tracked files, or untracked files that are not git-ignored), on a checkout +# that is not on the branch, and on an origin URL whose http(s) authority carries credentials (user:password@ or token@; +# ssh:// and git@host: URLs are fine, they carry no secret in the URL) +# 2. git fetch origin (no credentials, no prompt), refuses a history that is not a fast-forward +# 3. nothing new: says so and exits 0 (no stop, no backup, no restart) +# 4. only with --test: `git archive` of the NEW rev into a temp directory, `npm ci --omit=dev --ignore-scripts` and `npm test` there AS THE +# SERVICE USER (never as root, never in /opt/upstream); the live service keeps running meanwhile. Red = exit 1, nothing was touched +# 5. systemctl stop: from here the tree and the process never disagree (the old process lazily require()s modules, so it must not +# keep serving while the tree changes under it). Downtime = steps 6-9 +# 6. verified database snapshot taken from the stopped (final) database (upstream-admin backup + verify-backup); no snapshot, no +# update: the service is started again, exit 2, nothing changed +# 7. git merge --ff-only +# 8. npm ci --omit=dev --ignore-scripts, only if package.json / package-lock.json changed (or node_modules is missing) +# 9. systemctl start, then wait for /healthz (HEALTH_TIMEOUT seconds); on failure: systemctl stop, git reset --hard , +# npm ci again if the lock file had changed, systemctl start, wait again +# 10. prints old -> new revs and the commits that went out +# +# Exit codes: 0 updated (or already current), 1 failed and the old version runs again (or --test was red and nothing was touched), +# 2 refused or usage error (nothing was changed), 3 failed and the old version does NOT answer either (act now: +# journalctl -u upstream, restore the snapshot). +# +# An interrupt (Ctrl-C, SIGTERM) after the stop counts as a failure: before the merge the (untouched) old tree is simply started again, after +# it the old rev is put back first. SIGKILL or a power cut mid-update cannot be caught: check `git status`/`git log -1` and the unit, then rerun or +# `git reset --hard ` and `systemctl start upstream`. +# +# Not handled on purpose: a migration that already ran cannot be un-run by git. When the update contains new migrations the script says so and +# prints the snapshot to restore (docs/DEPLOY.md section 7) if the rolled-back code does not start. Migration 005_site_garrison.sql in particular +# adds site_stationed rows (units garrisoned in landing sites) that the old code does not know: it neither lists them nor charges their power +# nor lets them go home. Rolling back across it is only clean while nobody has garrisoned yet; otherwise restore the snapshot (and lose what +# players did since). +# +# Settings (environment, all optional): +# UPSTREAM_DIR /opt/upstream the git checkout +# UPSTREAM_UNIT upstream systemd unit name +# UPSTREAM_ENV_FILE /etc/upstream/upstream.env read for PORT (HEALTH_URL default) +# UPSTREAM_ADMIN upstream-admin the admin wrapper (runs as the service user) +# UPSTREAM_SERVICE_USER upstream the user --test runs npm ci / npm test as (when run as root) +# BACKUP_DIR /var/lib/upstream/backups where the pre-update snapshot goes +# BACKUP_KEEP 14 snapshots kept by the prune that backup does +# UPSTREAM_REMOTE origin git remote +# UPSTREAM_BRANCH main git branch (the checkout must be on it) +# HEALTH_URL http://127.0.0.1:$PORT/healthz (PORT from the env file, else 8080) +# HEALTH_TIMEOUT 30 seconds to wait for /healthz after a restart +# LOCK_DIR /run/upstream-update.lock stops two updates at once +# UPSTREAM_ALLOW_NONROOT=1 skip the root check (tests only) +set -eu +umask 022 # files from git/npm must stay readable by the service user whatever root's umask is + +APP_DIR=${UPSTREAM_DIR:-/opt/upstream} +UNIT=${UPSTREAM_UNIT:-upstream} +SVC_USER=${UPSTREAM_SERVICE_USER:-upstream} +ENV_FILE=${UPSTREAM_ENV_FILE:-/etc/upstream/upstream.env} +ADMIN=${UPSTREAM_ADMIN:-upstream-admin} +BACKUP_DIR=${BACKUP_DIR:-/var/lib/upstream/backups} +BACKUP_KEEP=${BACKUP_KEEP:-14} +REMOTE=${UPSTREAM_REMOTE:-origin} +BRANCH=${UPSTREAM_BRANCH:-main} +HEALTH_TIMEOUT=${HEALTH_TIMEOUT:-30} +LOCK_DIR=${LOCK_DIR:-/run/upstream-update.lock} +RUN_TESTS=0 +DRY_RUN=0 + +say() { printf '%s\n' "update: $*"; } +die() { printf '%s\n' "update: $*" >&2; exit "${2:-2}"; } + +while [ $# -gt 0 ]; do + case $1 in + --test) RUN_TESTS=1 ;; + --dry-run|-n) DRY_RUN=1 ;; + --timeout) [ $# -ge 2 ] || die "--timeout needs seconds"; HEALTH_TIMEOUT=$2; shift ;; + -h|--help) sed -n '2,/^set -eu/p' "$0" | sed -e '/^set -eu/d' -e 's/^# \{0,1\}//'; exit 0 ;; + *) die "unknown argument: $1 (try --help)" ;; + esac + shift +done +case $HEALTH_TIMEOUT in ''|*[!0-9]*) die "HEALTH_TIMEOUT must be a whole number of seconds" ;; esac + +# ---- 0. tools: a missing one must stop us BEFORE anything is stopped (without curl the health check can never pass, and the +# script would roll back a perfectly good release and then claim the rollback failed) ----------------------------------- +missing= +for tool in git curl npm systemctl "$ADMIN"; do + command -v "$tool" >/dev/null 2>&1 || missing="$missing $tool" +done +if [ "$RUN_TESTS" = 1 ]; then + for tool in tar mktemp; do command -v "$tool" >/dev/null 2>&1 || missing="$missing $tool"; done + if [ "${UPSTREAM_ALLOW_NONROOT:-0}" != 1 ]; then command -v runuser >/dev/null 2>&1 || missing="$missing runuser"; fi +fi +[ -z "$missing" ] || die "missing on the PATH:$missing. Install them (docs/DEPLOY.md section 3; the admin wrapper is deploy/upstream-admin) and rerun: nothing was touched" + +if [ -z "${HEALTH_URL:-}" ]; then + PORT= + if [ -r "$ENV_FILE" ]; then + PORT=$(sed -n 's/^[[:space:]]*PORT=//p' "$ENV_FILE" | tail -n 1 | sed -e 's/^"\(.*\)"$/\1/' -e "s/^'\(.*\)'\$/\1/") + fi + case $PORT in ''|*[!0-9]*) PORT=8080 ;; esac + HEALTH_URL=http://127.0.0.1:$PORT/healthz +fi + +if [ "${UPSTREAM_ALLOW_NONROOT:-0}" != 1 ] && [ "$(id -u)" != 0 ]; then + die "run as root (sudo): the checkout is root-owned and the unit is stopped and started" +fi + +# ---- 1. preconditions --------------------------------------------------------------------------------------------- +cd "$APP_DIR" 2>/dev/null || die "no such directory: $APP_DIR" +git rev-parse --is-inside-work-tree >/dev/null 2>&1 || die "$APP_DIR is not a git checkout" +url=$(git remote get-url "$REMOTE" 2>/dev/null) || die "git remote '$REMOTE' is not configured" +# Only a secret IN the URL is refused: user:password@ or token@ in the authority of an http(s) URL. ssh://git@host/... and git@host:path +# carry a login name, not a secret, and an '@' later in the path (https://example.org/a@b/c.git) is just a path. +case $url in + http://*|https://*) + authority=${url#*://}; authority=${authority%%/*} + case $authority in + *@*) die "remote '$REMOTE' has credentials in its URL; use a plain https:// URL (no user, no token) or an ssh remote, then rerun" ;; + esac ;; +esac +cur_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null || true) +[ "$cur_branch" = "$BRANCH" ] || die "checkout is on '${cur_branch:-a detached HEAD}', not '$BRANCH': fix it by hand (git checkout $BRANCH) before updating" +dirty=$(git status --porcelain) +if [ -n "$dirty" ]; then + printf '%s\n' "$dirty" | head -n 10 >&2 + die "working tree is dirty (above, first 10 lines): refusing to update. Commit, stash or remove the changes; they would be lost on rollback" +fi + +if ! mkdir "$LOCK_DIR" 2>/dev/null; then die "another update is running (lock $LOCK_DIR); remove it only if you are sure none is"; fi + +# State for the traps. STOPPED=1: we stopped the unit and have not started it again yet. MERGED=1: the tree is the new rev. +STOPPED=0 +MERGED=0 +TMP_DIR= +on_exit() { + rc=$? + trap - EXIT + if [ "$STOPPED" = 1 ]; then # an unexpected failure with the service down: never leave it down + printf '%s\n' "update: ABORTED with $UNIT stopped (exit $rc): starting it. Check git log -1, git status and journalctl -u $UNIT" >&2 + systemctl start "$UNIT" >/dev/null 2>&1 || printf '%s\n' "update: could not start $UNIT: start it by hand" >&2 + fi + [ -z "$TMP_DIR" ] || rm -rf "$TMP_DIR" + rmdir "$LOCK_DIR" 2>/dev/null || true + exit "$rc" +} +trap on_exit EXIT +# Ctrl-C / SIGTERM / hangup: before the stop nothing has changed, so just leave. After it the service must come back: with the old tree +# (not merged yet) or after putting the old rev back (merged). +on_signal() { + if [ "$MERGED" = 1 ]; then rollback "interrupted by a signal"; fi + if [ "$STOPPED" = 1 ]; then + say "interrupted by a signal before the merge: the tree is untouched, starting $UNIT again" + STOPPED=0 + systemctl start "$UNIT" || say "could not start $UNIT: start it by hand" + exit 1 + fi + exit 130 +} +trap on_signal INT TERM HUP + +# ---- 2/3. fetch, decide --------------------------------------------------------------------------------------------- +old=$(git rev-parse HEAD) +GIT_TERMINAL_PROMPT=0 git fetch --quiet "$REMOTE" "$BRANCH" || die "git fetch $REMOTE $BRANCH failed (network? URL: $url)" 1 +new=$(git rev-parse FETCH_HEAD) +short() { git rev-parse --short=9 "$1"; } +if [ "$old" = "$new" ]; then + say "already up to date at $(short "$old")" + exit 0 +fi +if ! git merge-base --is-ancestor "$old" "$new"; then + die "$REMOTE/$BRANCH ($(short "$new")) is not a fast-forward of the checkout ($(short "$old")): history was rewritten or the checkout has local commits. Not touching anything." +fi + +lock_changed=0 +git diff --quiet "$old" "$new" -- package.json package-lock.json || lock_changed=1 +[ -d node_modules ] || lock_changed=1 +migrations=$(git diff --name-only "$old" "$new" -- server/migrations | sed 's|^server/migrations/||' | tr '\n' ' ') +say "$(short "$old") -> $(short "$new"): $(git rev-list --count "$old..$new") commit(s)" +git log --oneline --no-decorate "$old..$new" | head -n 20 | sed 's/^/update: /' +[ "$lock_changed" = 0 ] || say "dependencies changed: npm ci --omit=dev --ignore-scripts will run" +[ -z "$migrations" ] || say "NEW MIGRATIONS in this update: $migrations(they run at the first start and cannot be undone by a rollback)" +case " $migrations" in + *" 005_site_garrison.sql "*) say " 005_site_garrison.sql adds garrisons in landing sites (site_stationed): the previous code cannot see those units, so once anybody has garrisoned a site a code-only rollback strands them; the snapshot is the way back" ;; +esac +if [ "$DRY_RUN" = 1 ]; then + say "dry run: nothing changed (the fetched commits are in .git, the tree and the service are untouched)" + exit 0 +fi + +# ---- helpers -------------------------------------------------------------------------------------------------------- +wait_healthy() { # seconds -> 0 as soon as /healthz answers 200 + _n=0 + while :; do + if curl -fsS --max-time 3 -o /dev/null "$HEALTH_URL" 2>/dev/null; then return 0; fi + [ "$_n" -lt "$1" ] || return 1 + _n=$((_n + 1)) + sleep 1 + done +} +install_deps() { + # --ignore-scripts: no package install script (ours or a dependency's) runs as root; ws needs none + say "npm ci --omit=dev --ignore-scripts" + npm ci --omit=dev --ignore-scripts --no-audit --no-fund +} +as_service_user() { + if [ "$(id -u)" = 0 ]; then runuser -u "$SVC_USER" -- "$@"; else "$@"; fi +} +rollback() { # $1 = why. Puts the old code back, starts it, checks. Never returns. + MERGED=0 + say "FAILED: $1" + say "rolling back to $(short "$old")" + systemctl stop "$UNIT" || say "systemctl stop $UNIT failed (the new code may still be running)" + STOPPED=1 + git reset --hard --quiet "$old" + rb=0 + if [ "$lock_changed" = 1 ]; then install_deps || { say "npm ci for the old code failed"; rb=1; }; fi + if [ "$rb" = 0 ] && systemctl start "$UNIT" && wait_healthy "$HEALTH_TIMEOUT"; then + STOPPED=0 + say "rolled back: $(short "$old") answers /healthz again" + if [ -n "$migrations" ]; then + say "this update had migrations ($migrations): the old code runs on the NEWER schema. If it misbehaves, stop the unit and restore the snapshot $snap (docs/DEPLOY.md section 7)" + case " $migrations" in + *" 005_site_garrison.sql "*) say "005_site_garrison.sql: units that players garrisoned in landing sites while the new code ran are rows in site_stationed that the old code neither shows, nor powers, nor sends home. If any site was garrisoned in that window, restore the snapshot instead (you lose what happened since it was taken)" ;; + esac + fi + exit 1 + fi + STOPPED=0 # reported; do not auto-start from the exit trap on top of a failed recovery + say "ROLLBACK DID NOT RECOVER the service. Look: journalctl -u $UNIT -n 50" + say "last resort: systemctl stop $UNIT, restore $snap (docs/DEPLOY.md section 7), start $UNIT" + exit 3 +} + +# ---- 4. optional tests, on an isolated copy of the NEW rev, as the service user, while the old version keeps serving ----------- +if [ "$RUN_TESTS" = 1 ]; then + TMP_DIR=$(mktemp -d "${TMPDIR:-/tmp}/upstream-update-test.XXXXXX") || die "mktemp failed, nothing was touched" + git archive "$new" | tar -x -C "$TMP_DIR" || die "could not extract $(short "$new") into $TMP_DIR, nothing was touched" 1 + [ "$(id -u)" != 0 ] || chown -R "$SVC_USER" "$TMP_DIR" + say "npm ci + npm test on $(short "$new") in $TMP_DIR as ${SVC_USER} (the live service is not touched)" + if ! as_service_user env -u DB_PATH -u PORT HOME="$TMP_DIR" npm_config_cache="$TMP_DIR/.npm-cache" \ + sh -c 'cd "$1" && npm ci --omit=dev --ignore-scripts --no-audit --no-fund && npm test --silent' sh "$TMP_DIR"; then + die "the test suite (or npm ci) failed on the new rev: nothing was stopped, changed or restarted" 1 + fi + rm -rf "$TMP_DIR"; TMP_DIR= +fi + +# ---- 5. stop: from here on the tree and the process never disagree ------------------------------------------------------ +say "stopping $UNIT" +systemctl stop "$UNIT" || die "systemctl stop $UNIT failed: tree untouched, the service state is unknown (systemctl status $UNIT)" 1 +STOPPED=1 + +# ---- 6. verified backup, from the final (stopped) database --------------------------------------------------------- +say "taking a verified snapshot" +snap= +if bk_out=$("$ADMIN" backup "$BACKUP_DIR" --keep "$BACKUP_KEEP"); then + printf '%s\n' "$bk_out" | sed 's/^/update: /' + snap=$(printf '%s\n' "$bk_out" | sed -n 's/^backup written: \(.*\) ([0-9]* bytes, verified)$/\1/p' | head -n 1) +fi +if [ -z "$snap" ] || ! "$ADMIN" verify-backup "$snap" >/dev/null; then + STOPPED=0 + say "no verified snapshot (backup failed, its output was not readable, or it does not verify): update NOT started, nothing was changed; starting $UNIT again" + systemctl start "$UNIT" && wait_healthy "$HEALTH_TIMEOUT" || { say "$UNIT does not answer after the restart: journalctl -u $UNIT -n 50"; exit 3; } + exit 2 +fi +say "snapshot ok: $snap" + +# ---- 7/8. new code, deps ------------------------------------------------------------------------------------------ +if ! git merge --ff-only --quiet "$new"; then + STOPPED=0 + say "fast-forward failed; tree unchanged, starting $UNIT again" + systemctl start "$UNIT" && wait_healthy "$HEALTH_TIMEOUT" || { say "$UNIT does not answer after the restart: journalctl -u $UNIT -n 50"; exit 3; } + exit 1 +fi +MERGED=1 +say "checked out $(short "$new")" +if [ "$lock_changed" = 1 ]; then install_deps || rollback "npm ci failed"; fi + +# ---- 9. start and look ------------------------------------------------------------------------------------------- +say "starting $UNIT" +systemctl start "$UNIT" || rollback "systemctl start $UNIT failed" +wait_healthy "$HEALTH_TIMEOUT" || rollback "no 200 from $HEALTH_URL within ${HEALTH_TIMEOUT}s" + +MERGED=0 +STOPPED=0 +# ---- 10. done ----------------------------------------------------------------------------------------------------- +say "OK: $(short "$old") -> $(short "$new"), $UNIT answers $HEALTH_URL" +say "snapshot from before the update: $snap" +exit 0 diff --git a/deploy/upstream-offsite b/deploy/upstream-offsite new file mode 100755 index 0000000..d3885ad --- /dev/null +++ b/deploy/upstream-offsite @@ -0,0 +1,69 @@ +#!/bin/sh +# Copy the newest VERIFIED database snapshot off the box. Started by upstream-offsite.service (timer), or by hand with +# `systemctl start upstream-offsite` (that gives it the user, the env file and the sandbox). Nothing happens unless +# OFFSITE_DEST is set (in /etc/upstream/upstream.env); docs/DEPLOY.md section 7 "Off-box copy". +# +# OFFSITE_DEST required. rsync destination DIRECTORY: user@host:/srv/backups/upstream/ or a local path (a mounted NAS) +# OFFSITE_METHOD rsync (the only method). scp was removed: it cannot refuse to overwrite a same-named file on the far side +# OFFSITE_SSH_KEY optional private key file (owned by the service user, mode 0600); used with IdentitiesOnly +# OFFSITE_KNOWN_HOSTS known_hosts file for the destination (default /etc/upstream/offsite_known_hosts when it exists); +# host keys are always checked (StrictHostKeyChecking=yes), BatchMode=yes: never a prompt +# OFFSITE_SSH_OPTS extra ssh options, e.g. "-p 2222" +# BACKUP_DIR where snapshots are written (default /var/lib/upstream/backups) +# UPSTREAM_ADMIN admin wrapper used for verify-backup (default upstream-admin) +# +# upstream-offsite --check exit 0 when OFFSITE_DEST is set, 1 when not (the unit's ExecCondition: unset = skipped quietly) +# +# Steps: pick the newest snapshot (by modification time) -> verify-backup it (integrity_check, schema present) -> copy it, never +# overwriting a file of the same name on the far side -> compare content with --checksum. Old snapshots on the far side +# are never deleted by this script (prune there, or set up your own retention). +# Exit codes: 0 copied (or already there), 1 failed / nothing to copy / not configured under --check, 2 usage or configuration error. +set -eu + +BACKUP_DIR=${BACKUP_DIR:-/var/lib/upstream/backups} +ADMIN=${UPSTREAM_ADMIN:-upstream-admin} +METHOD=${OFFSITE_METHOD:-rsync} +DEST=${OFFSITE_DEST:-} +KEY=${OFFSITE_SSH_KEY:-} +KNOWN=${OFFSITE_KNOWN_HOSTS:-/etc/upstream/offsite_known_hosts} +SSH_EXTRA=${OFFSITE_SSH_OPTS:-} + +say() { printf '%s\n' "offsite: $*"; } +die() { printf '%s\n' "offsite: $*" >&2; exit "${2:-1}"; } + +case ${1:-} in + --check) [ -n "$DEST" ]; exit $? ;; + '') ;; + *) die "usage: upstream-offsite [--check]" 2 ;; +esac + +[ -n "$DEST" ] || die "OFFSITE_DEST is not set: off-box copy is not configured (docs/DEPLOY.md section 7)" 2 +case $METHOD in + rsync) ;; + scp) die "OFFSITE_METHOD=scp is not supported any more: scp cannot refuse to overwrite a file of the same name on the far side. Use rsync (the far side needs rsync, or a forced rrsync command)" 2 ;; + *) die "OFFSITE_METHOD must be rsync, not '$METHOD'" 2 ;; +esac +[ -d "$BACKUP_DIR" ] || die "no backup directory $BACKUP_DIR" + +# newest snapshot by mtime (names sort by time too, but a same-second '-1' file would sort wrongly) +file= +for f in $(ls -1t "$BACKUP_DIR" 2>/dev/null); do + case $f in upstream-[0-9]*T[0-9]*Z.db|upstream-[0-9]*T[0-9]*Z-[0-9]*.db) file=$BACKUP_DIR/$f; break ;; esac +done +[ -n "$file" ] || die "no snapshot (upstream-*.db) in $BACKUP_DIR: nothing to copy" +"$ADMIN" verify-backup "$file" >/dev/null || die "newest snapshot $file does not verify: NOT copied (the daily backup unit should have failed too: journalctl -u upstream-backup)" + +SSH_OPTS="-o BatchMode=yes -o StrictHostKeyChecking=yes" +[ -z "$KEY" ] || SSH_OPTS="$SSH_OPTS -i $KEY -o IdentitiesOnly=yes" +[ ! -f "$KNOWN" ] || SSH_OPTS="$SSH_OPTS -o UserKnownHostsFile=$KNOWN" +[ -z "$SSH_EXTRA" ] || SSH_OPTS="$SSH_OPTS $SSH_EXTRA" +SSH="ssh $SSH_OPTS" # (paths in these settings must not contain spaces) +dest=${DEST%/}/ +name=$(basename "$file") + +# --ignore-existing: a snapshot name is a moment in time, a same-named file on the far side is never replaced +rsync -t --chmod=F600 --ignore-existing -e "$SSH" "$file" "$dest" || die "rsync to $DEST failed" +# content check of what is over there now (empty output = identical bytes) +diff=$(rsync -c -n -i -e "$SSH" "$file" "$dest" 2>&1) || die "could not re-read $DEST to compare: $diff" +[ -z "$diff" ] || die "far-side copy of $name differs from the verified local snapshot ($diff): a different file of that name already exists there" +say "ok: $name is on $DEST (checksum compared)" diff --git a/deploy/upstream-offsite.service b/deploy/upstream-offsite.service new file mode 100644 index 0000000..8e4e337 --- /dev/null +++ b/deploy/upstream-offsite.service @@ -0,0 +1,43 @@ +# Copy the newest verified snapshot off the box (rsync to OFFSITE_DEST). Started by upstream-offsite.timer, or by hand: +# systemctl start upstream-offsite. Does NOTHING until OFFSITE_DEST is set in /etc/upstream/upstream.env: the ExecCondition +# below then makes systemd skip the run quietly (no failure). See docs/DEPLOY.md section 7, "Off-box copy". +# +# install -m 0644 deploy/upstream-offsite.service deploy/upstream-offsite.timer /etc/systemd/system/ +# (after configuring) systemctl daemon-reload && systemctl enable --now upstream-offsite.timer +# +# Instead of the timer you can chain it to the backup: `systemctl edit upstream-backup` and add +# [Unit] +# OnSuccess=upstream-offsite.service + +[Unit] +Description=Upstream - copy the newest verified snapshot off the box +Documentation=file:///opt/upstream/docs/DEPLOY.md +# Not tied to upstream.service: copying a snapshot must work while the game is stopped. + +[Service] +Type=oneshot +User=upstream +Group=upstream +WorkingDirectory=/opt/upstream +# OFFSITE_DEST, OFFSITE_METHOD, OFFSITE_SSH_KEY, OFFSITE_KNOWN_HOSTS, OFFSITE_SSH_OPTS, BACKUP_DIR: see deploy/upstream-offsite. +EnvironmentFile=-/etc/upstream/upstream.env +Environment=BACKUP_DIR=/var/lib/upstream/backups +Environment=UPSTREAM_ADMIN=/usr/local/bin/upstream-admin +# Exit 1 from ExecCondition = skipped (not failed) when OFFSITE_DEST is unset or empty. +ExecCondition=/opt/upstream/deploy/upstream-offsite --check +ExecStart=/opt/upstream/deploy/upstream-offsite +# A failed copy must be visible: the unit fails and journalctl -u upstream-offsite shows why. +TimeoutStartSec=30min +Nice=10 +IOSchedulingClass=idle + +NoNewPrivileges=yes +CapabilityBoundingSet= +AmbientCapabilities= +# ssh/rsync need IP sockets; AF_UNIX for an ssh-agent or the resolver, AF_NETLINK for glibc's resolver (as in upstream.service) +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK +RestrictRealtime=yes +RestrictSUIDSGID=yes +LockPersonality=yes +SystemCallArchitectures=native +UMask=0077 diff --git a/deploy/upstream-offsite.timer b/deploy/upstream-offsite.timer new file mode 100644 index 0000000..9a2415e --- /dev/null +++ b/deploy/upstream-offsite.timer @@ -0,0 +1,15 @@ +# Off-box copy of the newest snapshot, daily at 05:00 (+ up to 10 min jitter): after upstream-backup.timer (04:15 + up to +# 10 min) has finished. Persistent: a run missed while the container was off happens at the next boot. Enable it only after +# OFFSITE_DEST is configured (docs/DEPLOY.md section 7); without it each run is skipped by the service's ExecCondition. + +[Unit] +Description=Upstream - daily off-box copy of the newest snapshot + +[Timer] +OnCalendar=*-*-* 05:00:00 +RandomizedDelaySec=10min +Persistent=true +Unit=upstream-offsite.service + +[Install] +WantedBy=timers.target diff --git a/docs/API.md b/docs/API.md index a4d91d2..c1ae705 100644 --- a/docs/API.md +++ b/docs/API.md @@ -26,7 +26,7 @@ REST JSON under `/api/v1/`. The machine-readable contract is `docs/openapi.json` | `GET /auth/tokens`, `DELETE /auth/tokens/:tokenId`, `POST /auth/logout` | list this account's active device tokens, revoke one, revoke the current one | | `GET /me` | user, operators (per world), POPs | | `POST /me/join {worldId?}` | an account with no operator (world reset, new world) founds its capital POP (201, returns `/me`); `409 conflict` if already joined | -| `GET /towns/:id` | full POP state: resources `{amount, rate, cap}` at `serverTime`, power, buildings with the server's build plan, queue | +| `GET /towns/:id` | full POP state: resources `{amount, rate, cap}` at `serverTime` (`cap` = Rack hall size minus the goods escrowed in open trade offers, `escrow` = those goods per resource), power, buildings with the server's build plan, queue | | `POST /towns/:id/build {key}` | build/upgrade one level of a field (`f1..f18`) or an infrastructure building | | `DELETE /towns/:id/queue/:eventId` | cancel a running build, 80% refund | | `POST /towns/:id/rename {name}` | rename a POP (2-40 chars) | @@ -94,7 +94,7 @@ exist). The cursor is a rank offset (`next` = ranks already seen). Each response Units are plain `{ unitId: count }` objects with the generic ids of `data.UNITS` (`port_scanner`, `soc_analyst`, `blue_team`, `honeypot`, `script_crew`, `botnet`, `ddos_rig`, `exploit_kit`, `rollout_crew`, `ma_team`); names live in `i18n.js`. `GET /towns/:id` -now carries `town.military`: units at home (`online` flag, `offlineSince`), reinforcements standing here and away, the training queue, +now carries `town.military`: units at home (`online` flag, `offlineSince`), reinforcements standing here and away, `units.garrisoned` `[{siteId, x, y, units}]` (this POP's units standing in backbone landing sites: they draw this POP's power), the training queue, what can be trained (cost, time, missing requirements), research levels and queue, transport links, and this POP's outgoing/incoming movements. Nothing resolves when you send it: combat, loot and arrival happen in the event queue at the arrival time, and reports and notifications (`incoming`, `report`, `train_done`, `research_done`, `movement_returned`, `movement_lost`, `transport_arrived`, @@ -105,7 +105,7 @@ buildings) tell you afterwards. | ----- | ------- | | `POST /towns/:id/train {unit, count}` | queue a batch (201). Batches of one training building (NOC / Ops lab / Rollout depot) run in order, buildings in parallel; queue limit 8 per building (`queue_full`) | | `POST /towns/:id/research {unit, stat}` | +5% `attack` or `defence` per level for one unit type, one research at a time per POP, level n needs a Research lab of level n + 2 | -| `POST /movements {fromTownId, type, toTownId \| x,y, units, ...}` | send `scan`, `raid`, `attack`, `takeover`, `reinforce`, `settle` (201). `type: transport` carries `cargo: {fiber, hardware, capital}` (Internet exchange: level = concurrent transports, 1000 each, `D.TRANSPORT.capacityPerLink`). Extra fields: `target` (building for exploit kits), `wild` (two field types for a new POP), `confirmEndProtection` | +| `POST /movements {fromTownId, type, toTownId \| x,y, units, ...}` | send `scan`, `raid`, `attack`, `takeover`, `reinforce`, `settle` (201). `type: transport` carries `cargo: {fiber, hardware, capital}` (Internet exchange: level = concurrent transports, each carries `rules.transportCapacity(speed)` = 1000 x the world speed; the POP view's `transport.capacityPerLink` already says the real number). Extra fields: `target` (building for exploit kits), `wild` (two field types for a new POP), `confirmEndProtection` | | `GET /movements` | your active movements (full detail, `recallableUntil`) and incoming ones from others: origin and ETA only, `type: "unknown"` | | `POST /movements/:id/recall` | turn an outbound movement around within the first 90 s (`recall_expired` after) | | `POST /towns/:id/withdraw {ownerTownId, units?}` | reinforcements in this POP go home (host kicks them out, or their owner calls them back) | @@ -121,7 +121,7 @@ or take over each other; only the same alliance or a confederation may reinforce the movement arrives and bounces it (units come home, a `movement_failed` report says why) if something changed. Report types: `raid`, `attack`, `takeover` (the same combat report: outcome, both sides' units and losses, attack/defence values, -firewall, loot, siege, takeover/loyalty), `scan` (attacker; intel when it succeeded), `scan_detected` (defender; attacker identity only +firewall, loot, `lootLeft` (what the raiders could carry and the target had, but their home Rack hall had no room for: it stayed with the target), siege, takeover/loyalty), `scan` (attacker; intel when it succeeded), `scan_detected` (defender; attacker identity only if the defender's scanners won), `incumbent`, `settle`, `reinforce`, `movement_failed`. Later stages append their routes here and to the route table. @@ -138,10 +138,10 @@ offer you have (older ones follow). `status`: `open`, `accepted`, `completed`, ` | `GET /trade/offers?worldId&townId&give&want&after&limit` | open offers of others that one of your POPs (or `townId`) can take: within `min(maxDistance, 10 x exchange level)`. Each carries `acceptableFrom: [{townId, distance}]`; `exchangeLevels` lists your exchanges and their reach | | `GET /trade/offers/mine?worldId&status&after&limit` | offers you posted or accepted, any status, with `role` | | `GET /trade/offers/:id` | one offer: open ones to every operator of the world, closed ones to the two parties (`not_found` otherwise) | -| `DELETE /trade/offers/:id` | cancel your open offer; the escrow returns to the POP, capped by its Rack hall (stock already above the cap stays; a refund never lifts it further, and the clipped part is lost without a notice: BALANCE.md S2). `offer_closed` when it is not open | -| `POST /trade/offers/:id/accept {townId}` | take it with one of your POPs (201): two transports leave at once (your payment, their goods); `own_offer`, `offer_closed`, `trade_out_of_range`, `no_transport_link`, `not_enough_resources`; all or nothing | +| `DELETE /trade/offers/:id` | cancel your open offer; the escrow returns to the POP and always fits: open escrow keeps its room in the Rack hall (`GET /towns/:id` `resources[r].cap` is hall size minus escrow, `escrow` lists it). Only a Rack hall shot down meanwhile can clip the refund; `returned.amount` is what was credited and a `trade_refund_clipped` notification says what was lost (BALANCE.md S2). `offer_closed` when it is not open | +| `POST /trade/offers/:id/accept {townId}` | take it with one of your POPs (201): two transports leave at once (your payment, their goods); `own_offer`, `offer_closed`, `trade_out_of_range`, `no_room_for_goods` (your Rack hall would not have room for the goods when they arrive, projected with production and other cargo on its way: refused up front because overflow on arrival is destroyed), `no_transport_link`, `not_enough_resources`; all or nothing | -Notifications: `trade_accepted` (poster), `trade_completed` (both, when both transports arrived), `trade_expired`, `trade_void` (the POP +Notifications: `trade_accepted` (poster), `trade_completed` (both, when both transports arrived), `trade_expired` (`returned` = what was credited), `trade_refund_clipped` `{offerId, townId, resource, lost, credited}` (a refund did not fit, rare), `trade_void` (the POP was taken over). Delivery notifications are the existing `transport_arrived` / `transport_delivered`. Direct transports (own POPs, any player) stay `POST /movements` with `type: "transport"`. @@ -151,20 +151,26 @@ player) stay `POST /movements` with `type: "transport"`. | ----- | ------- | | `GET /worlds/:id/status` | `phase` (`running`, `backbone_open`, `ended`), `ageDays`, `opensAt`, the 7 `sites` (empty before opening: `id` (null until first touched), `index`, `x`, `y`, `holder` `{allianceId, tag, name}` or null = incumbent, `takenBy`, `level`/`maxLevel`/`progress`, `pool` (stockpile), `build` `{toLevel, startedAt, dueAt}`, `next` `{toLevel, cost, durationMs}`), `winner`, `endsAt` (set once somebody won), `endedAt` | | `GET /worlds/:id/results` | the final snapshot once ended (`available: false` before): `winner`, `results.{operators, alliances, attackers, defenders, sites, totals}` (top 100 each, ranked) | -| `GET /backbone/:id` | one site; holders also get `contributions` (who shipped what) and `you` `{holder, canBuild, canShip, canAttack}` | +| `GET /backbone/:id` | one site (`shieldUntil` is set while a site that just changed hands cannot be attacked); holders also get `contributions` (who shipped what), `you` `{holder, canBuild, canShip, canAttack, canReinforce}`, `defence` `{static, garrison, total}` and `garrison` `[{ownerTownId, townName, operator, units, online, power, mine}]` (the units its members stationed there) | +| `POST /backbone/:id/withdraw {fromTownId, units?}` | call units of one of YOUR POPs home from the site's garrison (201; default all of them; only their owner; works whoever holds the site); `not_enough_units`, `not_found` | | `POST /backbone/:id/ship {fromTownId, cargo}` | send resources to a site your alliance holds (201, a transport: same links and capacity); arrives into the stockpile, or rides home if the site changed hands | | `POST /backbone/:id/build` | start the next node level (201), paid from the stockpile at once, one level at a time, any holder with `backboneBuild`; `max_level`, `already_queued`, `not_enough_resources`, `forbidden` (not a holder), `backbone_closed` | Taking a site is `POST /movements` with `type: "scan"` or `"attack"` and the site's `x, y` (no `toTownId`): needs an alliance, not against the own alliance or a NAP/confederation partner (`invalid_target`, `details.reason`: `no_alliance`, `own_site`, `pact`, -`landing_scan_or_attack_only`); before opening `backbone_closed`. Settling a landing tile is `invalid_target` (`backbone_site`), also before -it opens. Defence is static: `incumbentDefence x 12 x (1 + 0.03 x node level)`; a scan report shows it. Reports: scans as `scan` (with +`landing_scan_or_attack_only`, `site_shielded` + `details.until`); before opening `backbone_closed`. Settling a landing tile is `invalid_target` +(`backbone_site`), also before it opens. **Garrison:** `POST /movements` with `type: "reinforce"` and the site's `x, y` stations units there; only +members of the holding alliance (`invalid_target`, `details.reason: not_holder`; checked again at arrival, the units turn back with a +`movement_failed` report otherwise). Defence = static (`incumbentDefence x M x (1 + 0.03 x node level)`, M 12 unheld / 2 held) + the garrison +(online groups, with their owners' research); a scan report shows `intel.static`, `intel.garrison` `{units, power}` and `intel.defence` (the sum). +A `landing` report adds `defender.garrison` (per owner POP: sent, lost, survivors, offline) and `power.static` / `power.garrison`. Reports: scans as `scan` (with `site.type: "backbone"`), attacks as the new type `landing` (outcome, attack/defence, `taken`; recipients: the attacker and every member of the previous holder). `GET /map` lists open sites in `specials` as `type: "backbone"` with `site: {id, index, holder, level, maxLevel}`; `GET /map/tile` returns `type: "backbone"` and `backbone: {siteId, holder, level, pool, build, mine, canAttack}`. -Notifications: `backbone_open` (first touch), `backbone_taken` / `backbone_lost` (alliance members), `backbone_level` (every 10th level and the -last, holder members), `backbone_delivered` / `backbone_ship_bounced` (sender), `backbone_won` (everybody), `world_ended` (everybody). +Notifications: `backbone_open` (first touch), `backbone_taken` / `backbone_lost` (alliance members), `backbone_incoming` (holder members: a scan +or attack was sent at their site, `{siteId, index, x, y, arriveAt}`, no type, no sender), `garrison_arrived` / `garrison_released` (the owner of the +units; `reason`: `alliance_dissolved`, `left_alliance`, `town_lost`), `backbone_level` (every 10th level and the last, holder members), `backbone_delivered` / `backbone_ship_bounced` (sender), `backbone_won` (everybody), `world_ended` (everybody). **An ended world** answers every game command with `409 world_ended` (build, send, train, trade, alliances, diplomacy, backbone, report sharing, ...). Still allowed: `GET` everything (map, reports, rankings, towns, status, results), `POST /reports/read-all`, `POST @@ -178,3 +184,51 @@ reads one with its full data. Members with `viewSharedReports` only; `GET /allia **Allied incoming.** `GET /movements` has a new `alliedIncoming` list: movements heading for POPs of your alliance mates and of confederated alliances, same shape as `incoming` (type `unknown`, origin and ETA only) plus `ally: true` and `toOperator`. Friendly traffic (from partners of the target) is left out. + +## Notification types (complete list) + +Every row of `GET /notifications` has `type` and a `payload`; derived from the `notify` calls in `server/` (the list grows: clients treat an +unknown `type` as generic). WebSocket hint `{type:"notification", id, kind}` carries the same `type` as `kind` (docs/PROTOCOL.md). +`cargoLost` is `{resource: amount}` of what did not fit the Rack hall, exact, only the resources that lost something (rest of the +cargo was stored). + +| `type` | to | payload | +| ------ | -- | ------- | +| `build_done` | owner | `{townId, key, type, level}` | +| `train_done` | owner | `{townId, unit, count}` | +| `research_done` | owner | `{townId, unit, stat, level, key}` | +| `incoming` | target's owner | `{movementId, toTownId, fromTownId, arriveAt}` (movement type hidden) | +| `report` | report recipients | `{reportId, type, role}` | +| `movement_returned` | owner | `{movementId, townId, units, cargo, cargoLost}`; also for a bounced shipment that carries cargo home (backbone, trade): `cargoLost` says exactly what the full hall destroyed | +| `movement_lost` | owner | `{movementId}` (no POP left to go home to) | +| `transport_arrived` | receiver | `{movementId, townId, fromTownId, cargo, cargoLost, own}` | +| `transport_delivered` | sender (when not the receiver) | `{movementId, toTownId, cargo, cargoLost}` | +| `reinforcements_sent_home` | owner of the units | `{hostTownId, ownerTownId, units}` | +| `units_offline` | owner | `{townId, since}` (battery empty) | +| `units_decommissioned` | owner | `{townId, units}` (24 h offline) | +| `town_lost` / `town_gained` | old / new owner | `{townId, name, by}` / `{townId, name}` | +| `trade_accepted` | poster | `{offerId, townId, byTownId, give, want}` | +| `trade_completed` | both parties | see the trade section | +| `trade_expired` | poster | `{offerId, townId, returned: {resource, amount}}` | +| `trade_refund_clipped` | poster | `{offerId, townId, resource, lost, credited}` | +| `trade_void` | poster | `{offerId, townId}` (the POP changed hands) | +| `backbone_open` | everybody | `{sites: [{siteId, index, x, y}]}` (first touch after the sites open) | +| `backbone_taken` / `backbone_lost` | attacker's / old holder alliance | site and alliance brief | +| `backbone_incoming` | holder alliance | `{siteId, index, x, y, arriveAt}` (a scan or attack was sent; no type, no sender) | +| `backbone_level` | holder alliance | `{siteId, index, level}` | +| `backbone_delivered` | sender | `{movementId, siteId, cargo}` | +| `backbone_ship_bounced` | sender | `{movementId, siteId, cargo}` (site changed hands: the cargo rides home, `movement_returned` follows with `cargoLost`) | +| `backbone_won` | everybody | `{allianceId, name, tag, siteId, endsAt}` | +| `world_ended` | everybody | `{winner, endedAt}` | +| `garrison_arrived` | owner of the units | `{siteId, index, ownerTownId, units}` | +| `garrison_released` | owner of the units | `{siteId, index, ownerTownId, reason, units, movementId}`; `reason`: `alliance_dissolved`, `left_alliance`, `town_lost` (a voluntary withdraw sends no notification) | +| `alliance_invite` / `alliance_invite_declined` | invited operator / inviter | `{inviteId, allianceId, tag, name, by, expiresAt}` / `{inviteId, allianceId, by}` | +| `alliance_member_joined` / `alliance_member_left` | alliance members | `{allianceId, operatorId, name}` (`kicked` on left) | +| `alliance_kicked` | the kicked operator | `{allianceId, tag, name}` | +| `alliance_role` | the operator | `{allianceId, tag, from, role}` | +| `alliance_leader` | alliance members | `{allianceId, operatorId, name, from}` | +| `alliance_disbanded` | alliance members | `{reason, ...alliance brief}` | +| `alliance_message` / `message` | recipient | `{messageId, ...}` (`from`, `allianceId`/`tag`) | +| `diplomacy_proposal` / `diplomacy_declined` | leader + diplomat of the other / proposing alliance | `{proposalId, from \| by, state, expiresAt?}` | +| `diplomacy_changed` | both alliances | `{allianceId, other, from, to}` (also `reason: "disbanded"`) | +| `diplomacy_cancel_pending` / `diplomacy_cancel_revoked` | both alliances | `{allianceId, other, ...}` (a pact cancel is scheduled / was revoked) | diff --git a/docs/BALANCE.md b/docs/BALANCE.md index e3c9ff2..7d93bad 100644 --- a/docs/BALANCE.md +++ b/docs/BALANCE.md @@ -55,7 +55,7 @@ node tools/bot.js --help | invariant | how it is checked | |---|---| -| resources are conserved | `pools = sources + production - sinks`, per resource, at every midnight and at the end. Pools: POP stock, open trade escrow, cargo of movements that are out, landing-site stockpiles. **Production is exact**: a tap on `db.run` books the difference every `state.settle` writes (and drops it if the transaction rolls back). Sources: start stock of operators and founded POPs, the incumbent Hardware bonus. Sinks: build/train/research costs (command results), Backbone node levels, `cargoLost` in notifications (overflow at delivery), trade refunds clipped by the Rack hall cap (tap on the refund statement). Tolerance 0.5 per rounding event. | +| resources are conserved | `pools = sources + production - sinks`, per resource, at every midnight and at the end. Pools: POP stock, open trade escrow, cargo of movements that are out, landing-site stockpiles. **Production is exact**: a tap on `db.run` books the difference every `state.settle` writes (and drops it if the transaction rolls back). Sources: start stock of operators and founded POPs, the incumbent Hardware bonus. Sinks: build/train/research costs (command results), Backbone node levels, `cargoLost` in notifications (overflow at delivery), `trade_refund_clipped` notifications (a refund that did not fit: only after a shot-down Rack hall since B6, 0 in every standard run). Open trade escrow is a pool. Tolerance 0.5 per rounding event. | | units are conserved | alive (home + stationed + on the road) = trained (`trainDone` events that ran) - lost (battle, scan, incumbent, landing reports, decommission notifications) - consumed (3 crews per founded POP, 1 M&A team per loyalty hit). Exact. | | no negative stock | SQL scan of towns and landing sites. | | no failed events | `events.status = 'failed'` and any server log line mentioning a failure. | @@ -228,11 +228,34 @@ much as 1000 per link at both speeds (59 days at 1x; best level 94 on day 110 at was taken because the cost curve was set on purpose ("far more than anything else", DECISIONS E5, and DESIGN.md quotes 7.2 M) while carrying 500 units per trip is a convenience limit nobody argued for, and because it also lifts bulk trade a little. -**Not solved by B2:** speed does not shorten the end game the way it shortens everything else. A 3x world opens its sites on day 33, but -its alliances still take 76 days (seed 2) after that, about as long as a 1x world, because shipping is per sitting, not per hour (and -at day 33 the members are at field level ~12 with fewer links). `capacityPerLink x world speed` in `rules.transportPlan` would -restore the scaling (a 10x world with a final push finished 8.5 days after opening, below) but the client reads the constant directly -(trade form limits, send dialog), so it was left to the owner of that code. +**Not solved by B2 (solved by B7, below):** speed did not shorten the end game the way it shortens everything else. A 3x world opens its sites +on day 33, but its alliances still took 76 days (seed 2) after that, about as long as a 1x world, because shipping is per sitting, not per hour. + +(Re-measurement, 2026-10-11: the table above was measured on an older tree. The same command on HEAD today, `--days 240` because 175 is no longer enough, +gives a winner on day 234.7 (134 days after opening) for seed 1 and day 200.2 (100 days) for seed 2 at speed 1, not 164 and 156. Something since the B2 runs +(B4/B5, bot changes, other work in the tree) moved the end game; it was not bisected. Every "before" in B7 and E6 below is a run of today's HEAD, not a number from the B2 table.) + +### B7. Transport capacity x world speed (`rules.transportCapacity`) + +| parameter | old | new | file | +|---|---|---|---| +| link capacity | `TRANSPORT.capacityPerLink` (1000) at every speed | `rules.transportCapacity(speed)` = `capacityPerLink x speed` | `public/js/rules.js` (`transportPlan`, `tradeTermsCheck`), `server/military/views.js`, `public/js/screens/trade.js`, the bots | + +Why: one link makes one trip per sitting, and a sitting does not get more frequent when the world is faster, so at 3x the shipping that the node needs +(21.6 M units) took as many sittings as at 1x while everything else shortened. Cost: it applies to every transport and to the two sides of a trade +offer (each side must fit one transport); production is also x speed, so the ratio of what a POP makes per sitting to what it can carry is unchanged. +At speed 1 the factor is 1 and nothing changes, so **speed 1 cannot measure B7**: the table is speed 3 only. "Before" = HEAD today, "after" = this tree with +`--no-contest --set ENDGAME.heldDefenceMult=12` (the pre-E6 end game: striker only, held sites as heavy as before), so only the capacity differs. +`node tools/bot.js --players 50 --speed 3 --days 200 --seed S` (before, run from a `git archive HEAD` copy) and +`node tools/bot.js --players 50 --speed 3 --days 110 --seed S --no-contest --set ENDGAME.heldDefenceMult=12` (after). The sites open on day 33.3. + +| speed 3 | before: winner (days after the sites opened) | after (B7 only): winner (days after) | +|---|---|---| +| seed 1 | day 131.1 (97.7 days) | day 68.7 (35.4 days) | +| seed 2 | day 109.9 (76.5 days) | day 62.8 (29.4 days) | + +A 3x world now takes 29 to 35 days after opening, 2.6 to 2.8 times shorter, about a third of a 1x world's 100 to 134 days (which is what "3x" should mean), +instead of 77 to 98 days. Not measured: speed 10 with this change (the 10x numbers in section 5 are from the 500/1000 pass). Every run `INVARIANTS OK`. ### B4. Early-level build discount (the first hour and first day) @@ -388,10 +411,11 @@ net worth = everything spent on buildings, units and research plus the stock lef `MILITARY.cacheMax 0.7 + cachePerLevel 0.14`: 4-6k, 181, -4 to -5 %; `cacheMax 0.8 + cachePerLevel 0.2`: 2-3k, 87 to 164, -8 to -11 %; `MILITARY.raidLossFactor 0.8`: 4-6k, 142-158, -4 to -6 %; `script_crew carry 30, botnet 90`: 3k, 137-197, -7 to -12 %. Untouched: 10-11k, 188-198. None adopted: the untouched game is not dominant and bots scout better than most players will. -- **Loot is mostly wasted on arrival** (`m2-after-d30-s1`): loot is split evenly over Fiber, Hardware and Capital whatever the raider - needs, the raider's Hardware and Capital stores are usually full, and overflow at delivery is destroyed: over all deliveries of that run 77k Hardware, - 14k Capital and 2k Fiber vanished against 251k looted in total. Real value of a raid is mostly its Fiber. A rule that weights - the split by free storage would double the effective loot; that is a design change, not a number. +- **Loot was partly destroyed on arrival, and the incumbent bonus mostly** (fixed by B6, section 9; this bullet used to blame raid loot for all of it). Loot is split evenly over + Fiber, Hardware and Capital whatever the raider needs, the raider's Hardware and Capital stores are usually full, and overflow at delivery was destroyed. Split by where it + happened (new line "overflow by place" in the bot report; HEAD before B6, 30 days, seeds 1 / 2 / 3): raid returns lost 31k / 62k / 56k (17 to 22 % of the 187k / 275k / 268k + looted, mostly Hardware and Capital), and the **one-time incumbent Hardware bonus lost 64.7k / 64.0k / 82.2k of the 77.5k / 77.5k / 97.5k it granted (83 to 84 %)**: the earlier + "77k Hardware lost against 251k looted" was mostly that bonus. ### Takeover is expensive enough @@ -419,11 +443,9 @@ plus 4 substations), so the market has no natural counterparties and trade is mo other. Completed offers trade at 1.00 give/want (median). Not tuned: a thin market is an observation about this bot population, not a number to move. -**Server finding S2 (not fixed):** the escrow of an offer that expires or is cancelled after the POP's store filled up again is -refunded only up to the Rack hall cap (`trade.refund`, decision R1). The harness books it: 36 refunds per 30-day run (all three seeds) lose -12 to 15k Hardware and Capital in total (`arch-d30-s1`: 3.3k Hardware, 11.2k Capital in 36 events), invisibly to the player. -DESIGN.md used to say nothing is lost in trade (corrected to describe the cap). Fix options: credit the clipped part back as a transport that waits, or let escrow refunds -exceed the cap the way the existing "stock above a lowered cap is kept" rule does for stock. +**Server finding S2 (fixed by B6, section 9):** the escrow of an offer that expired or was cancelled after the POP's store filled up again was +refunded only up to the Rack hall cap (`trade.refund`, decision R1), invisibly to the player: 43 to 48 refunds per 30-day run lost 26 to 28k Hardware and Capital +(seeds 1 / 2 / 3: 27.8k in 48, 26.7k in 44, 26.1k in 43 events). Now escrow keeps its room in the hall and the same runs clip 0. ### Power binds early and then recedes @@ -452,7 +474,7 @@ the capital's units offline (transient, fixed by the next substation level). Not ## 5. The end game -### What the bots do +### What the bots do (before E6; the changes are in "E6" below) When the world is at day `ENDGAME.openDay / speed` every alliance with at least 3 members plans (a shared in-memory plan, what an alliance would agree in its chat): the site with the lowest static defence (a little weight on distance); ONE member with an Ops lab trains @@ -467,7 +489,7 @@ against the full static defence, so attacks cannot be added up); once the allian first attack that was strong enough; 3 of 3 landing attacks won), in the 3x world six sites were held by six alliances after 14 won attacks (sites change hands while the defence is still low). The static defence of a site at day 100 is 27k to 45k depending on the site (600 x 5.0 x 12 x a seeded +-25 %), i.e. an army of 700 to 1 150 Script crews before research, which the striker (the member with the best economy and an Ops lab) had within days. -- **Nothing is contested afterwards, and nothing can be.** The biggest army any single POP held at the end was 55 to 62k attack before research; +- **(Before E6, HEAD: fixed by the next subsection.) Nothing is contested afterwards, and nothing can be.** The biggest army any single POP held at the end was 55 to 62k attack before research; the defence of a built-up site was 200 to 240k at speed 1 (levels 89+), 370 to 440k at speed 3. Defence passes what one POP can send at node level ~25 (weakest site) to ~40. That is E1 (no garrisons) showing up: after the opening days the race is shipping and node build time, not war. The only interaction is the opening scramble (the 3x world saw 14 won attacks for 6 sites; the 1x worlds none after the @@ -483,16 +505,74 @@ against the full static defence, so attacks cannot be added up); once the allian `INVARIANTS OK` (the first speed-1 runs of this pass were flagged only because the bots kept commanding an ended world; the harness now stops and treats `world_ended` as expected). +### E6. Garrisons, a light static defence for held sites, a capture shield (the E1 finding) + +What changed (all in `data.js` / `rules.js`, reasoning in DECISIONS E6): members of the holding alliance can station units in a site (`reinforce` to its x,y), +the units defend on top of the static value at their owner's research and draw their owner's power, a lost attack kills (A/D)^1.5 of them, a won attack +wipes them and takes the site; the static defence of a HELD site is `ENDGAME.heldDefenceMult` = 2 x incumbent (was 12; unheld sites keep 12); +a site that changed hands is shielded for `ENDGAME.captureShieldHours` = 72 world hours (this was 24 in the first runs, see below). + +What the bots do now (`tools/bot/endgame.js`, `--no-contest` switches it off): the holders of a site train defenders (towards 1.1 x what the strongest +rival alliance could throw, shared by production, bots read it from the db: scouting is not simulated) and station every movable defender at the site; +the others, when the target has a garrison, train crews towards a share of 1.15 x static + 2.2 x garrison, and when a war game (`rules.resolveBattle`, wave by +wave over their members' real armies, nearest first) says the last wave takes the site, send their armies at their next sittings. A site without a garrison +is still taken by one striker with a single army that beats the static part (waves cannot wear a static number down). + +Commands: `node tools/bot.js --players 50 --speed S --days D --seed N [--no-contest] [--set ENDGAME.captureShieldHours=H]`. The "before" column is HEAD today +(run from a `git archive HEAD` copy: it does not contain the other changes that are in the working tree now, e.g. the loot cap and the escrow room). +Days after the sites opened (day 100.3 at 1x, 33.3 at 3x); "flips" = won attacks on a site somebody already held; "met a garrison" = attacks on a held site +that found units there. Every run finished `INVARIANTS OK` (the ledger counts garrisons). + +| world / seed | variant | winner: day (days after opening) | attacks on held sites | flips | met a garrison | units lost in landing battles (value) | +|---|---|---|---|---|---|---| +| 1x, 1 | before (HEAD) | 234.7 (134.4) | 0 | 0 | 0 | 1.05 M | +| 1x, 1 | **E6 adopted** (shield 72 h) | 202.8 (102.6) | 84 | 20 | 84 | 9.4 M | +| 1x, 1 | shield 24 h (first runs) | 202.8 (102.6) | 166 | 43 | 164 | 13.4 M | +| 1x, 2 | before (HEAD) | 200.2 (100.0) | 0 | 0 | 0 | 2.0 M | +| 1x, 2 | **E6 adopted** | 208.4 (108.1) | 194 | 33 | 186 | 13.5 M | +| 1x, 2 | shield 24 h | 220.7 (120.4) | 450 | 87 | 438 | 30.4 M | +| 3x, 1 | before (HEAD) | 131.1 (97.7) | 0 | 0 | 0 | 1.4 M | +| 3x, 1 | B7 only (`--no-contest`, held x12) | 68.7 (35.4) | 4 | 4 | 0 | 1.0 M | +| 3x, 1 | **E6 adopted** (B7 + garrisons, shield 72 h) | 65.1 (31.8) | 93 | 54 | 70 | 6.1 M | +| 3x, 1 | shield 24 h | 68.2 (34.9) | 188 | 142 | 108 | 12.7 M | +| 3x, 1 | no shield | 60.6 (27.3) | 271 | 246 | 77 | 12.6 M | +| 3x, 1 | shield 24 h, `heldDefenceMult` 3 | 68.2 (34.9) | 127 | 86 | 91 | 11.4 M | +| 3x, 2 | before (HEAD) | 109.9 (76.5) | 0 | 0 | 0 | 1.3 M | +| 3x, 2 | B7 only | 62.8 (29.4) | 4 | 4 | 0 | 1.0 M | +| 3x, 2 | **E6 adopted** | 69.8 (36.4) | 109 | 65 | 90 | 7.3 M | +| 3x, 2 | shield 24 h | 79.2 (45.8) | 266 | 174 | 193 | 14.5 M | +| 3x, 2 | no shield | 68.1 (34.7) | 241 | 231 | 52 | 8.5 M | +| 3x, 2 | shield 24 h, `heldDefenceMult` 3 | 80.9 (47.5) | 152 | 96 | 97 | 11.0 M | + +(The adopted rows were re-run once with the new default in `data.js` and reproduce the `--set ENDGAME.captureShieldHours=72` runs exactly: 3x seed 1, +winner 65.1, 54 flips.) + +Reading it: +- **Contests happen.** In the old world nobody attacked a held site after the opening (0 to 4 attacks, none against units). Now 84 to 194 attacks in the 100 days + after the opening at 1x and 93 to 109 in 32 to 36 days at 3x, 75 to 100 % of them against a garrison, 20 to 33 and 54 to 65 flips, 6 to 13 M of unit value dying in + landing battles (5 to 13 times before). That is a flip per site about every 25 to 35 days at 1x and about every 4 days at 3x (every 1.7 days with the 24 h shield). +- **The end game can still be won, and is not slower on average**: 1x, days after opening 102.6 / 108.1 (adopted) against 134.4 / 100.0 (before), mean 105 against 117; + 3x 31.8 / 36.4 against 35.4 / 29.4 with B7 only, mean 34 against 32. With two seeds per cell that is "no worse", not a measurement of a difference. +- **How much churn is right is the owner's call, and the numbers make it concrete.** With the 24 h shield 76 % (142 of 188) and 65 % (174 of 266) of the attacks on held + sites at 3x succeeded, a site flipped every ~1.7 real days and the winner took up to 46 days; with no shield 91 to 96 % succeeded (the new holder had no garrison yet). + With 72 h 24 % and 17 % of the attacks succeed at 1x (20 of 84, 33 of 194), 58 % and 60 % at 3x (54 of 93, 65 of 109), and the flips drop to 54 / 65 at 3x. A higher static defence (x3) did not help + (`heldDefenceMult` is bounded from above by what one POP can send, DECISIONS E6). Not measured: a shield at 1x beyond 72 h, 72 h at speed 10, other seeds than 1 and 2. +- **The static rule expires with world age** (DECISIONS E6): at world age 240 a held level-100 site's static part is ~51 000, at age 330 ~68 000, above the ~60 000 a + single POP can send. The runs end (the winner appears) before that at 1x; a world that is meant to run longer needs `heldDefenceMult` or the growth to be capped. +- **Not shown by these runs**: any human reaction. The holders do not react to `backbone_incoming` (they would garrison in time or recall), the attackers never feint, + nobody scouts with `scan` (the bots read the garrison from the db), and every bot of an alliance obeys the plan. All of that is less friction than people. + ## 6. Server findings | # | finding | status | |---|---|---| | S1 | **Cargo above the Rack hall cap was destroyed silently on bounced shipments.** A shipment that comes home (landing site changed hands, POP gone) rides back on a `link` return leg; `events/return.js` sent no notification for link legs, so the overflow was invisible to the player and to any audit. The conservation ledger found it as 1 000 Hardware + 2 718 Capital of drift in the first speed-10 end-game run (`node tools/bot.js --players 50 --days 14 --seed 1 --speed 10 --endgame-step-min 30`; with the fix the same command shows no drift, and it reproduces the bug if the `carrying` condition in `return.js` is taken out). | **fixed** (`return.js` notifies when a link leg carries cargo), `test/bot-server-fixes.test.js` fails without the fix | -| S2 | Trade escrow refunds are clipped at the Rack hall cap and the loss is not reported (section 4). | open, design decision | +| S2 | Trade escrow refunds were clipped at the Rack hall cap and the loss was not reported (section 4). | **fixed** by B6 (escrow keeps its room in the hall; a refund that still cannot fit, after a shot-down hall, is reported), `test/economy-leaks.test.js` | | S3 | `reports.id` is `INTEGER PRIMARY KEY` without `AUTOINCREMENT`; the 14-day cleanup can empty the table and SQLite then reuses low ids. A consumer that keeps "the last report id I saw" (the harness did, and silently missed every report after the first cleanup in a 170-day run) skips new reports. The API's own cursor (`GET /reports?after=` with `r.id < after`, newest first) is not hurt unless a client mixes old and new ids. Repro in five lines: insert three reports, `DELETE FROM reports`, insert one more: its id is 1 (the harness hit it in 170-day runs, where raids stop and every report expires). | open, low severity | -| S4 | Loot is split evenly over the three resources and destroyed on overflow (section 4). | open, design | +| S4 | Loot was split evenly over the three resources and destroyed on overflow; the incumbent bonus too (section 4). | **fixed** by B6 (loot limited to what home can bank, reported as `lootLeft`; the bonus is delivered above the cap), `test/economy-leaks.test.js` | | S5 | `ensureSites` is lazy (E2): the first touch of a landing site writes `backbone_open`; the harness reads sites with `E.siteStates` and never triggers it. No bug, noted so nobody expects the push in a bot run. | known | +| S6 | **Room is still not reserved everywhere.** (a) Several raids from one home used to each project the same free room and the loot of all of them was banked against it (the overflow destroyed on landing); `combat.homeRoom` now subtracts the cargo of return legs that are already on the road to that POP, so the later raid is limited (and reports `lootLeft`). `test/economy-leaks.test.js` (two raids from one home with room for one) fails without it. (b) Still open, reported but not prevented: stock that production, a trade delivery or a transport adds while loot or a bounced shipment is on the road. A **bounced backbone shipment** (the site changed hands) rides home on a return leg and finds the hall full if production refilled it; the overflow is destroyed, and `movement_returned` carries the exact `cargoLost` (the client now prints it: "LOST, the Rack hall was full: ..."). Nobody reserves room for the outbound or the return leg of a shipment: that would cap production for as long as a shipment is in flight. (c) **Trade accept** now refuses with `no_room_for_goods` when the acceptor's hall will not have room for the goods at arrival (projected with production and other cargo already on the road to that POP; a projection, not a guarantee: stock can still grow on the way and then the overflow is destroyed and reported as before). | (a) **fixed**, (b) **open, reported**, (c) **fixed as a refusal**; `test/trade-flow.test.js`, `test/economy-leaks.test.js` | ## 7. Bot bugs that moved the numbers (so nobody trusts an early number from this pass) @@ -507,14 +587,15 @@ against the full static defence, so attacks cannot be added up); once the allian ## 8. What is still unknown - Bots are not humans. They never forget to log in, never panic, never coordinate beyond a shared in-memory plan, never mis-click, and play - the same sittings every day. They do not use reinforcement, recall, the shared report folder, messages, sitters, or night play. They + the same sittings every day. They use reinforcement only to garrison landing sites (E6), and do not use recall, the shared report folder, messages, sitters, or night play. They never choose a different capital or sell their stock off before an attack. - No real players means no data on how many sittings a day people really play; the whole B1 argument rests on the 2-to-8 sittings-a-day band that the CLAUDE.md pitch implies. - Rural bonuses, wild slots and the Peering office size ladder were not examined. The offline/decommission power path never ran in a bot run. The alliance war/peace states were exercised (NAP, confederation, war appear in the runs) but never made to matter in a fight. -- The end game was run with a single plan per alliance that nobody contests after the first days (section 5); a determined rival with - several armies cannot beat a built-up site (single-POP attack ceiling), so there is no data on what an actual fight for a site would look like. +- The end game has a contest now (E6, section 5), played by bots that follow one shared plan per alliance, read their rivals' armies and the garrison from the + db, and do not react to `backbone_incoming`. How humans would garrison, recall, feint or sit on a site is unknown; `heldDefenceMult` 2 and the 72 h shield are first + guesses with two seeds per cell, and the static defence outgrows one POP's army around world age 280. - `--always-on` is an upper bound on attention, not a model of a person. @@ -524,3 +605,42 @@ against the full static defence, so attacks cannot be added up); once the allian After B4 the owner's first hour on the live world was still described as "a bit slow". B4's own measurement (variant "START.resources 1000", no discount) showed the mid game unchanged (head start 0 to 0.1 days) and a 60-minute first sitting going from 12.1 to 15.4 builds at 1 h, so `START.resources` is now 1000 per resource. Not re-measured in combination with B4 beyond a 50 x 30-day bot run that ended INVARIANTS OK. No human data. + +## 9. B6. Trade escrow keeps its room; loot is limited to what home can bank (S2 and S4) + +Rules (decision B6 in DECISIONS.md has the reasoning and the rejected options): +- **Trade (S2):** goods escrowed in open offers still occupy the Rack hall: that resource stops filling at hall size minus the escrow (`rules.storageCapOf`), so cancel / expiry / + void always fit and the escrow is no extra storage (R1 stays closed). Residual clip only after a shot-down hall; it sends `trade_refund_clipped`. +- **Loot (S4):** a win takes at most what the raiders' home Rack hall can bank when they are back (hall size minus the stock projected to then); a resource with no room is skipped and the + carry goes to the others; the rest stays with the victim and the report shows it as "Left behind". +- **Incumbent bonus:** the once-only 2 500 Hardware is delivered above the cap if the store is full. +No `data.js` number changed. + +**Before / after** (`node tools/bot.js --players 50 --days 30 --seed N --quiet --json out.json`, seeds 1 / 2 / 3; before = the tree at HEAD with the same reporting lines, after = this change; both +`INVARIANTS OK` in all six runs; every number from the report's "overflow by place", "trade refunds" and raid lines): + +| per 30-day run | before (s1 / s2 / s3) | after (s1 / s2 / s3) | +|---|---|---| +| raid loot destroyed on arrival (Fiber+Hardware+Capital) | 31.0k / 61.5k / 56.5k | 0.1k / 1.0k / 0.7k | +| incumbent bonus destroyed on arrival | 64.7k / 64.0k / 82.2k of 77.5k / 77.5k / 97.5k | 0 (all delivered: 57.5k / 60.0k / 87.5k) | +| trade refunds clipped (events) | 27.8k (48) / 26.7k (44) / 26.1k (43) | 0 (0) / 0 (0) / 0 (0) | +| transport deliveries over the cap | 0 / 0 / 0 | 0 / 0 / 1 event (474 Fiber) | +| loot per the reports (nominal, before = what the carry split gave, after = what was banked) | 187k / 275k / 268k in 170 / 214 / 193 raids | 144k / 207k / 175k in 190 / 247 / 189 raids | +| loot left behind for lack of room (new) | - | 63k / 80k / 79k | +| won raids with empty hands (new) | - | 1 / 4 / 0 | + +Side effects, mean of the three seeds: raider net worth 287.6k -> 288.3k, builder 357.7k -> 357.5k, builder median footprint 11 784 -> 11 824, Hardware lost to full stores 29 % -> 31 % of +what the rates would give (stores are as full as before, the loot just stops being destroyed). Offers completed per run 40 / 35 / 33 -> 42 / 28 / 39 (noise: the trajectories differ). + +How to read it: **what changed is where the loss happens, not what players earn.** Before, the part of a raid that did not fit was thrown away at the door; now it is not taken, so it stays in the +victim's stores (the 63 to 80k "left behind"), and the raider's net worth did not move. The loot that was banked per raid went down in these runs (about 920 -> 760 in seed 1, 1 000 -> 830 in seed 2, +1 100 -> 920 in seed 3, counting before as nominal minus overflow). I did not find the cause; the raid mix changed (raids 170 -> 190 in seed 1) so it may be the bots targeting differently, or +the projection being conservative, and it did not show up in net worth. Raiding is not stronger or weaker for it on this evidence. + +Also run: `--days 14 --speed 1 --seed 1` (the CLAUDE.md run), `--days 60 --seed 1`, and `--days 14 --speed 10 --endgame-step-min 30 --seed 1` (end game with shipments): all `INVARIANTS OK` +(the 60-day and speed-10 runs were not compared with a before; only the invariants were checked). + +Not verified / left: the projection ignores other deliveries that reach the home store in between (hence the 0.1 to 1.0k that is still destroyed and still reported through `cargoLost`); transport +deliveries (including trade goods) onto a full store still lose the overflow, reported; a human would see the shrunk Fiber/Hardware/Capital store while an offer is open (UI says so, text only, +nobody has looked at it on a phone); how the reserved room changes what offers players post is not measured beyond the offer counts above. + diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index f337ef8..dde562b 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -152,8 +152,8 @@ target's owner `incoming` (town + ETA) and no plain `town` hint, so the type and would have to be excluded from footprint rankings, the last-POP / capital / footprint-gate counts, `homeTownFor`, `/me`, spawn spacing and the Rack hall cap (shipped resources would be thrown away at 250), and a leader change would have to re-own it. The holder is the alliance (`holder_alliance_id`, FK `ON DELETE SET NULL`, the disband hook also clears it), `holder_operator_id` only records who took it. -Consequence, on purpose and to be revisited after the first world: **no units can stand at a site**, so there is no garrison and no -reinforcement. A site is defended by the static value `incumbentDefence x 12 x (1 + 0.03 x level)` only, i.e. exactly the "incumbent +Consequence, on purpose and to be revisited after the first world (**revisited in E6: garrisons exist now**; the rest of this paragraph is the +original reasoning): **no units can stand at a site**, so there is no garrison and no reinforcement. A site is defended by the static value `incumbentDefence x 12 x (1 + 0.03 x level)` only, i.e. exactly the "incumbent with a backbone multiplier" of DESIGN.md; holders defend by growing the node (higher level = harder to take), attackers can scan the exact number. Hooks into the military code are small: `combat.arriveSite` hands `backbone` tiles to `military/landing.js`, `arrivals.arriveTransport` hands shipments (`extra.siteId`) to `endgame.deliverShipment`, `sendMovement` calls `endgame.checkLandingTarget`. @@ -187,11 +187,45 @@ automatically as long as they carry one of those arguments. about 36 world days of building in total, level 100 alone 312 k each and 23 h). Pure guesses until a bot run (stage 7) says how much an alliance can ship; nothing here is balanced. +## E6 — Garrisons at landing sites, a light static defence for held sites, a capture shield (BALANCE.md section 5, E1 follow-up) +Problem (bot runs, BALANCE.md section 5): after the opening scramble nobody could contest a held site. Its static defence was 12 x incumbent x (1 + 0.03 x level), +200 to 440 k at node level 89+, and one attack is one movement from one POP, whose army tops out around 60 k attack; with no garrison there is nothing a wave can +wear down, so "attacks cannot be added up". Adding a garrison ON TOP of that static value would only have made held sites harder, not contestable. +Decided: +- **Static defence of a HELD site drops to `ENDGAME.heldDefenceMult` = 2** x incumbent defence (x the per-level bonus); an unheld site keeps `defenceMult` 12 (the + opening scramble is unchanged). The rule behind the number: static defence must stay below what one POP can send (about 60 k), otherwise the last wave of + a fight could never win and a built-up site would be out of reach again. At day 100 a held site is ~7 k at level 0, ~28 k at level 100; at day 170 level 100 it is ~37 k. +- **A garrison**: table `site_stationed(site_id, owner_town_id, unit, count)` (migration 005; `stationed` has a POP as host, a site is not a POP, E1). Members of the + holding alliance, and only them, `reinforce` a site with the existing movement type (target = the site's x,y); the check is made when sending and again at arrival + (a site that changed hands, or an alliance the sender left, turns the units back with a `movement_failed` report). Units are in exactly one place at a time; a table + of its own makes the conservation ledger count them (`tools/bot/ledger.js`). +- **Power**: garrison units draw their OWNER's POP (`state.unitDraw`, `power.drawingUnits`, `power.decommission`), because a site has no power budget; sending them + changes no one's total draw, units on the road draw nothing (as everywhere), an owner POP without power takes its group offline (it does not defend, a won attack still + wipes it) and decommission takes units out of the garrison last. Alternative rejected: free upkeep at the site (a bottomless defence) or an upkeep charged to the + alliance (no such budget exists). +- **Combat** is the POP law: `resolveBattle` with `staticDefence` AND defenders: D = static + the online groups' defence (their owner's research), no firewall, no + base defence; a lost attack kills (A/D)^1.5 of each group's units, a won attack kills them all and the attacker's alliance holds the site (level, stockpile and a + running build stay, as before). The static part loses nothing. No new combat rule, so waves resolve in arrival order, `(due_at, id)`, like every battle. + Rejected: a "breach" counter on the static part that heals over time (one more number and one more stored timestamp for the same effect). +- **Leaving**: `POST /backbone/:id/withdraw` (owner only, any time, works after the site changed hands) and automatic returns (a return movement each) when the owner + leaves or is kicked (`allianceLeave`, `allianceKick`), the alliance disbands (`onAllianceDissolved`, before the holder is cleared) or the owner's POP is taken over + (`combat.transferTown`, to the old owner's other POP). Rejected: "left in the site, withdrawable later" (the units of a non-member would defend a rival). +- **Capture shield**: `ENDGAME.captureShieldHours` = 72 world hours (/ speed) after a site changes hands, no attack on it (refused when sent, bounced at arrival). + A freshly taken held site has no garrison yet: with no shield bot runs flipped sites ~240 times in 27 to 35 days at 3x, with 24 h still ~140 to 175 times, with 72 h + 54 to 65 times and no slower a winner (BALANCE.md section 5; all of that is bots). Not a rule for unheld sites. +- **The static rule expires**: `incumbentDefence` grows with world age, so the held static part of a level-100 site passes one POP's ceiling (~60 k) around world age 280 + (real day ~93 at 3x). From then on only a garrison that waves have already worn down can be finished by one army; `heldDefenceMult` has to come down or the + growth stop at some age if a world is meant to run that long. +- **Not decided here, and why**: a captured site keeps its node level (the existing rule, "take it over"; the task also named "down a level" as an option); if the first + world shows the race ends by one late strike on a finished node, `captureLevelLoss` is the lever. +- **Notifications**: `backbone_incoming` (holders, no type, no sender), `garrison_arrived`, `garrison_released`; push gets a `town` hint for the owner POP. +Gaps: bots do not react to `backbone_incoming`, there is no sitter, `tools/admin.js inspect` does not list garrisons, a human alliance can still leave a site with zero garrison. + ## T1 — Trade: escrow, one link per side, reach by exchange level - Offers are escrowed in `trade_offers` and hold one transport link of the poster's POP while open (`movements.activeLinks` counts open offers), so accepting never fails for lack of a link on the poster's side and cannot exceed the exchange level. -- Each side of an offer must fit ONE transport (<= 1000, was 500 until B2); larger deals are several offers. The ratio band is count-based 1:2. -- Escrow returned WITHOUT the Rack hall cap at first (conservation beats the cap); review round 1 (R1) reversed that: refunds are capped like `cancelBuild` (stock already above the cap stays, the clipped part is lost silently, BALANCE.md S2). Deliveries keep the cap rule (`cargoLost`). +- Each side of an offer must fit ONE transport (`rules.transportCapacity(speed)`: 1000 x world speed, B7; was 500 until B2); larger deals are several offers. The ratio band is count-based 1:2. +- Escrow returned WITHOUT the Rack hall cap at first (conservation beats the cap); review round 1 (R1) reversed that: refunds are capped like `cancelBuild` (stock already above the cap stays, the clipped part is lost silently, BALANCE.md S2; superseded by B6: escrow keeps its room in the hall, so the refund fits). Deliveries keep the cap rule (`cargoLost`). - Reach: `10 tiles x exchange level` of the taker's POP, and the offer's own `maxDistance`; the poster's level only matters for the number of offers they can hold open. - A POP changing hands voids its open offers (`combat.transferTown` calls `trade.onTownTransferred`); the escrow stays in the POP. @@ -246,7 +280,7 @@ The end game is shipping-limited, not production-limited: 21.6 M units (7.2 M of won in each seed, 55 to 78 days after the sites opened (node build time alone is 36 days). Raising `ENDGAME.costGrowth` to 1.035 or the capacity to 2000 were measured and not taken (2000 leaves only the 36-day build floor as a constraint). Not solved: a 3x world takes about as long after the sites open as a 1x world, because shipping is per sitting, not per hour; `capacityPerLink x world speed` would fix it but the -client reads the constant. See BALANCE.md section 5. +client reads the constant. See BALANCE.md section 5. (Done in B7.) ## B3 — A bounced shipment reports its overflow `events/return.js` stayed silent for empty-carrier return legs AND for shipments that came home with cargo; cargo above the Rack hall cap is @@ -264,3 +298,73 @@ different slope (default mix field level +2 % on day 30, +0.1 % on day 60; 2 a d were measured and dropped: the first does nothing for the first hour and shifts the mid game, the second multiplies the head start (up to ~11 days) for no first-hour gain. Not done, and probably the bigger lever for an engaged player: a higher starting stock (1000 of each moved the mid game by 0 days and gave a 60-minute first sitting 15.4 builds at 1 h instead of 12.1). Left for the owner to call. + +## O1 — Admin `end-world` runs the real `worldEnd` handler (ops) +The first CLI version only set `status = 'ended'`: no ranking snapshot, `/results` stayed unavailable, pending events and trade escrow were left +behind. It now enqueues a `worldEnd` event (`reason: 'admin'`, due now) and processes it through the real `Scheduler` and the real handler, after +processing that world's already-due events in order; every handler call is guarded by a status re-check inside the transaction, so a running +server that handles the same event at the same moment cannot double-apply it. One implementation of "a world ends" instead of two. Cost: the CLI +is a separate process, so the `world_ended` notification rows it writes are not pushed over a running server's sockets. Not repairable: a world +the old command ended has no snapshot. + +## O2 — `deploy/update.sh` rolls back one step with `git reset --hard`, and does not touch migrations +The checkout is on `main` and the tree is required to be clean, so `git reset --hard ` loses nothing and keeps the branch (a +`git checkout ` would leave a detached HEAD that the next update refuses). The snapshot is taken (and verified) before any change; no +snapshot, no update. Migrations are forward-only (`DEPLOY.md` section 8): the script announces new ones before it starts and names the +snapshot to restore after a rollback, instead of pretending it can undo them. Origins with credentials in the URL are refused (the +checkout must use plain HTTPS; nothing secret in `.git/config`). + +## B6 — Trade escrow keeps its room in the Rack hall; loot is limited to what home can bank (BALANCE.md S2 and S4) +Two economy leaks the bot ledger priced (30 days, 50 players, seeds 1 to 3): 43 to 48 trade refunds a run clipped at the Rack hall cap, 26 to 28k lost +silently (S2); 17 to 22 % of the raid loot destroyed on arrival because the raiders' Hardware/Capital stores were full (S4), plus 83 to 84 % of the one-time +incumbent Hardware bonus (64 to 82k a run; BALANCE.md had blamed raid loot for this). +- **S2, chosen: escrow keeps its room.** `rules.storageCapOf(town, res) = hall size - town.escrow[res]` (the escrow is the sum of the POP's open offers, loaded by + `state.townFromRow`). While an offer is open that resource stops filling at hall size minus the escrow, so a refund always fits and the escrow is never extra + storage: R1's exploit (refill to the cap while the escrow is out, then cancel for cap + escrow) cannot happen, and nothing is lost. The one invariant to keep: + **every way out of `open` must settle the POP first**, because the cap changes there (`closeOffer` settles and credits BEFORE the status change; `tradeAccept` + settles the poster; creation settles before the insert). The same cap is used by deliveries (`addCargo`) and `cancelBuild`. The only residual clip is a Rack hall + shot down below stock + escrow; it sends `trade_refund_clipped` and the ledger books that notification as a sink (the SQL-statement tap is gone). + Rejected: a "held" amount the owner claims later (new state, command, route, expiry and a bounded hiding place, for the same outcome), and limiting the escrow + so it always fits (impossible: stock grows while the offer is open). Cost to the player: a POP with 700 Fiber escrowed has a Fiber store 700 smaller for up to 48 h; + the trade screen says so. +- **S4, chosen: take only what home can bank.** `combat.homeRoom` = hall room minus the stock projected to the moment the raiders are back (pure projection, no + write); `rules.lootSplit(carry, avail, room)` skips a resource with no room and shares the carry among the others; the rest stays with the victim and the report + has `lootLeft`. Not exact (other deliveries can still fill the store in between: 0.7k of 175k looted remains destroyed and reported via `cargoLost`). No home POP: + nothing is taken (before, it was deducted from the victim and vanished). +- **Incumbent bonus, chosen: delivered above the cap.** It can be earned once per site, so a full store must not eat it; `extra.bonus` on the return leg is credited + uncapped (kept, it only stops growing: the same rule as a lowered Rack hall). Bounded by 2 500 Hardware per site per operator; a reward gate (deferring the take) + was rejected because bots would re-attack for nothing. +Not changed: transport deliveries onto a full store still lose the overflow (reported; 0 to 1 event per 30-day run now). + +## B7 — Transport capacity scales with world speed (`rules.transportCapacity`) +Follow-up of B2: shipping is per sitting (one trip per link), not per hour, so the end game did not shorten with world speed. `D.TRANSPORT.capacityPerLink` stays the number +at speed 1 and `rules.transportCapacity(speed)` = `capacityPerLink x speed` is the ONLY reader of it: `transportPlan` (by `town.speed`), `tradeTermsCheck(terms, speed)` +(each side of an offer fits one transport), the POP view's `transport.capacityPerLink` (which the send dialog and the site sheet show), `client trade.js`, the bots. A test +(`test/transport-speed.test.js`) fails when a source file outside rules.js/data.js mentions the constant. Rejected: a flag in data.js to turn the scaling off (a bot run +with `--set TRANSPORT.capacityPerLink=...` reproduces any old value at a given speed). Numbers: BALANCE.md section 5. + +## E2E: how flights are made to land, and what the nb detector can and cannot see +- **Moving flights up instead of waiting.** `rules.latencyMs` has a 10 minute floor in real time, so a speed-1 raid, a trade leg or a site shipment cannot finish inside a test. The e2e + (`e2e/lib.js` `hurryMovement` / `hurryEvents`) writes the new due time into the movement row and its pending event and calls `scheduler.arm()`; the handlers run unchanged. Chosen over a fake + clock (the page uses the real browser clock and the server's `serverTime` offset) and over a speed-4000 world for everything (the flight must be on screen first: checks assert the countdown + before the move-up). Rejected: a test-only latency override in server code. +- **Norwegian check = detector + snapshot.** A raw key is any visible text matching `.`; an English leftover is visible text equal to the English text of a key whose nb text + differs (placeholders become wildcards). Both tables are snapshotted before the test touches anything, and the detector is calibrated on every run (it must find >= 8 English strings on the English POP + screen, and a planted key / a deleted nb string). It cannot see an nb string that was copy-pasted from English, so a separate check fails on any multi-word nb string identical to its English text. + Live switching is checked for visible text only; stale aria-labels after a live switch are reported in the run log, not failed (NEXT.md gaps). +- **`{type:'message'}` push now acts.** `messages.js` refetches the unread count (a poll that arrives while one is in flight asks once more) and the visible inbox / alliance feed / open thread. Before, the + hint was received and dropped. + +## R2 — Review round 2 fixes: update.sh order, offsite scp, room reservation, garrisons in the POP view +- **update.sh stops the service before it touches the tree** (it used to merge and `npm ci` under a running process that lazily `require()`s modules). The optional `--test` runs + on a `git archive` copy of the new rev in a temp dir, as the service user (`runuser`), with `npm ci --ignore-scripts`; never as root, never in `/opt/upstream`. The snapshot is + taken after the stop (final state of the database), so a failed snapshot costs a short outage and then the service is started again. Rejected: running tests as root in the live + tree (fetched code as root, and the mixed-code window); a second snapshot before the stop (two snapshots, still not the final state). +- **Rollback across migration 005** (site_stationed) is documented as unclean once anybody has garrisoned a site: old code does not know the table. No downgrade script (migrations are one-way, B-series rule). +- **scp removed from upstream-offsite**: scp cannot refuse to overwrite, and the docs promised never to. rsync with `--ignore-existing` is the only method; `OFFSITE_METHOD=scp` is rejected (exit 2). +- **Room for loot** is reserved only against return legs already on the road to the home POP (`combat.homeRoom`), not against production or deliveries that land meanwhile; bounced + shipments are reported with exact `cargoLost`, not prevented. Rejected for now: reserving room through the escrow mechanism for every shipment (caps production for as long as it is + out; a real economy change that wants a bot comparison first). BALANCE.md S6. +- **Trade accept refuses with `no_room_for_goods`** when the projected hall of the acceptor cannot take the goods; it does not clip or split the trade. The projection ignores stock that appears on the way. +- **`units.garrisoned`** in the POP view: units standing in landing sites draw the owner POP's power, so the owner's POP view lists them (site id and coordinates, units). + diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md index 6320cfa..8c2a618 100644 --- a/docs/DEPLOY.md +++ b/docs/DEPLOY.md @@ -15,12 +15,14 @@ layer. The differences are the Node version (`node:sqlite` needs 22.13+), a stat **What was and was not run while writing this** (so you know what to check on the real box): -* **Run:** `systemd-analyze verify` on the three unit files (syntax and directives only), the CLI `tools/admin.js` +* **Run:** `systemd-analyze verify` on the unit files (syntax and directives only; the two off-site units: only the expected "not executable" warning for a script path that does not exist on the dev machine), the CLI `tools/admin.js` and its tests on a dev machine (Node 24.21), a backup, verify and prune cycle, `sh -n` on `deploy/upstream-admin`. Re-checked on 2026-10-11 with the code as it is now (Node 24.21, scratch directory, no systemd): first boot with `DB_PATH`/`PORT`/`HOST` (migrations 001-004 applied, `created world 1`), `/healthz`, `/` headers, signup + build over the API, `admin.js` status / worlds / users / operators / inspect-town / events / replay-events / backup / verify-backup / ban / unban / grant / end-world (refusal without `--yes`), SIGTERM and restart (state, queue and password kept, no migrations re-applied; tokens revoked by `ban` stay revoked), SIGKILL then restart after a build fell due (`caught up 1 overdue event(s)`, the build level was applied), and a restore by copying a snapshot to a fresh `DB_PATH` and starting on it (section 7: it logged `caught up 1 overdue event(s)`). +* **Run, ops scripts (dev machine, stubs, no systemd):** `deploy/update.sh` and `deploy/upstream-offsite` and `admin.js end-world` through + `test/deploy-update.test.js`, `test/deploy-offsite.test.js`, `test/admin-endworld.test.js`; sections 7 and 8 say exactly what each covers. * **Taken from NETWALL's docs, not re-run for UPSTREAM:** everything about nginx Proxy Manager (labels, header behaviour, "Client addresses"). NETWALL's guide records what was observed against NPM v2.16.0. * **Never run:** a Proxmox LXC, a started unit under systemd, the timer firing on its own, a Node install from the @@ -113,6 +115,8 @@ mkdir -p /opt/upstream # from your workstation: # rsync -a --delete --exclude node_modules --exclude .git --exclude data --exclude e2e ./ root@:/opt/upstream/ # (needs server/, public/, tools/, deploy/, docs/, package.json, package-lock.json; `test/` is optional) +# or, the way the live box is run, a git checkout that deploy/update.sh updates later (section 8): +# git clone https://git.vanvikinternet.no/jvanvik/Upstream.git /opt/upstream (plain HTTPS URL, no token in it) cd /opt/upstream npm ci --omit=dev # only "ws"; follows the lockfile exactly chown -R root:root /opt/upstream @@ -131,6 +135,7 @@ install -m 0644 /opt/upstream/deploy/upstream.service /opt/upstream/deploy/upstr systemctl daemon-reload systemctl enable --now upstream upstream-backup.timer systemctl status upstream +# off-box copy of the snapshots is optional and not installed here: section 7 journalctl -u upstream -f ``` @@ -153,7 +158,8 @@ The first start prints `applied migrations: 001_init.sql, ...`, `created world 1 without it the database cannot be opened. * Shutdown: SIGTERM stops the scheduler timer, closes the listener and the database and exits 0 in about a second. Even a SIGKILL or power cut is survivable (WAL replay on the next open, then overdue events are caught up). -* `deploy/upstream-backup.service` (oneshot) and `.timer`: see section 7. +* `deploy/upstream-backup.service` (oneshot) and `.timer`: see section 7. `deploy/upstream-offsite.service` and `.timer` (optional off-box copy) and + `deploy/update.sh` (section 8) are not installed by the steps above. ## 4. Configuration @@ -237,7 +243,7 @@ upstream-admin help upstream-admin status # file, size, migrations, overdue events upstream-admin worlds upstream-admin create-world --name "Summer" --speed 2 --radius 60 --seed 1234 --end-in 90d -upstream-admin end-world 1 --yes # flag flip only, see below +upstream-admin end-world 1 --yes # same as the natural end: final ranking, escrow back, events cancelled upstream-admin users [--banned] # no hashes or tokens are ever printed upstream-admin operators [--world 1] upstream-admin ban mallory # sets banned, revokes all tokens: old tokens give 401, login 403 @@ -255,7 +261,8 @@ upstream-admin reset-world 1 --yes-destroy --backup /var/lib/upstream/backups -- upstream-admin migrate # apply pending migrations without starting the server ``` -All commands take `--json` (machine output) and `--db FILE` (otherwise `$DB_PATH`, otherwise `./data/game.db`). +All commands take `--json` (machine output) and `--db FILE` (otherwise `$DB_PATH`, otherwise `./data/game.db`). Piping into `head` is fine: a closed +pipe (EPIPE) stops the output quietly, no stack trace, and the exit code is kept. Exit codes: `0` ok, `1` failed, `2` usage error **or a destructive command missing its flag**, `3` not found. Safety rules the CLI follows: @@ -263,9 +270,16 @@ Safety rules the CLI follows: * Destructive or test-only commands refuse without a flag: `end-world` and `grant` need `--yes`; `reset-world` needs `--yes-destroy` (without it, it prints what it would delete and exits 2). `ban`, `unban`, `revoke-tokens` are reversible and need none. -* `end-world` just sets the world's status to `ended` (and `end_at` to now): signup and join stop and every game command answers - `world_ended`, but it writes no ranking snapshot (`GET /worlds/:id/results` stays `available: false`), cancels no pending event and - closes no trade offer. The natural end (a backbone winner, then the `worldEnd` event two world days later) does all of that. +* `end-world --yes` ends a world exactly like the natural end: it runs the real `worldEnd` event handler (`server/events/worldEnd.js`, + payload `{"reason":"admin"}`). So the final ranking snapshot is stored (`GET /worlds/:id/results` becomes `available: true`, `winner` + null unless the backbone race had a winner already), open trade offers are closed and their escrow goes back to the POPs, **every + other pending event of that world is cancelled** (builds in progress, training, movements on the road simply stop: the world is + frozen), status becomes `ended` with `end_at` = now, and every operator gets a `world_ended` notification. Events of that world that + were already due are processed first, in order, like the server's catch-up. Without `--yes` it refuses (exit 2) and says how many + pending events and open offers it would cancel and close. A world that is already ended is left alone (exit 0). Other worlds are untouched. + It works on a running or a stopped server; the CLI is a separate process, so a running server pushes nothing over WebSocket for the + notification rows it wrote: open clients learn from their next request (`world_ended` error) or the next `/me`. A world that an + older version of this command "ended" has no snapshot; the command says so and cannot repair it (reset the world or leave it). * `reset-world` deletes the world's game rows (everything with a `world_id`, plus tables pointing at them: towns, buildings, events, operators, alliances, messages, ... discovered from the schema, so tables added by later stages are covered) and **keeps accounts and tokens**; players must join the world again. It resets `start_at`, clears @@ -307,8 +321,10 @@ Change the schedule or retention with `systemctl edit upstream-backup.timer` / ` ### Off-box copy -Snapshots on the same disk die with the container. Pull them from another machine (NAS, workstation, the Proxmox host), -for example from cron or a timer there: +Snapshots on the same disk die with the container. Two ways to get them off the box; use one. Both only ever copy files that the backup +unit already verified, and neither deletes anything on the far side (retention over there is yours). + +**A. Pull from another machine** (NAS, workstation, the Proxmox host), for example from cron or a timer there: ```sh rsync -a --ignore-existing root@:/var/lib/upstream/backups/ /srv/backups/upstream/ @@ -319,6 +335,52 @@ the LXC stay on the backup host until you decide otherwise). Better than a root `authorized_keys` to `command="rrsync -ro /var/lib/upstream/backups",restrict ...` (`rrsync` comes with the `rsync` package; not run here). The files are owner-only (`upstream`), so the reading user needs root or a group ACL. +**B. Push from the box: `upstream-offsite.service` + `.timer`** (`deploy/`). Disabled until you configure it; nothing here is installed by +section 3. The script `deploy/upstream-offsite` picks the newest snapshot (by modification time), runs `verify-backup` on it (a snapshot that +does not verify is never copied), copies it with `rsync` to a directory (`scp` is not supported: it cannot refuse to overwrite, `OFFSITE_METHOD=scp` is rejected with exit 2), **never overwrites** a file of the same +name there, and re-reads the far copy and compares checksums. The timer fires daily at 05:00 (+ up to 10 min), after the backup timer (04:15). +It runs as the `upstream` user and fails visibly (`journalctl -u upstream-offsite`). + +Set it up (on the far side first, then the box): + +```sh +# far side (backup host): an account that can only write into one directory, no shell, append-only by convention +useradd --system --create-home --shell /usr/sbin/nologin upstream-backup # or a NAS user +install -d -o upstream-backup -m 0700 /srv/backups/upstream +# ~upstream-backup/.ssh/authorized_keys, one line (the key generated below): +# restrict,command="rrsync /srv/backups/upstream" ssh-ed25519 AAAA... upstream-offsite + +# the box (as root): a key only for this, owned by the service user (ssh refuses keys readable by others) +install -d -m 0750 -o root -g upstream /etc/upstream +ssh-keygen -t ed25519 -N '' -C upstream-offsite -f /etc/upstream/offsite_key +chown upstream:upstream /etc/upstream/offsite_key /etc/upstream/offsite_key.pub; chmod 0600 /etc/upstream/offsite_key +# the far side's host key, checked by eye: compare with `ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub` over there +ssh-keyscan -t ed25519 backup-host.example > /etc/upstream/offsite_known_hosts +ssh-keygen -lf /etc/upstream/offsite_known_hosts + +cat >> /etc/upstream/upstream.env <<'EOT' +OFFSITE_DEST=upstream-backup@backup-host.example:/ +OFFSITE_SSH_KEY=/etc/upstream/offsite_key +EOT +# with rrsync the destination path is relative to its root, hence ":/" (or ":" ). A plain directory also works: +# OFFSITE_DEST=/mnt/nas/upstream (a mounted share; then no key or known_hosts is needed) + +install -m 0644 /opt/upstream/deploy/upstream-offsite.service /opt/upstream/deploy/upstream-offsite.timer /etc/systemd/system/ +systemctl daemon-reload +systemctl start upstream-offsite # one run now: journalctl -u upstream-offsite -n 20 +systemctl enable --now upstream-offsite.timer +``` + +Settings (all in `/etc/upstream/upstream.env`): `OFFSITE_DEST` (required; without it every run is skipped quietly by the unit's +`ExecCondition`, so installing the timer early is harmless), `OFFSITE_METHOD` (only `rsync`; a far side without rsync needs `rrsync`/a different tool, scp was removed because it would overwrite), `OFFSITE_SSH_KEY`, `OFFSITE_KNOWN_HOSTS` (default `/etc/upstream/offsite_known_hosts`), +`OFFSITE_SSH_OPTS` (for example `-p 2222`). Host keys are always checked and ssh never prompts (`BatchMode=yes`). To copy right after each +backup instead of on its own timer: `systemctl edit upstream-backup` and add `[Unit]` `OnSuccess=upstream-offsite.service`. + +The key on the box can write to the far directory; make that directory the only thing it can reach (the `restrict,command="rrsync ..."` +line) and prune old files over there with a job that lives there, so a compromised game box cannot delete the history. +**Test it once for real**: check that the file arrived and that `upstream-admin verify-backup` accepts the far copy (a restore from it is section 7). `upstream-offsite` was exercised with a local directory as the destination (rsync, checksum +compare, no-overwrite, refusing an unverified snapshot); the ssh transport, `rrsync` and the units under systemd were **not** run. + ### Restore The restore is a file copy, and the time model makes it clean: the restored world simply fast-forwards. Every event that @@ -343,12 +405,77 @@ still fits, the server does not check for that. ## 8. Upgrading +`/opt/upstream` is a root-owned git checkout of `https://git.vanvikinternet.no/jvanvik/Upstream.git` (plain HTTPS, no credentials in the URL +or in `.git/config`; the script refuses an `http(s)://` origin URL that carries a user or token). Updates go through `deploy/update.sh`: + ```sh -upstream-admin backup /var/lib/upstream/backups --keep 14 # 1. snapshot first -rsync -a --delete --exclude node_modules --exclude .git --exclude data ./ root@:/opt/upstream/ # 2. new code (from your workstation) -cd /opt/upstream && npm ci --omit=dev && chown -R root:root /opt/upstream # 3. dependencies, ownership -systemctl restart upstream # 4. migrations apply at boot -journalctl -u upstream -n 30 # 5. "applied migrations: ..." then the listen banner +sudo sh /opt/upstream/deploy/update.sh --dry-run # fetch, list the commits and new migrations, change nothing +sudo sh /opt/upstream/deploy/update.sh # the real thing +sudo sh /opt/upstream/deploy/update.sh --test # also run `npm test` on the new code before the restart +``` + +In order, stopping at the first failure (once the service is stopped, the script always starts it again): + +0. **Tools**: `git`, `curl`, `npm`, `systemctl` and the admin wrapper must be on the PATH (`runuser`, `tar` and `mktemp` too with `--test`). + A missing one is exit 2 before anything is touched (without `curl` the health check could never pass and a good release would be rolled back). +1. **Refuses** on a dirty tree (tracked changes or untracked files that are not git-ignored; `node_modules/` and `data/` are ignored), on a + checkout that is not on `main` (detached HEAD included), on an `http(s)://` origin whose authority carries `user:password@` or `token@` + (an `ssh://git@host/...` or `git@host:path` remote is fine, so is an `@` later in the path), and while another update runs (lock directory + `/run/upstream-update.lock`). +2. `git fetch origin main`, no prompt. Not a fast-forward of the checkout (history rewritten, local commits): refuses, touches nothing. + Nothing new: "already up to date", exit 0, **no stop, no backup and no restart**. +3. Only with `--test`: `git archive` of the **new** rev into a temp directory, `npm ci --omit=dev --ignore-scripts` and `npm test` there **as the + service user** (`runuser -u upstream`, `HOME` and the npm cache inside the temp directory; never as root, never in `/opt/upstream`). The live + service keeps serving meanwhile. Red: exit 1, nothing was stopped or changed. (Fetched test code can still read what the service user can read, + for example the database; `--test` is for your own commits.) +4. `systemctl stop upstream`. **Why before the merge:** the running process `require()`s server modules lazily, so a process that keeps serving + while the tree changes under it can load new files into old code. From here the tree and the process never disagree; the downtime is steps 5-8. +5. **Verified snapshot** of the stopped (final) database: `upstream-admin backup /var/lib/upstream/backups --keep 14`, then `verify-backup` on the + file it wrote. No verified snapshot, no update: the service is started again, exit 2, nothing changed. The snapshot path is printed at the end. +6. `git merge --ff-only`. +7. `npm ci --omit=dev --ignore-scripts` **only if** `package.json` / `package-lock.json` changed (or `node_modules` is missing). No package install + script runs as root (`ws` needs none; if a future dependency needs one, run it by hand). +8. `systemctl start upstream`, then wait for `http://127.0.0.1:/healthz` (PORT from `/etc/upstream/upstream.env`, else 8080) for up to + 30 s (`HEALTH_TIMEOUT` or `--timeout N`). +9. **Rollback** on any failure from step 6 on: `systemctl stop` (a crash-looping new process must not run against the old tree), `git reset --hard + ` (the tree was clean, so nothing is lost; the branch stays on `main`), `npm ci` again if the lock file had changed, `systemctl start`, + wait for `/healthz` again. +10. Prints `old -> new` revs and the commits that went out. + +Exit codes: `0` updated or already current, `1` failed and the old version answers again (or `--test` was red), `2` refused or usage error +(nothing changed), `3` failed and the old version does **not** answer either (the output names the snapshot; `journalctl -u upstream -n 50`). + +Things the script cannot undo: **migrations**. A migration that ran at the new version's first start stays applied when the code is rolled +back. When the update contains new files in `server/migrations/` the script says so up front (`NEW MIGRATIONS ...`) and, after a rollback, prints +the snapshot to restore if the old code misbehaves on the newer schema (section 7: stop, restore, start; players lose what they did since the +snapshot). **Migration `005_site_garrison.sql`** is called out specially: it adds `site_stationed` (units garrisoned in backbone landing sites). +The previous code knows nothing of that table: it neither lists those units, nor charges their power, nor lets them go home. A code-only rollback +is therefore clean only while nobody has garrisoned a site since the new code started; otherwise restore the snapshot. A rollback target is always +the previous revision only, one step. An interrupt (Ctrl-C, SIGTERM) after the stop starts the service again (before the merge, on the untouched old +tree) or rolls back like any other failure (after it); SIGKILL or a power cut mid-update cannot be caught: then `git log -1`, `git status` and +`systemctl status upstream` tell where it stopped (if the service is down: `systemctl start upstream`; if the tree is already new but the service +ran the old code, `systemctl restart upstream`). The stop/start drops open WebSockets; clients reconnect on their own. + +Settings: `UPSTREAM_DIR`, `UPSTREAM_UNIT`, `UPSTREAM_ENV_FILE`, `UPSTREAM_ADMIN`, `BACKUP_DIR`, `BACKUP_KEEP`, `UPSTREAM_REMOTE`, +`UPSTREAM_SERVICE_USER` (the user `--test` runs as, default `upstream`), `UPSTREAM_BRANCH`, `HEALTH_URL`, `HEALTH_TIMEOUT`, `LOCK_DIR` (`sh update.sh --help` lists them). It needs `git`, `curl`, `npm`, `systemctl` and +`upstream-admin` (section 3) on the PATH of root (checked up front). + +**What was run:** `test/deploy-update.test.js` drives the real script with `sh` against a scratch bare origin and checkout and stubs for +`systemctl`, `curl`, `npm`, `upstream-admin` and `sleep`: up to date, update order (stop, snapshot, merge, start: the tree is old at the stop and new at the start), `npm ci --ignore-scripts` only when the lock +changed, `--test` (isolated copy, via a stub `runuser`), missing tools, dirty tree, credentials in the URL (and the ssh / `@`-in-path URLs that are allowed), detached HEAD, non-fast-forward, concurrent run, `--dry-run`, failing or unverifiable +backup, unhealthy new version (rollback, migrations warning, dependency restore), red tests, a rollback that does not recover (exit 3), `PORT` from the +env file. `sh -n`, `bash --posix -n` and `zsh -n` pass; `shellcheck` and `dash` were not available on the dev machine. **Not run:** the script on +the real box, against real systemd, a real `npm ci` / `npm test`, or a real `/healthz`. + +Updating **without git** (rsync from a workstation, the way section 3 first installed it) still works; do the same by hand: + +```sh +systemctl stop upstream # 1. stop FIRST: the old process lazily loads modules from the tree +upstream-admin backup /var/lib/upstream/backups --keep 14 # 2. snapshot of the stopped database +rsync -a --delete --exclude node_modules --exclude .git --exclude data ./ root@:/opt/upstream/ # 3. new code (from your workstation) +cd /opt/upstream && npm ci --omit=dev --ignore-scripts && chown -R root:root /opt/upstream # 4. dependencies, ownership +systemctl start upstream # 5. migrations apply at boot +journalctl -u upstream -n 30 # 6. "applied migrations: ..." then the listen banner curl -i http://127.0.0.1:8080/healthz ``` diff --git a/docs/DESIGN.md b/docs/DESIGN.md index ad381cb..eceab71 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -114,7 +114,8 @@ Movement types: scan, raid, attack, reinforce, settle, takeover, transport (reso 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. +Returning units carry loot and come back at the same speed. The one-time Hardware bonus of an incumbent site is delivered in full even +onto a full store (stock above the hall size is kept, it only stops growing): a reward that cannot be earned twice never vanishes at the door. Units cannot be re-routed while out. ## Combat @@ -126,8 +127,12 @@ Resolved at arrival, in the event queue, in order. Deterministic given the input 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). +- Loot: winner takes `min(carry, available)` from Fiber/Hardware/Capital evenly, never from Power, **and never more than the + raiders' home Rack hall can bank when they are back** (room = hall size minus the stock projected to that moment; a resource with + no room is skipped and its share goes to the others). What is not taken stays with the victim and the report lists it as "Left + behind" (`lootLeft`). Room already promised to other return legs still on the road to that POP (earlier raids, bounced shipments) is + subtracted first, so several raids from one home cannot all count on the same free room; stock that production or a delivery adds on the + way is not predicted (BALANCE.md S6). 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. @@ -165,9 +170,12 @@ pump-feeding. Accepting an offer spawns two transport movements. Direct transpor - An offer is "give `giveAmount` of `giveRes` for `wantAmount` of `wantRes`, within `maxDistance` tiles", posted from one POP that has an Internet exchange. Each side must fit ONE transport link (1..1000) and the two amounts differ by at most 1:2: `give <= 2 x want` and `want <= 2 x give` (count-based, the resources are not weighted). The resources must differ. -- The offered amount is **escrowed**: it leaves the POP when the offer is posted. Cancelling or expiry (48 h / world speed) credits it back - to the POP **capped by the Rack hall** (`trade.refund`, review fix R1: stock already above the cap stays, a refund never lifts it further). If - the POP's store filled up meanwhile, the clipped part is destroyed without a notice (BALANCE.md S2, open); otherwise nothing is created or lost. +- The offered amount is **escrowed**: it leaves the POP when the offer is posted, but **it keeps its room in the Rack hall**: while the + offer is open that resource stops filling at hall size minus the escrow (`rules.storageCapOf`; the HUD shows the lower cap). Cancelling + or expiry (48 h / world speed) therefore always fits: nothing is lost, and the escrow is no extra storage (review fix R1 stays true: a + refund never lifts stock above the hall size). The only case that can still clip a refund is a Rack hall that was shot down below stock + + escrow meanwhile; then the part that does not fit is lost and a `trade_refund_clipped` notification says how much (BALANCE.md S2). + A delivery of the traded goods onto a full store still loses the overflow and says so (`cargoLost`, as for every transport); accept refuses up front when that is projected. - **Reach:** a POP sees and takes offers of other operators within `min(offer.maxDistance, 10 x Internet exchange level)` tiles. The poster cannot take their own offer. - **Links:** an open offer holds one transport link of the poster's POP in reserve (open offers + running transports + returning carriers @@ -175,7 +183,8 @@ pump-feeding. Accepting an offer spawns two transport movements. Direct transpor - **Accepting** (one transaction): the acceptor's payment leaves their POP as a transport to the poster's POP (needs a free link and the resources there), the escrow leaves the poster's POP as a transport to the acceptor's POP; both arrive after `distance / 12 tiles/h / world speed`. The offer is `accepted`, then `completed` when both have been delivered. A delivery above the receiver's Rack hall cap - loses the overflow and says so (the existing transport rule). If the poster's POP is taken over while the offer is open, the offer + loses the overflow and says so (the existing transport rule), and accepting is refused (`no_room_for_goods`) when the acceptor's hall is projected + to have no room for the goods at arrival (production and cargo already on the way to that POP counted; a projection, not a promise). If the poster's POP is taken over while the offer is open, the offer ends (`void`) and the escrow stays in the POP. ## Incumbent (NPC) @@ -197,16 +206,33 @@ stays with the site. Landing sites cannot be settled, only taken. 80% of the map radius, at least 6 tiles apart, never in the free centre. They exist from the start (spawning and settling refuse them), the tile reads `backbone` from day 100 / speed (`rules.tileAt(seed, radius, x, y, ageDays)`; without the age argument terrain is unchanged). - **A site is not a POP** (DECISIONS E1): it has a holder alliance, a Backbone node level, a stockpile of Fiber/Hardware/Capital and at most - one level in progress. No units can stand there, so a site is defended by a static value only: - `defence = incumbentDefence(seed, x, y, age) x 12 x (1 + 0.03 x node level)`. At day 100 that is about 40 000 with no node, 160 000 at - level 100 (a Script crew attacks with 40). -- **Taking:** `scan` and `attack` only (no raid: the stockpile would be lootable; no takeover, no reinforce, no settle). The attacker must be in + one level in progress. Its defence is a static value plus a **garrison** (below): + `static = incumbentDefence(seed, x, y, age) x M x (1 + 0.03 x node level)` with M = 12 while nobody holds the site (the opening scramble) + and M = 2 once an alliance does (`ENDGAME.defenceMult`, `ENDGAME.heldDefenceMult`; DECISIONS E6). At day 100 an unheld site is about + 40 000, a held one about 7 000 at node level 0 and 28 000 at level 100 (a Script crew attacks with 40). +- **Garrison** (E6): members of the holding alliance (nobody else) can `reinforce` a site they hold: the units move in, count in its defence at + their owner's research, and keep drawing power from THEIR OWN POP (a site has no power budget; offline POP = offline units, decommission + takes them out of the garrison too). They leave by `POST /backbone/:id/withdraw` (owner only, any time), automatically when their owner + leaves or is kicked from the alliance, when the alliance disbands, or when the POP they belong to is taken over (a return movement each time), + and they die when the site is taken. A static + garrison defence is fought like a POP: a lost attack kills (attack/defence)^1.5 of the + garrison, so the next wave in arrival order faces less; the static part loses nothing, so the last wave alone must beat static + what + is left. That is what makes a held site contestable by several members (a single POP's army tops out around 60 000 attack), and why + `heldDefenceMult` is small: static defence must stay below what one POP can send or a built-up site would be out of reach again. +- **Capture shield:** a site that changed hands cannot be attacked for `ENDGAME.captureShieldHours` (72 world hours = 3 world days, / speed): + attacks are refused when sent (`site_shielded`) and turned back if the site was taken while they were on the road. Scans and garrisoning + are allowed. Without it a light static defence made sites flip every few hours in bot runs; 24 h still flipped them every ~1.7 real days + at 3x (BALANCE.md section 5). +- **Limit of the static rule:** `incumbentDefence` grows 4 % of its base per world day, so a held level-100 site's static part is ~51 000 + at world age 240 and ~68 000 at age 330, past what one POP can send (~60 000). The "static below one army" rule has an expiry date + (real day ~85 in a 3x world); then only a garrison already worn down by waves can be finished, and a holder with no garrison is the only one beatable. +- **Taking:** `scan` and `attack` only (no raid: the stockpile would be lootable; no takeover, no settle; `reinforce` only for the holder, above). The attacker must be in an alliance, and may not be in the holder's alliance or in a NAP / confederation with it (checked when sent and again on arrival, units come home otherwise). A full attack with attack > defence wins: the attacker's alliance holds the site. No loot, the site loses nothing, the survivors drive home. Level, stockpile and a running build stay with the site. A holder that disbands leaves the site to the incumbent (level kept). -- **Feeding the node:** members of the holder alliance send resources by transport (`POST /backbone/:id/ship`, same links, 1000 per link, 12 - tiles/h). On arrival they join the stockpile if the sender's alliance still holds the site, otherwise they ride home. A ledger records +- **Feeding the node:** members of the holder alliance send resources by transport (`POST /backbone/:id/ship`, same links, 1000 per link x the + world speed, 12 tiles/h). On arrival they join the stockpile if the sender's alliance still holds the site, otherwise they ride home (`backbone_ship_bounced`). The sender's Rack hall can have refilled while the shipment was away: what then does + not fit is destroyed and reported with exact amounts (`movement_returned.cargoLost`); no room is reserved for it (BALANCE.md S6). A ledger records who sent what. - **Building:** level L (1..100) costs `4000 x 1.045^(L-1)` of each resource (level 100: 312 301; about 7.2 million of each in total) and takes `2 h x 1.025^(L-1) / world speed` (level 100: 23 h; about 36 days of world time in total, one level at a time). The cost is paid from diff --git a/docs/NEXT.md b/docs/NEXT.md index 84a9ced..6193f2a 100644 --- a/docs/NEXT.md +++ b/docs/NEXT.md @@ -8,33 +8,35 @@ WebSocket push); stage 7 is partly done (bot harness + first balance pass, admin playtested by humans, and has never run on the real target (Debian LXC + systemd + nginx Proxy Manager).** Runnable and checked just now: -- `npm test`: 208 tests pass in about 7 s (rules as pure functions, commands/events/scheduler with a fake clock, REST over HTTP with every +- `npm test`: 264 tests pass in about 8 s (this tree) (rules as pure functions, commands/events/scheduler with a fake clock, REST over HTTP with every response checked against its schema, push with a real `ws` client, client logic, bot harness, admin CLI). `npm run openapi` leaves `docs/openapi.json` unchanged (it is in sync with the route table: 68 paths). - `node tools/bot.js --players 50 --days 14 --speed 1`: about 3 s, `INVARIANTS OK`. `node tools/admin.js help` works. - The deploy path from DEPLOY.md in a scratch directory, without systemd: first boot (migrations, world), `/healthz`, signup, a build, `admin.js` status/worlds/users/inspect/events/replay/backup/verify-backup/ban/grant, SIGTERM + restart (state kept), SIGKILL + restart after a build fell due (caught up in order), restore of a snapshot into a fresh `DB_PATH`. -- `npm run e2e` (`e2e/run.js`, Playwright): 61 checks pass (re-run after B4, 54 s). +- `npm run e2e` (`e2e/run.js` + `e2e/flows.js`, Playwright): 163 checks pass in about 137 s (smoke, units, movements + reports, reconnect, alliance + messages, trade, end game, nb, PWA); `E2E_SLOW=1` adds the 60 s polling-fallback suite. See "E2E" below. Never run: real devices, Safari/iOS, a Proxmox LXC, a unit under systemd, the backup timer firing, nginx Proxy Manager (WebSocket upgrade, idle timeouts, real client IPs), Let's Encrypt, a restore on the real box, load with many real sockets, any human player. Node 22.13 (the stated minimum) was not run, only 24.21. Known gaps, consolidated (the sections below have the detail and the reasoning): -- **Balance:** the first hour of a player who plays it all is limited by the 750 starting stock (about 12 builds), not by build time; a bigger stock was measured and not adopted (B4). nothing is tuned beyond B1, B2 and the B4 early-level build discount (BALANCE.md). Open: a 3x world's end game is as long as a 1x world's; after the opening days - nobody can contest a built-up landing site (no garrisons, E1); raid loot is split evenly and destroyed on overflow (S4); trade escrow - refunds are clipped at the Rack hall cap without a notice (S2); the capital runs out of things to build long before the backbone opens; +- **Balance:** the first hour of a player who plays it all is limited by the 750 starting stock (about 12 builds), not by build time; a bigger stock was measured and not adopted (B4). nothing is tuned beyond B1, B2 and the B4 early-level build discount (BALANCE.md). The end game follows world speed since B7 (3x: 29 to 35 days after the sites open, was 77 to 98) and a held landing site can be contested since E6 (garrisons, a + light static defence for held sites, a 72 h capture shield); both are first guesses measured with bots on two seeds (BALANCE.md B7 and E6), no human has played them, the static + defence outgrows what one POP can send around world age 280, and the bots do not react to `backbone_incoming`. Open: (S2 and S4, trade refunds clipped and loot/incumbent bonus destroyed on overflow, are fixed by B6: escrow keeps its room in the Rack hall, loot is limited to what home can bank; transport deliveries onto a full store, and a bounced backbone shipment that finds the hall refilled, still lose the overflow, reported with exact `cargoLost`; several raids from one home no longer share the same free room, S6; trade accept is refused with `no_room_for_goods` when the projected hall has no room); the capital runs out of things to build long before the backbone opens; the bots are not humans. - **Game rules not built:** cancelling training, sitters, night protection, a command to choose a new capital, power draw for units in transit, alliance rename/description, trade order book / price history / counter-offers, multi-link trade deals. - **Server:** no `backbone_open` push (sites are created lazily, E2); no `incoming` for confederates and no `town` hint for reinforcing owners; token revocation reaches an open socket only at the next 30 s ping; tokens never expire and there is no change-password route; no APNs/FCM sender; `reports.id` can be reused after a full cleanup (S3, low); no recovery sweeper if an `arrive`/`return` handler ever throws (R1); - HTTP connections per IP are not capped; admin `end-world` is a flag flip without ranking snapshot (DEPLOY.md section 6). + HTTP connections per IP are not capped. - **Client:** no service worker (no offline mode), no light theme, no unit icons or battle simulator, no sound/system notifications; a few one-tap destructive actions without confirmation; unread-badge state is partly in localStorage; ended-world locking is a DOM sweep. -- **Docs:** `docs/workflows/` (planned stage workflows, CLAUDE.md layout) is empty: no stage workflow was ever written there. + Found by the e2e and NOT fixed: after switching language live, screens that were already drawn keep ~15 English `aria-label`s (map zoom/label, refresh buttons, tab groups; visible + text is fine, a reload fixes it); an alliance message raises the More badge by 2 (the alerts feed and the unread message are both summed; by design of the badge, perhaps not intended). +- **Docs:** `docs/workflows/` has a short note per stage (written after the fact from NEXT and the git history; NEXT stays authoritative). - **Not run in a browser:** takeover/capture flows, the confederation `alliedIncoming` view, real devices (see the client sections). ## Done @@ -117,8 +119,8 @@ a phone profile (markup in a message stays text, counter/over-limit, 429 countdo move sheet, name-taken error, nb). Not run: real devices, Safari, Playwright suite, a long-list scroll test (>100 ranks), accepting an invite when the alliance is full, alliances at the size cap. Gaps: alliance rename/description and note editing have no UI (server has edit-note); no operator profile page; blocking needs an existing -conversation or message (the API takes an operator id and there is no name lookup); no live refresh (push is not wired, screens refetch -on open and on manual refresh); the alliance screen does not auto-refresh countdowns' targets after they pass; `App.state.operator.alliance` +conversation or message (the API takes an operator id and there is no name lookup); no live refresh (push is not wired for the alliance screen, which refetches +on open and on manual refresh; Messages follows the `message` push since the e2e pass); the alliance screen does not auto-refresh countdowns' targets after they pass; `App.state.operator.alliance` is refreshed from `/me` after alliance changes but is stale if you are kicked while away until the screen is opened. ## Client: military, expansion, WebSocket @@ -197,7 +199,7 @@ Built (More group; strings in `strings/{trade,world,alerts}.js`, en + nb): minute. Confederate Carol gets no push for `alliedIncoming` (known server gap): it shows when the Moves screen is opened or the poll runs, and never in her badge. Found and fixed in the client: `report` pushes now also refetch movements (the incoming banner used to linger up to a few seconds after the arrival). Not done / not claimed: -- Not run: real devices, Safari, a socket behind nginx Proxy Manager, throttled networks, the full Playwright suite (only the smoke e2e exists), long lists (offers > 25 per +- Not run: real devices, Safari, a socket behind nginx Proxy Manager, throttled networks, the combat/takeover/diplomacy flows in a browser, long lists (offers > 25 per filter paged only up to what the sweep seeded). - Ended-world locking is a DOM sweep, not per-button wiring: a new primary/danger button that is NOT a game command must carry `data-keep`. Messages, ranking and settings screens are exempt by selector. Open send/trade sheets that were opened before the end stay usable until the next DOM change or a refused command. @@ -209,6 +211,41 @@ Not done / not claimed: - Server bug found and fixed (tiny): `POST /reports/:id/share` threw a 500 when no `reportCleanup` event was pending (`ensureCleanup` needs `ctx.enqueue`); `reportShare` now wraps its ctx with `ctxOf`, regression test `test/report-share-cleanup.test.js` (failed before). +## E2E (`e2e/`, run with `npm run e2e`) +`e2e/run.js` (smoke suites: desktop, phone, layout, push) and `e2e/flows.js` (feature flows) boot the real server in-process (temp SQLite, real clock, `WORLD_SPEED` 4000 or 1) and drive +headless Chromium through `playwright-core`; `e2e/lib.js` holds the shared plumbing (`bootServer`, `newPage` with console/HTTP error capture, `hurryMovement` / `hurryEvents`). +Default run: 163 checks, about 137 s, no console error or failed request tolerated; every page gets a default action timeout of 8 s (`lib.js`), the smoke suites included. `node e2e/run.js ` runs named suites; `slow` only by name or `E2E_SLOW=1`. +- **units**: train 2 script crews through the sheet (cost preview scales, queue row with count and countdown, count pill), the batch completes (event moved up), units appear in the home list and + the database, an unaffordable train is explained and disabled, hosted reinforcements are listed and "send home" removes them and starts the return. +- **movements**: scan and raid from the Moves screen send dialog (coordinates, type, unit picker, preview, send), both in the outgoing list with countdown and recall button; the defender's page gets + the banner and the Moves badge by push (type and units hidden), both arrive, report badges on both sides, the Reports list (unread, then read on open, server read flag), the raid and scan report + sheets, the defender-side report. +- **reconnect**: the page's socket is closed and new ones refused; a raid launched in the gap is not shown; on reconnect a NEW socket opens and the missed raid appears (refetch on ready); a second raid + then shows by push within 6 s with the socket open and no reload. +- **alliance**: found (button disabled until valid), invite by name, accept on the other page, a broadcast written in Messages > Alliance, the unread badge on the other page by push, the feed row + (unread, sender), mark read, a second broadcast appearing live. +- **trade**: post (escrow), the offer on the taker's Offers tab, Take with the POP picker, both legs in flight (moved up past the 10 minute minimum latency), goods swapped, `completed` on both + "mine" tabs, an alert. +- **endgame** (own world backdated to day 100.5): banner "appear in" + how-it-works before, "open" + 7 site cards after, the held site is `mine` with Manage, others show scan/attack, a non-member + sees no Manage; the Manage sheet, ship 300 fiber (toast, transport row marked as a site shipment, stock drops), it lands and the stockpile and ledger show it. +- **nb**: live switch after every screen was drawn in English (visible text), reload and fresh render (text, aria-label, placeholder, title), nav labels, dynamic keys (`err.*` in the train sheet, + `send.reason.*`), raw-key detector, English-leftover detector, and a check that no multi-word nb string is a verbatim copy of its English text. The same detector sweeps pages that hold real + data at the end of the movements, alliance, trade and endgame flows (reports and sheets, alliance tabs, messages tabs, trade tabs, site manage sheet and dialogs). +- **pwa**: manifest link, `application/manifest+json`, display standalone, start_url inside scope and serving the shell, theme colours equal to the meta tag, every icon 200 + image type + PNG + dimensions equal to the declared sizes, a maskable icon, apple-touch-icon, no service worker. +- **slow**: `WebSocket` removed from the page; the raid is not shown within 8 s, then shows by polling (59 s in the run, worst case about 60 s), no reload, socket never open. +How the checks were shown to be able to fail (each mutation applied, the named suite run, reverted): units queue never drawn (units), home list never drawn (units), reports never marked read +(movements), manifest served as octet-stream (pwa), no refetch on socket ready (reconnect), no reconnect scheduling (reconnect), alliance accept sends decline (alliance), trade accept with a wrong POP +(trade), open banner never drawn and ship endpoint misspelt (endgame), a copy-pasted English string in the nb table (nb), polling interval removed (slow); the nb detector additionally runs a planted raw +key, a planted English string and a deleted nb string on the live page, and a calibration run in English (it must see >= 8 English strings on the POP screen). Message push: the push check failed +on the tree before the fix below. +Real app bugs found: (1) `{type:'message'}` push was received and ignored (the unread badge and the open Messages list only moved on the 60 s poll or a tab switch): `messages.js` now refetches the unread +count and the visible inbox / alliance feed / open thread on that hint (regression: alliance flow, fails without it); (2) the "New" button of the Messages header stayed English after a live language +switch (built once in `render()`): now set in `onShow` (regression: nb flow, "switched live"). Not fixed, see the gaps above: stale aria-labels after a live switch; More badge double counts a message. +Not covered: takeover/capture, diplomacy moves, confederation `alliedIncoming`, rankings content, reports share to the alliance folder, settings devices list, Firefox/WebKit, real devices. +Caveats: flights and trade legs are moved up with `UPDATE movements/events` + `scheduler.arm()`, not by waiting; the end-game world is made 100.5 days old by moving `worlds.start_at` and +the 7 site rows come from `ensureSites` (what the first scan or attack does) with the holder written by SQL; the 60 s slow suite is not in the default run. + ## Stage 6 (server half): WebSocket push Built: `/ws` on the game's HTTP server (`server/push.js` transport, `server/pushHooks.js` routing), contract in `docs/PROTOCOL.md`. Auth as first message (`ready` / close 4401), Origin check (`net.originAllowed`), per-IP cap `MAX_CONN_PER_IP` (HTTP 429), 1 KB frames, @@ -250,13 +287,15 @@ Not done / not claimed: - **Nothing here is balanced.** Defence multiplier 12 (+3% per level), node cost 4000 x 1.045^(L-1) (about 7.2 M of each resource in total), node time 2 h x 1.025^(L-1) (about 36 world days), 48 h offer ttl, 10 tiles of reach per exchange level, 500-per-side offers: first guesses, no bot run when written (now there is one: BALANCE.md section 5 says an 18-member alliance needs 55 to 78 days after the sites open with 1000 per link, and does not finish in 175 days with 500). -- **No garrison at landing sites** (E1): defence is static, holders cannot station units. If the first world shows the race is decided by who - hits first, the next step is a small `site_units` table with reinforce-to-site and defenders in `landing.js`. +- **Garrisons at landing sites** (E6, migration 005 `site_stationed`, `server/military/garrison.js`, `POST /backbone/:id/withdraw`): built and tested (`test/endgame-garrison.test.js`, + `test/client-garrison.test.js`), bots garrison and assault (`tools/bot/endgame.js`, `--no-contest` turns it off). Not built / not claimed: no `captureLevelLoss` + (a taken site keeps its node level), no sitter, `tools/admin.js inspect-town` does not list garrison units, the site sheet was not opened in a real browser, a holder cannot send + a member's units away, confederates cannot garrison (members only). - No `backbone_open` push at the moment the sites appear unless something touches a site first (E2); clients see the phase by polling status. - Trade: no multi-link deals (each side <= 500), no price history or order book, no counter-offers, no notification when a new offer appears in reach, offers are not hidden from enemies, the escrow of a taken-over POP goes to the conqueror. -- Ended worlds: movements still `out` and queued builds are left as they were (events cancelled, E3); `tools/admin.js end-world` only flips the status (no snapshot, no event cancellation) and `reset-world` - wipes a world's rows; neither runs the real `worldEnd` event (see DEPLOY.md section 6); several winners are impossible by design. +- Ended worlds: movements still `out` and queued builds are left as they were (events cancelled, E3); `tools/admin.js end-world` now runs the real `worldEnd` handler (snapshot, escrow back, events cancelled; ops part below); `reset-world` + wipes a world's rows without it (DEPLOY.md section 6); several winners are impossible by design. - The ranking snapshot is the same numbers as `/rankings`, computed once; `/rankings/*` after the end still compute live from the frozen state. - Client for all of this: see "Client: trade, end game, alerts" above. @@ -273,18 +312,25 @@ Server fix found by the harness: bounced shipments reported no overflow (`events Tests: `test/bot-run.test.js` (12 players x 6 days twice, identical stats, invariants, the checks catch tampering, a fast world reaches the end game), `test/bot-server-fixes.test.js`. Not done / not claimed: **the game is not balanced**; the bots are not humans (no reinforcement, recall, messages, sitters; fixed sittings). Open -items from the pass: a 3x world's end game is as long as a 1x world's (shipping is per sitting; `capacityPerLink x speed` needs the client to stop -reading the constant); trade escrow refunds are clipped at the Rack hall cap silently; raid loot is split evenly over resources and destroyed on overflow; -the capital runs out of things to build ~50 days before the backbone opens at 4 sittings a day; a built-up landing site is out of reach of any -single-POP army (no garrisons, E1), so there is no fight for a site after the first days. +items from the pass: (a 3x world's end game being as long as a 1x world's is fixed by B7, `rules.transportCapacity`); (trade escrow refund clipping and loot destruction on overflow were fixed afterwards by B6, BALANCE.md section 9); +the capital runs out of things to build ~50 days before the backbone opens at 4 sittings a day; (a built-up landing site being out of reach of any single-POP army is +answered by E6: garrisons and waves, BALANCE.md section 5). ## Stage 7 (ops part): admin CLI, deploy files Built: `tools/admin.js` (status, migrate, worlds, create-world, end-world, users, operators, ban/unban/revoke-tokens, inspect-operator/-town, events, replay-events [--simulate], backup/verify-backup (VACUUM INTO, verified, pruned), reset-world, grant), `deploy/` (service, backup service + timer, `upstream-admin` wrapper), `docs/DEPLOY.md`. Tests: `test/admin-cli.test.js`. Run by hand on 2026-10-11 in a scratch directory: see "Status at a glance". -Not done / not claimed: nothing of it has run under systemd or on Debian 13 (DEPLOY.md lists what was and was not run); no load test with real sockets; -world lifecycle through the CLI is partial (above); no scheduled "create next world". +Added later: `end-world` runs the real `worldEnd` event handler (final ranking snapshot so `/worlds/:id/results` is available, trade escrow back, +the world's other pending events cancelled, `world_ended` notifications; overdue events of that world are processed first; refuses without `--yes`), +quiet on EPIPE (`admin.js ... | head`); `deploy/update.sh` (git fast-forward update on the box: tools checked up front, service STOPPED before the tree changes (review R2), verified snapshot of the stopped db, `npm ci --ignore-scripts` only when the lock +changed, optional `--test` on a `git archive` copy as the service user, health check, rollback to the old rev, `--dry-run`); `deploy/upstream-offsite` + `.service`/`.timer` (off-box copy of the newest +verified snapshot to `OFFSITE_DEST`, skipped unless configured). Tests: `test/admin-endworld.test.js`, `test/deploy-update.test.js` (stubbed systemctl/curl/npm), +`test/deploy-offsite.test.js` (local directory as destination; needs rsync; scp was removed in R2). +Not done / not claimed: nothing of it has run under systemd or on Debian 13 (DEPLOY.md lists what was and was not run); `update.sh` and the off-site +copy were run only against stubs / a local directory (no real ssh, rrsync, systemd, runuser, npm ci or /healthz; shellcheck and dash were not available); a migration cannot be rolled back by +`update.sh` (it prints the snapshot to restore); `end-world` cannot repair a world ended by the old flag-flip version (no snapshot); the notification +rows the CLI writes are not pushed by a running server; no load test with real sockets; no scheduled "create next world". ## Not done - Stage 7 remainder: balance passes beyond B1, B2 and B4 with the open items above, a real world lifecycle (start, natural end, reset) driven from the CLI, - load test over HTTP/WebSocket, the full e2e suite and a human playtest. Everything else in CLAUDE.md "Working in stages" is built. + load test over HTTP/WebSocket, e2e for takeover/capture/diplomacy/confederation views, and a human playtest. Everything else in CLAUDE.md "Working in stages" is built. diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index ec17d40..b7fcaf8 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -43,7 +43,7 @@ One socket per device is enough; a user may have several (phone + desktop), each | `{"type":"pong","serverTime":n}` | answer to `ping` | same | | `{"type":"town","townId":n}` | POP `n` (yours) changed: build/train/research done, resources spent, units arrived, returned or died, attacked, ownership changed, a command from another device | refetch `GET /towns/:id` (if on screen) | | `{"type":"incoming","townId":n,"arriveAt":n}` | a movement from another operator was launched at your POP `townId`, arrives at `arriveAt`. Type and origin hidden on purpose (could be a scan, a raid, reinforcements or a transport). | show a warning with a countdown, refetch `GET /movements` for the details the API allows | -| `{"type":"notification","id":n,"kind":"..."}` | a row was added to your notifications. `kind` is `notifications.type`: `build_done`, `train_done`, `research_done`, `incoming`, `report`, `message`, `alliance_message`, `alliance_invite`, `town_lost`, `town_gained`, `transport_arrived`, `movement_returned`, `units_offline`, ... (the list grows, treat unknown kinds as generic) | bump the unread badge, `GET /notifications` | +| `{"type":"notification","id":n,"kind":"..."}` | a row was added to your notifications. `kind` is `notifications.type`: `build_done`, `train_done`, `research_done`, `incoming`, `report`, `message`, `alliance_message`, `alliance_invite`, `town_lost`, `town_gained`, `transport_arrived`, `movement_returned`, `units_offline`, `trade_refund_clipped`, `backbone_incoming`, `garrison_arrived`, `garrison_released`, ... (the complete list with payloads is "Notification types" at the end of docs/API.md; the list grows, treat unknown kinds as generic) | bump the unread badge, `GET /notifications` | | `{"type":"report","id":n}` | a battle or scan report with id `n` is ready for you | `GET /reports/:id` or refresh the list | | `{"type":"message","id":n}` | a direct or alliance message with id `n` arrived for you (not sent to its sender) | refresh the inbox | @@ -129,7 +129,7 @@ S: {"type":"pong","serverTime":1767236401000} | Source | Hint | | ------ | ---- | -| any `notifications` row (`scheduler.notify`, after the transaction committed) | `notification`; plus `incoming` / `report` / `message` for kinds `incoming` / `report` / `message`, `alliance_message`; plus `town` for kinds that change a POP whose owner may differ from the event's POP (`town_lost`, `town_gained`, `transport_arrived`, `transport_delivered`, `movement_returned`, `reinforcements_sent_home`) | +| any `notifications` row (`scheduler.notify`, after the transaction committed) | `notification`; plus `incoming` / `report` / `message` for kinds `incoming` / `report` / `message`, `alliance_message`; plus `town` for kinds that change a POP whose owner may differ from the event's POP (`town_lost`, `town_gained`, `transport_arrived`, `transport_delivered`, `movement_returned`, `reinforcements_sent_home`, `garrison_arrived`, `garrison_released`) | | a finished event (`scheduler.onEvent`) | `town` to the owner of `events.town_id` (build, train, research, power check) and of both ends of the movement for `arrive` / `return` | | a committed command (`commands.hooks.onCommand`) | `town` to the owner of the POP named in `townId`, `fromTownId`, `hostTownId`, `ownerTownId` or the new POP of `joinWorld`; for `recallMovement` both ends of the movement | diff --git a/docs/openapi.json b/docs/openapi.json index e16ea63..9755ccf 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -3,7 +3,7 @@ "info": { "title": "UPSTREAM API", "version": "1.0.0", - "description": "Generated by tools/gen-openapi.js from server/routes. Every response carries serverTime; errors use the { error: { code, message, details } } envelope. Codes: bad_request, validation_failed, unauthorized, invalid_credentials, forbidden, not_found, method_not_allowed, conflict, request_in_progress, idempotency_key_reuse, payload_too_large, rate_limited, internal_error, signup_closed, username_taken, world_full, unknown_building, not_buildable, max_level, requirements_not_met, already_queued, queue_full, not_enough_resources, peering_office_required, already_in_alliance, not_in_alliance, alliance_name_taken, alliance_tag_taken, alliance_full, invite_expired, leader_must_transfer, notes_full, diplomacy_invalid, diplomacy_pending, proposal_exists, proposal_expired, unknown_unit, not_researchable, not_enough_units, units_offline, invalid_target, target_protected, protection_active, out_of_range, footprint_too_low, cannot_takeover, recall_expired, capacity_exceeded, no_transport_link, trade_ratio, offer_closed, own_offer, trade_out_of_range, world_ended, backbone_closed" + "description": "Generated by tools/gen-openapi.js from server/routes. Every response carries serverTime; errors use the { error: { code, message, details } } envelope. Codes: bad_request, validation_failed, unauthorized, invalid_credentials, forbidden, not_found, method_not_allowed, conflict, request_in_progress, idempotency_key_reuse, payload_too_large, rate_limited, internal_error, signup_closed, username_taken, world_full, unknown_building, not_buildable, max_level, requirements_not_met, already_queued, queue_full, not_enough_resources, peering_office_required, already_in_alliance, not_in_alliance, alliance_name_taken, alliance_tag_taken, alliance_full, invite_expired, leader_must_transfer, notes_full, diplomacy_invalid, diplomacy_pending, proposal_exists, proposal_expired, unknown_unit, not_researchable, not_enough_units, units_offline, invalid_target, target_protected, protection_active, out_of_range, footprint_too_low, cannot_takeover, recall_expired, capacity_exceeded, no_transport_link, trade_ratio, offer_closed, own_offer, trade_out_of_range, no_room_for_goods, world_ended, backbone_closed" }, "servers": [ { @@ -2885,7 +2885,7 @@ }, "/backbone/{id}/ship": { "post": { - "summary": "Send resources from one of your POPs to a landing site your alliance holds (a transport: Internet exchange links, 500 each)", + "summary": "Send resources from one of your POPs to a landing site your alliance holds (a transport: Internet exchange links, 1000 each at world speed 1, times the world speed)", "tags": [ "world" ], @@ -3004,6 +3004,116 @@ } } }, + "/backbone/{id}/withdraw": { + "post": { + "summary": "Call units of one of your POPs home from a landing site's garrison (default: all of them). Only their owner can; works whoever holds the site now. Station units with POST /movements type reinforce at the site's x,y (members of the holding alliance only)", + "tags": [ + "world" + ], + "operationId": "postBackboneIdWithdraw", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "integer" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "fromTownId" + ], + "properties": { + "fromTownId": { + "type": "integer", + "minimum": 1 + }, + "units": { + "type": "object", + "additionalProperties": true, + "description": "defaults to the whole group" + } + } + } + } + } + }, + "security": [ + { + "bearer": [] + } + ], + "responses": { + "201": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GarrisonWithdrawn" + } + } + } + }, + "401": { + "description": "Error codes: unauthorized", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Error codes: not_found, unknown_unit", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Error codes: conflict, not_enough_units, world_ended", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Error codes: idempotency_key_reuse, validation_failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Error codes: internal_error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, "/diplomacy/proposals/{proposalId}": { "delete": { "summary": "Withdraw a proposal your alliance made (needs diplomacy)", @@ -7109,7 +7219,7 @@ } }, "409": { - "description": "Error codes: capacity_exceeded, no_transport_link, not_enough_resources, offer_closed, own_offer, trade_out_of_range, world_ended", + "description": "Error codes: capacity_exceeded, no_room_for_goods, no_transport_link, not_enough_resources, offer_closed, own_offer, trade_out_of_range, world_ended", "content": { "application/json": { "schema": { @@ -7850,6 +7960,26 @@ ], "additionalProperties": true }, + "escrow": { + "type": "object", + "properties": { + "fiber": { + "type": "number" + }, + "hardware": { + "type": "number" + }, + "capital": { + "type": "number" + } + }, + "required": [ + "fiber", + "hardware", + "capital" + ], + "additionalProperties": true + }, "military": { "$ref": "#/components/schemas/TownMilitary" } @@ -7870,7 +8000,8 @@ "buildings", "queue", "queueSlots", - "bonus" + "bonus", + "escrow" ], "additionalProperties": true }, @@ -9717,6 +9848,35 @@ "type": "object", "additionalProperties": true } + }, + "garrisoned": { + "type": "array", + "items": { + "type": "object", + "properties": { + "siteId": { + "type": "integer" + }, + "x": { + "type": "integer" + }, + "y": { + "type": "integer" + }, + "units": { + "type": "object", + "additionalProperties": true, + "description": "unit id -> count" + } + }, + "required": [ + "siteId", + "x", + "y", + "units" + ], + "additionalProperties": true + } } }, "required": [ @@ -9724,7 +9884,8 @@ "online", "offlineSince", "stationedHere", - "stationedAway" + "stationedAway", + "garrisoned" ], "additionalProperties": true }, @@ -10181,6 +10342,10 @@ "type": "integer", "nullable": true }, + "shieldUntil": { + "type": "integer", + "nullable": true + }, "level": { "type": "integer" }, @@ -10234,6 +10399,7 @@ "holder", "takenBy", "takenAt", + "shieldUntil", "level", "maxLevel", "progress", @@ -10370,13 +10536,17 @@ }, "canAttack": { "type": "boolean" + }, + "canReinforce": { + "type": "boolean" } }, "required": [ "holder", "canBuild", "canShip", - "canAttack" + "canAttack", + "canReinforce" ], "additionalProperties": true }, @@ -10410,6 +10580,69 @@ ], "additionalProperties": true } + }, + "defence": { + "type": "object", + "properties": { + "static": { + "type": "number" + }, + "garrison": { + "type": "number" + }, + "total": { + "type": "number" + } + }, + "required": [ + "static", + "garrison", + "total" + ], + "additionalProperties": true + }, + "garrison": { + "type": "array", + "items": { + "type": "object", + "properties": { + "ownerTownId": { + "type": "integer" + }, + "townName": { + "type": "string", + "nullable": true + }, + "operator": { + "type": "object", + "nullable": true, + "additionalProperties": true + }, + "units": { + "type": "object", + "additionalProperties": true + }, + "online": { + "type": "boolean" + }, + "power": { + "type": "number" + }, + "mine": { + "type": "boolean" + } + }, + "required": [ + "ownerTownId", + "townName", + "operator", + "units", + "online", + "power", + "mine" + ], + "additionalProperties": true + } } }, "required": [ @@ -10419,6 +10652,39 @@ ], "additionalProperties": true }, + "GarrisonWithdrawn": { + "type": "object", + "properties": { + "serverTime": { + "type": "integer" + }, + "movementId": { + "type": "integer" + }, + "siteId": { + "type": "integer" + }, + "fromTownId": { + "type": "integer" + }, + "units": { + "type": "object", + "additionalProperties": true + }, + "arriveAt": { + "type": "integer" + } + }, + "required": [ + "serverTime", + "movementId", + "siteId", + "fromTownId", + "units", + "arriveAt" + ], + "additionalProperties": true + }, "BackboneBuildStarted": { "type": "object", "properties": { @@ -10842,6 +11108,10 @@ "status": 409, "description": "That POP is too far from the offer (its max distance or your Internet exchange reach)." }, + "no_room_for_goods": { + "status": 409, + "description": "Your Rack hall will not have room for the goods when they arrive; make room (spend, or raise the hall) and accept again." + }, "world_ended": { "status": 409, "description": "This world has ended: it can still be read, but nothing can be changed." diff --git a/docs/workflows/README.md b/docs/workflows/README.md new file mode 100644 index 0000000..00eca72 --- /dev/null +++ b/docs/workflows/README.md @@ -0,0 +1,23 @@ +# Stage workflows + +One short note per stage of CLAUDE.md "Working in stages": goal, done-when, what was actually built, what is open. They were +written after the fact (2026-10-11) from `docs/NEXT.md`, `docs/DECISIONS.md`, `docs/BALANCE.md` and the git history, so they +describe what happened, not what was once planned. The authoritative status is `docs/NEXT.md`; if a note here disagrees, NEXT wins +and the note is stale. + +A stage is done when `npm test` passes, the smoke e2e passes, the docs (API, PROTOCOL, DESIGN, NEXT) match the code and the commit +message says honestly what was built, tested and NOT tested (CLAUDE.md). + +| Stage | Note | Commits | +|---|---|---| +| 0 Skeleton | [stage-0-skeleton.md](stage-0-skeleton.md) | b56b138 | +| 1 Economy | [stage-1-economy.md](stage-1-economy.md) | b56b138, 249818a (client) | +| 2 World | [stage-2-world.md](stage-2-world.md) | b56b138, 249818a (client) | +| 3 Military | [stage-3-military.md](stage-3-military.md) | 249818a, b18645d | +| 4 Expansion | [stage-4-expansion.md](stage-4-expansion.md) | 249818a, b18645d | +| 5 Social | [stage-5-social.md](stage-5-social.md) | 249818a, b18645d, 931f59e, d84b0c9 | +| 6 Push and polish | [stage-6-push-polish.md](stage-6-push-polish.md) | b18645d, 931f59e, cc0524d | +| 7 Ops and balance | [stage-7-ops-balance.md](stage-7-ops-balance.md) | 931f59e, cc0524d, bf7af06, 9104480 and later | + +Note: the work did not follow the stage order exactly. Stages 0-2 went in one commit, 3-5 in the next, and the end game and trade +(planned inside stage 5 / 7) arrived with the client work. The notes list the real commits. diff --git a/docs/workflows/stage-0-skeleton.md b/docs/workflows/stage-0-skeleton.md new file mode 100644 index 0000000..43a9df5 --- /dev/null +++ b/docs/workflows/stage-0-skeleton.md @@ -0,0 +1,22 @@ +# Stage 0: skeleton + +**Goal:** a server that boots, stores state in SQLite, runs a persistent event queue and answers a documented REST API, before any +game rule exists. + +**Done when:** repo layout in place; `server/db.js` (driver wrapper, transactions, checksummed migrations) and `server/clock.js` +(the only place that reads time); `scheduler.js` with catch-up after restart; router, error envelope, auth with hashed bearer +tokens, `/healthz`; `docs/openapi.json` generated and checked against the route table; systemd unit, backup timer, DEPLOY.md. + +## Built (b56b138) +- `node:sqlite` behind `server/db.js` (D1); migrations `NNN_name.sql` applied in a transaction each and refused if edited later. +- `Scheduler`: events processed strictly in `(due_at, id)` order, one transaction per event, a throwing handler marks the event + `failed` and the queue moves on; `catchUp()` before the listener opens; outbox so push only leaves after commit (stage 6). +- Router with `Idempotency-Key`, per-IP/per-token rate limits (login/signup stricter), 32 KB bodies, scrypt passwords, opaque + tokens stored hashed, strict CSP static server (NETWALL's `net.js`/`static.js`). +- `tools/gen-openapi.js` + a test that fails when a route and `openapi.json` disagree (D7). +- Deploy files, DEPLOY.md and the admin CLI were added at stage 7 (see there). + +## Open +- First commit had a manual smoke run only; unit tests arrived with each later stage. +- Never run: a unit under systemd, the backup timer firing on its own, Debian 13 with a real Node 22.13 (only 24.21 was used). +- Tokens never expire and there is no change-password route; revocation reaches an open socket at the next 30 s ping. diff --git a/docs/workflows/stage-1-economy.md b/docs/workflows/stage-1-economy.md new file mode 100644 index 0000000..460d749 --- /dev/null +++ b/docs/workflows/stage-1-economy.md @@ -0,0 +1,21 @@ +# Stage 1: economy + +**Goal:** one POP per operator with lazily evaluated resources, buildings with levels, a build queue and storage caps; a minimal +client (POP view, build menu, countdowns). + +**Done when:** `rules.resourcesAt(town, now)` is the only way to read a stock; every quantity that grows is `(amount, rate, +updatedAt)` (D3: one `towns.res_at`); build/cancel/rename commands validate and apply in one transaction; `buildDone` is an event. + +## Built +- Four resources (Fiber, Hardware, Capital, Power as a battery, D4), resource fields by slot (D8), infrastructure (Core router, + Rack hall, Battery bank, ...), build queue with a second slot unlocked by Core router level (B1: level 3, was 10), cancel. +- `public/js/data.js` holds all numbers; `rules.js` all formulas and loads in browser and Node. +- Client (249818a): login/signup, POP screen with live resource bar ticked from the server clock, build sheet with live + affordability, countdowns, power panel, en + nb, PWA manifest and icons. +- Later balance (BALANCE.md): B4 early-level build discount (levels 1-3 take x0.5/x0.67/x0.83), B5 start stock 1000. +- Fix G1: `buildDone` adds one level to what the building is *now* (test written first, failed before). + +## Open +- Nothing is balanced (bots only, 2 seeds for B4/B5); the first hour is limited by the start stock, not build time (B4/B5). +- The capital runs out of things to build long before the backbone opens (BALANCE section 5). +- No service worker, so no offline mode; no light theme. diff --git a/docs/workflows/stage-2-world.md b/docs/workflows/stage-2-world.md new file mode 100644 index 0000000..5747395 --- /dev/null +++ b/docs/workflows/stage-2-world.md @@ -0,0 +1,18 @@ +# Stage 2: world + +**Goal:** a seeded map, spawn placement, neutral land, a viewport query and a canvas map. + +**Done when:** `rules.tileAt(seed, radius, x, y)` is deterministic; new operators land on a spawn ring; `GET /map?x&y&r` returns +a window; the client map pans, pinches and culls tiles; every game row carries `world_id` (multi-world from day one). + +## Built +- First world is 101 x 101 (radius 50, D6), seed random at first boot; `worlds` is data, `create-world` makes more (stage 7). +- Rural areas are held by proximity in v1 (D5), not by a separate tile ownership model. +- `GET /map/tile`, chunked `GET /map` cache on the client, tile info sheet, `js/render.js` canvas (pan, pinch, wheel, keyboard). +- Seven landing sites are derived from the seed (`rules.backboneSites`) and excluded from spawn and settling from day 0. +- `POST /me/join` (9104480) lets an account without a POP found one in a running world after `reset-world`. + +## Open +- Map canvas has no inertia/fling. +- `/me` exposes the world seed, which the client ignores. +- Joining a second world was only tested on the default-world path. diff --git a/docs/workflows/stage-3-military.md b/docs/workflows/stage-3-military.md new file mode 100644 index 0000000..209a859 --- /dev/null +++ b/docs/workflows/stage-3-military.md @@ -0,0 +1,22 @@ +# Stage 3: military + +**Goal:** training queues, movements (attack, raid, reinforce, scout, return), combat at arrival, loot, reports, incoming warnings. + +**Done when:** every future thing is an `events` row; combat resolves only inside the event queue in `(due_at, id)` order; the +client sees incoming attacks without reload; a determinism test replays a fight identically. + +## Built (249818a server, b18645d client) +- 10 unit types and research in `data.js`/`rules.js`; `trainDone` per batch, sequential per building; `researchDone`. +- Movements: scan, raid, attack, takeover, reinforce, settle, transport; latency = distance / slowest unit; recall for 90 s; return + legs with loot; arrival re-validates everything and bounces (S3-4). +- Combat: firewall vs DDoS rigs, exploit kits on a chosen building, Rack hall cache, losses; reports are one row with many + recipients, 14-day cleanup (S3-3); beginner protection both directions (S3-7); power: offline units, decommission after 24 h (S3-1). +- Client: Units, Moves, Reports screens, the send dialog, incoming banner and badge, map movement lines. +- Review round 1 (d84b0c9, DECISIONS R1): proto smuggling in `validate.js`, trade-leg recall, escrow cap, rate limits, rankings DoS. + +## Open +- Training cannot be cancelled; no sitters, no night protection; units in transit draw no power. +- Nothing balanced: unit stats, costs and research curves are first guesses (BALANCE section 4: raiding profitable per raid but not + a winning strategy at equal attention; takeover expensive enough). +- No garrisons at landing sites (E1): after the opening days nobody can contest a built-up site. +- Takeover/capture flows and the confederation `alliedIncoming` view have no browser run. diff --git a/docs/workflows/stage-4-expansion.md b/docs/workflows/stage-4-expansion.md new file mode 100644 index 0000000..dc37789 --- /dev/null +++ b/docs/workflows/stage-4-expansion.md @@ -0,0 +1,19 @@ +# Stage 4: expansion + +**Goal:** found new POPs, conquer others, multi-POP UI. + +**Done when:** a Rollout crew founds a POP on a chosen wild slot; a hostile takeover moves loyalty to zero and flips owner with the +capital and last-POP protections; the UI switches between POPs. + +## Built (249818a server, b18645d client) +- Settle command with wild-slot choice; footprint gate counts the operator's total (S3-8); takeover with loyalty (S3-5); + incumbent (legacy telco) sites with static defence growing with world age and a one-time Hardware bonus; +10% research speed + per incumbent site held. +- Moving units between your own POPs (S3-9); transport links (S3-6). +- Client: POP switcher in the resource bar, expansion card on the POP screen, settle through the send dialog, red ring on POPs that + something is heading for, `refreshTowns` after a settle/takeover. + +## Open +- No command to choose a new capital; a captured POP keeps its footprint. +- The Hostile takeover button stays enabled on a capital/last POP (the client cannot know; the server refuses and the UI shows it). +- Settle and takeover resolution were exercised by fast-forwarding movement times in the DB, not by waiting in a browser. diff --git a/docs/workflows/stage-5-social.md b/docs/workflows/stage-5-social.md new file mode 100644 index 0000000..361db07 --- /dev/null +++ b/docs/workflows/stage-5-social.md @@ -0,0 +1,21 @@ +# Stage 5: social + +**Goal:** alliances, roles, messaging, diplomacy, marketplace and resource transport. + +**Done when:** an alliance can be founded, grown, governed and dissolved; diplomacy states change through events; messages and +rankings work; trade moves resources between POPs and players without creating or losing any. + +## Built +- Migration 003: alliances with roles and a stored size cap (S5-1), diplomacy (war, neutral, NAP, confederation; 24 h / speed pact + cancel via the `diploChange` event, S5-2), membership in two tables with one writer (S5-3), messages with per-recipient rows, + DB-backed rate limit and sanitising (S5-5/6), rankings computed per request with a 5 s footprint cache (S5-7/R1). +- Migration 004 (b18645d): Internet exchange trade (T1): offers with escrow, one link per side, 1:2 ratio band, accept = two + transports in one transaction, conservation asserted in tests; shared report folder (T2); `alliedIncoming` (G2). +- Client (b18645d, 931f59e): alliance, messages, rankings, trade (Exchange) screens, `SocUI`, all player text via `textContent`. + +## Open +- Alliance rename/description and note editing have no UI; no operator profile page; no sitter accounts; no message retention job + beyond the report/notification pruning. +- Trade: no order book, price history, counter-offers, multi-link deals, or "new offer in reach" notification; escrow refunds are + clipped at the Rack hall cap without a notice (S2); the escrow of a taken-over POP goes to the conqueror. +- The `SOCIAL` numbers (limits, TTLs, role table) are first guesses. diff --git a/docs/workflows/stage-6-push-polish.md b/docs/workflows/stage-6-push-polish.md new file mode 100644 index 0000000..aa51e47 --- /dev/null +++ b/docs/workflows/stage-6-push-polish.md @@ -0,0 +1,21 @@ +# Stage 6: push and polish + +**Goal:** WebSocket push, a notifications table, PWA, layout matrix, i18n nb/en. + +**Done when:** the game is fully playable with push disconnected; hints leave only after the transaction that caused them +committed; the layout holds on phone portrait/landscape and desktop; every notification type and error code has en + nb text. + +## Built +- `/ws` (b18645d): auth as the first message, Origin check, per-IP cap, 1 KB frames, token bucket, ping/pong with token re-check, + graceful 1001 on shutdown; hints `town`, `incoming`, `notification`, `report`, `message` (docs/PROTOCOL.md). Post-commit outbox (S6-1); + revocation polled, not pushed (S6-2); hints merged per tick (S6-3). +- Client `ws.js`: backoff 1..60 s, close-code handling, refetch after every `ready`; poll fallback (45 s down, 3 min up). Measured in + headless Chromium: incoming banner 214 ms after launch; fallback about 52 s. +- i18n en + nb with parity tests over every error `CODE` and every notification type (`test/client-alerts.test.js`). +- Smoke e2e (cc0524d): `e2e/run.js`, playwright-core, 61 checks, desktop, phone touch, layout matrix on 5 viewports. + +## Open +- No service worker (no offline mode), no light theme, no sound or system notifications, no APNs/FCM sender. +- Never run behind nginx Proxy Manager (upgrade headers, idle timeouts, real client IPs); real devices and Safari never run. +- Hint gaps: no `incoming` for confederates, no `town` hint for reinforcing owners, no `backbone_open` push (E2). +- Unread-badge state partly in localStorage; ended-world locking is a DOM sweep, not per-button wiring. diff --git a/docs/workflows/stage-7-ops-balance.md b/docs/workflows/stage-7-ops-balance.md new file mode 100644 index 0000000..9c6ea19 --- /dev/null +++ b/docs/workflows/stage-7-ops-balance.md @@ -0,0 +1,24 @@ +# Stage 7: ops and balance + +**Goal:** bot-driven balance passes, an admin CLI, a world lifecycle (start, end, reset), load test with bots, full e2e. + +**Done when (CLAUDE.md):** `tools/bot.js` runs N bots for X simulated days in seconds and balance claims cite a run; `tools/admin.js` +creates, ends and resets worlds; the deploy runs on the real target; a human has played a world. + +## Built +- `tools/bot.js` + `tools/bot/*` (931f59e): 50 bots x 14 days in about 3 s, 170 days in about 140 s, real server in-process with a + fake clock; exact resource and unit conservation, exit 1 when an invariant breaks. `docs/BALANCE.md` holds method and every run. +- Tuned with before/after runs: B1 second build slot at Core router 3, B2 transport 1000 per link, B4 early-level build discount, + B5 start stock 1000 (bf7af06). Server fix found by the harness: bounced shipments reported no overflow (B3). +- Admin CLI (status, migrate, worlds, create/end/reset-world, users, ban, inspect, events, replay-events, backup/verify-backup, + grant), deploy units, backup timer, DEPLOY.md. `end-world` now runs the real `worldEnd` handler (final ranking, escrow back, + events cancelled); quiet on a closed stdout pipe. +- Ops scripts: `deploy/update.sh` (backup, fast-forward, health check, rollback), `deploy/upstream-offsite.{service,timer}` + (off-box copy of the newest verified snapshot). Tests with stubs: `test/deploy-update.test.js`, `test/deploy-offsite.test.js`. + +## Open +- **Not balanced.** Bots are not humans. A 3x world's end game is as long as a 1x world's; raid loot splits evenly and is destroyed + on overflow; no fight for a built-up landing site (E1); the capital runs out of builds before the backbone opens. +- No load test over HTTP/WebSocket with many real sockets; the full e2e suite beyond the smoke run; no scheduled "create next world". +- Never run: Node 22.13 (the stated minimum), the update script or the off-site copy against real systemd/ssh, the backup timer on + its own, nginx Proxy Manager, a restore on the real box. diff --git a/e2e/flows.js b/e2e/flows.js new file mode 100644 index 0000000..d73556f --- /dev/null +++ b/e2e/flows.js @@ -0,0 +1,911 @@ +'use strict'; +/* + * Feature flows for the e2e (run through e2e/run.js): units, movements + reports, alliance + messages, trade, end game, Norwegian, + * PWA, reconnect and the polling fallback. Every flow drives the real UI in real Chromium against the in-process server and, where + * the UI is not the point, seeds what a long game would have built (buildings, units) straight into the DB, like the push suite. + * + * How a check can fail (so it cannot pass by accident): each check asserts something the page could not show before the action + * (the "before" state is asserted too), reads the database where the UI could lie, and the flows that depend on an acceleration + * (hurryMovement / hurryEvents) assert that it was needed (the countdown was on screen first). + */ +const L = require('./lib.js'); +const { check, group, sleep, PROFILES, noErrors, tapper, openFromMore, hurryMovement, hurryEvents, latestMovement, R } = L; + +const DAY = 24 * 3600 * 1000; +const uniq = () => String(Date.now() % 1e6) + Math.floor(Math.random() * 90 + 10); +const COUNTDOWN = /\d+:\d\d|\d+\s?[smh]\b/; // 0:07, 12 s, 3 min ... + +// Two players next to each other in a slow world: attacker has units, no beginner protection on either side. +function armedPair(S, nameA, nameB, units) { + return Promise.all([S.signup(nameA), S.signup(nameB)]).then(([a, b]) => { + const aT = S.db.get('SELECT * FROM towns WHERE id = ?', a.townId); + L.placeTown(S, b.townId, aT.x + 4, aT.y + 1); + S.db.run('UPDATE operators SET protection_until = 0'); + L.setBuildings(S, a.townId, { core_router: 10, ops_lab: 6, noc: 5, rack_hall: 6, battery_bank: 6 }); + for (const k of ['f13', 'f14', 'f15', 'f16']) S.db.run('UPDATE buildings SET level = 8 WHERE town_id = ? AND key = ?', a.townId, k); + S.db.run('UPDATE towns SET battery = 900, footprint = 100 WHERE id = ?', a.townId); + L.giveUnits(S, a.townId, units || { script_crew: 40, port_scanner: 6 }); + return { a, b, aT, bT: S.db.get('SELECT * FROM towns WHERE id = ?', b.townId) }; + }); +} + +// Navigate with the bottom bar (real clicks) to one of the five bar screens. +async function goBar(page, id, touch) { + await tapper(page, touch)('#nav [data-screen="' + id + '"]'); + await page.waitForSelector('[data-screen="' + id + '"]:not([hidden])', { timeout: 5000 }); +} +const sheetClosed = (page) => page.waitForSelector('.sheet', { state: 'detached', timeout: 5000 }); +const text = (page, sel) => page.innerText(sel).then((t) => t.replace(/\s+/g, ' ').trim()); +const navBadge = (page, id) => page.evaluate((i) => { const b = document.querySelector('#nav [data-screen="' + i + '"] .nav-badge'); return b && !b.hidden ? b.textContent.trim() : ''; }, id); + + +// ---- Norwegian sweep of pages that already hold real data (reports, alliance, offers, sites): used at the end of several suites. +async function nbScan(p, where, attrs) { + await sleep(450); + const r = await p.evaluate(nbLeaks, { attrs: attrs !== false }); + return r.raw.length || r.english.length ? where + ': raw keys ' + JSON.stringify(r.raw.slice(0, 5)) + ' English ' + JSON.stringify(r.english.slice(0, 5)) : null; +} +// Visit a screen in Norwegian and scan it, then run each [name, fn] step (open a sheet, switch a tab...) and scan again. +async function nbVisit(p, id, steps) { + await p.evaluate((i) => App.go(i), id); + await p.waitForSelector('[data-screen="' + id + '"]:not([hidden])'); + await sleep(500); + const out = []; + const r0 = await nbScan(p, id); if (r0) out.push(r0); + for (const [name, fn] of steps || []) { await fn(); const r = await nbScan(p, id + ' > ' + name); if (r) out.push(r); } + return out; +} +// Switch to Norwegian the way a player keeps it: the choice is stored and the page is reloaded, so every screen renders fresh in nb. +// (Switching live on screens that were already drawn is covered, for visible text, by the Norwegian suite.) +async function nbOn(p) { + await p.evaluate(() => App.setLang('nb')); + await p.reload(); + await p.waitForSelector('#nav:not([hidden])', { timeout: 15000 }); + await p.waitForFunction(() => document.documentElement.lang === 'nb'); +} + +// ================================================================== 5. units +async function suiteUnits(browser, S, U) { + group('5. units: train through the UI, queue + countdown, completion, home and stationed lists'); + const { a, b } = U; + const P = await L.openSignedIn(browser, S, a, PROFILES.desktop); + const { page } = P; + // The attacker's POP already has seeded crews (home list is never empty), so use the POP with fewer: a third player trains from scratch. + const c = await S.signup('Trainer' + uniq()); + L.setBuildings(S, c.townId, { noc: 3, ops_lab: 3 }); + S.db.run('UPDATE towns SET battery = 900, footprint = 100 WHERE id = ?', c.townId); + await P.ctx.close(); + const Q = await L.openSignedIn(browser, S, c, PROFILES.desktop, '#/units'); + const q = Q.page; + const before = {}; + await check('units screen: empty home list, trainable rows from the server, nothing queued', async () => { + await q.waitForSelector('[data-screen="units"]:not([hidden]) .mil-train[data-unit="script_crew"]'); + before.home = await text(q, '[data-screen="units"] .col:first-child .empty'); + if (!/./.test(before.home)) return 'no empty-state text for the home list'; + if (await q.locator('li.batch').count()) return 'a batch is queued before anything was trained'; + if (await q.locator('.mil-train.locked').count() < 3) return 'expected the high-tier units to be locked for a fresh POP'; + if (await q.locator('.mil-train[data-unit="script_crew"].locked').count()) return 'script_crew is locked although Ops lab 3 is built'; + }); + await check('train 2 script crews: sheet previews cost and time, queue shows the batch with a countdown', async () => { + await q.click('.mil-train[data-unit="script_crew"]'); + await q.waitForSelector('.sheet .mil-num'); + await q.fill('.sheet .mil-num', '2'); + const costs = await text(q, '.sheet .costs'); + if (!/160/.test(costs)) return 'cost preview did not scale to 2 units: ' + costs; // 2 x 80 fiber + const btnOff = await q.$eval('.sheet .btn.primary', (b) => b.disabled); + if (btnOff) return 'train button disabled although the POP can afford 2'; + await q.click('.sheet .btn.primary'); + await sheetClosed(q); + await q.waitForSelector('li.batch', { timeout: 5000 }); + const row = await text(q, 'li.batch'); + if (!/× 2/.test(row)) return 'queue row misses the count: ' + row; + if (!COUNTDOWN.test(row)) return 'queue row shows no countdown: ' + row; + const ev = S.db.get("SELECT payload FROM events WHERE type = 'trainDone' AND status = 'pending' AND town_id = ?", c.townId); + if (!ev) return 'the server has no pending trainDone event'; + const pill = await text(q, '[data-screen="units"] .card:has(li.batch) .card-head .pill'); + if (pill !== '1') return 'queue count pill is ' + pill; + }); + await check('the batch completes (event moved up): queue empties, units appear in the home list', async () => { + hurryEvents(S, 'trainDone', c.townId, 2000); + await q.waitForFunction(() => !document.querySelector('li.batch'), null, { timeout: 15000 }); + await q.waitForSelector('[data-screen="units"] li.unit', { timeout: 8000 }); + const row = await text(q, '[data-screen="units"] li.unit'); + if (!/× 2/.test(row)) return 'home list shows ' + row; + const n = S.db.get("SELECT count FROM town_units WHERE town_id = ? AND unit = 'script_crew'", c.townId); + if (!n || n.count !== 2) return 'database has ' + JSON.stringify(n); + if (await q.locator('[data-screen="units"] .col:first-child .empty').count()) return 'the home list still shows its empty-state text'; + }); + await check('a failed train is explained: not enough resources keeps the button disabled', async () => { + S.db.run('UPDATE towns SET fiber = 5, res_at = ? WHERE id = ?', Date.now(), c.townId); + await q.evaluate(() => App.refreshTown()); + await q.click('.mil-train[data-unit="script_crew"]'); + await q.waitForSelector('.sheet .btn.primary'); + await q.waitForFunction(() => { const b = document.querySelector('.sheet .btn.primary'); const r = document.querySelector('.sheet .reason'); return b && b.disabled && r && !r.hidden && r.textContent.trim().length > 3; }, null, { timeout: 4000 }); + await q.keyboard.press('Escape'); + }); + await check('stationed units: reinforcements hosted here are listed, "send home" removes them and starts a return', async () => { + const aT = S.db.get('SELECT * FROM towns WHERE id = ?', a.townId); + S.db.run('INSERT INTO stationed (host_town_id, owner_town_id, unit, count) VALUES (?, ?, ?, ?)', c.townId, b.townId, 'soc_analyst', 7); + await q.evaluate(() => App.refreshTown()); + await q.waitForFunction(() => /7/.test((document.querySelector('[data-screen="units"]') || {}).innerText || '') && !!document.querySelector('[data-screen="units"] .mil-group'), null, { timeout: 5000 }); + const grp = await text(q, '[data-screen="units"] .mil-group'); + if (!/soc/i.test(grp) && !/analyst/i.test(grp)) return 'group does not name the unit: ' + grp; + if (!new RegExp(b.name).test(grp)) return 'group does not name the owner: ' + grp; + await q.click('[data-screen="units"] .mil-group .btn'); + await q.waitForFunction(() => !document.querySelector('[data-screen="units"] .mil-group'), null, { timeout: 6000 }); + const left = S.db.get('SELECT COUNT(*) AS n FROM stationed WHERE host_town_id = ?', c.townId).n; + if (left !== 0) return 'stationed row still in the database'; + const ret = S.db.get("SELECT * FROM movements WHERE type = 'return' AND to_town_id = ? ORDER BY id DESC LIMIT 1", b.townId); + if (!ret) return 'no return movement for the owner'; + void aT; + }); + await check('units page: no console errors', async () => noErrors(Q)); + await Q.ctx.close(); +} + +// ================================================================== 6. movements + reports +async function suiteMovements(browser, S, U) { + group('6. movements and reports: scan + raid through the send dialog, outgoing list, arrival, report, incoming banner'); + const { a, b, bT } = U; + const A = await L.openSignedIn(browser, S, a, PROFILES.desktop, '#/movements', { keepLang: true }); + const B = await L.openSignedIn(browser, S, b, PROFILES.desktop, '#/pop', { keepLang: true }); + const ap = A.page, bp = B.page; + const label = (p, type) => p.evaluate((t) => App.mil.typeLabel(t), type); + async function sendThroughDialog(type, wantUnit, count) { + await ap.click('[data-screen="movements"] .head-actions .btn.primary'); // Send + await ap.waitForSelector('.sheet .send-coords'); + await ap.fill('.sheet input[aria-label="x"]', String(bT.x)); + await ap.fill('.sheet input[aria-label="y"]', String(bT.y)); + await ap.click('.sheet .send-coords .btn'); // Look up + await ap.waitForSelector('.sheet .send-target .pill-row'); + const tgt = await text(ap, '.sheet .send-target'); + if (!tgt.includes(bT.name)) throw new Error('target card does not show the defender POP: ' + tgt); + const lbl = await label(ap, type); + await ap.click('.sheet .seg-btn:has-text("' + lbl + '")'); + await ap.waitForFunction((l) => [...document.querySelectorAll('.sheet .seg-btn')].some((x) => x.textContent.trim() === l && x.getAttribute('aria-pressed') === 'true'), lbl, { timeout: 3000 }); + const pick = ap.locator('.sheet .mil-pick', { hasText: wantUnit }); + if (!(await pick.count())) throw new Error('no unit picker for ' + wantUnit); + if (await ap.locator('.sheet .send-preview').count()) throw new Error('a preview is shown before any unit is picked'); + await pick.locator('input[type=number]').fill(String(count || 1)); + await ap.waitForSelector('.sheet .send-preview', { timeout: 3000 }); + const prev = await text(ap, '.sheet .send-preview'); + if (!/\d/.test(prev)) throw new Error('no preview numbers: ' + prev); + if (await ap.$eval('.sheet .send-foot .btn.primary', (x) => x.disabled)) throw new Error('send button disabled: ' + (await text(ap, '.sheet .send-warn'))); + await ap.click('.sheet .send-foot .btn.primary'); + await sheetClosed(ap); + } + const stat = { raidId: 0, scanId: 0 }; + await check('defender: no banner, Moves badge empty before anything is sent', async () => { + await bp.waitForFunction(() => window.App && App.ws && App.ws.open, null, { timeout: 10000 }); + const vis = await bp.evaluate(() => { const el = document.querySelector('.mil-banner'); return !!el && !el.hidden && el.innerText.trim().length > 0; }); + if (vis) return 'banner visible before any send'; + if (await navBadge(bp, 'movements')) return 'badge visible before any send'; + }); + await check('attacker: scan through the send dialog shows up in the outgoing list with a countdown and a recall button', async () => { + await sendThroughDialog('scan', 'Port scanner', 3); + await ap.waitForSelector('[data-screen="movements"] li.out.type-scan', { timeout: 6000 }); + const row = await text(ap, '[data-screen="movements"] li.out.type-scan'); + if (!row.includes(bT.name)) return 'row does not name the target: ' + row; + if (!COUNTDOWN.test(row)) return 'no countdown in ' + row; + if (!(await ap.locator('li.out.type-scan .mil-recall').count())) return 'no recall button in the first 90 s'; + const mv = latestMovement(S, a.operatorId, 'scan'); + if (!mv) return 'no scan movement in the database'; + stat.scanId = mv.id; + }); + await check('attacker: raid through the send dialog, 20 crews, outgoing list has both legs', async () => { + await sendThroughDialog('raid', 'Script', 20); + await ap.waitForSelector('[data-screen="movements"] li.out.type-raid', { timeout: 6000 }); + const n = await ap.locator('[data-screen="movements"] li.out').count(); + if (n !== 2) return 'expected 2 outgoing rows, got ' + n; + const mv = latestMovement(S, a.operatorId, 'raid'); + if (!mv) return 'no raid movement in the database'; + stat.raidId = mv.id; + const units = JSON.parse(mv.units); + if (!(units.script_crew > 0)) return 'raid has no crews: ' + mv.units; + }); + await check('defender: incoming banner (2 movements, hidden type) and Moves badge by push, no reload', async () => { + await bp.waitForFunction(() => { const el = document.querySelector('.mil-banner'); return !!el && !el.hidden && el.innerText.trim().length > 0; }, null, { timeout: 6000, polling: 100 }); + const banner = await text(bp, '.mil-banner'); + if (!banner.includes('Alice') && !banner.includes(a.name)) return 'banner does not name the attacker: ' + banner; + if (!/2/.test(banner)) return 'banner does not count 2 incoming: ' + banner; + if (/raid|scan/i.test(banner)) return 'banner leaks the movement type: ' + banner; + await bp.waitForFunction(() => { const b = document.querySelector('#nav [data-screen="movements"] .nav-badge'); return b && !b.hidden && b.textContent.trim() === '2'; }, null, { timeout: 4000 }); + }); + await check('defender: Moves screen lists the incoming movements in red with origin and ETA, type unknown', async () => { + await goBar(bp, 'movements'); + await bp.waitForSelector('[data-screen="movements"] li.incoming'); + const n = await bp.locator('[data-screen="movements"] li.incoming').count(); + if (n !== 2) return 'expected 2 incoming rows, got ' + n; + const row = await text(bp, '[data-screen="movements"] li.incoming'); + if (!row.includes(a.name)) return 'incoming row does not name the attacker: ' + row; + if (/script|scanner/i.test(row)) return 'incoming row leaks the units: ' + row; + }); + await check('both movements arrive: banner goes away, reports unread on both sides (More badge)', async () => { + hurryMovement(S, stat.scanId, 2000); + hurryMovement(S, stat.raidId, 2600); + await bp.waitForFunction(() => App.mil && App.mil.reportsUnread > 0, null, { timeout: 15000, polling: 100 }); + await ap.waitForFunction(() => App.mil && App.mil.reportsUnread >= 2, null, { timeout: 15000, polling: 100 }); + await bp.waitForFunction(() => !document.querySelector('[data-screen="movements"] li.incoming'), null, { timeout: 6000 }); + if (!(await navBadge(ap, 'more'))) return 'attacker More badge is empty with unread reports'; + }); + await check('attacker: Reports screen lists the scan and the raid, unread; opening the raid shows verdict, units and loot', async () => { + await openFromMore(ap, false, 'reports', 'Reports'); + await ap.waitForSelector('[data-screen="reports"] button.alert.rep'); + const n = await ap.locator('[data-screen="reports"] button.alert.rep').count(); + if (n < 2) return 'expected >= 2 reports, got ' + n; + const unread = await ap.locator('[data-screen="reports"] button.alert.rep.new').count(); + if (unread !== n) return unread + ' of ' + n + ' reports are marked new'; + const raidBtn = ap.locator('[data-screen="reports"] button.alert.rep', { hasText: bT.name }).filter({ hasText: /Raid|Phishing/i }); + if (!(await raidBtn.count())) return 'no raid report row naming ' + bT.name + ': ' + (await text(ap, '[data-screen="reports"] ul.alert-list')); + await raidBtn.first().click(); + await ap.waitForSelector('.sheet .rep-verdict', { timeout: 5000 }); + const body = await text(ap, '.sheet .rep-detail'); + if (!body.includes(bT.name)) return 'report does not name the target POP: ' + body; + if (!/script/i.test(body)) return 'report lists no crews: ' + body; + await ap.keyboard.press('Escape'); + await ap.waitForFunction((len) => document.querySelectorAll('[data-screen="reports"] button.alert.rep.new').length < len, n, { timeout: 5000 }); + const row = S.db.get('SELECT COUNT(*) AS n FROM report_recipients WHERE user_id = ? AND read_at IS NOT NULL', a.userId); + if (!row || row.n !== 1) return 'server read flags after opening exactly one report: ' + JSON.stringify(row); + }); + await check('attacker: scan report opens from the list and says what it found', async () => { + const scanBtn = ap.locator('[data-screen="reports"] button.alert.rep', { hasText: /scan/i }).first(); + if (!(await scanBtn.count())) return 'no scan row'; + await scanBtn.click(); + await ap.waitForSelector('.sheet .rep-verdict', { timeout: 5000 }); + const body = await text(ap, '.sheet .rep-detail'); + if (!body.includes(bT.name)) return 'scan report does not name ' + bT.name + ': ' + body; + await ap.keyboard.press('Escape'); + }); + await check('defender: the raid report is in the Reports screen from the defender side', async () => { + await openFromMore(bp, false, 'reports', 'Reports'); + await bp.waitForSelector('[data-screen="reports"] button.alert.rep'); + const row = await text(bp, '[data-screen="reports"] button.alert.rep'); + if (!/Raid|Phishing/i.test(row)) return 'defender sees ' + row; + await bp.click('[data-screen="reports"] button.alert.rep'); + await bp.waitForSelector('.sheet .rep-verdict'); + const body = await text(bp, '.sheet .rep-detail'); + if (!/defender/i.test(body)) return 'detail does not tell the defender role: ' + body; + await bp.keyboard.press('Escape'); + }); + await check('Norwegian, with data on screen: reports list + raid and scan report sheets, movements, units, alerts (attacker) and the defender report: no raw keys, no English', async () => { + const out = []; + const openRows = (p, n) => async () => { for (let i = 0; i < n; i++) { const rows = p.locator('[data-screen="reports"] button.alert.rep'); await rows.nth(i).click(); await p.waitForSelector('.sheet .rep-verdict'); const r = await nbScan(p, 'report sheet ' + i); if (r) out.push(r); await p.keyboard.press('Escape'); await sheetClosed(p); } }; + await nbOn(ap); await nbOn(bp); + out.push(...await nbVisit(ap, 'reports', [['all report sheets', openRows(ap, 2)]])); + out.push(...await nbVisit(ap, 'movements')); + out.push(...await nbVisit(ap, 'units')); + out.push(...await nbVisit(ap, 'alerts')); + out.push(...await nbVisit(bp, 'reports', [['defender report sheet', openRows(bp, 1)]])); + out.push(...await nbVisit(bp, 'alerts')); + return out.length ? out.join('\n') : true; + }); + await check('movements pages: no console errors', async () => { const r = noErrors(A); return r === true ? noErrors(B) : r; }); + await A.ctx.close(); await B.ctx.close(); +} + + +// ================================================================== reconnect + polling fallback +// Wraps WebSocket so the test can see every socket the client opens, close one from the "network", and refuse new ones for a while. +const WS_SPY = () => { + const Native = window.WebSocket; + window.__socks = []; window.__wsBlock = false; + window.WebSocket = class extends Native { constructor(...a) { if (window.__wsBlock) throw new Error('ws blocked by e2e'); super(...a); window.__socks.push(this); } }; +}; +const WS_OFF = () => { window.WebSocket = undefined; }; // a browser or proxy without WebSocket: only the REST poll is left +const bannerShown = (p) => p.evaluate(() => { const el = document.querySelector('.mil-banner'); return !!el && !el.hidden && el.innerText.trim().length > 0; }); +const bannerWait = (p, ms) => p.waitForFunction(() => { const el = document.querySelector('.mil-banner'); return !!el && !el.hidden && el.innerText.trim().length > 0; }, null, { timeout: ms, polling: 100 }); + +async function suiteReconnect(browser, S) { + group('7. reconnect: the socket dies mid-session, the client reconnects, catches up what it missed, push works again'); + const { a, b } = await armedPair(S, 'Carol' + uniq(), 'Dave' + uniq(), { script_crew: 60 }); + const P = await L.openSignedIn(browser, S, b, PROFILES.desktop, '#/pop', { init: WS_SPY }); + const p = P.page; + const raid = (n) => S.api('/movements', 'POST', { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: n }, confirmEndProtection: true }, a.token); + let n0 = 0; + await check('socket is open, the page holds exactly one', async () => { + await p.waitForFunction(() => App.ws && App.ws.open, null, { timeout: 10000 }); + n0 = await p.evaluate(() => window.__socks.length); + if (n0 !== 1) return 'expected 1 socket, saw ' + n0; + }); + await check('connection drops (socket closed, new ones refused): client notices and is not open', async () => { + await p.evaluate(() => { window.__wsBlock = true; window.__socks[window.__socks.length - 1].close(); }); + await p.waitForFunction(() => App.ws && !App.ws.open, null, { timeout: 5000 }); + if (await bannerShown(p)) return 'banner before any raid'; + }); + await check('a raid launched during the gap is not shown yet (nothing can reach the page), the page stays usable', async () => { + await raid(20); + await sleep(2500); + if (await bannerShown(p)) return 'banner appeared while the socket was down (and the REST poll is 45 s away): the test would not prove the catch-up'; + await p.click('#nav [data-screen="map"]'); // still usable offline + await p.waitForSelector('[data-screen="map"]:not([hidden]) .map-canvas'); + await p.click('#nav [data-screen="pop"]'); + await p.waitForSelector('.town-name'); + }); + await check('network back: client reconnects with a NEW socket and catches up (banner for the missed raid) without a reload', async () => { + await p.evaluate(() => { window.__noReload = 'still-here'; window.__wsBlock = false; }); + await p.waitForFunction(() => App.ws && App.ws.open, null, { timeout: 25000 }); + const n1 = await p.evaluate(() => window.__socks.length); + if (n1 <= n0) return 'no new socket was opened (' + n0 + ' -> ' + n1 + ')'; + await bannerWait(p, 6000); + const banner = await text(p, '.mil-banner'); + if (!banner.includes(a.name)) return 'banner does not name the attacker: ' + banner; + }); + await check('after the reconnect a NEW raid shows by push (<= 6 s, socket open, no reload): the new socket really delivers', async () => { + await sleep(1500); // let the on-ready refetch settle: the next banner change must be push + const before = await text(p, '.mil-banner'); + await raid(10); + await p.waitForFunction((b0) => { const el = document.querySelector('.mil-banner'); return el && !el.hidden && el.innerText.replace(/\s+/g, ' ').trim() !== b0; }, before, { timeout: 6000, polling: 100 }); + if (!(await p.evaluate(() => App.ws.open))) return 'socket not open: it came from polling'; + if ((await p.evaluate(() => window.__noReload)) !== 'still-here') return 'page was reloaded'; + const banner = await text(p, '.mil-banner'); + if (!/2/.test(banner)) return 'banner does not count both raids: ' + banner; + }); + await check('reconnect page: no console errors', async () => noErrors(P)); + await P.ctx.close(); +} + +// Slow: no WebSocket at all. The incoming raid must still show up through the REST poll (45 s gap, 15 s tick). +async function suiteSlow(browser) { + group('9. (slow) push fallback: WebSocket unavailable, the incoming raid still appears by polling'); + const S = await L.bootServer({ speed: 1 }); + try { + const { a, b } = await armedPair(S, 'Erin' + uniq(), 'Finn' + uniq(), { script_crew: 40 }); + const P = await L.openSignedIn(browser, S, b, PROFILES.desktop, '#/pop', { init: WS_OFF }); + const p = P.page; + let sentAt = 0; + await check('page runs without any WebSocket: client reports not open', async () => { + await sleep(1200); + if (await p.evaluate(() => !!(App.ws && App.ws.open))) return 'a socket is open although WebSocket was removed'; + if (await bannerShown(p)) return 'banner before any raid'; + await p.evaluate(() => { window.__noReload = 'still-here'; }); + }); + await check('raid is sent; the banner is NOT shown within 8 s (no push), then appears by polling within 75 s, same page', async () => { + sentAt = Date.now(); + await S.api('/movements', 'POST', { fromTownId: a.townId, type: 'raid', toTownId: b.townId, units: { script_crew: 20 }, confirmEndProtection: true }, a.token); + await sleep(8000); + if (await bannerShown(p)) return 'banner appeared within 8 s: that is not the polling path'; + await bannerWait(p, 75000); + const ms = Date.now() - sentAt; + if ((await p.evaluate(() => window.__noReload)) !== 'still-here') return 'page was reloaded'; + if (await p.evaluate(() => !!App.ws.open)) return 'socket opened'; + console.log(' (banner by polling after ' + Math.round(ms / 1000) + ' s)'); + }); + await check('fallback page: no console errors', async () => noErrors(P)); + await P.ctx.close(); + } finally { await S.close(); } +} + + +// ================================================================== 8. alliance + messages +async function suiteAlliance(browser, S) { + group('10. alliance: found, invite, accept, a message to the alliance, read on the other page (badge, feed)'); + const a = await S.signup('Ally' + uniq()), b = await S.signup('Beau' + uniq()); + for (const u of [a, b]) L.setBuildings(S, u.townId, { peering_office: 1 }); + const tag = 'T' + uniq().slice(-3), name = 'Blue Team ' + uniq(); + const A = await L.openSignedIn(browser, S, a, PROFILES.desktop, '#/pop', { keepLang: true }); + const B = await L.openSignedIn(browser, S, b, PROFILES.desktop, '#/pop', { keepLang: true }); + const ap = A.page, bp = B.page; + await check('not in an alliance yet: the screen offers founding, the create button is disabled until name and tag are valid', async () => { + await openFromMore(ap, false, 'alliance', 'Alliance'); + await ap.waitForSelector('#soc-name'); + if (!(await ap.$eval('.soc-card .btn.primary.wide', (x) => x.disabled))) return 'create enabled with empty fields'; + await ap.fill('#soc-name', name); await ap.fill('#soc-tag', tag); + if (await ap.$eval('.soc-card .btn.primary.wide', (x) => x.disabled)) return 'create still disabled with valid fields'; + }); + await check('found it: overview shows the name, tag, you as leader and 1 member; the server agrees', async () => { + await ap.click('.soc-card .btn.primary.wide'); + await ap.waitForSelector('.soc-head .soc-name'); + const head = await text(ap, '.soc-head'); + if (!head.includes(name) || !head.includes('[' + tag + ']')) return 'head: ' + head; + const row = S.db.get('SELECT COUNT(*) AS n FROM alliance_members WHERE operator_id = ?', a.operatorId); + if (!row || row.n !== 1) return 'server has no membership row for the founder'; + }); + await check('invite the other player by name from the Members tab: pending list shows them', async () => { + await ap.click('.soc-tabs [data-tab="members"]'); + await ap.waitForSelector('.soc-inline input'); + await ap.fill('.soc-inline input', b.name); + await ap.click('.soc-inline .btn.primary'); + await ap.waitForFunction((n) => [...document.querySelectorAll('.soc-content .soc-item')].some((x) => x.innerText.includes(n)), b.name, { timeout: 5000 }); + }); + await check('invitee: the invitation is on the Alliance screen; accepting makes them a member (2 of N)', async () => { + await openFromMore(bp, false, 'alliance', 'Alliance'); + await bp.waitForSelector('.soc-invite'); + const inv = await text(bp, '.soc-invite'); + if (!inv.includes(name)) return 'invite card: ' + inv; + await bp.click('.soc-invite .btn.primary'); + await bp.waitForSelector('.soc-head .soc-name'); + const head = await text(bp, '.soc-head'); + if (!head.includes(name) || !/2/.test(head)) return 'head after joining: ' + head; + await bp.click('.soc-tabs [data-tab="members"]'); + await bp.waitForFunction((n) => document.querySelectorAll('.soc-member').length === 2 && document.body.innerText.includes(n), a.name, { timeout: 5000 }); + }); + const msg = 'Hold the line ' + uniq(); + let moreBefore = 0; + await check('before: the invitee has no unread message (the More badge may carry alerts, it must not carry messages)', async () => { + await bp.click('#nav [data-screen="pop"]'); + await bp.waitForSelector('.town-name'); + await sleep(1200); // the unread poll runs at session start + const unread = await bp.evaluate(() => App.state.unreadMsgs || 0); + if (unread !== 0) return 'unread messages before any was sent: ' + unread; + moreBefore = Number(await navBadge(bp, 'more')) || 0; + }); + await check('leader writes to the alliance (Messages > Alliance tab > composer)', async () => { + await openFromMore(ap, false, 'messages', 'Messages'); + await ap.click('[data-screen="messages"] .soc-tabs [data-tab="alliance"]'); + await ap.waitForSelector('[data-screen="messages"] .soc-composer textarea'); + await ap.fill('[data-screen="messages"] .soc-composer textarea', msg); + await ap.click('[data-screen="messages"] .soc-composer .btn.primary'); + await ap.waitForFunction((m) => [...document.querySelectorAll('[data-screen="messages"] .soc-feed')].some((x) => x.innerText.includes(m)), msg, { timeout: 5000 }); + }); + await check('invitee page (no reload): unread badge appears on More within 6 s (push hint)', async () => { + await bp.waitForFunction((n0) => { const b = document.querySelector('#nav [data-screen="more"] .nav-badge'); return App.state.unreadMsgs === 1 && b && !b.hidden && Number(b.textContent) > n0; }, moreBefore, { timeout: 6000, polling: 100 }); + }); + await check('invitee: Messages screen shows the broadcast as unread in the Alliance feed with the sender; reading clears the badge', async () => { + await openFromMore(bp, false, 'messages', 'Messages'); + await bp.click('[data-screen="messages"] .soc-tabs [data-tab="alliance"]'); + await bp.waitForSelector('[data-screen="messages"] .soc-feed'); + const row = await text(bp, '[data-screen="messages"] .soc-feed'); + if (!row.includes(msg)) return 'feed row: ' + row; + if (!row.includes(a.name)) return 'feed row does not name the sender: ' + row; + const wasUnread = await bp.locator('[data-screen="messages"] .soc-feed.unread').count(); + if (!wasUnread) return 'the broadcast is not marked unread'; + await bp.click('[data-screen="messages"] .soc-tabs [data-tab="inbox"]'); + await bp.click('[data-screen="messages"] .soc-toolbar .btn'); // mark all read + await bp.waitForFunction((n0) => { const b = document.querySelector('#nav [data-screen="more"] .nav-badge'); return App.state.unreadMsgs === 0; }, moreBefore, { timeout: 6000 }); + const left = S.db.get('SELECT COUNT(*) AS n FROM message_recipients WHERE operator_id = ? AND read_at IS NULL', b.operatorId).n; + if (left !== 0) return left + ' unread rows left on the server'; + }); + await check('invitee sits on the Alliance feed: a second broadcast appears live (push), unread, without pressing refresh', async () => { + await bp.click('[data-screen="messages"] .soc-tabs [data-tab="alliance"]'); + await bp.waitForFunction((m) => [...document.querySelectorAll('[data-screen="messages"] .soc-feed')].some((x) => x.innerText.includes(m)), msg, { timeout: 4000 }); + const msg2 = 'Second wave ' + uniq(); + await S.api('/messages', 'POST', { text: msg2, toAlliance: true }, a.token); + await bp.waitForFunction((m) => [...document.querySelectorAll('[data-screen="messages"] .soc-feed')].some((x) => x.innerText.includes(m)), msg2, { timeout: 6000, polling: 100 }); + await bp.waitForFunction(() => App.state.unreadMsgs === 1, null, { timeout: 4000 }); + }); + await check('Norwegian, as alliance members: alliance overview / members / diplomacy, messages tabs: no raw keys, no English', async () => { + const out = []; + const tab = (p, id) => async () => { await p.click('.soc-tabs [data-tab="' + id + '"]'); }; + const mtab = (p, id) => async () => { await p.click('[data-screen="messages"] .soc-tabs [data-tab="' + id + '"]'); }; + for (const p of [ap, bp]) { + await nbOn(p); + out.push(...await nbVisit(p, 'alliance', [['members', tab(p, 'members')], ['diplomacy', tab(p, 'diplomacy')]])); + out.push(...await nbVisit(p, 'messages', [['alliance', mtab(p, 'alliance')], ['sent', mtab(p, 'sent')], ['blocked', mtab(p, 'blocked')], ['inbox', mtab(p, 'inbox')]])); + } + return out.length ? out.join('\n') : true; + }); + await check('alliance pages: no console errors', async () => { const r = noErrors(A); return r === true ? noErrors(B) : r; }); + await A.ctx.close(); await B.ctx.close(); +} + +// ================================================================== 9. trade +async function suiteTrade(browser, S) { + group('11. trade: post an offer, take it from a second user, both see it complete'); + const a = await S.signup('Tara' + uniq()), b = await S.signup('Tom' + uniq()); + const aT = S.db.get('SELECT * FROM towns WHERE id = ?', a.townId); + L.placeTown(S, b.townId, aT.x + 3, aT.y + 1); + for (const u of [a, b]) { L.setBuildings(S, u.townId, { internet_exchange: 3, rack_hall: 6 }); S.db.run('UPDATE towns SET fiber = 1000, hardware = 1000, capital = 1000, res_at = ? WHERE id = ?', Date.now(), u.townId); } + const stock = (u) => S.db.get('SELECT fiber, hardware FROM towns WHERE id = ?', u.townId); + // accept refuses a taker whose Rack hall is projected full at arrival (no_room_for_goods); this world is fast, so switch the taker's fields off + S.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%'", b.townId); + const A = await L.openSignedIn(browser, S, a, PROFILES.desktop, '#/pop', { keepLang: true }); + const B = await L.openSignedIn(browser, S, b, PROFILES.desktop, '#/pop', { keepLang: true }); + const ap = A.page, bp = B.page; + const before = { a: null, b: null }; + await check('poster: Exchange > New offer, default terms (give 100 fiber, want 100 hardware) are valid, post enabled', async () => { + before.a = stock(a); before.b = stock(b); + await openFromMore(ap, false, 'trade', 'Trade'); + await ap.click('[data-screen="trade"] .trd-tabs [data-tab="new"]'); + await ap.waitForSelector('.trd-form .btn.primary'); + await ap.waitForFunction(() => { const x = document.querySelector('.trd-form .btn.primary'); return x && !x.disabled; }, null, { timeout: 6000 }); + const msgs = await text(ap, '.trd-msgs'); + if (msgs) return 'validation messages shown: ' + msgs; + }); + await check('post it: lands on "mine" with an open offer and a countdown; the escrow left the POP', async () => { + await ap.click('.trd-form .btn.primary'); + await ap.waitForSelector('li.trd-offer[data-status="open"]'); + const row = await text(ap, 'li.trd-offer[data-status="open"]'); + if (!/100/.test(row)) return 'offer row: ' + row; + const off = S.db.get("SELECT * FROM trade_offers WHERE status = 'open'"); + if (!off) return 'no open offer in the database'; + const now = stock(a); + if (!(now.fiber < before.a.fiber - 20)) return 'fiber was not escrowed: ' + before.a.fiber + ' -> ' + now.fiber; + }); + await check('taker: the offer is listed on the Offers tab with who posted it; Take opens the POP picker with a preselected POP', async () => { + await openFromMore(bp, false, 'trade', 'Trade'); + await bp.waitForSelector('[data-screen="trade"] li.trd-offer', { timeout: 8000 }); + const row = await text(bp, '[data-screen="trade"] li.trd-offer'); + if (!row.includes(a.name)) return 'offer row does not name the poster: ' + row; + await bp.click('[data-screen="trade"] li.trd-offer .btn.primary'); + await bp.waitForSelector('.trd-accept .trd-pop input:checked'); + }); + await check('accept it: sheet closes, the offer leaves the Offers list, the taker POP dispatches its 100 hardware', async () => { + await bp.click('.trd-accept .send-foot .btn.primary'); + await sheetClosed(bp); + await bp.waitForFunction(() => !document.querySelector('[data-screen="trade"] li.trd-offer'), null, { timeout: 8000 }); + const leg = S.db.get("SELECT cargo FROM movements WHERE owner_id = ? AND type = 'transport' AND status = 'out'", b.operatorId); + if (!leg || JSON.parse(leg.cargo).hardware !== 100) return 'the taker has no 100 hardware leg in flight: ' + (leg && leg.cargo); + }); + await check('both transports land (the 10 minute minimum latency is moved up): both POPs hold the swapped goods, the offer is completed', async () => { + const legs = S.db.all("SELECT id FROM movements WHERE type = 'transport' AND status = 'out'"); + if (legs.length !== 2) return 'expected 2 transport legs in flight, found ' + legs.length; + if (S.db.get("SELECT status FROM trade_offers ORDER BY id DESC LIMIT 1").status !== 'accepted') return 'offer is not in the accepted state while the goods are in flight'; + legs.forEach((m, i) => hurryMovement(S, m.id, 1500 + i * 400)); + for (let i = 0; i < 40; i++) { const o = S.db.get('SELECT status FROM trade_offers ORDER BY id DESC LIMIT 1'); if (o && o.status === 'completed') break; await sleep(250); } + const o = S.db.get('SELECT status FROM trade_offers ORDER BY id DESC LIMIT 1'); + if (!o || o.status !== 'completed') return 'offer status ' + (o && o.status); + const na = stock(a), nb = stock(b); + if (!(na.hardware > before.a.hardware + 80)) return 'poster hardware ' + before.a.hardware + ' -> ' + na.hardware; + if (!(nb.fiber > before.b.fiber + 80)) return 'taker fiber ' + before.b.fiber + ' -> ' + nb.fiber; + }); + await check('poster sees it complete: "mine" tab status completed, an alert for it, no open offers left', async () => { + await ap.click('#nav [data-screen="pop"]'); + await openFromMore(ap, false, 'trade', 'Trade'); + await ap.click('[data-screen="trade"] .trd-tabs [data-tab="mine"]'); + await ap.waitForSelector('li.trd-offer[data-status="completed"]', { timeout: 8000 }); + if (await ap.locator('li.trd-offer[data-status="open"]').count()) return 'an open offer is still listed'; + await openFromMore(ap, false, 'alerts', 'Alerts'); + await ap.waitForFunction(() => /complet|settled|fullf/i.test(document.querySelector('[data-screen="alerts"]').innerText), null, { timeout: 6000 }); + }); + await check('taker sees it complete too: "mine" tab shows their side as completed', async () => { + await bp.click('#nav [data-screen="pop"]'); + await openFromMore(bp, false, 'trade', 'Trade'); + await bp.click('[data-screen="trade"] .trd-tabs [data-tab="mine"]'); + await bp.waitForSelector('li.trd-offer[data-status="completed"]', { timeout: 8000 }); + const row = await text(bp, 'li.trd-offer[data-status="completed"]'); + if (!/100/.test(row)) return 'taker row: ' + row; + }); + await check('Norwegian, with offers on screen: every Trade tab on both pages, the alerts feed: no raw keys, no English', async () => { + const out = []; + for (const p of [ap, bp]) { + await nbOn(p); + const tab = (id) => async () => { await p.click('[data-screen="trade"] .trd-tabs [data-tab="' + id + '"]'); }; + out.push(...await nbVisit(p, 'trade', [['new', tab('new')], ['mine', tab('mine')], ['send', tab('send')], ['offers', tab('offers')]])); + out.push(...await nbVisit(p, 'alerts')); + } + return out.length ? out.join('\n') : true; + }); + await check('trade pages: no console errors', async () => { const r = noErrors(A); return r === true ? noErrors(B) : r; }); + await A.ctx.close(); await B.ctx.close(); +} + + +// ================================================================== 12. end game +async function suiteEndgame(browser) { + group('12. end game: world screen before and after the landing sites open, site list, a shipment to a held site'); + const speed = 4000; + const S = await L.bootServer({ speed }); + try { + const g = await S.signup('Gina' + uniq()), h = await S.signup('Hank' + uniq()); + const sites = R.backboneSites(S.world.seed, S.world.map_radius); + L.placeTown(S, g.townId, sites[0].x - 4, sites[0].y); + L.setBuildings(S, g.townId, { peering_office: 1, internet_exchange: 2, rack_hall: 8, core_router: 5 }); + S.db.run('UPDATE towns SET fiber = 3000, hardware = 3000, capital = 3000, res_at = ? WHERE id = ?', Date.now(), g.townId); + S.db.run('UPDATE operators SET protection_until = 0'); + const al = await S.api('/alliances', 'POST', { name: 'Gold Backbone', tag: 'GOLD' }, g.token); + const P = await L.openSignedIn(browser, S, g, PROFILES.desktop, '#/pop', { keepLang: true }); + const Q = await L.openSignedIn(browser, S, h, PROFILES.phone, '#/pop'); + const p = P.page; + await check('before day 100: banner counts down to the landing sites, the how-it-works card is shown, no sites listed', async () => { + await openFromMore(p, false, 'world', 'Backbone'); + await p.waitForSelector('.wld-banner'); + const banner = await text(p, '.wld-banner'); + if (!/appear in/i.test(banner)) return 'banner: ' + banner; + if (!(await p.locator('.wld-how li').count())) return 'no how-it-works card while running'; + if (await p.locator('li.wld-site').count()) return 'sites listed before they exist'; + if (await p.locator('.wld-banner.open').count()) return 'open banner before day 100'; + }); + await check('the world moves to day 100.5 (start date backdated, sites created like the first touch does): banner flips to open with 7 sites', async () => { + S.db.run('UPDATE worlds SET start_at = ? WHERE id = ?', Date.now() - Math.round(100.5 * DAY / speed), S.world.id); + const st = await S.api('/worlds/' + S.world.id + '/status', 'GET', undefined, g.token); + if (st.phase !== 'backbone_open' || st.sites.length !== 7) return 'server says phase ' + st.phase + ' with ' + st.sites.length + ' sites'; + const rows = require('../server/endgame').ensureSites(S.db, S.db.get('SELECT * FROM worlds WHERE id = ?', S.world.id), Date.now()); // what the first scan or attack does + if (rows.length !== 7) return 'ensureSites made ' + rows.length + ' rows'; + S.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ?, taken_at = ? WHERE world_id = ? AND idx = 0', al.allianceId, g.operatorId, Date.now(), S.world.id); + await p.click('[data-screen="world"] .page-head .icon-btn'); // refresh + await p.waitForSelector('.wld-banner.open', { timeout: 6000 }); + const n = await p.locator('li.wld-site').count(); + if (n !== 7) return 'expected 7 site cards, got ' + n; + const banner = await text(p, '.wld-banner.open'); + if (!/open/i.test(banner)) return 'banner: ' + banner; + }); + await check('site list: site 1 is held by [GOLD] and marked as yours with a Manage button; the six others are incumbent with a scan/attack button', async () => { + const mine = await text(p, 'li.wld-site.mine'); + if (!mine.includes('GOLD') || !/Landing site 1/.test(mine)) return 'site 1 card: ' + mine; + if (!(await p.locator('li.wld-site.mine .btn.primary', { hasText: 'Manage' }).count())) return 'no Manage button on the held site'; + const others = await p.locator('li.wld-site:not(.mine)').count(); + if (others !== 6) return 'expected 6 other sites, got ' + others; + const incumbents = await p.locator('li.wld-site:not(.mine) .pill.dim').count(); + if (incumbents !== 6) return 'expected 6 incumbent pills, got ' + incumbents; + if (!(await p.locator('li.wld-site:not(.mine) .btn.primary', { hasText: 'Scan or attack' }).count())) return 'no scan/attack button'; + }); + await check('another player (phone, no alliance) sees the same phase and the sites, and no Manage button', async () => { + await openFromMore(Q.page, true, 'world', 'Backbone'); + await Q.page.waitForSelector('.wld-banner.open', { timeout: 6000 }); + if ((await Q.page.locator('li.wld-site').count()) !== 7) return 'not 7 sites'; + if (await Q.page.locator('.btn', { hasText: 'Manage' }).count()) return 'a non-member is offered Manage'; + const holder = await text(Q.page, 'li.wld-site:first-child'); + if (!holder.includes('GOLD')) return 'site 1 holder not shown: ' + holder; + }); + await check('Manage opens the site sheet: level, stock (empty), the next level cost and the ship section', async () => { + await p.click('li.wld-site.mine .btn.primary'); + await p.waitForSelector('.wld-manage .wld-sec'); + const body = await text(p, '.wld-manage'); + if (!/Ship resources/i.test(body)) return 'no ship section: ' + body.slice(0, 200); + if (!(await p.locator('.wld-manage .mil-pick').count())) return 'no cargo pickers'; + }); + let shipId = 0; + await check('ship 300 fiber from the POP: toast, a site shipment appears on Moves, the POP stock drops', async () => { + const stockNow = () => p.evaluate(async () => { await App.refreshTown(); return App.resourcesNow().amounts.fiber; }); + const f0 = await stockNow(); + await p.locator('.wld-manage .mil-pick', { hasText: 'Fiber' }).locator('input[type=number]').fill('300'); + const goLabel = await p.evaluate(() => App.t('wld.ship.go')); + const go = p.locator('.wld-manage .btn.primary', { hasText: new RegExp('^\\s*' + goLabel + '\\s*$') }); + if (await go.evaluate((x) => x.disabled)) return 'ship button disabled'; + await go.click(); + await p.waitForFunction(() => /on its way/i.test(document.getElementById('toasts').innerText), null, { timeout: 5000 }); + const mv = S.db.get("SELECT * FROM movements WHERE owner_id = ? AND type = 'transport' AND status = 'out' ORDER BY id DESC LIMIT 1", g.operatorId); + if (!mv) return 'no transport movement'; + shipId = mv.id; + if (JSON.parse(mv.cargo).fiber !== 300) return 'cargo ' + mv.cargo; + const f1 = await stockNow(); + if (!(f1 < f0 - 150)) return 'fiber on screen ' + f0 + ' -> ' + f1; + await p.keyboard.press('Escape'); + await p.evaluate(() => App.go('movements')); + await p.waitForSelector('[data-screen="movements"] li.out'); + const row = await text(p, '[data-screen="movements"] li.out'); + if (!/landing site/i.test(row)) return 'moves row does not mark the site shipment: ' + row; + }); + await check('the shipment lands (10 minute minimum latency moved up): the site stockpile holds 300 fiber, the sheet shows it, the ledger names the shipper', async () => { + hurryMovement(S, shipId, 1500); + for (let i = 0; i < 40; i++) { if (S.db.get('SELECT fiber FROM landing_sites WHERE world_id = ? AND idx = 0', S.world.id).fiber === 300) break; await sleep(250); } + const f = S.db.get('SELECT fiber FROM landing_sites WHERE world_id = ? AND idx = 0', S.world.id).fiber; + if (f !== 300) return 'site stockpile has ' + f + ' fiber'; + await p.evaluate(() => App.go('world')); + await p.waitForSelector('li.wld-site.mine .btn.primary'); + await p.click('li.wld-site.mine .btn.primary'); + await p.waitForFunction(() => /300/.test(document.querySelector('.wld-manage') ? document.querySelector('.wld-manage').innerText : ''), null, { timeout: 5000 }); + const body = await text(p, '.wld-manage'); + if (!body.includes(g.name)) return 'ledger does not name ' + g.name + ': ' + body.slice(-300); + await p.keyboard.press('Escape'); + }); + await check('Norwegian, with 7 sites on screen: world screen, the Manage sheet (ship, ledger) and the scan/attack dialog: no raw keys, no English', async () => { + const out = []; + await nbOn(p); + await p.evaluate(() => App.go('world')); + await p.waitForSelector('li.wld-site.mine .btn.primary'); + out.push(...await nbVisit(p, 'world', [ + ['manage sheet', async () => { await p.click('li.wld-site.mine .btn.primary'); await p.waitForSelector('.wld-manage .wld-sec'); }], + ['closed', async () => { await p.keyboard.press('Escape'); await sheetClosed(p); }], + ['scan or attack dialog', async () => { await p.click('li.wld-site:not(.mine) .btn.primary >> nth=0'); await p.waitForSelector('.sheet .send-target .pill-row'); }], + ])); + await p.keyboard.press('Escape'); + return out.length ? out.join('\n') : true; + }); + await check('end game pages: no console errors', async () => { const r = noErrors(P); return r === true ? noErrors(Q) : r; }); + await P.ctx.close(); await Q.ctx.close(); + } finally { await S.close(); } +} + + +// ================================================================== 13. Norwegian +// Runs in the page. Finds (1) raw i18n keys on screen ("pop.build", "err.x": what t() returns for a key nobody defined) and (2) English +// leftovers: a visible string equal to the English text of a key whose Norwegian text is different. Both tables come from a snapshot taken +// before the test touched anything, so a deleted nb key is still known to be an nb key. +function nbLeaks(opts) { + if (!window.__I18N0) window.__I18N0 = JSON.parse(JSON.stringify(UpstreamI18n.strings)); + const withAttrs = !opts || opts.attrs !== false; + const snap = window.__I18N0; + const en = snap.en, nb = snap.nb; + const nbValues = new Set(Object.values(nb)); + const prefixes = Object.keys(en).map((k) => k.split('.')[0]).filter((v, i, a) => a.indexOf(v) === i); + const rawRe = new RegExp('(?:^|[^A-Za-z0-9_.])((?:' + prefixes.join('|') + ')\\.[A-Za-z][A-Za-z0-9_]*(?:\\.[A-Za-z0-9_]+)*)', 'g'); + const esc = (x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const exact = new Map(), tpl = []; + for (const k of Object.keys(en)) { + const e = en[k]; + if (nb[k] === undefined || nb[k] === e || nbValues.has(e) || !/[A-Za-z]{3}/.test(e)) continue; + if (/\{\w+\}/.test(e)) { const body = esc(e).replace(/\\\{\w+\\\}/g, '.+?').replace(/\{\w+\}/g, '.+?'); if (body.replace(/\.\+\?/g, '').replace(/\\./g, '.').trim().length >= 4) tpl.push({ k, re: new RegExp('^' + body + '$') }); } else exact.set(e, k); + } + const visible = (el) => { for (let n = el; n && n !== document.body; n = n.parentElement) { if (n.hidden || (n.getAttribute && n.getAttribute('aria-hidden') === 'true' && n.tagName !== 'SPAN')) return false; } return el.getClientRects().length > 0; }; + const raw = [], english = []; + const seen = new Set(); + const test = (txt, where) => { + txt = txt.replace(/\s+/g, ' ').trim(); + if (!txt || seen.has(where + txt)) return; + seen.add(where + txt); + let m; rawRe.lastIndex = 0; + while ((m = rawRe.exec(txt))) raw.push(m[1] + ' in "' + txt.slice(0, 60) + '"'); + if (exact.has(txt)) english.push(exact.get(txt) + ' = "' + txt + '"'); + else for (const t of tpl) if (t.re.test(txt)) { english.push(t.k + ' ~ "' + txt.slice(0, 70) + '"'); break; } + }; + for (const root of document.querySelectorAll('#app, #sheet-root')) { + const w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + for (let n = w.nextNode(); n; n = w.nextNode()) if (n.parentElement && visible(n.parentElement) && !n.parentElement.closest('script, style, [data-user]')) test(n.nodeValue, 'text'); + if (withAttrs) for (const el of root.querySelectorAll('[aria-label], [placeholder], [title]')) if (visible(el)) for (const a of ['aria-label', 'placeholder', 'title']) if (el.getAttribute(a)) test(el.getAttribute(a), a); + } + test(document.title, 'title'); + return { raw: [...new Set(raw)], english: [...new Set(english)] }; +} + +async function suiteNorwegian(browser, S) { + group('13. Norwegian: switch in Settings, main screens and dialogs have no raw keys and no English leftovers'); + const u = await S.signup('Nora' + uniq()); + const P = await L.openSignedIn(browser, S, u, PROFILES.desktop, '#/pop', { keepLang: true }); + const p = P.page; + const leaks = () => p.evaluate(nbLeaks); + const report = (r) => (r.raw.length || r.english.length ? 'raw keys: ' + JSON.stringify(r.raw.slice(0, 6)) + ' English leftovers: ' + JSON.stringify(r.english.slice(0, 6)) : true); + await check('calibration: in English the detector reports many "English leftovers" on the real POP screen (so it does see the UI text), and nav says Map', async () => { + await p.evaluate(() => { window.__I18N0 = JSON.parse(JSON.stringify(UpstreamI18n.strings)); }); + if ((await p.evaluate(() => document.documentElement.lang)) !== 'en') return 'page does not start in English'; + const kart = await text(p, '#nav [data-screen="map"]'); + if (kart !== 'Map') return 'nav label is ' + kart; + await p.waitForSelector('.tile[data-key="f1"]'); + const r = await leaks(); + if (r.english.length < 8) return 'the detector found only ' + r.english.length + ' English strings on the English POP screen: ' + JSON.stringify(r.english); + }); + await check('no multi-word Norwegian string is a verbatim copy of its English text (the detector cannot see a copy-pasted untranslated string, this does)', async () => { + const same = await p.evaluate(() => { const en = window.__I18N0.en, nb = window.__I18N0.nb; return Object.keys(en).filter((k) => en[k] === nb[k] && /[A-Za-z]{3,}\s+[A-Za-z]{2,}/.test(en[k])); }); + if (same.length) return same.length + ' strings are identical in nb and en: ' + same.slice(0, 8).join(', '); + }); + const screens = ['pop', 'map', 'units', 'movements', 'reports', 'alerts', 'rankings', 'alliance', 'messages', 'trade', 'world', 'settings']; + // Part A: the player visits every screen in English (each is drawn once), then switches language live in Settings. + // Static labels built once in render() would stay English; only visible text is compared here (stale aria-labels are reported, not failed). + for (const id of screens) await check('(setup) English screen ' + id + ' is drawn', async () => { await p.evaluate((i) => App.go(i), id); await p.waitForSelector('[data-screen="' + id + '"]:not([hidden])'); await sleep(250); }); + await check('Settings > language: tap Norsk; html lang, nav labels and the stored choice switch at once, no reload', async () => { + await p.evaluate(() => { window.__noReload = 'still-here'; }); + await openFromMore(p, false, 'settings', 'Settings'); + const label = await p.evaluate(() => App.t('settings.lang.nb')); + await p.click('[data-screen="settings"] .seg-btn:has-text("' + label + '")'); + await p.waitForFunction(() => document.documentElement.lang === 'nb', null, { timeout: 3000 }); + const nav = await p.$$eval('#nav .nav-lbl', (els) => els.map((e) => e.textContent.trim())); + const want = await p.evaluate(() => ['nav.pop', 'nav.map', 'nav.units', 'nav.movements', 'nav.more'].map((k) => window.__I18N0.nb[k])); + if (JSON.stringify(nav) !== JSON.stringify(want)) return 'nav ' + JSON.stringify(nav) + ' != ' + JSON.stringify(want); + const stored = await p.evaluate(() => localStorage.getItem('upstream.lang')); + if (stored !== 'nb') return 'stored language ' + stored; + if ((await p.evaluate(() => window.__noReload)) !== 'still-here') return 'page reloaded'; + }); + await check('nav is fully Norwegian: no label equals its English text unless both languages spell it the same (POP)', async () => { + const bad = await p.evaluate(() => { const en = window.__I18N0.en, nb = window.__I18N0.nb; const out = []; for (const b of document.querySelectorAll('#nav .nav-btn')) { const t = b.querySelector('.nav-lbl').textContent.trim(); const k = Object.keys(en).find((x) => /^nav\./.test(x) && nb[x] === t); if (!k) out.push('"' + t + '" is no nb nav label'); } return out; }); + if (bad.length) return bad.join('; '); + await p.click('#nav [data-screen="more"]'); + await p.waitForSelector('.more-list .row-btn'); + const rows = await p.$$eval('.more-list .row-title', (els) => els.map((e) => e.textContent.trim())); + const en = await p.evaluate(() => window.__I18N0.en), nbt = await p.evaluate(() => window.__I18N0.nb); + const enRows = rows.filter((r) => Object.keys(en).some((k) => /^nav\./.test(k) && en[k] === r && nbt[k] !== r)); + await p.keyboard.press('Escape'); + if (enRows.length) return 'More list has English rows: ' + enRows.join(', '); + if (rows.length < 6) return 'More list has only ' + rows.length + ' rows'; + }); + await check('detector self-test: a planted raw key and an English string on the live page are both reported; planted nb gap is reported', async () => { + await p.evaluate(() => { const d = document.createElement('div'); d.id = 'plant'; d.innerHTML = '

pop.build.nothing

Region map

err.not_enough_resources

'; document.getElementById('view').appendChild(d); }); + const r = await leaks(); + await p.evaluate(() => document.getElementById('plant').remove()); + if (!r.raw.some((x) => /pop\.build\.nothing/.test(x)) || !r.raw.some((x) => /err\.not_enough_resources/.test(x))) return 'raw keys not found: ' + JSON.stringify(r); + if (!r.english.some((x) => /Region map/.test(x))) return 'English leftover not found: ' + JSON.stringify(r); + await p.evaluate(() => { const nb = UpstreamI18n.strings.nb; window.__nbGap = nb['screen.alerts']; delete nb['screen.alerts']; App.go('alerts'); }); + await p.waitForSelector('[data-screen="alerts"]:not([hidden])'); + await sleep(500); + const r2 = await leaks(); + await p.evaluate(() => { UpstreamI18n.strings.nb['screen.alerts'] = window.__nbGap; }); + if (!r2.english.some((x) => /screen\.alerts/.test(x) || /Alerts/.test(x))) return 'a deleted nb string was not reported: ' + JSON.stringify(r2); + }); + const visitAll = async (id, attrs) => { + await p.evaluate((i) => App.go(i), id); + await p.waitForSelector('[data-screen="' + id + '"]:not([hidden])', { timeout: 5000 }); + await sleep(id === 'map' ? 1200 : 600); + if (id !== 'map' && (await p.evaluate((i) => document.querySelector('[data-screen="' + i + '"]').innerText.trim().length, id)) < 5) return 'screen is empty'; + if (attrs === false) { const withAttrs = await p.evaluate(nbLeaks, { attrs: true }); for (const x of withAttrs.english) staleAttrs.add(id + ': ' + x); } + return report(await p.evaluate(nbLeaks, { attrs })); + }; + const staleAttrs = new Set(); + // Part A (continued): every screen was drawn in English before the live switch above; now each is shown and scanned. + for (const id of screens) await check('nb, switched live: screen ' + id + ' shows no raw keys and no English text', async () => visitAll(id, false)); + // Part B: reload (the choice is stored): every screen renders fresh in Norwegian, text and aria-labels / placeholders / titles + await check('reload keeps Norwegian; nav in nb', async () => { + if (staleAttrs.size) console.log(' (known gap, not a failure: ' + staleAttrs.size + ' English aria-label/title strings stay on screens drawn before a live switch, e.g. ' + [...staleAttrs].slice(0, 3).join(' | ') + ')'); + await p.reload(); + await p.waitForSelector('#nav:not([hidden])', { timeout: 15000 }); + if ((await text(p, '#nav [data-screen="map"]')) !== 'Kart') return 'nav label after reload: ' + (await text(p, '#nav [data-screen="map"]')); + }); + for (const id of screens) await check('nb, fresh render: screen ' + id + ' shows no raw keys, no English text, no English aria-labels', async () => visitAll(id, true)); + await check('nb dialogs: build sheet, locked-unit train sheet (dynamic err.* text), send dialog with greyed types', async () => { + const out = []; + await p.evaluate(() => App.go('pop')); await p.waitForSelector('.tile[data-key="f1"]'); + await p.click('.tile[data-key="f1"]'); await p.waitForSelector('.sheet .btn.primary'); + out.push(['build sheet', report(await leaks())]); + await p.keyboard.press('Escape'); await sheetClosed(p); + await p.evaluate(() => App.go('units')); await p.waitForSelector('.mil-train.locked'); + await p.click('.mil-train.locked >> nth=0'); await p.waitForSelector('.sheet .reason:not([hidden])'); + out.push(['train sheet', report(await leaks())]); + const reason = await text(p, '.sheet .reason'); + const nbReason = await p.evaluate(() => window.__I18N0.nb['err.requirements_not_met']); + if (!reason.startsWith(nbReason)) return 'locked unit reason is "' + reason + '", expected it to start with "' + nbReason + '"'; + await p.keyboard.press('Escape'); await sheetClosed(p); + await p.evaluate(() => App.go('movements')); await p.waitForSelector('[data-screen="movements"] .head-actions .btn.primary'); + await p.click('[data-screen="movements"] .head-actions .btn.primary'); await p.waitForSelector('.sheet .chips .chip-btn'); + await p.click('.sheet .chips .chip-btn >> nth=0'); await p.waitForSelector('.sheet .send-why, .sheet .seg-btn'); + await sleep(500); + out.push(['send dialog', report(await leaks())]); + await p.keyboard.press('Escape'); await sheetClosed(p); + const bad = out.filter(([, r]) => r !== true).map(([n, r]) => n + ': ' + r); + if (bad.length) return bad.join('\n'); + }); + await check('switching back to English restores English labels', async () => { + await p.evaluate(() => App.setLang('en')); + if ((await text(p, '#nav [data-screen="map"]')) !== 'Map') return 'English did not come back'; + if ((await p.evaluate(() => document.documentElement.lang)) !== 'en') return 'html lang stayed nb'; + }); + await check('nb pages: no console errors', async () => noErrors(P)); + await P.ctx.close(); +} + +// ================================================================== 14. PWA +async function suitePwa(browser, S) { + group('14. PWA: manifest, icons, start_url, install hints'); + const get = async (url) => { const r = await fetch(url); return { status: r.status, type: r.headers.get('content-type') || '', buf: Buffer.from(await r.arrayBuffer()), cc: r.headers.get('cache-control') || '' }; }; + const html = await (await fetch(S.base + '/')).text(); + let manifest = null, mUrl = ''; + await check('index links the manifest; it is served 200 as application/manifest+json and parses', async () => { + const m = /'; + mUrl = new URL(m[1], S.base + '/').href; + const r = await get(mUrl); + if (r.status !== 200) return 'status ' + r.status; + if (!/^application\/manifest\+json/.test(r.type)) return 'content-type ' + r.type; + manifest = JSON.parse(r.buf.toString('utf8')); + }); + await check('manifest: standalone display, name, short_name, theme + background colours, start_url inside scope and serving the app', async () => { + if (manifest.display !== 'standalone') return 'display ' + manifest.display; + if (!manifest.name || !manifest.short_name) return 'name / short_name missing'; + for (const k of ['theme_color', 'background_color']) if (!/^#[0-9a-f]{6}$/i.test(manifest[k] || '')) return k + ' is ' + manifest[k]; + const start = new URL(manifest.start_url, mUrl), scope = new URL(manifest.scope || '.', mUrl); + if (start.origin !== new URL(S.base).origin) return 'start_url leaves the origin: ' + start.href; + if (!start.pathname.startsWith(scope.pathname)) return 'start_url ' + start.pathname + ' is outside scope ' + scope.pathname; + const r = await get(start.href); + if (r.status !== 200 || !/text\/html/.test(r.type)) return 'start_url answers ' + r.status + ' ' + r.type; + if (!/id="app"/.test(r.buf.toString('utf8'))) return 'start_url does not serve the app shell'; + const tc = / { + const icons = manifest.icons || []; + const png = (sz, purpose) => icons.find((i) => i.sizes === sz && i.type === 'image/png' && (i.purpose || 'any').split(' ').includes(purpose)); + if (!png('192x192', 'any')) return 'no 192 png (any)'; + if (!png('512x512', 'any')) return 'no 512 png (any)'; + if (!png('512x512', 'maskable')) return 'no maskable 512 png'; + for (const i of icons) { + const r = await get(new URL(i.src, mUrl).href); + if (r.status !== 200) return i.src + ' -> ' + r.status; + if (!/^image\//.test(r.type)) return i.src + ' content-type ' + r.type; + if (r.type.includes('png')) { + if (r.buf.readUInt32BE(0) !== 0x89504e47) return i.src + ' is not a PNG'; + const w = r.buf.readUInt32BE(16), h = r.buf.readUInt32BE(20); + if (i.sizes !== w + 'x' + h) return i.src + ' declares ' + i.sizes + ' but is ' + w + 'x' + h; + } + } + const touch = / { + const P = await L.newPage(browser, PROFILES.phone); + await P.page.goto(S.base + '/'); + await P.page.waitForSelector('.auth-form'); + const info = await P.page.evaluate(async () => { + const link = document.querySelector('link[rel=manifest]'); + const r = await fetch(link.href); + const regs = navigator.serviceWorker ? (await navigator.serviceWorker.getRegistrations()).length : -1; + return { href: link.href, ok: r.ok, type: r.headers.get('content-type'), viewport: document.querySelector('meta[name=viewport]').content, capable: !!document.querySelector('meta[name=mobile-web-app-capable]'), regs }; + }); + await P.ctx.close(); + if (!info.ok || !/manifest\+json/.test(info.type)) return 'manifest fetched from the page: ' + JSON.stringify(info); + if (!/viewport-fit=cover/.test(info.viewport)) return 'viewport ' + info.viewport; + if (!info.capable) return 'no mobile-web-app-capable meta'; + if (info.regs > 0) return 'a service worker is registered (NEXT says there is none)'; + return noErrors(P); + }); +} + +module.exports = { suiteUnits, suiteMovements, suiteReconnect, suiteSlow, suiteAlliance, suiteTrade, suiteEndgame, suiteNorwegian, suitePwa, armedPair, goBar, text, navBadge, sheetClosed, uniq, DAY, COUNTDOWN }; diff --git a/e2e/lib.js b/e2e/lib.js index d5ac5d2..606791f 100644 --- a/e2e/lib.js +++ b/e2e/lib.js @@ -107,13 +107,15 @@ async function newPage(browser, ctxOpts, o) { o = o || {}; const ctx = await browser.newContext(ctxOpts); const page = await ctx.newPage(); + page.setDefaultTimeout(8000); // a missing element fails in 8 s, not 30 s const errors = []; page.on('console', (m) => { if (m.type() === 'error' || m.type() === 'warning') errors.push(m.type() + ': ' + m.text() + (m.location() && m.location().url ? ' @ ' + m.location().url : '')); }); page.on('pageerror', (e) => errors.push('pageerror: ' + e.message)); page.on('requestfailed', (r) => { if (!/\/ws(\?|$)/.test(r.url()) && !(r.failure() && /ERR_ABORTED/.test(r.failure().errorText))) errors.push('requestfailed: ' + r.url() + ' ' + (r.failure() && r.failure().errorText)); }); page.on('response', (r) => { if (r.status() >= 400 && !(o.allowStatus || []).includes(r.status())) errors.push('HTTP ' + r.status() + ' ' + r.request().method() + ' ' + r.url()); }); page.on('dialog', (d) => { errors.push('dialog: ' + d.message()); d.dismiss(); }); - await page.addInitScript(() => { try { localStorage.setItem('upstream.lang', 'en'); } catch (e) { /* ignore */ } }); + if (!o.keepLang) await page.addInitScript(() => { try { localStorage.setItem('upstream.lang', 'en'); } catch (e) { /* ignore */ } }); + if (o.init) await page.addInitScript(o.init); // runs before the app's scripts, on every navigation return { ctx, page, errors }; } // Sign in by token injection (fast path used by the layout matrix and the push test). @@ -155,4 +157,39 @@ async function overflowReport(page) { }); } -module.exports = { ROOT, PASSWORD, sleep, group, check, record, summary, results, bootServer, landNear, placeTown, setBuildings, giveUnits, PROFILES, newPage, openSignedIn, overflowReport, R }; +// ---------------------------------------------------------------- helpers shared by run.js and flows.js +const noErrors = (p, label) => (p.errors.length ? (label || 'console') + ' errors:\n' + p.errors.join('\n') : true); + +// Tap/click that does the right thing for the profile (real touch events on phones, real mouse on desktop). +const tapper = (page, touch) => (sel, opts) => (touch ? page.tap(sel, opts) : page.click(sel, opts)); + +// Open a "More" screen (Rankings, Alerts, Settings, Trade, World) the way a player does: nav -> More -> row. +async function openFromMore(page, touch, id, label) { + const tap = tapper(page, touch); + await tap('#nav [data-screen="more"]'); + await page.waitForSelector('.more-list .row-btn'); + await page.locator('.more-list .row-btn', { hasText: label }).first().waitFor({ timeout: 3000 }); + await tap('.more-list .row-btn:has-text("' + label + '")'); + await page.waitForSelector('[data-screen="' + id + '"]:not([hidden])', { timeout: 5000 }); + await sleep(500); // let its first fetch land (errors show up here) +} + +// A flight that normally takes the world's real time (speed 1) is made to land in `inMs`: both the movement row and its event move, +// then the scheduler re-arms. This is what a long wait would have done; the handlers still run as in production. +function hurryMovement(S, movementId, inMs) { + const at = Date.now() + (inMs === undefined ? 2500 : inMs); + S.db.run('UPDATE movements SET arrive_at = ? WHERE id = ?', at, movementId); + S.db.run("UPDATE events SET due_at = ? WHERE status = 'pending' AND type IN ('arrive', 'return') AND json_extract(payload, '$.movementId') = ?", at, Number(movementId)); + S.srv.scheduler.arm(); + return at; +} +// Same for any pending event of a type (a training batch, a build). +function hurryEvents(S, type, townId, inMs) { + const at = Date.now() + (inMs === undefined ? 2500 : inMs); + S.db.run("UPDATE events SET due_at = ? WHERE status = 'pending' AND type = ? AND town_id = ?", at, type, townId); + S.srv.scheduler.arm(); + return at; +} +const latestMovement = (S, ownerOperatorId, type) => S.db.get("SELECT * FROM movements WHERE owner_id = ? AND status = 'out' " + (type ? 'AND type = ? ' : '') + 'ORDER BY id DESC LIMIT 1', ...(type ? [ownerOperatorId, type] : [ownerOperatorId])); + +module.exports = { noErrors, tapper, openFromMore, hurryMovement, hurryEvents, latestMovement, ROOT, PASSWORD, sleep, group, check, record, summary, results, bootServer, landNear, placeTown, setBuildings, giveUnits, PROFILES, newPage, openSignedIn, overflowReport, R }; diff --git a/e2e/run.js b/e2e/run.js index 72b4051..5b4395b 100644 --- a/e2e/run.js +++ b/e2e/run.js @@ -1,33 +1,39 @@ 'use strict'; /* - * UPSTREAM smoke e2e (npm run e2e). Boots the real server in-process (temp SQLite file, fast world) and drives real Chromium - * through playwright-core. Target: 1-2 minutes. Exit code 1 if any check fails. + * UPSTREAM e2e (npm run e2e). Boots the real server in-process (temp SQLite file, fast or slow world) and drives real Chromium + * through playwright-core. Target: under 3 minutes for the default set. Exit code 1 if any check fails. * - * node e2e/run.js all suites - * node e2e/run.js push layout only the named suites (desktop, phone, layout, push) + * node e2e/run.js all default suites (everything except 'slow') + * node e2e/run.js push units only the named suites + * E2E_SLOW=1 node e2e/run.js also the slow suite; node e2e/run.js slow runs only it (about 70 s) * E2E_HEADED=1 node e2e/run.js watch it * E2E_SHOTS=dir node e2e/run.js save a screenshot after each flow / on each failure into dir * - * What it does NOT do: it is not the full suite (no combat balance, no alliance/trade flows, no Firefox/WebKit, no real proxy). + * Suites: desktop phone layout push smoke: sign-up, build, map, nav, layout matrix, push by WebSocket (e2e/run.js) + * units movements reconnect slow world (speed 1), seeded buildings and units; flights are moved up like the push suite does (e2e/flows.js) + * alliance trade nb pwa fast world; nb = Norwegian (raw keys, English leftovers, live switch and fresh render), pwa = manifest and icons + * endgame own world backdated to day 100.5: phase banner, 7 sites, ship to a held site + * slow opt-in: no WebSocket at all, the raid must still show up by REST polling (45 s gap) + * + * What it does NOT do: no combat balance, takeover/capture flows, confederation views or diplomacy moves, no Firefox/WebKit, no real + * devices, no real proxy (nginx Proxy Manager), no load. Flights that take real minutes (speed 1, 10 minute minimum latency) are + * moved up in the database (UPDATE movements/events + scheduler.arm), the handlers themselves run unchanged. */ const fs = require('fs'); const path = require('path'); const { chromium } = require('playwright-core'); const L = require('./lib.js'); -const { check, group, sleep, PROFILES } = L; +const F = require('./flows.js'); +const { check, group, sleep, PROFILES, noErrors, tapper, openFromMore } = L; const SHOTS = process.env.E2E_SHOTS || ''; const want = process.argv.slice(2); -const wanted = (n) => !want.length || want.includes(n); +const SLOW = ['slow']; // opt-in suites: only by name or with E2E_SLOW=1 +const wanted = (n) => (want.length ? want.includes(n) : !SLOW.includes(n) || !!process.env.E2E_SLOW); if (SHOTS) fs.mkdirSync(SHOTS, { recursive: true }); const shot = async (page, name) => { if (SHOTS) await page.screenshot({ path: path.join(SHOTS, name + '.png') }).catch(() => {}); }; -const noErrors = (p, label) => (p.errors.length ? (label || 'console') + ' errors:\n' + p.errors.join('\n') : true); - // ---------------------------------------------------------------- shared flow pieces -// Tap/click that does the right thing for the profile (real touch events on phones, real mouse on desktop). -const tapper = (page, touch) => (sel, opts) => (touch ? page.tap(sel, opts) : page.click(sel, opts)); - async function signUpThroughUi(P, name, touch) { const tap = tapper(P.page, touch); await P.page.goto(P.base + '/'); @@ -72,17 +78,6 @@ async function mapTap(page, touch) { return title; } -// Open a "More" screen (Rankings, Alerts, Settings, Trade, World) the way a player does: nav -> More -> row. -async function openFromMore(page, touch, id, label) { - const tap = tapper(page, touch); - await tap('#nav [data-screen="more"]'); - await page.waitForSelector('.more-list .row-btn'); - await page.locator('.more-list .row-btn', { hasText: label }).first().waitFor({ timeout: 3000 }); - await tap('.more-list .row-btn:has-text("' + label + '")'); - await page.waitForSelector('[data-screen="' + id + '"]:not([hidden])', { timeout: 5000 }); - await sleep(500); // let its first fetch land (errors show up here) -} - async function navReachable(page, vw, vh) { return page.evaluate(([w, h]) => { const nav = document.getElementById('nav'); @@ -272,6 +267,18 @@ async function suitePush(browser) { } finally { await S.close(); } } +// Units + movements + reports share one slow world (speed 1: a raid really takes half an hour, so the flight is on screen; the +// arrival is moved up by hurryMovement, like the push suite does). +async function suiteMilitary(browser) { + const S = await L.bootServer({ speed: 1 }); + try { + const U = await F.armedPair(S, 'Alice' + F.uniq(), 'Bob' + F.uniq()); + if (wanted('units')) await F.suiteUnits(browser, S, U); + if (wanted('movements')) await F.suiteMovements(browser, S, U); + if (wanted('reconnect')) await F.suiteReconnect(browser, S); + } finally { await S.close(); } +} + // ---------------------------------------------------------------- main (async () => { const t0 = Date.now(); @@ -284,6 +291,18 @@ async function suitePush(browser) { if (wanted('phone')) await suitePhone(browser, S); if (wanted('layout')) await suiteLayout(browser, S); if (wanted('push')) await suitePush(browser); + if (wanted('alliance') || wanted('trade') || wanted('nb') || wanted('pwa')) { + const S2 = await L.bootServer({ speed: 4000 }); + try { + if (wanted('alliance')) await F.suiteAlliance(browser, S2); + if (wanted('trade')) await F.suiteTrade(browser, S2); + if (wanted('nb')) await F.suiteNorwegian(browser, S2); + if (wanted('pwa')) await F.suitePwa(browser, S2); + } finally { await S2.close(); } + } + if (wanted('units') || wanted('movements') || wanted('reconnect')) await suiteMilitary(browser); + if (wanted('endgame')) await F.suiteEndgame(browser); + if (wanted('slow')) await F.suiteSlow(browser); } catch (e) { L.record('harness: unexpected exception', false, e && e.stack || String(e)); } finally { diff --git a/public/js/alertkinds.js b/public/js/alertkinds.js index 65308fe..638b0ef 100644 --- a/public/js/alertkinds.js +++ b/public/js/alertkinds.js @@ -38,12 +38,14 @@ trade_accepted: (n, p) => ({ icon: 'swap', title: t('alerts.trade_accepted', { give: amt(p.give), want: amt(p.want) }), detail: t('alerts.build_done.in', { town: town(p.townId) }), go: 'trade', params: { tab: 'mine' } }), trade_completed: (n, p) => ({ icon: 'swap', title: t('alerts.trade_completed', { give: amt(p.give), want: amt(p.want) }), detail: '', go: 'trade', params: { tab: 'mine' } }), trade_expired: (n, p) => ({ icon: 'clock', title: t('alerts.trade_expired'), detail: t('alerts.trade_expired.back', { what: amt(p.returned), town: town(p.townId) }), go: 'trade', params: { tab: 'mine' } }), + trade_refund_clipped: (n, p) => ({ icon: 'alert', title: t('alerts.trade_refund_clipped', { what: amt({ resource: p.resource, amount: p.lost }) }), detail: t('alerts.trade_refund_clipped.why', { town: town(p.townId) }), go: 'trade', params: { tab: 'mine' } }), trade_void: (n, p) => ({ icon: 'alert', title: t('alerts.trade_void'), detail: t('alerts.build_done.in', { town: town(p.townId) }), go: 'trade', params: { tab: 'mine' } }), // ---- end game backbone_open: (n, p) => Object.assign({ icon: 'b-backbone_node', title: t('alerts.backbone_open'), detail: t('alerts.backbone_open.n', { n: (p.sites || []).length || 7 }) }, worldGo(null)), backbone_taken: (n, p) => Object.assign({ icon: 'flag', title: t('alerts.backbone_taken', { n: site(p) }), detail: [t('alerts.level', { n: p.level || 0 }), p.from ? t('alerts.backbone_taken.from', { tag: tag(p.from) }) : t('alerts.backbone_taken.incumbent'), there(p)].filter(Boolean).join(' · ') }, worldGo(p)), backbone_lost: (n, p) => Object.assign({ icon: 'alert', title: t('alerts.backbone_lost', { n: site(p), tag: tag(p.by) }), detail: [t('alerts.level', { n: p.level || 0 }), there(p)].filter(Boolean).join(' · ') }, worldGo(p)), + backbone_incoming: (n, p) => Object.assign({ icon: 'alert', title: t('alerts.backbone_incoming', { n: site(p) }), detail: [p.arriveAt ? t('alerts.backbone_incoming.at', { time: c.clockTime(p.arriveAt) }) : '', there(p)].filter(Boolean).join(' · ') }, worldGo(p)), backbone_level: (n, p) => Object.assign({ icon: 'b-backbone_node', title: t('alerts.backbone_level', { n: site(p), level: p.level }), detail: '' }, worldGo(p)), backbone_delivered: (n, p) => ({ icon: 'box', title: t('alerts.backbone_delivered'), detail: cargoText(p.cargo), go: 'world', params: null }), backbone_ship_bounced: (n, p) => ({ icon: 'alert', title: t('alerts.backbone_ship_bounced'), detail: cargoText(p.cargo), go: 'movements', params: null }), diff --git a/public/js/data.js b/public/js/data.js index bff8d8f..4d5dcf7 100644 --- a/public/js/data.js +++ b/public/js/data.js @@ -219,6 +219,8 @@ // Resource transport between POPs (trade is built on it): `links` concurrent transports = Internet exchange level. // capacityPerLink was 500; 1000 since docs/BALANCE.md B2 (the end game was shipping-limited: 21.6 M units in 500-unit trips). + // It is the capacity at world speed 1: the real capacity is rules.transportCapacity(speed) = capacityPerLink x speed (BALANCE.md B7), because + // trips are per sitting, not per hour. Never read this constant directly in the client or in a command. const TRANSPORT = { building: 'internet_exchange', speed: 12, capacityPerLink: 1000 }; // Which unit roles may go on which movement type. @@ -261,7 +263,10 @@ graceDays: 2, // after level maxLevel is reached the world ends this long after (divided by world speed) siteRingMin: 0.35, siteRingMax: 0.8, // landing sites sit between these fractions of the map radius siteMinSpacing: 6, // tiles between two sites - defenceMult: 12, // incumbent site defence x this = the heavy defence of a landing site + defenceMult: 12, // incumbent site defence x this = the heavy defence of a landing site that NOBODY holds (the opening scramble) + captureShieldHours: 72, // a site that has just changed hands cannot be attacked for this long (world hours, / speed): time for its new holders to garrison it (BALANCE.md E6: 24 h let sites flip every few hours) + heldDefenceMult: 2, // a site HELD by an alliance: its static defence is incumbent defence x this (x the per-level bonus); units its members + // station there (garrison, docs/DECISIONS.md E6) count on top, so a held site is as strong as its garrison defencePerLevel: 0.03, // + 3% per built Backbone node level (the node is a bigger target) scanStrength: 40, // a landing site counts as this many scanners when scanned maxLevel: 100, // = BUILDINGS.backbone_node.maxLevel diff --git a/public/js/endcore.js b/public/js/endcore.js index e1a097c..ebe7a23 100644 --- a/public/js/endcore.js +++ b/public/js/endcore.js @@ -78,10 +78,21 @@ // Share of the way to the opening day, 0..1. const openProgress = (status) => (status && status.openDay ? Math.max(0, Math.min(1, status.ageDays / status.openDay)) : 0); + // The garrison of a site as the holders' manage sheet shows it (GET /backbone/:id: `defence` + `garrison`): rows sorted by defence, with the + // share of the whole defence, and what the static part is worth. -> { static, garrison, total, rows: [{ ownerTownId, townName, name, units, power, share, mine, online }] } + function garrisonView(data) { + const def = (data && data.defence) || { static: 0, garrison: 0, total: 0 }; + const rows = ((data && data.garrison) || []).map((g) => ({ + ownerTownId: g.ownerTownId, townName: g.townName, name: g.operator ? g.operator.name : '', units: g.units || {}, power: g.power || 0, + share: def.total > 0 ? (g.online ? (g.power || 0) / def.total : 0) : 0, mine: !!g.mine, online: g.online !== false, + })).sort((a, b) => b.power - a.power || a.ownerTownId - b.ownerTownId); + return { static: def.static, garrison: def.garrison, total: def.total, rows }; + } + const sumCargo = (c) => Object.keys(c || {}).reduce((s, k) => s + (c[k] || 0), 0); // Rows of a final ranking list for display: the first `n` (a snapshot holds the top 100). const topRows = (list, n) => (list || []).slice(0, n); - return { leading, buildProgress, missing, holderKind, buildCheck, phaseNow, openProgress, sumCargo, topRows }; + return { leading, buildProgress, missing, holderKind, buildCheck, phaseNow, openProgress, sumCargo, topRows, garrisonView }; })); diff --git a/public/js/main.js b/public/js/main.js index 6595471..d6e336c 100644 --- a/public/js/main.js +++ b/public/js/main.js @@ -320,7 +320,7 @@ const town = { id: td.id, speed: st.world.speed, updatedAt: at, res: { fiber: td.resources.fiber.amount, hardware: td.resources.hardware.amount, capital: td.resources.capital.amount, battery: td.power.buffer }, - footprint: td.footprint, buildings, unitDraw: Math.max(0, Math.round(td.power.draw - bdraw)), bonus: td.bonus || {}, + footprint: td.footprint, buildings, unitDraw: Math.max(0, Math.round(td.power.draw - bdraw)), bonus: td.bonus || {}, escrow: td.escrow || {}, }; return town; }; diff --git a/public/js/milcore.js b/public/js/milcore.js index bbc209f..162a4dd 100644 --- a/public/js/milcore.js +++ b/public/js/milcore.js @@ -75,7 +75,7 @@ const b = t.backbone || {}; add('scan', has('scan'), 'no_units'); if (!c.allianceId) add('attack', false, 'no_alliance'); - else if (b.mine) add('attack', false, 'own_site'); + else if (b.mine) { add('attack', false, 'own_site'); add('reinforce', has('reinforce'), 'no_units'); } // members of the holding alliance garrison the site else add('attack', has('attack'), 'no_units'); } else if (t.type === 'land') { const s = t.settle || {}; diff --git a/public/js/milstate.js b/public/js/milstate.js index ceca775..fe8c553 100644 --- a/public/js/milstate.js +++ b/public/js/milstate.js @@ -155,14 +155,20 @@ kinds.report = (n, p) => ({ icon: 'report', title: App.t('alerts.report', { type: mil.reportTypeLabel(p.type) }), detail: '', go: 'reports', params: { open: p.reportId } }); kinds.train_done = (n, p) => ({ icon: 'units', title: App.t('alerts.train_done', { n: App.fmt.num(p.count), unit: mil.unitName(p.unit) }), detail: App.t('alerts.build_done.in', { town: townTxt(p.townId) }), go: 'units' }); kinds.research_done = (n, p) => ({ icon: 'flask', title: App.t('alerts.research_done', { unit: mil.unitName(p.unit), stat: App.t('stat.' + p.stat), level: p.level }), detail: App.t('alerts.build_done.in', { town: townTxt(p.townId) }), go: 'units' }); - kinds.movement_returned = (n, p) => ({ icon: 'return', title: App.t('alerts.movement_returned'), detail: [mil.unitsText(p.units)].concat(D.RESOURCES.some((r) => p.cargo && p.cargo[r]) ? [Object.keys(p.cargo).filter((r) => p.cargo[r]).map((r) => App.fmt.num(p.cargo[r]) + ' ' + App.resName(r)).join(', ')] : []).join(' · '), go: 'movements' }); + // Cargo that did not fit the Rack hall when it came home / arrived (cargoLost, exact amounts per resource): said out loud, never silent. + const lostText = (lost) => (D.RESOURCES.some((r) => lost && lost[r] > 0) ? [App.t('alerts.cargo_lost', { what: D.RESOURCES.filter((r) => lost[r] > 0).map((r) => App.fmt.num(lost[r]) + ' ' + App.resName(r)).join(', ') })] : []); + kinds.movement_returned = (n, p) => ({ icon: 'return', title: App.t('alerts.movement_returned'), detail: [mil.unitsText(p.units)].concat(D.RESOURCES.some((r) => p.cargo && p.cargo[r]) ? [Object.keys(p.cargo).filter((r) => p.cargo[r]).map((r) => App.fmt.num(p.cargo[r]) + ' ' + App.resName(r)).join(', ')] : [], lostText(p.cargoLost)).filter(Boolean).join(' · '), go: 'movements' }); kinds.movement_lost = () => ({ icon: 'alert', title: App.t('alerts.movement_lost'), detail: '', go: 'movements' }); - kinds.transport_arrived = (n, p) => ({ icon: 'box', title: App.t('alerts.transport_arrived', { town: townTxt(p.townId) }), detail: Object.keys(p.cargo || {}).filter((r) => p.cargo[r]).map((r) => App.fmt.num(p.cargo[r]) + ' ' + App.resName(r)).join(', '), go: 'movements' }); + kinds.transport_arrived = (n, p) => ({ icon: 'box', title: App.t('alerts.transport_arrived', { town: townTxt(p.townId) }), detail: Object.keys(p.cargo || {}).filter((r) => p.cargo[r]).map((r) => App.fmt.num(p.cargo[r]) + ' ' + App.resName(r)).concat(lostText(p.cargoLost)).join(' · '), go: 'movements' }); kinds.transport_delivered = (n, p) => ({ icon: 'box', title: App.t('alerts.transport_delivered'), detail: Object.keys(p.cargo || {}).filter((r) => p.cargo[r]).map((r) => App.fmt.num(p.cargo[r]) + ' ' + App.resName(r)).join(', '), go: 'movements' }); kinds.units_offline = (n, p) => ({ icon: 'power', title: App.t('alerts.units_offline'), detail: App.t('alerts.build_done.in', { town: townTxt(p.townId) }), go: 'units' }); kinds.units_decommissioned = (n, p) => ({ icon: 'power', title: App.t('alerts.units_decommissioned'), detail: mil.unitsText(p.units), go: 'units' }); kinds.town_lost = (n, p) => ({ icon: 'alert', title: App.t('alerts.town_lost', { name: p.name }), detail: p.by ? App.t('alerts.town_lost.by', { name: p.by.name }) : '', go: 'pop' }); kinds.town_gained = (n, p) => ({ icon: 'pop', title: App.t('alerts.town_gained', { name: p.name }), detail: '', go: 'pop' }); kinds.reinforcements_sent_home = (n, p) => ({ icon: 'return', title: App.t('alerts.reinforcements_home'), detail: mil.unitsText(p.units), go: 'units' }); + // garrisons at backbone landing sites (docs/DECISIONS.md E6) + const siteGo = (p) => ({ go: 'world', params: Number.isInteger(p.index) ? { site: p.index } : null }); + kinds.garrison_arrived = (n, p) => Object.assign({ icon: 'shield', title: App.t('alerts.garrison_arrived', { n: Number.isInteger(p.index) ? p.index + 1 : '?' }), detail: mil.unitsText(p.units) }, siteGo(p)); + kinds.garrison_released = (n, p) => Object.assign({ icon: 'return', title: App.t('alerts.garrison_released', { n: Number.isInteger(p.index) ? p.index + 1 : '?' }), detail: [App.t('alerts.garrison_released.' + (p.reason === 'alliance_dissolved' || p.reason === 'left_alliance' || p.reason === 'town_lost' ? p.reason : 'other')), mil.unitsText(p.units)].filter(Boolean).join(' · ') }, siteGo(p)); }()); diff --git a/public/js/rules.js b/public/js/rules.js index 85ec5ee..103c409 100644 --- a/public/js/rules.js +++ b/public/js/rules.js @@ -228,6 +228,12 @@ return Math.round(F.storageBase * Math.pow(F.storageGrowth, r.level - 1)); } + // Room the Rack hall has for ONE resource: goods escrowed in open Internet exchange offers (town.escrow, per resource) still occupy + // the hall, so the stock stops growing at the hall's size minus the escrow and a refund always fits (nothing is lost, nothing is stored extra). + function storageCapOf(town, res) { + return Math.max(0, storageCap(town) - ((town.escrow && town.escrow[res]) || 0)); + } + function batteryCap(town) { const b = town.buildings.battery_bank; return b && b.level > 0 ? Math.round(F.batteryBase * Math.pow(F.batteryGrowth, b.level - 1)) : 0; @@ -266,16 +272,17 @@ function resourcesAt(town, now) { const dtH = Math.max(0, now - town.updatedAt) / HOUR; const rates = ratesPerHour(town); - const cap = storageCap(town); const bcap = batteryCap(town); const speed = town.speed || 1; - const out = {}; + const out = {}, caps = {}; for (const r of D.RESOURCES) { // An amount already above the cap (the rack hall was lowered) is kept, it just stops growing. - out[r] = Math.max(0, Math.min(Math.max(cap, town.res[r]), town.res[r] + rates[r] * dtH)); + caps[r] = storageCapOf(town, r); + out[r] = Math.max(0, Math.min(Math.max(caps[r], town.res[r]), town.res[r] + rates[r] * dtH)); } out.battery = Math.max(0, Math.min(bcap, town.res.battery + rates.powerNet * speed * dtH)); - return { amounts: out, caps: { fiber: cap, hardware: cap, capital: cap, battery: bcap }, rates }; + caps.battery = bcap; + return { amounts: out, caps, rates }; } // When will the battery hit zero (ms epoch)? null if it never does at the current rates. Units go offline then. @@ -569,7 +576,9 @@ // o.kind: 'attack' (full) | 'raid' // o.attackers: { units, research } // o.defenders: [{ id, units, research }] everything defending the POP (home crews first, then each reinforcement) - // o.firewall: Firewall level of the target; o.staticDefence: a number for an incumbent site (no groups, no losses) + // o.firewall: Firewall level of the target; o.staticDefence: a number for an incumbent site (no groups, no losses). A held backbone + // landing site passes BOTH: the static number plus the garrison groups; then D = static + the groups' raw defence (no firewall, no + // base defence) and the groups lose units by the same loss law as in a POP (the static part never loses anything). // Full attack: the loser loses everything, the winner loses (loser/winner)^1.5 of its units. // Raid: both sides lose 0.5 * (weaker/stronger)^1.5, whoever wins. Ties go to the defender. function resolveBattle(o) { @@ -581,7 +590,7 @@ const raw = groups.map((g) => defencePower(g.units, g.research)); const rawTotal = raw.reduce((s, v) => s + v, 0); const isStatic = o.staticDefence !== undefined && o.staticDefence !== null; - const Dv = isStatic ? o.staticDefence : (rawTotal + MIL.defenceBase) * firewallMult(effFw); + const Dv = isStatic ? o.staticDefence + rawTotal : (rawTotal + MIL.defenceBase) * firewallMult(effFw); const attackerWins = A > Dv; const hi = Math.max(A, Dv), lo = Math.min(A, Dv); const ratio = hi > 0 ? lo / hi : 0; @@ -593,7 +602,7 @@ } else { attF = 1; defF = Math.min(1, Math.pow(ratio, MIL.lossExponent)); } - if (isStatic) defF = 0; + if (isStatic && !groups.length) defF = 0; const a = applyLoss(att, attF); const defenders = groups.map((g, i) => { const r = applyLoss(g.units, defF); @@ -615,15 +624,19 @@ // Loot: `carry` is split evenly over Fiber/Hardware/Capital; what one resource cannot give is shared by the others. // avail = what can be taken. -> whole-number { fiber, hardware, capital }. - function lootSplit(carry, avail) { + // `room` (optional, per resource) = what the raiders' home Rack hall can still bank: a resource with no room is not taken at all + // and the carry goes to the others, so loot is never destroyed on arrival (default: no limit). + function lootSplit(carry, avail, room) { const take = { fiber: 0, hardware: 0, capital: 0 }; + const lim = {}; + for (const r of D.RESOURCES) lim[r] = Math.min(avail[r], room && room[r] !== undefined ? room[r] : Infinity); let left = Math.max(0, carry); for (let pass = 0; pass < 4 && left > 1e-9; pass++) { - const open = D.RESOURCES.filter((r) => avail[r] - take[r] > 1e-9); + const open = D.RESOURCES.filter((r) => lim[r] - take[r] > 1e-9); if (!open.length) break; const share = left / open.length; for (const r of open) { - const t = Math.min(share, avail[r] - take[r]); + const t = Math.min(share, lim[r] - take[r]); take[r] += t; left -= t; } } @@ -716,6 +729,9 @@ // ---- transport (trade is built on it): concurrent links = Internet exchange level, each carries up to capacityPerLink const transportLinks = (town) => buildingLevel(town, D.TRANSPORT.building); + // What one link carries in a world of this speed: capacityPerLink x speed (trips are per sitting, not per hour, so a faster world must carry + // more per trip or its end game stays as slow as a 1x world's, BALANCE.md B7). The ONLY place that reads D.TRANSPORT.capacityPerLink. + const transportCapacity = (speed) => Math.max(1, Math.round(D.TRANSPORT.capacityPerLink * (speed > 0 ? speed : 1))); // Codes: validation_failed, capacity_exceeded, no_transport_link, not_enough_resources. function transportPlan(town, cargo, activeLinks, now) { let total = 0; @@ -725,7 +741,8 @@ } if (total < 1) return { ok: false, code: 'validation_failed' }; if (activeLinks >= transportLinks(town)) return { ok: false, code: 'no_transport_link', links: transportLinks(town), active: activeLinks }; - if (total > D.TRANSPORT.capacityPerLink) return { ok: false, code: 'capacity_exceeded', capacity: D.TRANSPORT.capacityPerLink, total }; + const capacity = transportCapacity(town.speed); + if (total > capacity) return { ok: false, code: 'capacity_exceeded', capacity, total }; const have = resourcesAt(town, now).amounts; for (const r of D.RESOURCES) if (have[r] + 1e-6 < (cargo[r] || 0)) return { ok: false, code: 'not_enough_resources' }; return { ok: true, total }; @@ -737,8 +754,8 @@ // Is the exchange rate within the 1:ratioMax band (give/want in [1/ratioMax, ratioMax])? const tradeRatioOk = (give, want) => give > 0 && want > 0 && give <= want * D.TRADE.ratioMax && want <= give * D.TRADE.ratioMax; // Validate the terms of a new offer. `o` = { giveRes, giveAmount, wantRes, wantAmount, maxDistance }. Codes: validation_failed, - // trade_ratio, capacity_exceeded. Does not look at the town (resources, links) - the command does. - function tradeTermsCheck(o) { + // trade_ratio, capacity_exceeded (one transport at the world's `speed`). Does not look at the town (resources, links) - the command does. + function tradeTermsCheck(o, speed) { const bad = (path, message) => ({ ok: false, code: 'validation_failed', errors: [{ path, message }] }); if (D.RESOURCES.indexOf(o.giveRes) < 0) return bad('giveRes', 'must be one of ' + D.RESOURCES.join(', ')); if (D.RESOURCES.indexOf(o.wantRes) < 0) return bad('wantRes', 'must be one of ' + D.RESOURCES.join(', ')); @@ -746,7 +763,7 @@ if (!Number.isInteger(o.giveAmount) || o.giveAmount < 1) return bad('giveAmount', 'must be a whole number >= 1'); if (!Number.isInteger(o.wantAmount) || o.wantAmount < 1) return bad('wantAmount', 'must be a whole number >= 1'); if (!Number.isInteger(o.maxDistance) || o.maxDistance < 1 || o.maxDistance > D.TRADE.maxDistance) return bad('maxDistance', 'must be a whole number of tiles 1..' + D.TRADE.maxDistance); - const cap = D.TRANSPORT.capacityPerLink; + const cap = transportCapacity(speed); if (o.giveAmount > cap || o.wantAmount > cap) return { ok: false, code: 'capacity_exceeded', capacity: cap }; if (!tradeRatioOk(o.giveAmount, o.wantAmount)) return { ok: false, code: 'trade_ratio', max: D.TRADE.ratioMax }; return { ok: true }; @@ -756,9 +773,15 @@ const tradeInRange = (dist, maxDistance, level) => level >= 1 && dist <= maxDistance && dist <= tradeReach(level); // ---- end game: backbone landing sites - // Heavy static defence of a landing site: the incumbent's site defence x defenceMult, plus defencePerLevel per node level. - function backboneDefence(seed, x, y, ageDays, level) { - return Math.round(incumbentDefence(seed, x, y, ageDays) * D.ENDGAME.defenceMult * (1 + D.ENDGAME.defencePerLevel * Math.max(0, level || 0))); + // Static defence of a landing site: the incumbent's site defence x a multiplier, plus defencePerLevel per node level. Nobody holds it: + // defenceMult (heavy, the opening scramble). An alliance holds it (`held`): heldDefenceMult, and its garrison comes on top (E6). + function backboneDefence(seed, x, y, ageDays, level, held) { + const mult = held ? D.ENDGAME.heldDefenceMult : D.ENDGAME.defenceMult; + return Math.round(incumbentDefence(seed, x, y, ageDays) * mult * (1 + D.ENDGAME.defencePerLevel * Math.max(0, level || 0))); + } + // Until when a landing site that changed hands at `takenAt` cannot be attacked (0 = no shield). Only a HELD site has one: the caller checks that. + function siteShieldUntil(takenAt, speed) { + return takenAt ? takenAt + Math.round(D.ENDGAME.captureShieldHours * HOUR / (speed || 1)) : 0; } // Cost to build the Backbone node UP TO `level` (1..maxLevel), per resource. function backboneCost(level) { @@ -784,10 +807,10 @@ } return { - unitDef, unitCount, costValue, unitValue, researchKey, researchLevel, researchMult, unitStat, unitCost, trainTimeMs, unitMissing, trainPlan, researchCost, researchTimeMs, researchSpeedBonus, researchPlan, slowestSpeed, movementMs, transportMs, checkUnitsForType, isProtected, firewallMult, effectiveFirewall, attackPower, defencePower, applyLoss, resolveBattle, battlePoints, cacheFraction, lootSplit, carryOf, siegeLevels, loyaltyDrop, takeoverBlock, footprintGate, settleCheck, cleanWild, newTownBuildings, scanStrength, resolveScan, incumbentDefence, decommissionMs, decommissionPlan, transportLinks, transportPlan, rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn, + unitDef, unitCount, costValue, unitValue, researchKey, researchLevel, researchMult, unitStat, unitCost, trainTimeMs, unitMissing, trainPlan, researchCost, researchTimeMs, researchSpeedBonus, researchPlan, slowestSpeed, movementMs, transportMs, checkUnitsForType, isProtected, firewallMult, effectiveFirewall, attackPower, defencePower, applyLoss, resolveBattle, battlePoints, cacheFraction, lootSplit, carryOf, siegeLevels, loyaltyDrop, takeoverBlock, footprintGate, settleCheck, cleanWild, newTownBuildings, scanStrength, resolveScan, incumbentDefence, decommissionMs, decommissionPlan, transportLinks, transportCapacity, transportPlan, rng, hash, distance, tileAt, ruralNear, ruralBonus, pickSpawn, terrainAt, backboneSites, backboneSiteAt, isBackboneSite, worldAgeDays, worldPhase, tradeReach, tradeRatioOk, tradeTermsCheck, tradeInRange, - backboneDefence, backboneCost, backboneTimeMs, backbonePlan, - buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, earlyTimeFactor, queueSlots, storageCap, batteryCap, + backboneDefence, siteShieldUntil, backboneCost, backboneTimeMs, backbonePlan, + buildingDef, isFieldKey, fieldLayout, buildingCost, coreLevel, buildTimeMs, earlyTimeFactor, queueSlots, storageCap, storageCapOf, batteryCap, fieldOutputPerHour, ratesPerHour, resourcesAt, batteryEmptyAt, unitsOnline, footprintPerDay, footprintAt, allianceCap, allianceCan, roleRank, outranks, diplomacyMove, pactCancelMs, footprintNeeded, loyaltyAt, buildPlan, initialBuildings, latencyMs, diff --git a/public/js/screens/map.js b/public/js/screens/map.js index 1fbea26..35bc6e2 100644 --- a/public/js/screens/map.js +++ b/public/js/screens/map.js @@ -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)) }))); diff --git a/public/js/screens/messages.js b/public/js/screens/messages.js index 38a8ff4..3cf0ddf 100644 --- a/public/js/screens/messages.js +++ b/public/js/screens/messages.js @@ -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++; }, }); }()); diff --git a/public/js/screens/reports.js b/public/js/screens/reports.js index 58e9632..57572b2 100644 --- a/public/js/screens/reports.js +++ b/public/js/screens/reports.js @@ -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; } diff --git a/public/js/screens/send.js b/public/js/screens/send.js index 057d621..9596de5 100644 --- a/public/js/screens/send.js +++ b/public/js/screens/send.js @@ -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') })); diff --git a/public/js/screens/trade.js b/public/js/screens/trade.js index 93ec7af..bb06b66 100644 --- a/public/js/screens/trade.js +++ b/public/js/screens/trade.js @@ -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') }), diff --git a/public/js/screens/units.js b/public/js/screens/units.js index 862fb06..79d6e6d 100644 --- a/public/js/screens/units.js +++ b/public/js/screens/units.js @@ -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; } diff --git a/public/js/screens/world.js b/public/js/screens/world.js index 7717504..1af63ef 100644 --- a/public/js/screens/world.js +++ b/public/js/screens/world.js @@ -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); diff --git a/public/js/strings/alerts.js b/public/js/strings/alerts.js index f57ac69..2ec7dcc 100644 --- a/public/js/strings/alerts.js +++ b/public/js/strings/alerts.js @@ -13,6 +13,8 @@ 'alerts.trade_expired': 'An offer of yours expired', 'alerts.trade_expired.back': '{what} is back in {town}', 'alerts.trade_void': 'An offer was voided: the POP changed hands', + 'alerts.trade_refund_clipped': 'A refund did not fit: {what} was lost', + 'alerts.trade_refund_clipped.why': 'The Rack hall of {town} was too small for the rest of the escrow', // end game 'alerts.backbone_open': 'The backbone landing sites are open', 'alerts.backbone_open.n': '{n} landing sites are up for grabs. Scan one, then take it.', @@ -20,6 +22,7 @@ 'alerts.backbone_taken.from': 'from {tag}', 'alerts.backbone_taken.incumbent': 'from the incumbent', 'alerts.backbone_lost': 'Landing site {n} was taken by {tag}', 'alerts.backbone_level': 'Backbone node on site {n} reached level {level}', + 'alerts.backbone_incoming': 'Something is on its way to your landing site {n}', 'alerts.backbone_incoming.at': 'arrives {time}', 'alerts.backbone_delivered': 'Your shipment reached the landing site', 'alerts.backbone_ship_bounced': 'A shipment was turned back: the site changed hands', 'alerts.backbone_won': '{name} completed the Backbone', @@ -51,12 +54,15 @@ 'alerts.trade_expired': 'Et tilbud fra deg gikk ut', 'alerts.trade_expired.back': '{what} er tilbake i {town}', 'alerts.trade_void': 'Et tilbud ble ugyldig: POP-en skiftet eier', + 'alerts.trade_refund_clipped': 'En refusjon fikk ikke plass: {what} gikk tapt', + 'alerts.trade_refund_clipped.why': 'Rack-hallen i {town} var for liten til resten av depositumet', 'alerts.backbone_open': 'Ryggradens landingspunkter er åpne', 'alerts.backbone_open.n': '{n} landingspunkter kan tas. Skann ett, og ta det.', 'alerts.backbone_taken': 'Alliansen din tok landingspunkt {n}', 'alerts.backbone_taken.from': 'fra {tag}', 'alerts.backbone_taken.incumbent': 'fra inkumbenten', 'alerts.backbone_lost': 'Landingspunkt {n} ble tatt av {tag}', 'alerts.backbone_level': 'Ryggradsnoden på punkt {n} nådde nivå {level}', + 'alerts.backbone_incoming': 'Noe er på vei mot landingspunkt {n} som du holder', 'alerts.backbone_incoming.at': 'kommer {time}', 'alerts.backbone_delivered': 'Forsendelsen din nådde landingspunktet', 'alerts.backbone_ship_bounced': 'En forsendelse ble snudd: punktet skiftet eier', 'alerts.backbone_won': '{name} fullførte Ryggraden', diff --git a/public/js/strings/military.js b/public/js/strings/military.js index 7ef5c3b..b218321 100644 --- a/public/js/strings/military.js +++ b/public/js/strings/military.js @@ -36,7 +36,7 @@ 'units.offline.title': 'Units offline', 'units.offline.body': 'The battery is empty, so your units are switched off and cannot be sent. Add power (Substation) or get rid of draw.', 'units.offline.decom': 'Units are decommissioned in', 'units.home': 'At home', 'units.home.empty': 'No units here yet. Train some below.', - 'units.hosted': 'Reinforcements here', 'units.away': 'Your units elsewhere', + 'units.garrisoned': 'In landing sites (they still draw this POP\'s power)', 'units.garrisoned.site': 'Landing site at {x}, {y}', 'units.hosted': 'Reinforcements here', 'units.away': 'Your units elsewhere', 'units.sendHome': 'Send home', 'units.callBack': 'Call back', 'units.withdrawn': 'On their way home.', 'units.training': 'Training', 'units.training.empty': 'Nothing in training.', 'units.train': 'Train units', 'units.needs': 'Needs', 'units.perUnit': '{t} each', 'units.count': 'Number of units', 'units.max': 'As many as I can afford', @@ -94,7 +94,7 @@ 'rep.failed.title': '{type} failed', 'rep.failed.home': 'Units and cargo are on their way home.', 'rep.reason.invalid_target': 'The target is no longer valid.', 'rep.reason.not_allied': 'The target is no longer an ally.', 'rep.reason.own_town': 'The POP changed hands and is yours now.', 'rep.reason.pact': 'A pact with the target now prevents this.', 'rep.reason.protected': 'The target is under beginner protection.', 'rep.reason.target_gone': 'The target is gone.', - 'rep.reason.out_of_range': 'The site is out of range.', 'rep.reason.footprint_too_low': 'Your footprint was too low.', + 'rep.reason.site_shielded': 'The site had just changed hands and is protected for a while.', 'rep.reason.not_holder': 'Your alliance no longer holds the site, so the units could not join its garrison.', 'rep.reason.out_of_range': 'The site is out of range.', 'rep.reason.footprint_too_low': 'Your footprint was too low.', 'rep.role.attacker': 'You attacked', 'rep.role.defender': 'You were attacked', 'rep.role.reinforcer': 'Your reinforcements were there', 'rep.role.sender': 'You sent', 'rep.role.target': 'You were the target', 'rep.expires': 'kept until {t}', 'rep.arrived': 'Arrived {t}', 'rep.attacker': 'Attacker', 'rep.defender': 'Defender', 'rep.target': 'Target', 'rep.from': 'From', 'rep.host': 'Host', 'rep.site': 'Site', 'rep.scannedBy': 'Scanned by', @@ -102,7 +102,7 @@ 'rep.attackerUnits': 'Attacking units', 'rep.defenderUnits': 'Defending units', 'rep.units': 'Units', 'rep.scanners': 'Scanners', 'rep.sent': 'Sent', 'rep.lost': 'Lost', 'rep.left': 'Left', 'rep.noUnits': 'No units.', 'rep.group.home': 'Home defence', 'rep.group.reinf': 'Reinforcements from {town}', 'rep.group.offline': 'offline, no defence', - 'rep.loot': 'Loot', 'rep.cache': '{p}% of the stock was hidden in the Rack hall.', 'rep.siege': 'Siege', 'rep.siege.line': '{name} damaged: level {a} → {b}', + 'rep.loot': 'Loot', 'rep.lootLeft': 'Left behind', 'rep.lootLeft.why': 'The raiders could carry this, but their home Rack hall had no room for it when they would be back. It stayed with the target.', 'rep.cache': '{p}% of the stock was hidden in the Rack hall.', 'rep.siege': 'Siege', 'rep.siege.line': '{name} damaged: level {a} → {b}', 'rep.takeover': 'Takeover', 'rep.takeover.loyalty': 'Customer loyalty', 'rep.takeover.capital': 'A capital cannot change hands, it can only be drained.', 'rep.takeover.captured': 'The POP is now under new ownership.', 'rep.takeover.blocked.last_pop': 'The target\'s last POP cannot be taken.', 'rep.takeover.blocked.footprint': 'Your footprint is too low to hold another POP.', 'rep.intel': 'Intel', 'rep.intel.resources': 'Resources in stock', 'rep.intel.units': 'Units', 'rep.intel.offline': 'Their units are offline.', 'rep.intel.buildings': 'Buildings', 'rep.intel.outgoing': 'Their movements', @@ -110,10 +110,12 @@ // ---- notification feed 'alerts.incoming': 'Incoming movement', 'alerts.incoming.at': 'Heading for {town}, arrives {time}', 'alerts.report': 'New report: {type}', 'alerts.train_done': '{n} × {unit} trained', 'alerts.research_done': '{unit}: {stat} level {level} researched', - 'alerts.movement_returned': 'Units are home', 'alerts.movement_lost': 'A movement lost its way home', + 'alerts.cargo_lost': 'LOST, the Rack hall was full: {what}', 'alerts.movement_returned': 'Units are home', 'alerts.movement_lost': 'A movement lost its way home', 'alerts.transport_arrived': 'Cargo arrived at {town}', 'alerts.transport_delivered': 'Your cargo was delivered', 'alerts.units_offline': 'Units went offline: battery empty', 'alerts.units_decommissioned': 'Units decommissioned after too long without power', 'alerts.town_lost': '{name} was taken over', 'alerts.town_lost.by': 'By {name}', 'alerts.town_gained': '{name} is now yours', 'alerts.reinforcements_home': 'Reinforcements sent home', + 'alerts.garrison_arrived': 'Your units joined the garrison of landing site {n}', 'alerts.garrison_released': 'Your units left landing site {n} and are on their way home', + 'alerts.garrison_released.alliance_dissolved': 'The alliance was disbanded', 'alerts.garrison_released.left_alliance': 'You are no longer in the alliance that holds it', 'alerts.garrison_released.town_lost': 'The POP they belong to was taken over', 'alerts.garrison_released.other': 'Called home', // ---- expansion 'exp.title': 'Expansion', 'exp.count': '{n} POPs', 'exp.crews': 'Rollout crews at home', 'exp.footprint': 'Footprint (this POP / needed in total)', 'exp.footprint.v': '{have} / {need}', @@ -159,7 +161,7 @@ 'units.offline.title': 'Enheter offline', 'units.offline.body': 'Batteriet er tomt, så enhetene er slått av og kan ikke sendes. Legg til strøm (Transformatorstasjon) eller kutt trekk.', 'units.offline.decom': 'Enhetene avvikles om', 'units.home': 'Hjemme', 'units.home.empty': 'Ingen enheter her ennå. Tren noen under.', - 'units.hosted': 'Forsterkninger her', 'units.away': 'Dine enheter andre steder', + 'units.garrisoned': 'I landingspunkter (de trekker fortsatt strøm fra denne POP-en)', 'units.garrisoned.site': 'Landingspunkt ved {x}, {y}', 'units.hosted': 'Forsterkninger her', 'units.away': 'Dine enheter andre steder', 'units.sendHome': 'Send hjem', 'units.callBack': 'Kall tilbake', 'units.withdrawn': 'På vei hjem.', 'units.training': 'Trening', 'units.training.empty': 'Ingenting under trening.', 'units.train': 'Tren enheter', 'units.needs': 'Krever', 'units.perUnit': '{t} per stk.', 'units.count': 'Antall enheter', 'units.max': 'Så mange jeg har råd til', @@ -214,7 +216,7 @@ 'rep.failed.title': '{type} mislyktes', 'rep.failed.home': 'Enheter og last er på vei hjem.', 'rep.reason.invalid_target': 'Målet er ikke gyldig lenger.', 'rep.reason.not_allied': 'Målet er ikke lenger alliert.', 'rep.reason.own_town': 'POP-en skiftet eier og er din nå.', 'rep.reason.pact': 'En avtale med målet hindrer dette nå.', 'rep.reason.protected': 'Målet har nybegynnerbeskyttelse.', 'rep.reason.target_gone': 'Målet finnes ikke lenger.', - 'rep.reason.out_of_range': 'Stedet er utenfor rekkevidde.', 'rep.reason.footprint_too_low': 'Fotavtrykket ditt var for lavt.', + 'rep.reason.site_shielded': 'Punktet hadde nettopp skiftet eier og er beskyttet en stund.', 'rep.reason.not_holder': 'Alliansen din holder ikke punktet lenger, så enhetene kunne ikke bli med i garnisonen.', 'rep.reason.out_of_range': 'Stedet er utenfor rekkevidde.', 'rep.reason.footprint_too_low': 'Fotavtrykket ditt var for lavt.', 'rep.role.attacker': 'Du angrep', 'rep.role.defender': 'Du ble angrepet', 'rep.role.reinforcer': 'Forsterkningene dine var der', 'rep.role.sender': 'Du sendte', 'rep.role.target': 'Du var målet', 'rep.expires': 'lagres til {t}', 'rep.arrived': 'Ankom {t}', 'rep.attacker': 'Angriper', 'rep.defender': 'Forsvarer', 'rep.target': 'Mål', 'rep.from': 'Fra', 'rep.host': 'Vert', 'rep.site': 'Sted', 'rep.scannedBy': 'Skannet av', @@ -222,17 +224,19 @@ 'rep.attackerUnits': 'Angripende enheter', 'rep.defenderUnits': 'Forsvarende enheter', 'rep.units': 'Enheter', 'rep.scanners': 'Skannere', 'rep.sent': 'Sendt', 'rep.lost': 'Tapt', 'rep.left': 'Igjen', 'rep.noUnits': 'Ingen enheter.', 'rep.group.home': 'Hjemmeforsvar', 'rep.group.reinf': 'Forsterkninger fra {town}', 'rep.group.offline': 'offline, uten forsvar', - 'rep.loot': 'Bytte', 'rep.cache': '{p} % av lageret var skjult i Racksalen.', 'rep.siege': 'Beleiring', 'rep.siege.line': '{name} skadet: nivå {a} → {b}', + 'rep.loot': 'Bytte', 'rep.lootLeft': 'Latt igjen', 'rep.lootLeft.why': 'Raiderne kunne ha båret dette, men Racksalen hjemme hadde ikke plass da de var tilbake. Det ble hos målet.', 'rep.cache': '{p} % av lageret var skjult i Racksalen.', 'rep.siege': 'Beleiring', 'rep.siege.line': '{name} skadet: nivå {a} → {b}', 'rep.takeover': 'Oppkjøp', 'rep.takeover.loyalty': 'Kundelojalitet', 'rep.takeover.capital': 'En hovedstad kan ikke skifte eier, bare tappes.', 'rep.takeover.captured': 'POP-en har nå ny eier.', 'rep.takeover.blocked.last_pop': 'Målets siste POP kan ikke tas.', 'rep.takeover.blocked.footprint': 'Fotavtrykket ditt er for lavt til å holde enda en POP.', 'rep.intel': 'Etterretning', 'rep.intel.resources': 'Ressurser på lager', 'rep.intel.units': 'Enheter', 'rep.intel.offline': 'Enhetene deres er offline.', 'rep.intel.buildings': 'Bygninger', 'rep.intel.outgoing': 'Bevegelsene deres', 'alerts.incoming': 'Innkommende bevegelse', 'alerts.incoming.at': 'På vei mot {town}, ankommer {time}', 'alerts.report': 'Ny rapport: {type}', 'alerts.train_done': '{n} × {unit} ferdig trent', 'alerts.research_done': '{unit}: {stat} nivå {level} ferdig forsket', - 'alerts.movement_returned': 'Enhetene er hjemme', 'alerts.movement_lost': 'En bevegelse fant ikke veien hjem', + 'alerts.cargo_lost': 'GIKK TAPT, Rack-hallen var full: {what}', 'alerts.movement_returned': 'Enhetene er hjemme', 'alerts.movement_lost': 'En bevegelse fant ikke veien hjem', 'alerts.transport_arrived': 'Last kom frem til {town}', 'alerts.transport_delivered': 'Lasten din er levert', 'alerts.units_offline': 'Enheter gikk offline: tomt batteri', 'alerts.units_decommissioned': 'Enheter avviklet etter for lenge uten strøm', 'alerts.town_lost': '{name} ble overtatt', 'alerts.town_lost.by': 'Av {name}', 'alerts.town_gained': '{name} er nå din', 'alerts.reinforcements_home': 'Forsterkninger sendt hjem', + 'alerts.garrison_arrived': 'Enhetene dine ble med i garnisonen på landingspunkt {n}', 'alerts.garrison_released': 'Enhetene dine forlot landingspunkt {n} og er på vei hjem', + 'alerts.garrison_released.alliance_dissolved': 'Alliansen ble oppløst', 'alerts.garrison_released.left_alliance': 'Du er ikke lenger i alliansen som holder det', 'alerts.garrison_released.town_lost': 'POP-en de hører til ble overtatt', 'alerts.garrison_released.other': 'Kalt hjem', 'exp.title': 'Ekspansjon', 'exp.count': '{n} POP-er', 'exp.crews': 'Utrullingslag hjemme', 'exp.footprint': 'Fotavtrykk (denne POP-en / kreves totalt)', 'exp.footprint.v': '{have} / {need}', 'exp.range': 'Rekkevidde fra dine POP-er', 'exp.hint': 'Tre utrullingslag etablerer en POP på tomt land. En ny POP krever også nok totalt fotavtrykk.', diff --git a/public/js/strings/trade.js b/public/js/strings/trade.js index 23f87dd..1613fdf 100644 --- a/public/js/strings/trade.js +++ b/public/js/strings/trade.js @@ -33,7 +33,7 @@ 'trd.new.match': 'Match', 'trd.new.band': 'Fair range for what you ask: {lo} to {hi}.', 'trd.new.maxDist': 'Max distance (tiles)', 'trd.new.maxDistHint': 'Only POPs this close can take it. 1 to {max}.', 'trd.new.level': 'Posting needs an Internet exchange of level 1 or higher: this POP has level {lv} (reach {reach} tiles). A taker needs level {need} to trade across {d} tiles.', - 'trd.new.rules': 'Each side fits one transport link, at most {cap}, and the two amounts may differ by at most 1:{n}. What you give is held in escrow and one link is reserved until somebody takes the offer, you cancel it, or it expires after {ttl}.', + 'trd.new.rules': 'Each side fits one transport link, at most {cap}, and the two amounts may differ by at most 1:{n}. What you give is held in escrow and one link is reserved until somebody takes the offer, you cancel it, or it expires after {ttl}. The goods keep their room in your Rack hall meanwhile (that store stops filling by that amount below the hall size), so they always fit back.', 'trd.new.links': 'Free transport links here: {free} of {links}.', 'trd.new.go': 'Post offer', 'trd.new.done': 'Offer posted. The goods wait in escrow.', 'trd.v.giveRes': 'Pick a resource to give.', 'trd.v.wantRes': 'Give and want must be different resources.', 'trd.v.giveAmount': 'Give at least 1.', 'trd.v.wantAmount': 'Ask for at least 1.', 'trd.v.maxDistance': 'Max distance must be a whole number of tiles.', 'trd.v.terms': 'Check the terms.', @@ -51,6 +51,7 @@ 'trd.err.range': 'That POP is {d} tiles away. The offer reaches {max} tiles and your exchange reaches {reach}.', 'trd.err.ratio': 'The two amounts may differ by at most 1:{n}.', 'trd.err.cap': 'Each side must fit one transport link: at most {n}.', 'err.trade_ratio': 'The two amounts may differ by at most 1:2.', 'err.offer_closed': 'That offer is not open any more.', 'err.own_offer': 'You cannot take your own offer.', + 'err.no_room_for_goods': 'Your Rack hall will not have room for those goods when they arrive: spend some stock or raise the hall first.', 'err.trade_out_of_range': 'That POP is too far from the offer: its max distance or your exchange reach is exceeded.', }, nb: { @@ -81,7 +82,7 @@ 'trd.new.match': 'Likt', 'trd.new.band': 'Rimelig område for det du ber om: {lo} til {hi}.', 'trd.new.maxDist': 'Maks avstand (felt)', 'trd.new.maxDistHint': 'Bare POP-er så nær kan ta det. 1 til {max}.', 'trd.new.level': 'Å legge ut krever et Internettknutepunkt på nivå 1 eller høyere: denne POP-en har nivå {lv} (rekkevidde {reach} felt). Den som tar det trenger nivå {need} for å handle over {d} felt.', - 'trd.new.rules': 'Hver side må rommes av én transportlenke, maks {cap}, og de to mengdene kan avvike med høyst 1:{n}. Det du gir holdes i depot og én lenke reserveres til noen tar tilbudet, du trekker det, eller det utløper etter {ttl}.', + 'trd.new.rules': 'Hver side må rommes av én transportlenke, maks {cap}, og de to mengdene kan avvike med høyst 1:{n}. Det du gir holdes i depot og én lenke reserveres til noen tar tilbudet, du trekker det, eller det utløper etter {ttl}. Varene beholder plassen sin i Racksalen i mellomtiden (lageret slutter å fylles så mye under salens størrelse), så de får alltid plass igjen.', 'trd.new.links': 'Ledige transportlenker her: {free} av {links}.', 'trd.new.go': 'Legg ut tilbud', 'trd.new.done': 'Tilbudet er lagt ut. Varene venter i depot.', 'trd.v.giveRes': 'Velg en ressurs å gi.', 'trd.v.wantRes': 'Du må gi og ønske ulike ressurser.', 'trd.v.giveAmount': 'Gi minst 1.', 'trd.v.wantAmount': 'Be om minst 1.', 'trd.v.maxDistance': 'Maks avstand må være et helt antall felt.', 'trd.v.terms': 'Sjekk vilkårene.', @@ -99,6 +100,7 @@ 'trd.err.range': 'Den POP-en er {d} felt unna. Tilbudet rekker {max} felt og knutepunktet ditt rekker {reach}.', 'trd.err.ratio': 'De to mengdene kan avvike med høyst 1:{n}.', 'trd.err.cap': 'Hver side må rommes av én transportlenke: høyst {n}.', 'err.trade_ratio': 'De to mengdene kan avvike med høyst 1:2.', 'err.offer_closed': 'Det tilbudet er ikke åpent lenger.', 'err.own_offer': 'Du kan ikke ta ditt eget tilbud.', + 'err.no_room_for_goods': 'Rack-hallen din får ikke plass til varene når de kommer: bruk noe av lageret eller bygg ut hallen først.', 'err.trade_out_of_range': 'Den POP-en er for langt unna tilbudet: maks avstand eller knutepunktets rekkevidde er overskredet.', }, }); diff --git a/public/js/strings/world.js b/public/js/strings/world.js index 1d2bfcc..2f8b6fa 100644 --- a/public/js/strings/world.js +++ b/public/js/strings/world.js @@ -33,12 +33,18 @@ 'wld.ship.head': 'Ship resources', 'wld.ship.no': 'Only members of the holding alliance can ship.', 'wld.ship.go': 'Ship', 'wld.ship.cargo': 'Cargo', 'wld.ship.hint': 'A shipment is a transport: up to {n} per link. It lands in the stockpile, or rides home if the site has changed hands on the way.', 'wld.ship.done': 'Shipment on its way.', 'wld.ledger': 'Who shipped what', + 'wld.gar.head': 'Garrison', 'wld.gar.static': 'Static defence', 'wld.gar.units': 'Stationed units', 'wld.gar.total': 'Whole defence', 'wld.gar.empty': 'Nobody has stationed units here. A held site is only as strong as its garrison.', + 'wld.gar.hint': 'Members of the alliance can station units here (Station units). They defend together with the static part, draw power from the POP they come from, and a lost wave only kills part of them. A won attack wipes them all.', + 'wld.gar.station': 'Station units', 'wld.gar.withdraw': 'Call home', 'wld.gar.withdrawn': 'Units on their way home.', 'wld.gar.offline': 'offline (no power at home)', 'wld.gar.mine': 'yours', 'wld.gar.share': '{p}% of the defence', 'wld.results': 'Final standings', 'wld.rank.operators': 'Operators', 'wld.rank.alliances': 'Alliances', 'wld.rank.attackers': 'Attackers', 'wld.rank.defenders': 'Defenders', 'wld.rank.empty': 'Nobody on this list.', 'wld.rank.totals': '{o} operators in {a} alliances', 'tile.backbone': 'Backbone landing site', 'map.legend.backbone': 'Landing site', 'map.info.openWorld': 'Backbone race', 'map.info.backbone': 'A backbone landing site. The first alliance to build the node here to level {max} wins the world.', - 'send.landing.hint': 'A landing site has no garrison: only its static defence counts (a scan shows the number, about {mult} times an incumbent site). Winning makes your alliance the holder.', + 'send.landing.hint': 'A landing site is defended by its static defence (a scan shows the number: about {mult} times an incumbent site while nobody holds it, much less once an alliance does) plus the garrison its holders have stationed there. A lost wave only kills part of the garrison, so the next one faces less. Winning wipes the garrison and makes your alliance the holder.', + 'send.landing.reinforce': 'Units you station here defend the site together with the other members\' garrison and keep drawing power from the POP they come from. Only members of the holding alliance can. You can call them home at any time from the site sheet; they leave automatically if you leave the alliance.', + 'send.invalid.site_shielded': 'The site changed hands recently and cannot be attacked yet (see the site card).', 'wld.shield': 'Protected until {t}', + 'send.invalid.not_holder': 'Only members of the alliance that holds the site can station units there.', 'send.transport.rival': 'This is a POP you do not own: the cargo is a gift, and its owner sees an incoming movement until it lands. For a trade use the Internet exchange.', 'send.reason.no_alliance': 'only alliance members can attack a landing site', 'send.reason.own_site': 'your alliance already holds this site', 'send.invalid.no_alliance': 'Join an alliance first.', 'send.invalid.own_site': 'Your alliance holds that site.', @@ -48,6 +54,7 @@ 'report.type.landing': 'Landing site attack', 'rep.vs': '{a} vs {d}', 'rep.by': 'By {name}', 'rep.attackerWon': 'Attacker won', 'rep.defenderWon': 'Defender won', 'rep.landing.title': 'Landing site {n}', 'rep.landing.taken': 'Site taken', 'rep.landing.held': 'Site held', 'rep.landing.holder': 'Holder', + 'rep.landing.garrisonOf': 'Garrison of {name}', 'rep.landing.takenLine': '{tag} took the site.', 'rep.landing.heldLine': 'The defence held. The site did not change hands.', 'rep.tab.mine': 'My reports', 'rep.tab.alliance': 'Alliance', 'rep.sharedBy': 'shared by {name}', 'rep.folder.none': 'Join an alliance to use the shared folder.', 'rep.folder.empty': 'Nothing shared yet. Open a report and share it with the alliance.', @@ -86,12 +93,18 @@ 'wld.ship.head': 'Send ressurser', 'wld.ship.no': 'Bare medlemmer av eieralliansen kan sende.', 'wld.ship.go': 'Send', 'wld.ship.cargo': 'Last', 'wld.ship.hint': 'En forsendelse er en transport: opptil {n} per lenke. Den lander på lageret, eller drar hjem hvis punktet har skiftet eier underveis.', 'wld.ship.done': 'Forsendelsen er på vei.', 'wld.ledger': 'Hvem sendte hva', + 'wld.gar.head': 'Garnison', 'wld.gar.static': 'Statisk forsvar', 'wld.gar.units': 'Stasjonerte enheter', 'wld.gar.total': 'Hele forsvaret', 'wld.gar.empty': 'Ingen har stasjonert enheter her. Et holdt punkt er bare så sterkt som garnisonen.', + 'wld.gar.hint': 'Medlemmer av alliansen kan stasjonere enheter her (Stasjoner enheter). De forsvarer sammen med den statiske delen, trekker strøm fra POP-en de kommer fra, og en tapt bølge dreper bare en del av dem. Et vunnet angrep tømmer alle.', + 'wld.gar.station': 'Stasjoner enheter', 'wld.gar.withdraw': 'Kall hjem', 'wld.gar.withdrawn': 'Enhetene er på vei hjem.', 'wld.gar.offline': 'offline (ingen strøm hjemme)', 'wld.gar.mine': 'dine', 'wld.gar.share': '{p}% av forsvaret', 'wld.results': 'Sluttresultat', 'wld.rank.operators': 'Operatører', 'wld.rank.alliances': 'Allianser', 'wld.rank.attackers': 'Angripere', 'wld.rank.defenders': 'Forsvarere', 'wld.rank.empty': 'Ingen på denne listen.', 'wld.rank.totals': '{o} operatører i {a} allianser', 'tile.backbone': 'Landingspunkt for ryggraden', 'map.legend.backbone': 'Landingspunkt', 'map.info.openWorld': 'Ryggradskappløpet', 'map.info.backbone': 'Et landingspunkt for ryggraden. Første allianse som bygger noden her til nivå {max} vinner verdenen.', - 'send.landing.hint': 'Et landingspunkt har ingen garnison: bare det statiske forsvaret teller (en skanning viser tallet, omtrent {mult} ganger et inkumbentpunkt). Seier gjør alliansen din til eier.', + 'send.landing.hint': 'Et landingspunkt forsvares av sitt statiske forsvar (en skanning viser tallet: omtrent {mult} ganger et inkumbentpunkt så lenge ingen holder det, mye mindre når en allianse gjør det) pluss garnisonen holderne har stasjonert der. En tapt bølge dreper bare en del av garnisonen, så den neste møter mindre. Seier tømmer garnisonen og gjør alliansen din til eier.', + 'send.landing.reinforce': 'Enheter du stasjonerer her forsvarer punktet sammen med garnisonen til de andre medlemmene og trekker fortsatt strøm fra POP-en de kommer fra. Bare medlemmer av eieralliansen kan. Du kan kalle dem hjem når som helst fra punktarket; de går automatisk hjem hvis du forlater alliansen.', + 'send.invalid.site_shielded': 'Punktet skiftet eier nylig og kan ikke angripes ennå (se punktkortet).', 'wld.shield': 'Beskyttet til {t}', + 'send.invalid.not_holder': 'Bare medlemmer av alliansen som holder punktet kan stasjonere enheter der.', 'send.transport.rival': 'Dette er en POP du ikke eier: lasten er en gave, og eieren ser en innkommende bevegelse til den lander. For handel, bruk Internettknutepunktet.', 'send.reason.no_alliance': 'bare alliansemedlemmer kan angripe et landingspunkt', 'send.reason.own_site': 'alliansen din holder allerede dette punktet', 'send.invalid.no_alliance': 'Bli med i en allianse først.', 'send.invalid.own_site': 'Alliansen din holder det punktet.', @@ -101,6 +114,7 @@ 'report.type.landing': 'Angrep på landingspunkt', 'rep.vs': '{a} mot {d}', 'rep.by': 'Av {name}', 'rep.attackerWon': 'Angriper vant', 'rep.defenderWon': 'Forsvarer vant', 'rep.landing.title': 'Landingspunkt {n}', 'rep.landing.taken': 'Punktet ble tatt', 'rep.landing.held': 'Punktet holdt', 'rep.landing.holder': 'Eier', + 'rep.landing.garrisonOf': 'Garnisonen til {name}', 'rep.landing.takenLine': '{tag} tok punktet.', 'rep.landing.heldLine': 'Forsvaret holdt. Punktet skiftet ikke eier.', 'rep.tab.mine': 'Mine rapporter', 'rep.tab.alliance': 'Allianse', 'rep.sharedBy': 'delt av {name}', 'rep.folder.none': 'Bli med i en allianse for å bruke den delte mappen.', 'rep.folder.empty': 'Ingenting delt ennå. Åpne en rapport og del den med alliansen.', diff --git a/server/commands/allianceKick.js b/server/commands/allianceKick.js index 03cb958..674a5c0 100644 --- a/server/commands/allianceKick.js +++ b/server/commands/allianceKick.js @@ -13,6 +13,7 @@ module.exports = function allianceKick(ctx, { userId, allianceId, operatorId }) if (!R.outranks(member.role, t.role)) throw new GameError('forbidden', { need: 'outrank', role: member.role, targetRole: t.role }); const target = db.get('SELECT id, name FROM operators WHERE id = ?', operatorId); A.removeMember(db, operatorId); + require('../military/garrison').releaseOperator(require('../military/ctx')(ctx), operatorId, 'left_alliance'); // its units standing in the alliance's landing sites go home A.notifyOperator(ctx, operatorId, 'alliance_kicked', { allianceId: alliance.id, tag: alliance.tag, name: alliance.name }); A.notifyAlliance(ctx, alliance.id, 'alliance_member_left', { allianceId: alliance.id, operatorId, name: target.name, kicked: true }); return { changed: true }; diff --git a/server/commands/allianceLeave.js b/server/commands/allianceLeave.js index c9c4565..31d972e 100644 --- a/server/commands/allianceLeave.js +++ b/server/commands/allianceLeave.js @@ -18,6 +18,7 @@ module.exports = function allianceLeave(ctx, { userId, allianceId }) { return { changed: true, disbanded: true }; } A.removeMember(db, op.id); + require('../military/garrison').releaseOperator(require('../military/ctx')(ctx), op.id, 'left_alliance'); // its units standing in the alliance's landing sites go home A.notifyAlliance(ctx, alliance.id, 'alliance_member_left', { allianceId: alliance.id, operatorId: op.id, name: op.name, kicked: false }); return { changed: true, disbanded: false }; }; diff --git a/server/commands/cancelBuild.js b/server/commands/cancelBuild.js index 42b78d1..80aff9d 100644 --- a/server/commands/cancelBuild.js +++ b/server/commands/cancelBuild.js @@ -14,8 +14,8 @@ module.exports = function cancelBuild(ctx, { userId, townId, eventId }) { if (!ev) throw new GameError('not_found', { what: 'queue entry' }); settle(db, town, now); const cost = JSON.parse(ev.payload).cost || {}; - const cap = require('../../public/js/rules.js').storageCap(town); - for (const r of D.RESOURCES) town.res[r] = Math.min(Math.max(cap, town.res[r]), town.res[r] + Math.floor((cost[r] || 0) * REFUND)); + const R = require('../../public/js/rules.js'); + for (const r of D.RESOURCES) town.res[r] = Math.min(Math.max(R.storageCapOf(town, r), town.res[r]), town.res[r] + Math.floor((cost[r] || 0) * REFUND)); db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', town.res.fiber, town.res.hardware, town.res.capital, town.id); db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ?", now, ev.id); return { cancelled: ev.id }; diff --git a/server/commands/index.js b/server/commands/index.js index cafd32a..640737c 100644 --- a/server/commands/index.js +++ b/server/commands/index.js @@ -48,6 +48,7 @@ const handlers = { tradeAccept: require('./tradeAccept'), backboneBuild: require('./backboneBuild'), backboneShip: require('./backboneShip'), + withdrawGarrison: require('./withdrawGarrison'), }; function createCommands({ db, clock, scheduler }) { diff --git a/server/commands/sendMovement.js b/server/commands/sendMovement.js index 384cfa6..6405be8 100644 --- a/server/commands/sendMovement.js +++ b/server/commands/sendMovement.js @@ -95,9 +95,13 @@ module.exports = function sendMovement(ctx0, args) { extra.target = t; } } else if (type === 'reinforce') { - if (!tgt.town) throw new GameError('invalid_target', { reason: 'no_town' }); - if (!U.mayReinforce(db, op.id, tgt.town.owner_id)) throw new GameError('invalid_target', { reason: 'not_allied' }); - defOp = U.getOperator(db, tgt.town.owner_id); + if (!tgt.town && tgt.tile.type === 'backbone') { + require('../endgame').checkLandingReinforce(db, world, op, tgt, now, ctx); // the garrison of a landing site: members of the holder only + } else { + if (!tgt.town) throw new GameError('invalid_target', { reason: 'no_town' }); + if (!U.mayReinforce(db, op.id, tgt.town.owner_id)) throw new GameError('invalid_target', { reason: 'not_allied' }); + defOp = U.getOperator(db, tgt.town.owner_id); + } } else if (type === 'settle') { const own = U.operatorTowns(db, op.id); let nearest = Infinity; @@ -119,6 +123,7 @@ module.exports = function sendMovement(ctx0, args) { const uid = U.userOfOperator(db, defOp.id); if (uid) ctx.notify(uid, from.worldId, 'incoming', { movementId: mv.id, toTownId: tgt.town.id, fromTownId: from.id, arriveAt }); // type hidden } + if (!tgt.town && tgt.tile.type === 'backbone' && (type === 'attack' || type === 'scan')) require('../endgame').notifyLandingIncoming(ctx, world, tgt, op, mv); return { movementId: mv.id, type, fromTownId: from.id, toTownId: tgt.town ? tgt.town.id : null, to: { x: tgt.x, y: tgt.y }, units, departAt: now, arriveAt, protectionEnded: endProtection }; }; module.exports.resolveTarget = resolveTarget; diff --git a/server/commands/tradeAccept.js b/server/commands/tradeAccept.js index 74cc06c..e2ce3e8 100644 --- a/server/commands/tradeAccept.js +++ b/server/commands/tradeAccept.js @@ -5,12 +5,14 @@ * the usual transport rules: capacity, resources), * - the poster's escrow leaves as a transport to the acceptor's POP (on the link the open offer held in reserve), * - the offer becomes `accepted`; it is `completed` when both transports have been delivered (see server/trade.js). - * Any failure rolls everything back. Not your own offer; the acceptor's POP needs an Internet exchange and must be in range + * Any failure rolls everything back. Not your own offer; the acceptor's Rack hall must have room for the goods when they arrive + * (projected: stock after paying, plus production, minus other cargo already on its way to this POP), else `no_room_for_goods` + * (goods that do not fit on arrival are destroyed, so the trade is refused up front; economics are otherwise unchanged); the acceptor's POP needs an Internet exchange and must be in range * (the offer's max distance and the exchange's reach). */ const R = require('../../public/js/rules.js'); const { GameError } = require('../errors'); -const { settle, loadWorld } = require('../state'); +const { settle, loadWorld, loadTown } = require('../state'); const { ownedTown } = require('./build'); const { launchTransport } = require('./sendTransport'); const ctxOf = require('../military/ctx'); @@ -32,15 +34,22 @@ module.exports = function tradeAccept(ctx0, { userId, offerId, townId }) { if (level < 1) throw new GameError('no_transport_link', { links: 0, active: 0 }); if (!R.tradeInRange(dist, o.max_distance, level)) throw new GameError('trade_out_of_range', { distance: dist, maxDistance: o.max_distance, reach: R.tradeReach(level) }); settle(db, mine, now); + settle(db, loadTown(db, poster.id), now); // the escrow leaves the poster's Rack hall now: settle under the cap it shaped (rules.storageCapOf) // acceptor -> poster: the wanted resource (validates links, capacity and resources, deducts, inserts the movement) const pay = launchTransport(ctx, mine, poster, { [o.want_res]: o.want_amount }, { tradeId: o.id, role: 'payment' }); // poster -> acceptor: the escrow const world = loadWorld(db, o.world_id); + const arriveAt = now + R.transportMs(dist, world.speed); + const room = R.resourcesAt(mine, arriveAt); // `mine` is settled and already paid; production until arrival is projected + let booked = 0; // cargo of this resource already on its way here will take room first + for (const row of db.all("SELECT cargo FROM movements WHERE status = 'out' AND to_town_id = ? AND type IN ('transport', 'return')", mine.id)) booked += JSON.parse(row.cargo || '{}')[o.give_res] || 0; + const free = Math.floor(room.caps[o.give_res] - room.amounts[o.give_res] - booked); + if (free < o.give_amount) throw new GameError('no_room_for_goods', { resource: o.give_res, amount: o.give_amount, room: Math.max(0, free) }); const goods = M.insertMovement(ctx, { worldId: o.world_id, ownerId: o.operator_id, type: 'transport', fromTownId: poster.id, toTownId: mine.id, from: { x: poster.x, y: poster.y }, to: { x: mine.x, y: mine.y }, units: {}, cargo: { [o.give_res]: o.give_amount }, - departAt: now, arriveAt: now + R.transportMs(dist, world.speed), extra: { tradeId: o.id, role: 'goods' }, + departAt: now, arriveAt, extra: { tradeId: o.id, role: 'goods' }, }); db.run("UPDATE trade_offers SET status = 'accepted', accepted_by_operator = ?, accepted_town_id = ?, accepted_at = ?, goods_movement_id = ?, payment_movement_id = ? WHERE id = ?", mine.ownerId, mine.id, now, goods.id, pay.id, o.id); diff --git a/server/commands/tradeCancel.js b/server/commands/tradeCancel.js index 02fe5d0..7f1b0cd 100644 --- a/server/commands/tradeCancel.js +++ b/server/commands/tradeCancel.js @@ -10,6 +10,6 @@ module.exports = function tradeCancel(ctx0, { userId, offerId }) { const o = T.getOffer(db, offerId); if (!o || T.userOfOperator(db, o.operator_id) !== userId) throw new GameError('not_found', { what: 'offer' }); if (o.status !== 'open') throw new GameError('offer_closed', { status: o.status }); - T.closeOffer(ctx, o, 'cancelled', now); - return { offerId: o.id, status: 'cancelled', returned: { resource: o.give_res, amount: o.give_amount } }; + const back = T.closeOffer(ctx, o, 'cancelled', now); + return { offerId: o.id, status: 'cancelled', returned: { resource: o.give_res, amount: Math.round(back.credited) } }; }; diff --git a/server/commands/tradeOffer.js b/server/commands/tradeOffer.js index 78fd2fe..3566872 100644 --- a/server/commands/tradeOffer.js +++ b/server/commands/tradeOffer.js @@ -15,7 +15,7 @@ const T = require('../trade'); module.exports = function tradeOffer(ctx, { userId, townId, giveRes, giveAmount, wantRes, wantAmount, maxDistance }) { const { db, now, scheduler } = ctx; const town = ownedTown(db, userId, townId); - const terms = R.tradeTermsCheck({ giveRes, giveAmount, wantRes, wantAmount, maxDistance }); + const terms = R.tradeTermsCheck({ giveRes, giveAmount, wantRes, wantAmount, maxDistance }, town.speed); if (!terms.ok) throw new GameError(terms.code, terms); const links = R.transportLinks(town); const inUse = M.activeLinks(db, town.id); diff --git a/server/commands/withdrawGarrison.js b/server/commands/withdrawGarrison.js new file mode 100644 index 0000000..2d66ed7 --- /dev/null +++ b/server/commands/withdrawGarrison.js @@ -0,0 +1,30 @@ +'use strict'; +/* + * POST /backbone/:id/withdraw {fromTownId, units?}: units of one of YOUR POPs that stand in a landing site go home. Only their owner can + * call them back (the holding alliance has no way to send somebody else's units away; leaving the alliance does it automatically). + * `units` defaults to the whole group. They stop defending the site and stop drawing the owner's power at once, and drive home as a + * return movement (so they are in no battle on the way). Works whoever holds the site now, also after it changed hands. + */ +const { GameError } = require('../errors'); +const { ownedTown } = require('./build'); +const ctxOf = require('../military/ctx'); +const U = require('../military/units'); +const G = require('../military/garrison'); +const E = require('../endgame'); + +module.exports = function withdrawGarrison(ctx0, { userId, siteId, fromTownId, units }) { + const ctx = ctxOf(ctx0); + const { db } = ctx; + const site = E.siteRow(db, siteId); + if (!site) throw new GameError('not_found', { what: 'landing site' }); + const owner = ownedTown(db, userId, fromTownId); + if (owner.worldId !== site.world_id) throw new GameError('not_found', { what: 'town' }); + const have = G.ownedAt(db, site.id, owner.id); + let take = units && Object.keys(units).length ? U.cleanUnits(units) : have; + take = Object.fromEntries(Object.entries(take).filter(([, n]) => n > 0)); + if (U.isEmpty(take)) throw new GameError('not_enough_units', { reason: 'nothing stationed' }); + for (const k of Object.keys(take)) if ((have[k] || 0) < take[k]) throw new GameError('not_enough_units', { unit: k, have: have[k] || 0, want: take[k] }); + const mv = G.sendHome(ctx, site, owner.id, take, { withdrawn: true }); + if (!mv) throw new GameError('conflict', { what: 'no POP to return to' }); + return { movementId: mv.id, siteId: site.id, fromTownId: owner.id, units: take, arriveAt: mv.arriveAt }; +}; diff --git a/server/endgame.js b/server/endgame.js index 6f5126c..a53ce72 100644 --- a/server/endgame.js +++ b/server/endgame.js @@ -5,8 +5,9 @@ * Representation (DECISIONS.md E1): a landing site is NOT a POP. It is a row of `landing_sites` (position from the world seed, * holder alliance, node level, stockpile, build in progress). The tile reads 'backbone' (rules.tileAt with the world age) from * D.ENDGAME.openDay on; before that it is plain land that nobody may settle or spawn on. A site is defended by a static value - * only (rules.backboneDefence: incumbent defence x defenceMult, + a bonus per node level), so there are no reinforcements at a - * site. Holders keep the level when the site is taken; the stockpile and a running build stay with the site as well. + * (rules.backboneDefence: incumbent defence x defenceMult while nobody holds it, x heldDefenceMult once an alliance does, + a bonus per node + * level) PLUS the garrison its holders station there (server/military/garrison.js, DECISIONS E6). The level stays with the site when it is + * taken; the stockpile and a running build stay with the site as well. * * Time: world age is in world days (real days x speed). Everything here takes `now` (ms) from the caller. */ @@ -61,7 +62,7 @@ function siteView(db, world, s, row) { id: row ? row.id : null, index: s.index, x: s.x, y: s.y, holder: row ? allianceInfo(db, row.holder_alliance_id) : null, takenBy: row ? opBrief(db, row.holder_operator_id) : null, takenAt: row ? row.taken_at : null, - level, maxLevel: E.maxLevel, progress: level / E.maxLevel, pool, build, + level, maxLevel: E.maxLevel, progress: level / E.maxLevel, pool, build, shieldUntil: row && shieldUntil(row, world) || null, next: level < E.maxLevel ? { toLevel: level + 1, cost: R.backboneCost(level + 1), durationMs: R.backboneTimeMs(level + 1, world.speed) } : null, }; } @@ -121,14 +122,31 @@ function notifyWorld(ctx, worldId, type, payload) { // ---------------------------------------------------------------- taking a site, winning, the end -// Sending checks (sendMovement): landing sites can be scanned and attacked, nothing else. Attacking needs an alliance; you cannot -// attack a site your own alliance or a pact partner holds. +// Sending checks (sendMovement): landing sites can be scanned and attacked, and reinforced by members of the alliance that holds them; +// nothing else. Attacking needs an alliance; you cannot attack a site your own alliance or a pact partner holds. function checkLandingTarget(db, world, op, tgt, type, now, ctx) { if (type !== 'scan' && type !== 'attack') throw new GameError('invalid_target', { reason: 'landing_scan_or_attack_only' }); if (type !== 'attack') return; if (!op.alliance_id) throw new GameError('invalid_target', { reason: 'no_alliance' }); const row = ensureSites(db, world, now, ctx).find((r) => r.idx === tgt.tile.site); denyIfFriendly(db, op, row); + const until = shieldUntil(row, world); + if (until > now) throw new GameError('invalid_target', { reason: 'site_shielded', until }); +} +// A site that changed hands is shielded for D.ENDGAME.captureShieldHours (E6): its new holders need time to garrison it. 0 = not shielded (unheld sites never are). +function shieldUntil(row, world) { + return row && row.holder_alliance_id && row.taken_at ? R.siteShieldUntil(row.taken_at, world.speed) : 0; +} +// Reinforcing a landing site (the garrison, E6): members of the holding alliance only. Checked again when the units arrive. +function checkLandingReinforce(db, world, op, tgt, now, ctx) { + const row = ensureSites(db, world, now, ctx).find((r) => r.idx === tgt.tile.site); + if (!op.alliance_id || !row || !row.holder_alliance_id || row.holder_alliance_id !== op.alliance_id) throw new GameError('invalid_target', { reason: 'not_holder' }); +} +// Tell the holders that something is on its way to their site (the type is hidden, like `incoming` for a POP). Nothing for an unheld site. +function notifyLandingIncoming(ctx, world, tgt, op, mv) { + const row = siteAt(ctx.db, world.id, tgt.tile.site); + if (!row || !row.holder_alliance_id || row.holder_alliance_id === op.alliance_id) return; + notifyAlliance(ctx, row.holder_alliance_id, 'backbone_incoming', { siteId: row.id, index: row.idx, x: row.x, y: row.y, arriveAt: mv.arriveAt }); } function denyIfFriendly(db, op, row) { if (!row || !row.holder_alliance_id) return; @@ -163,7 +181,10 @@ function maybeWin(ctx, site, now) { } // An alliance is gone: its sites are the incumbent's again (the level stays with the site). -function onAllianceDissolved(ctx, allianceId) { +function onAllianceDissolved(ctx0, allianceId) { + const ctx = require('./military/ctx')(ctx0); + const G = require('./military/garrison'); + for (const s of ctx.db.all('SELECT * FROM landing_sites WHERE holder_alliance_id = ?', allianceId)) G.releaseSite(ctx, s, 'alliance_dissolved'); // the garrison goes home ctx.db.run('UPDATE landing_sites SET holder_alliance_id = NULL WHERE holder_alliance_id = ?', allianceId); } @@ -188,5 +209,5 @@ function deliverShipment(ctx, mv, now) { module.exports = { DAY, ageDays, phase, isOpen, ensureSites, siteRow, siteAt, siteStates, siteView, allianceInfo, opBrief, winnerView, statusView, - guard, worldOfCommand, notifyAlliance, notifyWorld, checkLandingTarget, denyIfFriendly, transferSite, maybeWin, onAllianceDissolved, deliverShipment, + guard, worldOfCommand, notifyAlliance, notifyWorld, checkLandingTarget, shieldUntil, checkLandingReinforce, notifyLandingIncoming, denyIfFriendly, transferSite, maybeWin, onAllianceDissolved, deliverShipment, }; diff --git a/server/endgameQueries.js b/server/endgameQueries.js index 7f0c931..b391a8b 100644 --- a/server/endgameQueries.js +++ b/server/endgameQueries.js @@ -7,6 +7,7 @@ const { GameError } = require('./errors'); const { loadWorld } = require('./state'); const A = require('./alliances'); const E = require('./endgame'); +const Garrison = require('./military/garrison'); function createEndgameQueries({ db, clock, scheduler }) { const fresh = () => { scheduler.runDue(); return clock.now(); }; @@ -35,8 +36,14 @@ function createEndgameQueries({ db, clock, scheduler }) { const s = R.backboneSites(w.seed, w.map_radius).find((x) => x.index === row.idx); const m = A.membership(db, op.id); const holder = !!(m && row.holder_alliance_id && m.alliance_id === row.holder_alliance_id); - const out = { serverTime: now, site: E.siteView(db, w, s, row), you: { holder, canBuild: holder && R.allianceCan(m.role, 'backboneBuild'), canShip: holder, canAttack: !!op.alliance_id && !(holder) } }; + const out = { serverTime: now, site: E.siteView(db, w, s, row), you: { holder, canBuild: holder && R.allianceCan(m.role, 'backboneBuild'), canShip: holder, canAttack: !!op.alliance_id && !(holder), canReinforce: holder } }; if (holder) { + // what defends the site: the static part + the garrison (online groups only), and who owns the units (E6) + const gv = Garrison.view(db, row.id, now); + const mineTowns = new Set(db.all('SELECT id FROM towns WHERE owner_id = ?', op.id).map((t) => t.id)); + const st = R.backboneDefence(w.seed, row.x, row.y, E.ageDays(w, now), row.level, true); + out.defence = { static: st, garrison: gv.power, total: st + gv.power }; + out.garrison = gv.groups.map((g) => Object.assign({}, g, { mine: mineTowns.has(g.ownerTownId) })); out.contributions = db.all(`SELECT c.operator_id AS oid, o.name AS name, c.fiber, c.hardware, c.capital FROM landing_contributions c JOIN operators o ON o.id = c.operator_id WHERE c.site_id = ? ORDER BY (c.fiber + c.hardware + c.capital) DESC, c.operator_id`, row.id) .map((c) => ({ operatorId: c.oid, name: c.name, fiber: c.fiber, hardware: c.hardware, capital: c.capital })); diff --git a/server/errors.js b/server/errors.js index 02f2612..ad64f57 100644 --- a/server/errors.js +++ b/server/errors.js @@ -61,6 +61,7 @@ const CODES = { offer_closed: [409, 'That offer is not open any more.'], own_offer: [409, 'You cannot accept your own offer.'], trade_out_of_range: [409, 'That POP is too far from the offer (its max distance or your Internet exchange reach).'], + no_room_for_goods: [409, 'Your Rack hall will not have room for the goods when they arrive; make room (spend, or raise the hall) and accept again.'], world_ended: [409, 'This world has ended: it can still be read, but nothing can be changed.'], backbone_closed: [409, 'The backbone landing sites have not appeared yet.'], }; diff --git a/server/events/return.js b/server/events/return.js index 367783a..b98b640 100644 --- a/server/events/return.js +++ b/server/events/return.js @@ -22,7 +22,7 @@ module.exports = function ret(ctx, ev) { const town = loadTown(db, dest.id); settle(db, town, ev.dueAt); U.addHome(db, town.id, mv.units); - const lost = addCargo(db, town, mv.cargo); + const lost = addCargo(db, town, mv.cargo, mv.extra && mv.extra.bonus); P.reschedule(ctx, town.id, ev.dueAt); // Empty carriers coming home (extra.link) are silent; a bounced shipment that carries cargo is not: its overflow is reported. const carrying = D.RESOURCES.some((r) => mv.cargo && mv.cargo[r] > 0); diff --git a/server/events/tradeExpire.js b/server/events/tradeExpire.js index 81e6e7d..ba7a6f8 100644 --- a/server/events/tradeExpire.js +++ b/server/events/tradeExpire.js @@ -6,7 +6,7 @@ const T = require('../trade'); module.exports = function tradeExpire(ctx, ev) { const o = T.getOffer(ctx.db, ev.payload.offerId); if (!o || o.status !== 'open') return; - T.closeOffer(ctx, o, 'expired', ev.dueAt); + const back = T.closeOffer(ctx, o, 'expired', ev.dueAt); const uid = T.userOfOperator(ctx.db, o.operator_id); - if (uid) ctx.notify(uid, o.world_id, 'trade_expired', { offerId: o.id, townId: o.town_id, returned: { resource: o.give_res, amount: o.give_amount } }); + if (uid) ctx.notify(uid, o.world_id, 'trade_expired', { offerId: o.id, townId: o.town_id, returned: { resource: o.give_res, amount: Math.round(back.credited) } }); }; diff --git a/server/migrations/005_site_garrison.sql b/server/migrations/005_site_garrison.sql new file mode 100644 index 0000000..39b7405 --- /dev/null +++ b/server/migrations/005_site_garrison.sql @@ -0,0 +1,12 @@ +-- Garrisons at backbone landing sites (docs/DECISIONS.md E6). Units of owner_town_id's operator standing in a landing site that the +-- operator's alliance holds. They defend the site (on top of its static defence) and draw the OWNER's power (state.unitDraw), because +-- a site has no power budget of its own. Same shape as `stationed`, whose host is a POP; a site is not a POP (E1), hence a table of its own. +-- Written only by commands/events inside their transaction; the bot ledger counts these units as alive. +CREATE TABLE site_stationed ( + site_id INTEGER NOT NULL REFERENCES landing_sites(id), + owner_town_id INTEGER NOT NULL REFERENCES towns(id), + unit TEXT NOT NULL, + count INTEGER NOT NULL CHECK (count > 0), + PRIMARY KEY (site_id, owner_town_id, unit) +); +CREATE INDEX site_stationed_owner ON site_stationed(owner_town_id); diff --git a/server/military/arrivals.js b/server/military/arrivals.js index 942d32e..c5df7b4 100644 --- a/server/military/arrivals.js +++ b/server/military/arrivals.js @@ -17,14 +17,15 @@ const townBrief = (t) => t ? { id: t.id, name: t.name, x: t.x, y: t.y } : null; const opBrief = (o) => o ? { id: o.id, name: o.name, asNumber: o.as_number } : null; // Add resources to a SETTLED town, capped at its storage (an amount already above the cap is kept). -> what was lost -function addCargo(db, town, cargo) { - const cap = R.storageCap(town); +// `bonus` (optional, per resource) is part of the cargo that is credited even above the Rack hall size (one-time rewards). +function addCargo(db, town, cargo, bonus) { const lost = {}; for (const r of D.RESOURCES) { const add = (cargo && cargo[r]) || 0; if (!add) continue; const cur = town.res[r]; - const next = Math.min(Math.max(cap, cur), cur + add); + const free = Math.max(0, add - ((bonus && bonus[r]) || 0)); + const next = Math.min(Math.max(R.storageCapOf(town, r), cur), cur + free) + (add - free); // escrowed goods of open offers keep their room (storageCapOf) lost[r] = Math.max(0, Math.round(cur + add - next)); town.res[r] = next; } @@ -50,6 +51,7 @@ function bounce(ctx, mv, now, reason, details) { function arriveReinforce(ctx, mv, ev) { const { db } = ctx; const now = ev.dueAt; + if (!mv.toTownId) return require('./landing').reinforce(ctx, mv, ev); // a backbone landing site: the garrison (E6) const target = mv.toTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.toTownId) : null; if (!target || !U.mayReinforce(db, mv.ownerId, target.owner_id)) return bounce(ctx, mv, now, 'not_allied'); const ownerTown = U.homeTownFor(db, mv.ownerId, mv.fromTownId); diff --git a/server/military/combat.js b/server/military/combat.js index dd7f05c..9524ab8 100644 --- a/server/military/combat.js +++ b/server/military/combat.js @@ -49,12 +49,34 @@ function addPoints(db, operatorId, column, v) { const sumValues = (list) => list.reduce((acc, u) => U.sumInto(acc, u), {}); // Survivors drive home (with loot). No survivors, no movement. -function sendHome(ctx, mv, survivors, cargo) { +function sendHome(ctx, mv, survivors, cargo, extra) { const { db } = ctx; if (U.isEmpty(survivors)) return null; const dest = U.homeTownFor(db, mv.ownerId, mv.fromTownId); if (!dest) return null; - return M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: survivors, cargo: cargo || {}, parentId: mv.id, extra: {} }); + return M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: mv.toTownId, at: mv.to, to: dest, units: survivors, cargo: cargo || {}, parentId: mv.id, extra: extra || {} }); +} + +// What the raiders' home can bank per resource when they are back: Rack hall room minus the stock projected to that moment (pure +// projection, nothing is written). No home or no survivors to carry anything: no room at all (the loot would never be delivered). +function homeRoom(ctx, mv, survivors, now, world) { + const none = { fiber: 0, hardware: 0, capital: 0 }; + const dest = U.homeTownFor(ctx.db, mv.ownerId, mv.fromTownId); + if (!dest || U.isEmpty(survivors)) return none; + const home = loadTown(ctx.db, dest.id); + const bankAt = now + R.movementMs(R.distance(mv.to.x, mv.to.y, dest.x, dest.y), survivors, world.speed); + const cur = R.resourcesAt(home, bankAt); + // Room already promised: cargo of other return legs still on the road to this POP (earlier raids, bounced shipments) will be banked + // too, so two raids that each see the same free room cannot both fill it (the later one is limited, not destroyed on landing). + // One-time bonus cargo (extra.bonus) is credited above the cap and holds no room. + const booked = { fiber: 0, hardware: 0, capital: 0 }; + for (const row of ctx.db.all("SELECT cargo, extra FROM movements WHERE type = 'return' AND status = 'out' AND to_town_id = ? AND owner_id = ?", dest.id, mv.ownerId)) { + const c = JSON.parse(row.cargo || '{}'), bonus = (JSON.parse(row.extra || '{}').bonus) || {}; + for (const r of D.RESOURCES) booked[r] += Math.max(0, (c[r] || 0) - (bonus[r] || 0)); + } + const room = {}; + for (const r of D.RESOURCES) room[r] = Math.max(0, Math.floor(cur.caps[r] - cur.amounts[r] - booked[r])); + return room; } function arrive(ctx, mv, ev) { @@ -106,12 +128,17 @@ function arrive(ctx, mv, ev) { // ---- loot let loot = { fiber: 0, hardware: 0, capital: 0 }; + const lootLeft = {}; // available and carried, but with no room to bank at home let hidden = 0; if (win) { hidden = kind === 'raid' ? R.cacheFraction(target.buildings.rack_hall ? target.buildings.rack_hall.level : 0) : 0; const avail = {}; for (const r of D.RESOURCES) avail[r] = target.res[r] * (1 - hidden); - loot = R.lootSplit(R.carryOf(survivorsAtt), avail); + // Only what the raiders' home Rack hall can bank when they arrive is taken; the rest stays with the victim and the report says so (S4). + const room = homeRoom(ctx, mv, survivorsAtt, now, world); + loot = R.lootSplit(R.carryOf(survivorsAtt), avail, room); + const wanted = R.lootSplit(R.carryOf(survivorsAtt), avail); + for (const r of D.RESOURCES) if (wanted[r] > loot[r]) lootLeft[r] = wanted[r] - loot[r]; for (const r of D.RESOURCES) target.res[r] -= loot[r]; db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', target.res.fiber, target.res.hardware, target.res.capital, target.id); } @@ -163,7 +190,7 @@ function arrive(ctx, mv, ev) { attacker: { operator: opBrief(attackerOp), town: townBrief(origin), units: { sent: mv.units, lost: attLost, survivors: survivorsAtt } }, defender: { operator: opBrief(defOp), town: townBrief(target), online, groups: groupReports.map((g) => ({ ownerTownId: g.ownerTownId, sent: g.sent, lost: g.lost, survivors: g.survivors, offline: g.offline })) }, power: { attack: b.A, defence: b.D, defenceRaw: b.defenceRaw, firewallLevel: fwLevel, effectiveFirewall: b.effectiveFirewall }, - loot, cacheHidden: hidden, siege, takeover, capturedTown: captured, returnMovementId: ret ? ret.id : null, + loot, lootLeft, cacheHidden: hidden, siege, takeover, capturedTown: captured, returnMovementId: ret ? ret.id : null, }; const summary = { type: mv.type, outcome: data.outcome, attacker: opBrief(attackerOp), defender: opBrief(defOp), target: townBrief(target), loot, captured }; const recipients = [{ userId: U.userOfOperator(db, attackerOp.id), role: 'attacker' }, { userId: U.userOfOperator(db, defOp.id), role: 'defender' }]; @@ -247,7 +274,9 @@ function arriveSite(ctx, mv, now, world) { bonus = { hardware: D.INCUMBENT.hardwareBonus, researchSpeedBonus: R.researchSpeedBonus(U.incumbentTakes(db, attackerOp.id)) }; } } - const ret = sendHome(ctx, mv, survivors, cargo); + // The once-only bonus is delivered in full even when the Rack hall is full (stock above the hall size is kept, it only stops growing): a reward + // that can never be earned again must not vanish at the door (S4, events/return.js reads extra.bonus). + const ret = sendHome(ctx, mv, survivors, cargo, bonus ? { bonus: { hardware: bonus.hardware } } : {}); createReport(ctx, { worldId: mv.worldId, type: 'incumbent', now, summary: { outcome: b.attackerWins ? 'attacker_won' : 'defender_won', site, bonus }, @@ -264,6 +293,7 @@ function arriveSite(ctx, mv, now, world) { // standing elsewhere are re-homed, the new owner starts at conqueredLoyalty. function transferTown(ctx, town, newOp, oldOp, now) { const { db } = ctx; + require('./garrison').releaseTown(ctx, town.id, 'town_lost'); // what this POP had standing in a landing site goes home to its old owner (E6) db.run('UPDATE towns SET owner_id = ?, is_capital = 0, loyalty = ?, loyalty_at = ? WHERE id = ?', newOp.id, D.EXPANSION.conqueredLoyalty, now, town.id); db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE town_id = ? AND type IN ('trainDone', 'researchDone') AND status = 'pending'", now, town.id); db.run("UPDATE events SET payload = json_set(payload, '$.userId', ?) WHERE town_id = ? AND type = 'buildDone' AND status = 'pending'", U.userOfOperator(db, newOp.id), town.id); diff --git a/server/military/garrison.js b/server/military/garrison.js new file mode 100644 index 0000000..bc384e8 --- /dev/null +++ b/server/military/garrison.js @@ -0,0 +1,139 @@ +'use strict'; +/* + * Garrisons at backbone landing sites (docs/DECISIONS.md E6): units of an operator whose alliance holds the site, standing in the + * site and defending it on top of its static defence. Table `site_stationed(site_id, owner_town_id, unit, count)`. + * + * Rules in one place: + * - Only members of the HOLDING alliance may station units (checked when sending and again when the units arrive). + * - The units draw the power of their OWNER's POP (state.unitDraw), so garrisoning moves no power around; they are online + * exactly when that POP's units are. Always loadTown + settle the owner BEFORE changing its garrison (the draw is part of its rates). + * - A unit lives in exactly one place: home (town_units), stationed in a POP, in a garrison, or in a movement. Every function here + * moves units, none creates or deletes them except through a battle report (losses) or `lost` below (no POP to go home to). + * - Units leave a garrison only by (a) the owner withdrawing them, (b) the owner leaving/being kicked from the alliance or the alliance + * dissolving, (c) the owner's POP changing hands, (d) dying in a battle, (e) decommission when the owner's POP has no power. + * (a) to (c) are return movements to the owner's home, so nothing is ever lost on the way. + */ +const R = require('../../public/js/rules.js'); +const D = require('../../public/js/data.js'); +const { GameError } = require('../errors'); +const { loadTown, settle } = require('../state'); +const U = require('./units'); +const M = require('./movements'); +const P = require('./power'); + +// Units of one owner POP in a site as { unit: count }. +function ownedAt(db, siteId, ownerTownId) { + const out = {}; + for (const r of db.all('SELECT unit, count FROM site_stationed WHERE site_id = ? AND owner_town_id = ?', siteId, ownerTownId)) out[r.unit] = r.count; + return out; +} + +// Everything standing in a site, grouped by owner POP: [{ ownerTownId, ownerOpId, units }] (ordered by owner POP id: a stable battle order). +function groups(db, siteId) { + const by = new Map(); + for (const r of db.all('SELECT s.owner_town_id AS tid, s.unit AS unit, s.count AS count, t.owner_id AS oid FROM site_stationed s LEFT JOIN towns t ON t.id = s.owner_town_id WHERE s.site_id = ? ORDER BY s.owner_town_id, s.unit', siteId)) { + if (!by.has(r.tid)) by.set(r.tid, { ownerTownId: r.tid, ownerOpId: r.oid, units: {} }); + by.get(r.tid).units[r.unit] = r.count; + } + return Array.from(by.values()); +} + +// All units an owner POP has standing in sites (its draw): { unit: count }. +function ofTown(db, ownerTownId) { + const out = {}; + for (const r of db.all('SELECT unit, SUM(count) AS n FROM site_stationed WHERE owner_town_id = ? GROUP BY unit', ownerTownId)) out[r.unit] = r.n; + return out; +} + +function setUnit(db, siteId, ownerTownId, unit, count) { + if (count > 0) db.run('INSERT INTO site_stationed (site_id, owner_town_id, unit, count) VALUES (?, ?, ?, ?) ON CONFLICT (site_id, owner_town_id, unit) DO UPDATE SET count = excluded.count', siteId, ownerTownId, unit, count); + else db.run('DELETE FROM site_stationed WHERE site_id = ? AND owner_town_id = ? AND unit = ?', siteId, ownerTownId, unit); +} +function add(db, siteId, ownerTownId, units) { + const cur = ownedAt(db, siteId, ownerTownId); + for (const k of Object.keys(units || {})) if (units[k] > 0) setUnit(db, siteId, ownerTownId, k, (cur[k] || 0) + units[k]); +} +function remove(db, siteId, ownerTownId, units) { + const cur = ownedAt(db, siteId, ownerTownId); + for (const k of Object.keys(units || {})) if (units[k] > 0 && (cur[k] || 0) < units[k]) throw new GameError('not_enough_units', { unit: k, have: cur[k] || 0, want: units[k] }); + for (const k of Object.keys(units || {})) if (units[k] > 0) setUnit(db, siteId, ownerTownId, k, cur[k] - units[k]); +} + +// Defence figures of a site's garrison at `now`: only groups whose owner POP is online defend (like units at home). Reads only (online is projected). +// -> { groups: [{ id, ownerTownId, ownerOpId, units, research, online }], power: raw defence of the online groups } +function defenders(db, siteId, now) { + const out = []; + let power = 0; + for (const g of groups(db, siteId)) { + const town = loadTown(db, g.ownerTownId); + const online = !town || P.online(town, now); + const research = U.researchLevels(db, g.ownerTownId); + out.push({ id: 'from:' + g.ownerTownId, ownerTownId: g.ownerTownId, ownerOpId: g.ownerOpId, units: g.units, research, online }); + if (online) power += R.defencePower(g.units, research); + } + return { groups: out, power }; +} + +// Take `units` out of the site and send them home to their owner (the owner POP, or the operator's capital/oldest POP when that POP has changed +// hands). The owner POP is settled first and its power rescheduled. -> the return movement, or null when the owner has no POP left (units gone). +function sendHome(ctx, site, ownerTownId, units, extra) { + const { db, now } = ctx; + units = Object.fromEntries(Object.entries(units).filter(([, n]) => n > 0)); + if (U.isEmpty(units)) return null; + const ownerTown = db.get('SELECT * FROM towns WHERE id = ?', ownerTownId); + const town = ownerTown ? loadTown(db, ownerTownId) : null; + if (town) settle(db, town, now); // the draw of the owner changes now + remove(db, site.id, ownerTownId, units); + if (town) P.reschedule(ctx, town.id, now); + const opId = ownerTown ? ownerTown.owner_id : null; + const dest = opId ? U.homeTownFor(db, opId, ownerTownId) : null; + if (!dest) return null; + return M.launchReturn(ctx, { worldId: site.world_id, ownerId: dest.owner_id, fromTownId: null, at: { x: site.x, y: site.y }, to: dest, units, cargo: {}, extra: Object.assign({ garrison: true }, extra || {}) }); +} + +// Everything of one owner POP in one site goes home. -> units sent +function releaseGroup(ctx, site, ownerTownId, reason) { + const units = ownedAt(ctx.db, site.id, ownerTownId); + if (U.isEmpty(units)) return {}; + const mv = sendHome(ctx, site, ownerTownId, units, { released: reason }); + const t = ctx.db.get('SELECT owner_id AS oid, world_id AS wid FROM towns WHERE id = ?', ownerTownId); + const uid = t ? U.userOfOperator(ctx.db, t.oid) : null; + if (uid) ctx.notify(uid, site.world_id, 'garrison_released', { siteId: site.id, index: site.idx, ownerTownId, reason, units, movementId: mv ? mv.id : null }); + return units; +} + +// The whole garrison of a site goes home (the holding alliance is gone). +function releaseSite(ctx, site, reason) { + for (const g of groups(ctx.db, site.id)) releaseGroup(ctx, site, g.ownerTownId, reason); +} + +// Everything an operator has standing in sites goes home (it left or was kicked from the holding alliance). Only sites of its OLD alliance +// can hold its units, so this takes no alliance argument. +function releaseOperator(ctx, operatorId, reason) { + const { db } = ctx; + const rows = db.all(`SELECT DISTINCT s.site_id AS sid, s.owner_town_id AS tid FROM site_stationed s JOIN towns t ON t.id = s.owner_town_id WHERE t.owner_id = ? ORDER BY s.site_id, s.owner_town_id`, operatorId); + for (const r of rows) releaseGroup(ctx, db.get('SELECT * FROM landing_sites WHERE id = ?', r.sid), r.tid, reason); +} + +// A POP changed hands (takeover): whatever it had standing in sites goes home to its OLD owner (like units it had in other POPs). +function releaseTown(ctx, ownerTownId, reason) { + const { db } = ctx; + for (const r of db.all('SELECT DISTINCT site_id AS sid FROM site_stationed WHERE owner_town_id = ? ORDER BY site_id', ownerTownId)) { + releaseGroup(ctx, db.get('SELECT * FROM landing_sites WHERE id = ?', r.sid), ownerTownId, reason); + } +} + +// Read model for a site: groups with owner and units, total raw defence (online groups only) and the static part. +function view(db, siteId, now) { + const d = defenders(db, siteId, now); + return { + power: d.power, + groups: d.groups.map((g) => { + const op = g.ownerOpId ? db.get('SELECT id, name FROM operators WHERE id = ?', g.ownerOpId) : null; + const t = db.get('SELECT id, name, x, y FROM towns WHERE id = ?', g.ownerTownId); + return { ownerTownId: g.ownerTownId, townName: t ? t.name : null, operator: op ? { operatorId: op.id, name: op.name } : null, units: g.units, online: g.online, power: R.defencePower(g.units, g.research) }; + }), + }; +} + +module.exports = { ownedAt, groups, ofTown, add, remove, setUnit, defenders, sendHome, releaseGroup, releaseSite, releaseOperator, releaseTown, view }; diff --git a/server/military/landing.js b/server/military/landing.js index d0cfc44..be550cf 100644 --- a/server/military/landing.js +++ b/server/military/landing.js @@ -1,9 +1,14 @@ 'use strict'; /* - * Arrival of a scan or an attack at a backbone landing site (hooked from combat.arriveSite, runs inside the `arrive` event). - * A site is defended by a static value only: rules.backboneDefence(seed, x, y, world age, node level). Beating it as a member - * of an alliance makes that alliance the holder (level, stockpile and a running build stay with the site). The site never - * loses anything, so there is no loot and no raid; survivors drive home. Re-validates at arrival like every movement. + * Arrival of a scan, an attack or a reinforcement at a backbone landing site (scan/attack hooked from combat.arriveSite, reinforce from + * arrivals.arriveReinforce; all run inside the `arrive` event, at its due time, so waves resolve strictly in arrival order). + * + * Defence of a site = static value (rules.backboneDefence: heavy while nobody holds it, a modest `heldDefenceMult` once an alliance does, + * both growing with the node level) + the garrison: units that members of the holding alliance stationed there (server/military/garrison.js, + * DECISIONS E6), counted with their owner's defence research while their owner POP is online. A lost attack kills the same share of the + * garrison as it would in a POP (ratio^1.5 of its units), so the next wave faces less; a won attack wipes it and the attacker's alliance + * holds the site (level, stockpile and a running build stay with the site). The static part loses nothing; survivors drive home. + * Re-validates at arrival like every movement. */ const R = require('../../public/js/rules.js'); const D = require('../../public/js/data.js'); @@ -11,10 +16,21 @@ const U = require('./units'); const M = require('./movements'); const E = require('../endgame'); const { createReport } = require('./reports'); +const G = require('./garrison'); +const P = require('./power'); +const { loadTown, loadWorld, settle } = require('../state'); const { bounce, townBrief, opBrief } = require('./arrivals'); const SCAN_STRENGTH = D.ENDGAME.scanStrength; // a landing site counts as this many defending scanners +// Battle points (the same bookkeeping as POP combat; combat.js keeps its own copy of this helper private). +function addPoints(db, operatorId, column, v) { + if (!operatorId || !(v > 0)) return; + db.run('INSERT INTO operator_stats (operator_id, attack_points, defense_points) VALUES (?, 0, 0) ON CONFLICT (operator_id) DO NOTHING', operatorId); + const col = column === 'attack' ? 'attack_points' : 'defense_points'; + db.run('UPDATE operator_stats SET ' + col + ' = ' + col + ' + ? WHERE operator_id = ?', v, operatorId); +} + function sendHome(ctx, mv, survivors) { if (U.isEmpty(survivors)) return null; const dest = U.homeTownFor(ctx.db, mv.ownerId, mv.fromTownId); @@ -22,7 +38,27 @@ function sendHome(ctx, mv, survivors) { return M.launchReturn(ctx, { worldId: mv.worldId, ownerId: mv.ownerId, fromTownId: null, at: mv.to, to: dest, units: survivors, cargo: {}, parentId: mv.id, extra: {} }); } -module.exports = function arriveLanding(ctx, mv, now, world, tile) { +// A member of the holding alliance's units reach the site: they join its garrison. Anybody else, or a site that changed hands on the road, bounces them. +function reinforce(ctx, mv, ev) { + const { db } = ctx; + const now = ev.dueAt; + const world = loadWorld(db, mv.worldId); + const tile = R.tileAt(world.seed, world.map_radius, mv.to.x, mv.to.y, E.ageDays(world, now)); + if (tile.type !== 'backbone') return bounce(ctx, mv, now, 'invalid_target'); + const site = E.ensureSites(db, world, now, ctx).find((r) => r.idx === tile.site); + const op = U.getOperator(db, mv.ownerId); + if (!op.alliance_id || !site.holder_alliance_id || site.holder_alliance_id !== op.alliance_id) return bounce(ctx, mv, now, 'not_holder'); + const ownerTown = U.homeTownFor(db, mv.ownerId, mv.fromTownId); + if (!ownerTown) return; // the sender lost every POP meanwhile: nothing to belong to + const town = loadTown(db, ownerTown.id); + settle(db, town, now); // the owner's draw is the same as before the trip, but only from this moment + G.add(db, site.id, ownerTown.id, mv.units); + P.reschedule(ctx, town.id, now); + const uid = U.userOfOperator(db, op.id); + if (uid) ctx.notify(uid, mv.worldId, 'garrison_arrived', { siteId: site.id, index: site.idx, ownerTownId: ownerTown.id, units: mv.units }); +} + +function arriveLanding(ctx, mv, now, world, tile) { const { db } = ctx; if (mv.type !== 'scan' && mv.type !== 'attack') return bounce(ctx, mv, now, 'invalid_target'); const rows = E.ensureSites(db, world, now, ctx); @@ -31,13 +67,24 @@ module.exports = function arriveLanding(ctx, mv, now, world, tile) { const origin = mv.fromTownId ? db.get('SELECT * FROM towns WHERE id = ?', mv.fromTownId) : null; const uid = U.userOfOperator(db, attackerOp.id); const where = { x: site.x, y: site.y, index: site.idx, siteId: site.id, level: site.level, holder: E.allianceInfo(db, site.holder_alliance_id) }; - const staticDef = R.backboneDefence(world.seed, site.x, site.y, E.ageDays(world, now), site.level); + const held = !!site.holder_alliance_id; + const staticDef = R.backboneDefence(world.seed, site.x, site.y, E.ageDays(world, now), site.level, held); + const def = G.defenders(db, site.id, now); // the garrison (read only: nothing changes until the battle is resolved) + const active = def.groups.filter((g) => g.online); + where.held = held; if (mv.type === 'scan') { const sa = R.scanStrength(mv.units.port_scanner || 0, mv.extra.research); - const res = R.resolveScan(sa, SCAN_STRENGTH); + let sd = SCAN_STRENGTH; + for (const g of active) sd += R.scanStrength(g.units.port_scanner || 0, g.research); + const res = R.resolveScan(sa, sd); const loss = R.applyLoss(mv.units, res.lossFraction); - const intel = res.success ? { defence: staticDef, level: site.level, holder: where.holder, build: site.build_to ? { toLevel: site.build_to, dueAt: site.build_due_at } : null } : null; + const garrisonUnits = {}; + for (const g of def.groups) U.sumInto(garrisonUnits, g.units); + const intel = res.success ? { + defence: staticDef + def.power, static: staticDef, level: site.level, holder: where.holder, build: site.build_to ? { toLevel: site.build_to, dueAt: site.build_due_at } : null, + garrison: { units: garrisonUnits, power: def.power, offline: def.groups.filter((g) => !g.online).map((g) => g.ownerTownId) }, + } : null; createReport(ctx, { worldId: mv.worldId, type: 'scan', now, summary: { success: res.success, site: Object.assign({ type: 'backbone' }, where) }, data: { success: res.success, detail: res.detail, site: Object.assign({ type: 'backbone' }, where), scanners: { sent: mv.units, lost: loss.lost, survivors: loss.survivors }, intel }, @@ -50,18 +97,50 @@ module.exports = function arriveLanding(ctx, mv, now, world, tile) { // attack: alliance members only, and not against the own alliance or a pact partner (the world may have changed since it left) if (!attackerOp.alliance_id) return bounce(ctx, mv, now, 'no_alliance'); try { E.denyIfFriendly(db, attackerOp, site); } catch (e) { return bounce(ctx, mv, now, e.details.reason || 'invalid_target'); } + const shield = E.shieldUntil(site, world); + if (shield > now) return bounce(ctx, mv, now, 'site_shielded', { until: shield }); // it changed hands while the attack was on the road - const b = R.resolveBattle({ kind: 'attack', attackers: { units: mv.units, research: mv.extra.research || {} }, defenders: [], firewall: 0, staticDefence: staticDef }); + const b = R.resolveBattle({ + kind: 'attack', attackers: { units: mv.units, research: mv.extra.research || {} }, + defenders: active.map((g) => ({ id: g.id, units: g.units, research: g.research })), firewall: 0, staticDefence: staticDef, + }); const survivors = Object.assign({}, b.attacker.survivors); const oldHolder = site.holder_alliance_id; + + // ---- the garrison: losses (a won attack wipes every group, offline ones included), written after settling each owner POP (its draw changes) + const wipe = b.attackerWins || b.defenderLossFraction >= 1; // (the offline groups are not in the battle, but a lost site takes them with it) + const garrisonReport = []; + let defenderLost = {}; + for (const g of def.groups) { + const res = b.defenders.find((d) => d.id === g.id); + let left, lost; + if (wipe) { left = {}; lost = g.units; } else if (res) { left = res.survivors; lost = res.lost; } else { left = g.units; lost = {}; } + if (!U.isEmpty(lost)) { + const town = loadTown(db, g.ownerTownId); + if (town) settle(db, town, now); + for (const k of Object.keys(g.units)) G.setUnit(db, site.id, g.ownerTownId, k, left[k] || 0); + if (town) P.reschedule(ctx, town.id, now); + } + U.sumInto(defenderLost, lost); + garrisonReport.push({ ownerTownId: g.ownerTownId, ownerOpId: g.ownerOpId, sent: g.units, lost, survivors: left, share: res ? res.share : 0, offline: !res }); + } + const attLost = b.attacker.lost; + addPoints(db, attackerOp.id, 'attack', R.battlePoints(defenderLost)); + const defPts = R.battlePoints(attLost); + for (const g of garrisonReport) addPoints(db, g.ownerOpId, 'defense', defPts * g.share); + if (b.attackerWins) E.transferSite(ctx, site, attackerOp, now); const ret = sendHome(ctx, mv, survivors); const data = { outcome: b.attackerWins ? 'attacker_won' : 'defender_won', arrivedAt: now, site: Object.assign({ type: 'backbone' }, where), origin: townBrief(origin), attacker: { operator: opBrief({ id: attackerOp.id, name: attackerOp.name, as_number: attackerOp.as_number }), alliance: E.allianceInfo(db, attackerOp.alliance_id), units: { sent: mv.units, lost: b.attacker.lost, survivors } }, - power: { attack: b.A, defence: b.D }, taken: b.attackerWins, returnMovementId: ret ? ret.id : null, + defender: { staticDefence: staticDef, garrison: garrisonReport.map((g) => ({ ownerTownId: g.ownerTownId, operator: g.ownerOpId ? opBrief(U.getOperator(db, g.ownerOpId)) : null, sent: g.sent, lost: g.lost, survivors: g.survivors, offline: g.offline })) }, + power: { attack: b.A, defence: b.D, static: staticDef, garrison: b.defenceRaw }, taken: b.attackerWins, returnMovementId: ret ? ret.id : null, }; const recipients = [{ userId: uid, role: 'attacker' }]; if (oldHolder) for (const m of db.all('SELECT o.user_id AS uid FROM alliance_members am JOIN operators o ON o.id = am.operator_id WHERE am.alliance_id = ?', oldHolder)) recipients.push({ userId: m.uid, role: 'defender' }); createReport(ctx, { worldId: mv.worldId, type: 'landing', now, summary: { outcome: data.outcome, site: data.site, attacker: data.attacker.operator, taken: b.attackerWins }, data, recipients }); -}; +} + +module.exports = arriveLanding; +module.exports.reinforce = reinforce; diff --git a/server/military/power.js b/server/military/power.js index 04edb16..04a176b 100644 --- a/server/military/power.js +++ b/server/military/power.js @@ -14,6 +14,7 @@ const R = require('../../public/js/rules.js'); const D = require('../../public/js/data.js'); const { loadTown, settle } = require('../state'); const U = require('./units'); +const garrison = () => require('./garrison'); // lazy: garrison.js needs this module const EPS = D.MILITARY.batteryEpsilon; @@ -23,10 +24,12 @@ function online(town, now) { return !(c.amounts.battery <= EPS && c.rates.powerNet < 0); } -// Every unit drawing power in the POP: home + reinforcements hosted here, as { unit: count }. +// Every unit drawing power in the POP: home + reinforcements hosted here + its own units standing in backbone landing sites (they draw +// their owner's power, E6), as { unit: count }. function drawingUnits(db, townId) { const out = U.homeUnits(db, townId); for (const g of U.hostedGroups(db, townId)) U.sumInto(out, g.units); + U.sumInto(out, garrison().ofTown(db, townId)); return out; } @@ -52,7 +55,7 @@ function reschedule(ctx, townId, now) { ctx.enqueue({ worldId: town.worldId, dueAt: Math.max(now, row.offline_since + R.decommissionMs(town.speed)), type: 'powerCheck', townId, payload: { townId } }); } -// Decommission the most expensive units (home first, then reinforcements) until the draw fits. The town is settled. +// Decommission the most expensive units (home first, then reinforcements, then its own garrison units) until the draw fits. The town is settled. function decommission(ctx, town, now) { const { db } = ctx; const units = drawingUnits(db, town.id); @@ -77,6 +80,14 @@ function decommission(ctx, town, now) { note(ot ? U.userOfOperator(db, ot.oid) : null, unit, n); } } + if (left > 0) { // its own units standing in landing sites + const G = garrison(); + for (const r of db.all('SELECT site_id, count FROM site_stationed WHERE owner_town_id = ? AND unit = ? ORDER BY site_id', town.id, unit)) { + if (left <= 0) break; + const n = Math.min(r.count, left); + G.setUnit(db, r.site_id, town.id, unit, r.count - n); left -= n; note(ownerUser, unit, n); + } + } removed[unit] = plan[unit] - left; } for (const [userId, lost] of byOwner) if (userId) ctx.notify(userId, town.worldId, 'units_decommissioned', { townId: town.id, units: lost }); diff --git a/server/military/views.js b/server/military/views.js index d17cfe0..a216cbc 100644 --- a/server/military/views.js +++ b/server/military/views.js @@ -6,7 +6,7 @@ const R = require('../../public/js/rules.js'); const D = require('../../public/js/data.js'); const { GameError } = require('../errors'); -const { loadWorld } = require('../state'); +const { loadWorld, hasTable } = require('../state'); const U = require('./units'); const P = require('./power'); @@ -78,6 +78,16 @@ function movementLists(db, operatorId, townId) { return out; } +// [{ siteId, x, y, units }] of one owner POP's units standing in landing sites (the `site_stationed` rows), ordered by site. +function garrisonGroups(db, townId) { + const by = new Map(); + for (const r of db.all('SELECT s.site_id AS sid, l.x AS x, l.y AS y, s.unit AS unit, s.count AS count FROM site_stationed s JOIN landing_sites l ON l.id = s.site_id WHERE s.owner_town_id = ? ORDER BY s.site_id, s.unit', townId)) { + if (!by.has(r.sid)) by.set(r.sid, { siteId: r.sid, x: r.x, y: r.y, units: {} }); + by.get(r.sid).units[r.unit] = r.count; + } + return Array.from(by.values()); +} + // The military part of GET /towns/:id (the town object is already loaded and belongs to the caller). function townMilitary(db, t, now, world) { const home = U.homeUnits(db, t.id); @@ -85,6 +95,8 @@ function townMilitary(db, t, now, world) { const names = townNames(db, U.hostedGroups(db, t.id).map((g) => g.ownerTownId).concat(U.awayGroups(db, t.id).map((g) => g.hostTownId))); const hosted = U.hostedGroups(db, t.id).map((g) => ({ ownerTownId: g.ownerTownId, ownerTownName: names.get(g.ownerTownId) ? names.get(g.ownerTownId).name : null, owner: names.get(g.ownerTownId) ? names.get(g.ownerTownId).owner : null, units: g.units })); const away = U.awayGroups(db, t.id).map((g) => ({ hostTownId: g.hostTownId, hostTownName: names.get(g.hostTownId) ? names.get(g.hostTownId).name : null, units: g.units })); + // Units of this POP standing in backbone landing sites its alliance holds: they draw THIS POP's power (state.unitDraw), so they belong here. + const garrisoned = hasTable(db, 'site_stationed') ? garrisonGroups(db, t.id) : []; const training = db.all("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'trainDone' AND status = 'pending' ORDER BY due_at, id", t.id) .map((e) => { const p = JSON.parse(e.payload); return { id: e.id, unit: p.unit, count: p.count, building: p.building, startAt: p.startAt, dueAt: e.due_at }; }); const rq = db.get("SELECT id, due_at, payload FROM events WHERE town_id = ? AND type = 'researchDone' AND status = 'pending' ORDER BY due_at, id LIMIT 1", t.id); @@ -99,10 +111,10 @@ function townMilitary(db, t, now, world) { const op = U.getOperator(db, t.ownerId); const links = R.transportLinks(t); return { - units: { home, online, offlineSince: offline ? offline.offline_since : null, stationedHere: hosted, stationedAway: away }, + units: { home, online, offlineSince: offline ? offline.offline_since : null, stationedHere: hosted, stationedAway: away, garrisoned }, training, trainable, research: { levels: U.researchLevels(db, t.id), queue: rq ? { id: rq.id, unit: rp.unit, stat: rp.stat, toLevel: rp.toLevel, startedAt: rp.startedAt, dueAt: rq.due_at } : null, speedBonus: bonus, maxLevel: D.RESEARCH.maxLevel }, - transport: { links, active: require('./movements').activeLinks(db, t.id), capacityPerLink: D.TRANSPORT.capacityPerLink }, + transport: { links, active: require('./movements').activeLinks(db, t.id), capacityPerLink: R.transportCapacity(world.speed) }, movements: movementLists(db, t.ownerId, t.id), protectionUntil: op.protection_until, }; diff --git a/server/pushHooks.js b/server/pushHooks.js index 28170ef..668a9fe 100644 --- a/server/pushHooks.js +++ b/server/pushHooks.js @@ -24,6 +24,7 @@ const TOWN_KINDS = { town_lost: 'townId', town_gained: 'townId', transport_arrived: 'townId', transport_delivered: 'toTownId', movement_returned: 'townId', reinforcements_sent_home: 'ownerTownId', + garrison_arrived: 'ownerTownId', garrison_released: 'ownerTownId', // units of that POP joined / left a landing site garrison: its power draw changed }; // Command args that name a POP the command changed (the receiving POP of a movement is NOT listed: the defender gets diff --git a/server/queries.js b/server/queries.js index d046a57..19f8793 100644 --- a/server/queries.js +++ b/server/queries.js @@ -68,7 +68,7 @@ function createQueries({ db, clock, scheduler }) { id: t.id, name: t.name, x: t.x, y: t.y, isCapital: t.isCapital, ownerId: t.ownerId, worldId: t.worldId, loyalty, footprint: R.footprintAt(t, now), footprintPerDay: R.footprintPerDay(t), resources, power, buildings, queue, queueSlots: R.queueSlots(t), - bonus: t.bonus, + bonus: t.bonus, escrow: t.escrow, military: require('./military/views').townMilitary(db, t, now, world), }, }; diff --git a/server/routes/schemas.js b/server/routes/schemas.js index 32944ca..be2a66a 100644 --- a/server/routes/schemas.js +++ b/server/routes/schemas.js @@ -29,6 +29,7 @@ const schemas = { power: obj({ out: num, draw: num, net: num, buffer: num, bufferCap: num, bufferRate: num, online: bool }), buildings: arr({ $ref: 'BuildingView' }), queue: arr({ $ref: 'QueueEntry' }), queueSlots: int, bonus: obj({ fiber: num, hardware: num, capital: num }), + escrow: obj({ fiber: num, hardware: num, capital: num }), // goods in open Internet exchange offers: they still occupy the Rack hall (resources[r].cap already excludes them) }), TownResponse: obj({ serverTime: int, town: { $ref: 'Town' } }), MapTown: obj({ id: int, name: str, x: int, y: int, isCapital: bool, owner: obj({ id: int, name: str, asNumber: int, allianceId: { type: ['integer', 'null'] }, alliance: { type: ['object', 'null'], properties: { id: int, tag: str, name: str }, additionalProperties: true }, protected: bool }) }), diff --git a/server/routes/schemasEndgame.js b/server/routes/schemasEndgame.js index a02c7a2..c8530b6 100644 --- a/server/routes/schemasEndgame.js +++ b/server/routes/schemasEndgame.js @@ -21,7 +21,7 @@ module.exports = function addEndgameSchemas(schemas, { int, num, str, bool, obj, // ---- end game LandingSite: obj({ id: nint, index: int, x: int, y: int, holder: { type: ['object', 'null'], properties: { allianceId: int, tag: str, name: str }, additionalProperties: true }, - takenBy: { type: ['object', 'null'], additionalProperties: true }, takenAt: nint, level: int, maxLevel: int, progress: num, pool: Cost, + takenBy: { type: ['object', 'null'], additionalProperties: true }, takenAt: nint, shieldUntil: nint, level: int, maxLevel: int, progress: num, pool: Cost, build: { type: ['object', 'null'], properties: { toLevel: int, startedAt: int, dueAt: int }, additionalProperties: true }, next: { type: ['object', 'null'], properties: { toLevel: int, cost: Cost, durationMs: int }, additionalProperties: true }, }), @@ -31,9 +31,13 @@ module.exports = function addEndgameSchemas(schemas, { int, num, str, bool, obj, }), WorldResults: obj({ serverTime: int, available: bool, status: str, winner: { type: ['object', 'null'], additionalProperties: true }, endsAt: nint, results: { type: ['object', 'null'], additionalProperties: true } }), LandingSiteResponse: obj({ - serverTime: int, site: { $ref: 'LandingSite' }, you: obj({ holder: bool, canBuild: bool, canShip: bool, canAttack: bool }), + serverTime: int, site: { $ref: 'LandingSite' }, you: obj({ holder: bool, canBuild: bool, canShip: bool, canAttack: bool, canReinforce: bool }), contributions: arr(obj({ operatorId: int, name: str, fiber: int, hardware: int, capital: int })), + // holders only: what defends the site now (static part + the units members station there) and who owns the units + defence: obj({ static: num, garrison: num, total: num }), + garrison: arr(obj({ ownerTownId: int, townName: nstr, operator: { type: ['object', 'null'], additionalProperties: true }, units: { type: 'object', additionalProperties: true }, online: bool, power: num, mine: bool })), }, ['serverTime', 'site', 'you']), + GarrisonWithdrawn: obj({ serverTime: int, movementId: int, siteId: int, fromTownId: int, units: { type: 'object', additionalProperties: true }, arriveAt: int }), BackboneBuildStarted: obj({ serverTime: int, siteId: int, eventId: int, toLevel: int, startedAt: int, dueAt: int, cost: Cost }), // ---- shared reports ReportShared: obj({ serverTime: int, changed: bool, reportId: int, allianceId: int }), diff --git a/server/routes/schemasMilitary.js b/server/routes/schemasMilitary.js index e48fd03..4cc57c6 100644 --- a/server/routes/schemasMilitary.js +++ b/server/routes/schemasMilitary.js @@ -29,7 +29,7 @@ module.exports = function addMilitarySchemas(schemas, { int, num, str, bool, obj settle: obj({ possible: bool, code: { type: ['string', 'null'] }, footprint: num, footprintNeeded: num, maxDistance: int }), }, ['serverTime', 'x', 'y', 'type', 'distances', 'settle']), TownMilitary: obj({ - units: obj({ home: Units, online: bool, offlineSince: nint, stationedHere: arr(free), stationedAway: arr(free) }), + units: obj({ home: Units, online: bool, offlineSince: nint, stationedHere: arr(free), stationedAway: arr(free), garrisoned: arr(obj({ siteId: int, x: int, y: int, units: Units })) }), training: arr(obj({ id: int, unit: str, count: int, building: str, startAt: int, dueAt: int })), trainable: arr(obj({ unit: str, building: str, role: str, cost: Cost, timeMs: int, missing: arr(free), locked: bool })), research: obj({ levels: free, queue: { type: ['object', 'null'], additionalProperties: true }, speedBonus: num, maxLevel: int }), diff --git a/server/routes/trade.js b/server/routes/trade.js index 3224988..7e28291 100644 --- a/server/routes/trade.js +++ b/server/routes/trade.js @@ -47,7 +47,7 @@ function register(router, services) { summary: 'Take an open offer with one of your POPs: two transports leave at once (your payment, their goods) and the offer is settled when both arrive', tag: 'trade', status: 201, body: { type: 'object', required: ['townId'], properties: { townId: int1 } }, response: { $ref: 'TradeAccepted' }, - errors: errs.concat(['offer_closed', 'own_offer', 'trade_out_of_range', 'no_transport_link', 'capacity_exceeded', 'not_enough_resources', 'world_ended']), + errors: errs.concat(['offer_closed', 'own_offer', 'trade_out_of_range', 'no_room_for_goods', 'no_transport_link', 'capacity_exceeded', 'not_enough_resources', 'world_ended']), }, ({ user, params, body }) => reply(201, commands.run('tradeAccept', { userId: user.id, offerId: params.id, townId: body.townId }))); } module.exports = { register }; diff --git a/server/routes/world.js b/server/routes/world.js index 5b577fa..1c0dbe4 100644 --- a/server/routes/world.js +++ b/server/routes/world.js @@ -26,12 +26,18 @@ function register(router, services) { }, ({ user, params }) => eg.site(user.id, params.id)); router.post('/backbone/:id/ship', { - summary: 'Send resources from one of your POPs to a landing site your alliance holds (a transport: Internet exchange links, 500 each)', tag: 'world', status: 201, + summary: 'Send resources from one of your POPs to a landing site your alliance holds (a transport: Internet exchange links, 1000 each at world speed 1, times the world speed)', tag: 'world', status: 201, body: { type: 'object', required: ['fromTownId', 'cargo'], properties: { fromTownId: { type: 'integer', minimum: 1 }, cargo: { type: 'object', additionalProperties: true, description: 'fiber/hardware/capital -> amount' } } }, response: { $ref: 'MovementSent' }, errors: errs.concat(['forbidden', 'backbone_closed', 'capacity_exceeded', 'no_transport_link', 'not_enough_resources', 'world_ended']), }, ({ user, params, body }) => reply(201, commands.run('backboneShip', { userId: user.id, siteId: params.id, fromTownId: body.fromTownId, cargo: body.cargo }))); + router.post('/backbone/:id/withdraw', { + summary: 'Call units of one of your POPs home from a landing site\'s garrison (default: all of them). Only their owner can; works whoever holds the site now. Station units with POST /movements type reinforce at the site\'s x,y (members of the holding alliance only)', tag: 'world', status: 201, + body: { type: 'object', required: ['fromTownId'], properties: { fromTownId: { type: 'integer', minimum: 1 }, units: { type: 'object', additionalProperties: true, description: 'defaults to the whole group' } } }, + response: { $ref: 'GarrisonWithdrawn' }, errors: errs.concat(['not_enough_units', 'unknown_unit', 'conflict', 'world_ended']), + }, ({ user, params, body }) => reply(201, commands.run('withdrawGarrison', { userId: user.id, siteId: params.id, fromTownId: body.fromTownId, units: body.units }))); + router.post('/backbone/:id/build', { summary: 'Start the next Backbone node level on a landing site your alliance holds (paid from the site\'s stockpile; one level at a time, up to level ' + D.ENDGAME.maxLevel + ')', tag: 'world', status: 201, response: { $ref: 'BackboneBuildStarted' }, diff --git a/server/state.js b/server/state.js index c7991a7..f708c97 100644 --- a/server/state.js +++ b/server/state.js @@ -25,6 +25,7 @@ function townFromRow(db, row, world) { loyalty: row.loyalty, loyaltyAt: row.loyalty_at, buildings, unitDraw: unitDraw(db, row.id), + escrow: escrowOf(db, row.id), bonus: R.ruralBonus(world.seed, world.map_radius, row.x, row.y), }; } @@ -39,9 +40,20 @@ function unitDraw(db, townId) { if (hasTable(db, 'stationed')) { for (const r of db.all('SELECT unit, count FROM stationed WHERE host_town_id = ?', townId)) if (D.UNITS && D.UNITS[r.unit]) draw += D.UNITS[r.unit].draw * r.count; } + // Units of this POP standing in backbone landing sites (garrisons, E6) draw from their OWNER: a site has no power budget. + if (hasTable(db, 'site_stationed')) { + for (const r of db.all('SELECT unit, SUM(count) AS count FROM site_stationed WHERE owner_town_id = ? GROUP BY unit', townId)) if (D.UNITS && D.UNITS[r.unit]) draw += D.UNITS[r.unit].draw * r.count; + } return draw; } +// Goods this POP has escrowed in open Internet exchange offers, per resource: they still occupy the Rack hall (rules.storageCapOf). +function escrowOf(db, townId) { + const out = { fiber: 0, hardware: 0, capital: 0 }; + for (const r of db.all("SELECT give_res, SUM(give_amount) AS n FROM trade_offers WHERE town_id = ? AND status = 'open' GROUP BY give_res", townId)) out[r.give_res] = r.n; + return out; +} + const tableCache = new Map(); function hasTable(db, name) { if (!tableCache.has(db)) tableCache.set(db, new Map()); @@ -79,4 +91,4 @@ function pendingBuilds(db, townId) { .map((e) => Object.assign({ id: e.id, dueAt: e.due_at }, JSON.parse(e.payload))); } -module.exports = { loadWorld, loadTown, townFromRow, settle, spend, pendingBuilds, hasTable }; +module.exports = { loadWorld, loadTown, townFromRow, escrowOf, settle, spend, pendingBuilds, hasTable }; diff --git a/server/trade.js b/server/trade.js index 1dee68f..73a77a8 100644 --- a/server/trade.js +++ b/server/trade.js @@ -10,8 +10,12 @@ * cancelled the poster took it back: the escrow is credited to the POP again * expired ttl ran out (event `tradeExpire`): same * void the poster's POP changed hands while the offer was open: the escrow stays in that POP (it goes with the POP) - * Nothing is created or lost: escrow is returned WITHOUT the Rack hall cap (an amount above the cap is kept, it only stops - * growing); the only loss anywhere is what a delivery cannot store (the existing cargoLost rule of transports). + * Escrowed goods keep occupying the POP's Rack hall (S2 in docs/BALANCE.md, rules.storageCapOf): while an offer is open the stock + * of that resource stops growing at hall size minus escrow, so the refund always fits. Nothing is lost and the escrow is no extra + * storage (decision R1). The one case that can still clip a refund is a Rack hall that was shot down below stock + escrow in the + * meantime; that loss is reported (`trade_refund_clipped`). Every way out of `open` must settle the POP first (the cap changes + * there): closeOffer does, and so does tradeAccept for the poster's POP. The only other loss anywhere in trade is what a delivery + * cannot store (the existing cargoLost rule of transports). */ const R = require('../public/js/rules.js'); const D = require('../public/js/data.js'); @@ -20,15 +24,17 @@ const M = require('./military/movements'); const COL = { fiber: 'fiber', hardware: 'hardware', capital: 'capital' }; -// Credit `amount` of `res` to a POP (settled first, capped by the Rack hall: escrow cannot be used to store past it). +// Credit `amount` of `res` back to a POP that is still carrying the escrow in its Rack hall (the offer is still `open` when this +// runs, so the town's escrow includes it). Settled first. -> the part that did not fit (only after a lowered Rack hall), else 0 function refund(db, townId, res, amount, at) { const town = loadTown(db, townId); - if (!town) return; + if (!town) return 0; settle(db, town, at); - // Capped like cancelBuild: stock already above the Rack hall cap stays, but a refund never lifts it further. - const cap = Math.max(R.storageCap(town), town.res[res]); - const next = Math.min(cap, town.res[res] + amount); + // The hall's room once this offer is gone is storageCapOf + amount. Stock already above it stays (like cancelBuild), a refund never lifts it further. + const room = Math.max(R.storageCapOf(town, res) + amount, town.res[res]); + const next = Math.min(room, town.res[res] + amount); db.run('UPDATE towns SET ' + COL[res] + ' = ? WHERE id = ?', next, townId); + return Math.max(0, town.res[res] + amount - next); } const getOffer = (db, id) => db.get('SELECT * FROM trade_offers WHERE id = ?', id) || null; @@ -37,13 +43,18 @@ function expiryMs(speed) { return Math.round(D.TRADE.ttlHours * D.HOUR_MS / (spe function userOfOperator(db, operatorId) { const o = db.get('SELECT user_id FROM operators WHERE id = ?', operatorId); return o ? o.user_id : null; } -// Close an open offer and give the escrow back to its POP. `status`: cancelled | expired | void. -> the offer row (before) +// Close an open offer and give the escrow back to its POP. `status`: cancelled | expired | void. -> { credited, lost } function closeOffer(ctx, offer, status, at) { const { db } = ctx; + const lost = refund(db, offer.town_id, offer.give_res, offer.give_amount, at); // BEFORE the status changes: the open escrow shaped the settle db.run('UPDATE trade_offers SET status = ?, closed_at = ? WHERE id = ?', status, at, offer.id); if (offer.expire_event_id) db.run("UPDATE events SET status = 'cancelled', done_at = ? WHERE id = ? AND status = 'pending'", at, offer.expire_event_id); - refund(db, offer.town_id, offer.give_res, offer.give_amount, at); - return offer; + const lostWhole = Math.round(lost); + if (lostWhole > 0) { + const uid = userOfOperator(db, offer.operator_id); + if (uid) ctx.notify(uid, offer.world_id, 'trade_refund_clipped', { offerId: offer.id, townId: offer.town_id, resource: offer.give_res, lost: lostWhole, credited: offer.give_amount - lostWhole }); + } + return { credited: offer.give_amount - lost, lost }; } // A POP changed hands (takeover): its open offers end and the escrow stays with the POP. Called from combat.transferTown. diff --git a/test/admin-endworld.test.js b/test/admin-endworld.test.js new file mode 100644 index 0000000..f694eef --- /dev/null +++ b/test/admin-endworld.test.js @@ -0,0 +1,125 @@ +'use strict'; +/* tools/admin.js end-world: it must end a world exactly like the natural end (worldEnd event handler): final ranking stored and + * served by /worlds/:id/results, trade escrow returned, pending events cancelled, notifications written, refusal without --yes. + * Also: a closed stdout pipe (`admin.js help | head`) is not an error. A file DB shared by the fixture and the CLI, fake clock. */ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawn } = require('child_process'); +const admin = require('../tools/admin.js'); +const T = require('./military-helpers'); +const { createEndgameQueries } = require('../server/endgameQueries'); +const { H } = T; + +function cli(file, args, now) { + const out = [], err = []; + const code = admin.main(args.concat(['--db', file]), { out: (s) => out.push(s), err: (s) => err.push(s), env: {}, now: () => now }); + const text = out.join('\n'); + return { code, out: text, err: err.join('\n'), json: args.includes('--json') ? JSON.parse(text) : null }; +} + +// A world with two operators, an open trade offer (escrow), a pending build and one build that is already overdue. +function fixture() { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'upstream-endworld-')); + const file = path.join(dir, 'game.db'); + const h = T.setup({ file }); + const a = T.addOperator(h, 'alice', { x: 5, y: 0 }); + const b = T.addOperator(h, 'bob', { x: 9, y: 0 }); + h.run('build', { userId: a.userId, townId: a.townId, key: 'f1' }); + const offer = h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'fiber', giveAmount: 400, wantRes: 'hardware', wantAmount: 300, maxDistance: 30 }).offer; + return { h, file, a, b, offer, eg: createEndgameQueries(h) }; +} + +test('end-world refuses without --yes, says what it would do, and changes nothing', () => { + const { h, file, a, eg } = fixture(); + const r = cli(file, ['end-world', String(h.worldId)], h.clock.now()); + assert.equal(r.code, 2); + assert.match(r.err, /refusing without --yes/); + assert.match(r.err, /1 open trade offer/); + assert.equal(h.db.get('SELECT status FROM worlds').status, 'running'); + assert.equal(eg.results(a.userId, h.worldId).available, false); +}); + +test('end-world --yes runs the real worldEnd: ranking snapshot, results available, escrow back, events cancelled, players notified', () => { + const { h, file, a, b, offer, eg } = fixture(); + const fiberBefore = T.town(h, a.townId).fiber; + assert.ok(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'pending'").n >= 2); + const now = h.clock.now() + 60 * 1000; // the offer's expiry and the build are still in the future + + const r = cli(file, ['end-world', String(h.worldId), '--yes', '--json'], now); + assert.equal(r.code, 0, r.err); + assert.equal(r.json.changed, true); + assert.equal(r.json.ranking, true); + assert.equal(r.json.operators, 2); + assert.equal(r.json.closedOffers, 1); + + const w = h.db.get('SELECT * FROM worlds WHERE id = ?', h.worldId); + assert.equal(w.status, 'ended'); + assert.equal(w.end_at, now); + // exactly what GET /worlds/:id/results serves after a natural end + const res = eg.results(b.userId, h.worldId); + assert.equal(res.available, true); + assert.equal(res.status, 'ended'); + assert.equal(res.results.at, now); + assert.equal(res.results.operators.length, 2); + assert.deepEqual(res.results.operators.map((o) => o.rank), [1, 2]); + assert.equal(res.results.totals.operators, 2); + assert.equal(res.results.winner, null, 'nobody won the race: the admin ended it'); + + // the event row is the same shape the natural end leaves, and nothing is left pending + const ev = h.db.get("SELECT * FROM events WHERE type = 'worldEnd'"); + assert.equal(ev.status, 'done'); + assert.deepEqual(JSON.parse(ev.payload), { reason: 'admin' }); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'pending'").n, 0); + assert.ok(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'cancelled'").n >= 2); + // escrow went back to the POP, the offer is closed + assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'expired'); + assert.ok(T.town(h, a.townId).fiber >= fiberBefore + 400, 'the 400 are back in the POP (plus what it produced meanwhile)'); + // every operator is told + for (const u of [a, b]) assert.equal(T.notes(h, u.userId, 'world_ended').length, 1); + // the world is frozen for commands + assert.throws(() => h.run('build', { userId: b.userId, townId: b.townId, key: 'f1' }), (e) => e.code === 'world_ended'); + + // second run: already ended, no change, exit 0, and no second ranking or notification + const again = cli(file, ['end-world', String(h.worldId), '--json'], now + 1000); + assert.equal(again.code, 0); + assert.equal(again.json.changed, false); + assert.equal(again.json.ranking, true); + assert.equal(T.notes(h, a.userId, 'world_ended').length, 1); +}); + +test('end-world processes events that were already due first, in order (a finished build is not lost)', () => { + const { h, file, a, eg } = fixture(); + const q = h.db.get("SELECT due_at FROM events WHERE type = 'buildDone'"); + assert.ok(q); + const now = q.due_at + 5000; // the server was stopped: the build fell due before the CLI ran + const r = cli(file, ['end-world', String(h.worldId), '--yes', '--json'], now); + assert.equal(r.code, 0, r.err); + assert.ok(r.json.caughtUpFirst >= 1); + assert.equal(h.db.get("SELECT status FROM events WHERE type = 'buildDone'").status, 'done'); + assert.equal(h.db.get("SELECT level FROM buildings WHERE town_id = ? AND key = 'f1'", a.townId).level >= 1, true); + assert.equal(eg.results(a.userId, h.worldId).available, true); +}); + +test('end-world only touches the named world', () => { + const { h, file } = fixture(); + const { createWorld } = require('../server/world'); + const second = createWorld(h.db, h.clock.now(), { seed: 7, mapRadius: 20 }); + h.db.run("INSERT INTO events (world_id, due_at, type, payload, status, created_at) VALUES (?, ?, 'reportCleanup', '{}', 'pending', ?)", second, h.clock.now() + 99 * H, h.clock.now()); + assert.equal(cli(file, ['end-world', String(h.worldId), '--yes'], h.clock.now() + 1000).code, 0); + assert.equal(h.db.get('SELECT status FROM worlds WHERE id = ?', second).status, 'running'); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE world_id = ? AND status = 'pending'", second).n, 1); + assert.equal(h.db.get('SELECT COUNT(*) AS n FROM world_rankings WHERE world_id = ?', second).n, 0); +}); + +test('a closed stdout pipe is quiet: `admin.js help | head` prints no EPIPE stack trace and keeps the exit code', async () => { + const child = spawn(process.execPath, [path.join(__dirname, '..', 'tools', 'admin.js'), 'help'], { stdio: ['ignore', 'pipe', 'pipe'] }); + child.stdout.destroy(); // the reader goes away before the CLI has written anything + let err = ''; + child.stderr.on('data', (d) => { err += d; }); + const code = await new Promise((resolve) => child.on('close', resolve)); + assert.equal(err, ''); + assert.equal(code, 0); +}); diff --git a/test/client-alerts.test.js b/test/client-alerts.test.js index 6aa6636..42d876d 100644 --- a/test/client-alerts.test.js +++ b/test/client-alerts.test.js @@ -39,10 +39,12 @@ const SAMPLES = { trade_completed: { offerId: 3, give: T, want: W }, trade_expired: { offerId: 3, townId: 1, returned: T }, trade_void: { offerId: 3, townId: 1 }, + trade_refund_clipped: { offerId: 3, townId: 1, resource: 'fiber', lost: 120, credited: 280 }, backbone_open: { sites: [{ siteId: 1, index: 0, x: 3, y: 4 }, { siteId: 2, index: 1, x: 5, y: 6 }] }, backbone_taken: { siteId: 1, index: 2, x: 10, y: -4, level: 12, by: { allianceId: 7, tag: 'NSP', name: 'North Sea Peering' }, from: { allianceId: 8, tag: 'FTC', name: 'Fjord' } }, backbone_lost: { siteId: 1, index: 2, x: 10, y: -4, level: 12, by: { allianceId: 8, tag: 'FTC', name: 'Fjord' }, from: { allianceId: 7, tag: 'NSP', name: 'North Sea Peering' } }, backbone_level: { siteId: 1, index: 2, level: 20 }, + backbone_incoming: { siteId: 1, index: 2, x: 10, y: -4, arriveAt: 1767225600000 }, backbone_delivered: { movementId: 5, siteId: 1, cargo: { fiber: 500, hardware: 0, capital: 120 } }, backbone_ship_bounced: { movementId: 5, siteId: 1, cargo: { fiber: 500 } }, backbone_won: { allianceId: 7, name: 'North Sea Peering', tag: 'NSP', siteId: 1, endsAt: 1767225600000 }, diff --git a/test/client-garrison.test.js b/test/client-garrison.test.js new file mode 100644 index 0000000..d15e379 --- /dev/null +++ b/test/client-garrison.test.js @@ -0,0 +1,66 @@ +'use strict'; +/* Client side of the landing-site garrison (docs/DECISIONS.md E6): who may reinforce a site, how the manage sheet reads the server's + * garrison, strings in both languages. Pure logic and source checks, no browser. */ +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('fs'); +const path = require('path'); +const Mil = require('../public/js/milcore.js'); +const End = require('../public/js/endcore.js'); +const I18n = require('../public/js/i18n.js'); +const D = require('../public/js/data.js'); +const ROOT = path.join(__dirname, '..', 'public', 'js'); +for (const f of fs.readdirSync(path.join(ROOT, 'strings')).sort()) if (f.endsWith('.js')) require('../public/js/strings/' + f); + +const tile = (mine) => ({ type: 'backbone', x: 10, y: 10, backbone: { index: 2, mine, holder: { allianceId: 7, tag: 'X', name: 'X' } } }); + +test('send dialog: members of the holding alliance can reinforce a site (and not attack it); everybody else attacks or scans', () => { + const home = { soc_analyst: 20, script_crew: 10, port_scanner: 3 }; + const mine = Mil.moveOptions({ tile: tile(true), home, transport: { links: 0, active: 0 }, allianceId: 7 }); + assert.deepEqual(mine.map((o) => [o.type, o.ok]), [['scan', true], ['attack', false], ['reinforce', true]]); + assert.equal(mine.find((o) => o.type === 'attack').reason, 'own_site'); + const none = Mil.moveOptions({ tile: tile(true), home: { script_crew: 5 }, transport: {}, allianceId: 7 }); + assert.equal(none.find((o) => o.type === 'reinforce').ok, true, 'attackers can garrison too'); + const noUnits = Mil.moveOptions({ tile: tile(true), home: {}, transport: {}, allianceId: 7 }); + assert.deepEqual(noUnits.find((o) => o.type === 'reinforce'), { type: 'reinforce', ok: false, reason: 'no_units' }); + const rival = Mil.moveOptions({ tile: tile(false), home, transport: {}, allianceId: 8 }); + assert.deepEqual(rival.map((o) => o.type), ['scan', 'attack'], 'a rival cannot reinforce'); + const loner = Mil.moveOptions({ tile: tile(false), home, transport: {}, allianceId: null }); + assert.deepEqual(loner.map((o) => o.type), ['scan', 'attack']); + assert.equal(loner.find((o) => o.type === 'attack').reason, 'no_alliance'); +}); + +test('garrisonView: rows by defence, share of the whole defence, your own marked, offline groups count nothing', () => { + const data = { + defence: { static: 8000, garrison: 12000, total: 20000 }, + garrison: [ + { ownerTownId: 5, townName: 'B POP', operator: { operatorId: 2, name: 'bea' }, units: { soc_analyst: 100 }, online: true, power: 2500, mine: false }, + { ownerTownId: 3, townName: 'A POP', operator: { operatorId: 1, name: 'ann' }, units: { blue_team: 120 }, online: true, power: 9600, mine: true }, + { ownerTownId: 9, townName: 'C POP', operator: null, units: { soc_analyst: 10 }, online: false, power: 250, mine: false }, + ], + }; + const v = End.garrisonView(data); + assert.deepEqual(v.rows.map((r) => r.ownerTownId), [3, 5, 9]); + assert.equal(v.rows[0].mine, true); + assert.equal(v.rows[0].share, 9600 / 20000); + assert.equal(v.rows[2].share, 0, 'an offline group defends nothing'); + assert.equal(v.rows[2].online, false); + assert.equal(v.rows[2].name, ''); + assert.deepEqual([v.static, v.garrison, v.total], [8000, 12000, 20000]); + assert.deepEqual(End.garrisonView({}).rows, [], 'a missing block is an empty garrison'); + assert.equal(End.garrisonView(null).total, 0); +}); + +test('every string the garrison UI uses exists in en and nb', () => { + const src = ['screens/world.js', 'screens/send.js', 'milstate.js', 'alertkinds.js'].map((f) => fs.readFileSync(path.join(ROOT, f), 'utf8')).join('\n'); + const keys = new Set([...src.matchAll(/App\.t\('((?:wld\.gar|send\.landing|alerts\.garrison|alerts\.backbone_incoming)[a-zA-Z_.]*)'/g)].map((m) => m[1]).filter((k) => !k.endsWith('.')).concat(['send.invalid.not_holder', 'send.invalid.site_shielded', 'wld.shield', 'rep.landing.garrisonOf', 'alerts.garrison_released.alliance_dissolved', 'alerts.garrison_released.left_alliance', 'alerts.garrison_released.town_lost', 'alerts.garrison_released.other'])); + assert.ok(keys.size >= 12, 'found the keys (' + keys.size + ')'); + for (const l of ['en', 'nb']) for (const k of keys) assert.ok(I18n.strings[l][k], l + ' has ' + k); +}); + +test('nothing in the client reads TRANSPORT.capacityPerLink directly (a link carries capacityPerLink x world speed: rules.transportCapacity)', () => { + const walk = (dir) => fs.readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? walk(path.join(dir, e.name)) : e.name.endsWith('.js') ? [path.join(dir, e.name)] : [])); + const hits = walk(ROOT).filter((f) => !/[\\/](data|rules)\.js$/.test(f) && /TRANSPORT\.capacityPerLink/.test(fs.readFileSync(f, 'utf8'))); + assert.deepEqual(hits, []); + assert.ok(D.TRANSPORT.capacityPerLink > 0); +}); diff --git a/test/deploy-offsite.test.js b/test/deploy-offsite.test.js new file mode 100644 index 0000000..c6a278e --- /dev/null +++ b/test/deploy-offsite.test.js @@ -0,0 +1,118 @@ +'use strict'; +/* deploy/upstream-offsite: newest snapshot, verified first, copied (rsync to a local directory standing in for the far side), + * never overwritten, content compared. ssh itself is not exercised (no remote host here). */ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawnSync } = require('child_process'); +const admin = require('../tools/admin.js'); +const { openDb, migrate } = require('../server/db'); + +const SCRIPT = path.join(__dirname, '..', 'deploy', 'upstream-offsite'); +const haveRsync = spawnSync('rsync', ['--version']).status === 0; +const opts = { skip: !haveRsync && 'rsync not installed' }; + +// the real tools/admin.js does the verification, exactly like on the server (upstream-admin wrapper replaced by a tiny sh) +function fixture() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'upstream-offsite-')); + const p = (...n) => path.join(root, ...n); + fs.mkdirSync(p('backups')); fs.mkdirSync(p('far')); + fs.writeFileSync(p('admin'), '#!/bin/sh\nexec node "' + path.join(__dirname, '..', 'tools', 'admin.js') + '" "$@"\n', { mode: 0o755 }); + const dbFile = p('game.db'); + const db = openDb(dbFile); migrate(db); + db.run("INSERT INTO worlds (name, seed, speed, map_radius, status, start_at, created_at) VALUES ('w', 1, 1, 10, 'running', 0, 0)"); + db.close(); + const snap = (name, ageSec) => { + const code = admin.main(['backup', p('backups'), '--db', dbFile], { out() {}, err() {}, env: {}, now: () => Date.UTC(2026, 9, 11, 4, 15, 0) + (snap.n = (snap.n || 0) + 1) * 1000 }); + assert.equal(code, 0); + const made = fs.readdirSync(p('backups')).filter((f) => f.startsWith('upstream-')).sort().pop(); + if (name) fs.renameSync(p('backups', made), p('backups', name)); + const t = (Date.now() - ageSec * 1000) / 1000; + fs.utimesSync(p('backups', name || made), t, t); + return name || made; + }; + const run = (args, env) => { + const r = spawnSync('sh', [SCRIPT].concat(args || []), { encoding: 'utf8', env: Object.assign({}, process.env, { BACKUP_DIR: p('backups'), UPSTREAM_ADMIN: p('admin'), OFFSITE_DEST: p('far'), OFFSITE_KNOWN_HOSTS: p('none') }, env || {}) }); + return { code: r.status, out: r.stdout, err: r.stderr, all: r.stdout + r.stderr }; + }; + return { p, snap, run, far: () => fs.readdirSync(p('far')).sort() }; +} + +test('--check is the ExecCondition: unset destination = exit 1, set = 0', opts, () => { + const f = fixture(); + assert.equal(f.run(['--check'], { OFFSITE_DEST: '' }).code, 1); + assert.equal(f.run(['--check']).code, 0); + const r = f.run([], { OFFSITE_DEST: '' }); + assert.equal(r.code, 2); + assert.match(r.err, /not configured/); +}); + +test('copies the newest snapshot (by mtime, also against a same-second -1 name), verified, mode 0600, content identical', opts, () => { + const f = fixture(); + f.snap('upstream-20261010T041500Z.db', 7200); + const newest = f.snap('upstream-20261011T041500Z-1.db', 60); // sorts BEFORE a plain ...Z.db by name, but is the newer one + f.snap('upstream-20261011T041500Z.db', 3600); + const r = f.run(); + assert.equal(r.code, 0, r.all); + assert.deepEqual(f.far(), [newest]); + assert.deepEqual(fs.readFileSync(f.p('far', newest)), fs.readFileSync(f.p('backups', newest))); + assert.equal(fs.statSync(f.p('far', newest)).mode & 0o777, 0o600); + assert.match(r.out, /checksum compared/); + // the copy is a real snapshot + assert.equal(admin.verifySnapshot(f.p('far', newest)).integrity, 'ok'); + // again: already there, still exit 0 + assert.equal(f.run().code, 0); + assert.deepEqual(f.far(), [newest]); +}); + +test('a snapshot that does not verify is never copied', opts, () => { + const f = fixture(); + const name = f.snap('upstream-20261011T041500Z.db', 60); + fs.writeFileSync(f.p('backups', name), 'not a database'); + const r = f.run(); + assert.equal(r.code, 1); + assert.match(r.err, /does not verify/); + assert.deepEqual(f.far(), []); +}); + +test('nothing to copy, and a different file of the same name on the far side, are failures (never overwritten)', opts, () => { + const f = fixture(); + assert.equal(f.run().code, 1); + const name = f.snap('upstream-20261011T041500Z.db', 60); + fs.writeFileSync(f.p('far', name), 'someone else was here'); + const r = f.run(); + assert.equal(r.code, 1); + assert.match(r.err, /differs/); + assert.equal(fs.readFileSync(f.p('far', name), 'utf8'), 'someone else was here'); +}); + +test('OFFSITE_METHOD=scp is refused (scp would overwrite), nothing is copied', () => { + const f = fixture(); + f.snap('upstream-20261011T041500Z.db', 60); + const r = f.run([], { OFFSITE_METHOD: 'scp' }); + assert.equal(r.code, 2); + assert.match(r.err, /scp is not supported|not supported any more/); + assert.deepEqual(f.far(), []); +}); + +test('an unwritable far side fails loudly', opts, () => { + const f = fixture(); + f.snap('upstream-20261011T041500Z.db', 60); + const r = f.run([], { OFFSITE_DEST: f.p('nope', 'deeper', 'dir') }); + assert.equal(r.code, 1); + assert.match(r.err, /failed/); +}); + +test('the unit files point at the script and gate on OFFSITE_DEST', () => { + const dir = path.join(__dirname, '..', 'deploy'); + const svc = fs.readFileSync(path.join(dir, 'upstream-offsite.service'), 'utf8'); + assert.match(svc, /^ExecCondition=\/opt\/upstream\/deploy\/upstream-offsite --check$/m); + assert.match(svc, /^ExecStart=\/opt\/upstream\/deploy\/upstream-offsite$/m); + assert.match(svc, /^Type=oneshot$/m); + const timer = fs.readFileSync(path.join(dir, 'upstream-offsite.timer'), 'utf8'); + assert.match(timer, /^Unit=upstream-offsite\.service$/m); + assert.ok((fs.statSync(path.join(dir, 'upstream-offsite')).mode & 0o111) !== 0, 'executable bit (ExecStart needs it)'); + assert.equal(spawnSync('sh', ['-n', SCRIPT]).status, 0); +}); diff --git a/test/deploy-update.test.js b/test/deploy-update.test.js new file mode 100644 index 0000000..3646fe9 --- /dev/null +++ b/test/deploy-update.test.js @@ -0,0 +1,416 @@ +'use strict'; +/* deploy/update.sh against a scratch "server": a bare origin, a checkout standing in for /opt/upstream, and stub + * systemctl / curl / npm / upstream-admin / sleep on the PATH. Nothing real is touched. It checks the script's logic + * (order of steps, refusals, rollback, exit codes), not systemd, a real Node or a real network. */ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawnSync } = require('child_process'); + +const SCRIPT = path.join(__dirname, '..', 'deploy', 'update.sh'); +const haveGit = spawnSync('git', ['--version']).status === 0; +const opts = { skip: !haveGit && 'git not installed' }; + +const STUBS = { + systemctl: `echo "systemctl $* [tree=$(git -C "$UPSTREAM_DIR" rev-parse HEAD)]" >> "$STUB_DIR/calls.log" +[ "$1" = start ] && [ -e "$STUB_DIR/restart_fail" ] && exit 1 +[ "$1" = stop ] && [ -e "$STUB_DIR/stop_fail" ] && exit 1 +if [ "$1" = start ] && [ -e "$STUB_DIR/kill_once" ]; then rm -f "$STUB_DIR/kill_once"; kill -TERM $PPID; fi +exit 0`, + curl: `echo "curl $*" >> "$STUB_DIR/calls.log" +[ -e "$UPSTREAM_DIR/BROKEN" ] && exit 22 +exit 0`, + sleep: 'exit 0', + npm: `echo "npm $* [cwd=$PWD]" >> "$STUB_DIR/calls.log" +case $1 in + ci) [ -e "$STUB_DIR/npm_fail" ] && exit 1 ;; + test) [ -e "$PWD/TESTFAIL" ] && exit 1 ;; +esac +exit 0`, + 'upstream-admin': `echo "upstream-admin $*" >> "$STUB_DIR/calls.log" +case $1 in + backup) [ -e "$STUB_DIR/backup_fail" ] && { echo "error: disk full" >&2; exit 1; } + mkdir -p "$2"; f="$2/upstream-20261011T041500Z.db"; echo snap > "$f" + echo "backup written: $f (5 bytes, verified)" ;; + verify-backup) [ -e "$STUB_DIR/verify_fail" ] && exit 1; [ -f "$2" ] || exit 3 ;; +esac +exit 0`, +}; + +const GIT_ENV = { GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null', GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@example.com', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@example.com' }; +function git(cwd, ...args) { + const r = spawnSync('git', args, { cwd, encoding: 'utf8', env: Object.assign({}, process.env, GIT_ENV) }); + assert.equal(r.status, 0, 'git ' + args.join(' ') + ': ' + r.stderr); + return r.stdout.trim(); +} + +// origin (bare) + a working clone `dev` to push from + `app` = the checkout on the "server" +function fixture() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'upstream-update-')); + const p = (n) => path.join(root, n); + for (const d of ['origin.git', 'dev', 'app', 'bin', 'stub']) fs.mkdirSync(p(d)); + git(p('origin.git'), 'init', '--bare', '-b', 'main', '-q'); + git(p('dev'), 'init', '-b', 'main', '-q'); + git(p('dev'), 'remote', 'add', 'origin', p('origin.git')); + fs.writeFileSync(p('dev/package.json'), '{"name":"x"}\n'); + fs.writeFileSync(p('dev/package-lock.json'), '{"v":1}\n'); + fs.writeFileSync(p('dev/.gitignore'), 'node_modules/\n'); + fs.writeFileSync(p('dev/server.js'), '// v1\n'); + git(p('dev'), 'add', '-A'); git(p('dev'), 'commit', '-q', '-m', 'v1'); + git(p('dev'), 'push', '-q', 'origin', 'main'); + git(root, 'clone', '-q', p('origin.git'), p('app')); + fs.mkdirSync(p('app/node_modules')); + for (const [name, body] of Object.entries(STUBS)) { fs.writeFileSync(p('bin/' + name), '#!/bin/sh\n' + body + '\n', { mode: 0o755 }); } + const f = { + root, app: p('app'), dev: p('dev'), stub: p('stub'), backups: p('backups'), + old: git(p('app'), 'rev-parse', 'HEAD'), + head: () => git(p('app'), 'rev-parse', 'HEAD'), + calls: () => (fs.existsSync(p('stub/calls.log')) ? fs.readFileSync(p('stub/calls.log'), 'utf8').split('\n').filter(Boolean) : []), + // a new commit on origin; files = { path: content | null } + publish(files, msg) { + for (const [n, c] of Object.entries(files)) { + if (c === null) fs.rmSync(path.join(p('dev'), n), { force: true }); + else { fs.mkdirSync(path.dirname(path.join(p('dev'), n)), { recursive: true }); fs.writeFileSync(path.join(p('dev'), n), c); } + } + git(p('dev'), 'add', '-A'); git(p('dev'), 'commit', '-q', '-m', msg || 'next'); + git(p('dev'), 'push', '-q', 'origin', 'main'); + return git(p('dev'), 'rev-parse', 'HEAD'); + }, + run(args, env) { + const r = spawnSync('sh', [SCRIPT].concat(args || []), { + encoding: 'utf8', + env: Object.assign({}, process.env, GIT_ENV, { + PATH: p('bin') + path.delimiter + process.env.PATH, STUB_DIR: p('stub'), UPSTREAM_DIR: p('app'), UPSTREAM_ADMIN: p('bin/upstream-admin'), + UPSTREAM_ALLOW_NONROOT: '1', BACKUP_DIR: p('backups'), LOCK_DIR: p('lock'), UPSTREAM_ENV_FILE: p('none.env'), HEALTH_TIMEOUT: '2', + }, env || {}), + }); + return { code: r.status, out: r.stdout, err: r.stderr, all: r.stdout + r.stderr }; + }, + }; + return f; +} +const idx = (calls, prefix) => calls.findIndex((c) => c.startsWith(prefix)); + +test('already up to date: exit 0, no backup, no restart', opts, () => { + const f = fixture(); + const r = f.run(); + assert.equal(r.code, 0, r.all); + assert.match(r.out, /already up to date/); + assert.deepEqual(f.calls(), []); + assert.equal(fs.existsSync(path.join(f.root, 'lock')), false, 'lock released'); +}); + +test('update: snapshot first, fast-forward, no npm ci when the lock is unchanged, restart, health check, old -> new printed', opts, () => { + const f = fixture(); + const next = f.publish({ 'server.js': '// v2\n' }, 'second'); + const r = f.run(); + assert.equal(r.code, 0, r.all); + assert.equal(f.head(), next); + assert.match(r.out, new RegExp(f.old.slice(0, 9) + ' -> ' + next.slice(0, 9))); + assert.match(r.out, /second/, 'the commit subjects that went out are listed'); + const c = f.calls(); + assert.ok(idx(c, 'systemctl stop upstream') >= 0 && idx(c, 'upstream-admin backup') > idx(c, 'systemctl stop'), 'the snapshot comes from the stopped database'); + assert.ok(idx(c, 'upstream-admin verify-backup') > idx(c, 'upstream-admin backup')); + assert.ok(idx(c, 'systemctl start upstream') > idx(c, 'upstream-admin verify-backup'), 'start only after the snapshot'); + assert.ok(idx(c, 'curl') > idx(c, 'systemctl start')); + assert.match(c[idx(c, 'systemctl stop')], new RegExp('tree=' + f.old), 'mixed-code window: the service is stopped while the tree is still the OLD one'); + assert.match(c[idx(c, 'systemctl start')], new RegExp('tree=' + next), '... and started only when the tree is the NEW one'); + assert.equal(c.filter((x) => x.startsWith('systemctl')).length, 2, 'one stop, one start'); + assert.equal(c.some((x) => x.startsWith('npm')), false, 'no npm ci, no npm test'); + assert.match(c.find((x) => x.startsWith('upstream-admin backup')), new RegExp('backup ' + f.backups.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ' --keep 14')); +}); + +test('npm ci --omit=dev only when package-lock changed; npm test only with --test', opts, () => { + const f = fixture(); + f.publish({ 'package-lock.json': '{"v":2}\n' }); + let r = f.run(); + assert.equal(r.code, 0, r.all); + assert.ok(f.calls().some((x) => x.startsWith('npm ci --omit=dev --ignore-scripts')), 'no install scripts as root'); + assert.ok(idx(f.calls(), 'npm ci') > idx(f.calls(), 'systemctl stop') && idx(f.calls(), 'npm ci') < idx(f.calls(), 'systemctl start'), 'deps change only while the service is stopped'); + assert.equal(f.calls().some((x) => x.startsWith('npm test')), false); + + const g = fixture(); + g.publish({ 'server.js': '// v2\n' }); + r = g.run(['--test']); + assert.equal(r.code, 0, r.all); + const c = g.calls(); + assert.ok(idx(c, 'npm test') >= 0 && idx(c, 'npm test') < idx(c, 'systemctl stop'), 'tests run before the service is touched'); + const cwd = (/\[cwd=(.*)\]$/.exec(c[idx(c, 'npm test')]) || [])[1]; + assert.ok(cwd && !cwd.startsWith(g.app), 'tests run in an isolated copy, never in the live tree: ' + cwd); + assert.equal(fs.existsSync(cwd), false, 'the copy is removed again'); + assert.deepEqual(c.filter((x) => x.startsWith('npm ci')).length, 1, 'only the isolated copy got an npm ci (lock unchanged)'); + assert.match(c[idx(c, 'npm ci')], /--ignore-scripts/); +}); + +test('a dirty tree is refused before anything happens (tracked change and untracked file)', opts, () => { + for (const dirty of [(f) => fs.writeFileSync(path.join(f.app, 'server.js'), '// hotfix\n'), (f) => fs.writeFileSync(path.join(f.app, 'stray.txt'), 'x')]) { + const f = fixture(); + f.publish({ 'server.js': '// v2\n' }); + dirty(f); + const r = f.run(); + assert.equal(r.code, 2); + assert.match(r.err, /dirty/); + assert.equal(f.head(), f.old); + assert.deepEqual(f.calls(), []); + } + // ignored files (node_modules, data) are not dirt + const g = fixture(); + g.publish({ 'server.js': '// v2\n' }); + fs.writeFileSync(path.join(g.app, 'node_modules', 'x.js'), '1'); + assert.equal(g.run().code, 0); +}); + +test('refuses: credentials in the origin URL, detached HEAD, a rewritten history, a second run at the same time', opts, () => { + let f = fixture(); + git(f.app, 'remote', 'set-url', 'origin', 'https://jvanvik:glpat-secret@git.example.com/jvanvik/Upstream.git'); + let r = f.run(); + assert.equal(r.code, 2); + assert.match(r.err, /credentials/); + assert.ok(!r.all.includes('glpat-secret'), 'the token is never echoed'); + assert.deepEqual(f.calls(), []); + + f = fixture(); + git(f.app, 'checkout', '-q', '--detach'); + r = f.run(); + assert.equal(r.code, 2); + assert.match(r.err, /detached HEAD/); + + f = fixture(); // origin gets a different history (force push) + git(f.dev, 'reset', '-q', '--hard', 'HEAD'); + fs.writeFileSync(path.join(f.dev, 'server.js'), '// other\n'); + git(f.dev, 'commit', '-q', '--amend', '-a', '-m', 'rewritten'); + git(f.dev, 'push', '-q', '-f', 'origin', 'main'); + r = f.run(); + assert.equal(r.code, 2); + assert.match(r.err, /not a fast-forward/); + assert.equal(f.head(), f.old); + assert.deepEqual(f.calls(), []); + + f = fixture(); + f.publish({ 'server.js': '// v2\n' }); + fs.mkdirSync(path.join(f.root, 'lock')); + r = f.run(); + assert.equal(r.code, 2); + assert.match(r.err, /another update/); + assert.equal(f.head(), f.old); +}); + +test('--dry-run fetches and reports, changes nothing', opts, () => { + const f = fixture(); + f.publish({ 'server.js': '// v2\n', 'server/migrations/005_x.sql': 'select 1;\n' }, 'with a migration'); + const r = f.run(['--dry-run']); + assert.equal(r.code, 0, r.all); + assert.match(r.out, /NEW MIGRATIONS.*005_x\.sql/); + assert.match(r.out, /dry run/); + assert.equal(f.head(), f.old); + assert.deepEqual(f.calls(), []); +}); + +test('no verified snapshot, no update', opts, () => { + let f = fixture(); + f.publish({ 'server.js': '// v2\n' }); + fs.writeFileSync(path.join(f.stub, 'backup_fail'), ''); + let r = f.run(); + assert.equal(r.code, 2); + assert.match(r.out, /no verified snapshot/); + assert.equal(f.head(), f.old); + assert.equal(f.calls().filter((x) => x.startsWith('systemctl')).map((x) => x.split(' ')[1]).join(), 'stop,start', 'stopped for the snapshot, started again when there is none'); + assert.equal(f.calls().some((x) => x.startsWith('npm')), false); + + f = fixture(); + f.publish({ 'server.js': '// v2\n' }); + fs.writeFileSync(path.join(f.stub, 'verify_fail'), ''); + r = f.run(); + assert.equal(r.code, 2); + assert.match(r.out, /no verified snapshot/); + assert.equal(f.head(), f.old); +}); + +test('new version does not answer /healthz: rolled back to the old rev, restarted, exit 1; migrations are called out with the snapshot', opts, () => { + const f = fixture(); + f.publish({ BROKEN: 'x', 'server/migrations/005_x.sql': 'select 1;\n' }, 'bad release'); + const r = f.run(); + assert.equal(r.code, 1, r.all); + assert.match(r.out, /FAILED: no 200 from/); + assert.match(r.out, /rolled back: .* answers \/healthz again/); + assert.match(r.out, /migrations \(005_x\.sql \).*restore the snapshot .*upstream-20261011T041500Z\.db/); + assert.equal(f.head(), f.old); + assert.equal(fs.existsSync(path.join(f.app, 'BROKEN')), false, 'the tree is the old one again'); + assert.equal(f.calls().filter((x) => x.startsWith('systemctl start')).length, 2, 'start for the new code, start for the old'); + assert.equal(f.calls().filter((x) => x.startsWith('systemctl stop')).length, 2, 'the broken new process is stopped before the tree is put back'); + assert.match(r.out, /005_x\.sql/); +}); + +test('rollback across migration 005_site_garrison.sql warns about stranded garrisons', opts, () => { + const f = fixture(); + f.publish({ BROKEN: 'x', 'server/migrations/005_site_garrison.sql': 'select 1;\n' }, 'garrison'); + const dry = f.run(['--dry-run']); + assert.match(dry.out, /005_site_garrison\.sql adds garrisons in landing sites/); + const r = f.run(); + assert.equal(r.code, 1, r.all); + assert.match(r.out, /site_stationed.*neither shows, nor powers, nor sends home/); +}); + +test('rollback restores dependencies when the lock file had changed', opts, () => { + const f = fixture(); + f.publish({ BROKEN: 'x', 'package-lock.json': '{"v":2}\n' }); + const r = f.run(); + assert.equal(r.code, 1, r.all); + assert.equal(f.calls().filter((x) => x.startsWith('npm ci --omit=dev')).length, 2, 'ci for the new lock, ci again for the old one'); + assert.equal(f.head(), f.old); +}); + +test('a failing npm ci or a red --test rolls back; a red suite never restarts the service for the new code', opts, () => { + let f = fixture(); + f.publish({ 'package-lock.json': '{"v":2}\n' }); + fs.writeFileSync(path.join(f.stub, 'npm_fail'), ''); + let r = f.run(); + // npm ci fails for the new AND the old lock (the stub fails always), so the rollback itself cannot recover + assert.equal(r.code, 3, r.all); + assert.equal(f.calls().filter((x) => x.startsWith('systemctl start')).length, 0, 'no start on top of a failed recovery'); + assert.match(r.out, /npm ci for the old code failed/); + + f = fixture(); + f.publish({ TESTFAIL: 'x' }, 'red'); + r = f.run(['--test']); + assert.equal(r.code, 1, r.all); + assert.match(r.err, /test suite .*failed/); + assert.equal(f.head(), f.old); + assert.equal(f.calls().some((x) => x.startsWith('systemctl')), false, 'the live service was not even stopped'); +}); + +test('rollback that does not recover: exit 3 with the snapshot named', opts, () => { + const f = fixture(); + f.publish({ 'server.js': '// v2\n' }); + fs.writeFileSync(path.join(f.stub, 'restart_fail'), ''); + const r = f.run(); + assert.equal(r.code, 3, r.all); + assert.match(r.out, /ROLLBACK DID NOT RECOVER/); + assert.match(r.out, /upstream-20261011T041500Z\.db/); + assert.equal(f.head(), f.old); +}); + +test('a SIGTERM after the merge puts the old rev back and restarts (the next run must not say "up to date" with the old process running)', opts, () => { + const f = fixture(); + f.publish({ 'server.js': '// v2\n' }); + fs.writeFileSync(path.join(f.stub, 'kill_once'), ''); // the first systemctl restart sends TERM to the script + const r = f.run(); + assert.equal(r.code, 1, r.all); + assert.match(r.out, /FAILED: interrupted by a signal/); + assert.equal(f.head(), f.old); + assert.equal(fs.existsSync(path.join(f.root, 'lock')), false, 'lock released'); + assert.equal(f.calls().filter((x) => x.startsWith('systemctl start')).length, 2); +}); + +test('PORT comes from the env file for the health check; the script is plain POSIX sh syntax', opts, () => { + const f = fixture(); + f.publish({ 'server.js': '// v2\n' }); + fs.writeFileSync(path.join(f.root, 'none.env'), 'SIGNUP_CODE=x\nPORT="9090"\n'); + assert.equal(f.run().code, 0); + assert.ok(f.calls().some((x) => x.startsWith('curl') && x.includes('http://127.0.0.1:9090/healthz'))); + assert.equal(spawnSync('sh', ['-n', SCRIPT]).status, 0); + assert.equal(/^\s*(local|source|declare|typeset)\s|\[\[(?!:)|\[ [^\]]*==|<\(|\$\{[A-Za-z_]+(\/|,,|\^\^)/m.test(fs.readFileSync(SCRIPT, 'utf8').replace(/^\s*#.*$/gm, '')), false, 'no bashisms the usual way'); +}); + +// --------------------------------------------------------------------------------------------------------------------------- +// review fixes: tools up front, credentials check, mixed-code window, tests as the service user in an isolated copy +const SYS_TOOLS = ['git', 'sh', 'sed', 'tr', 'head', 'tail', 'id', 'rm', 'rmdir', 'mkdir', 'env', 'tar', 'mktemp', 'cat', 'basename', 'dirname', 'ls', 'chmod', 'date', 'uname', 'grep', 'awk', 'mv', 'cp', 'ln', 'readlink', 'sort', 'cut', 'wc', 'xargs', 'true', 'false', 'test', 'expr', 'printf', 'ssh']; +// a PATH holding the stubs plus a few real tools, and NOT curl (or whatever is left out) +function restrictedPath(f, leaveOut) { + const sys = path.join(f.root, 'sys'); + fs.mkdirSync(sys, { recursive: true }); + for (const t of SYS_TOOLS) { + if (leaveOut.includes(t)) continue; + const r = spawnSync('sh', ['-c', 'command -v ' + t], { encoding: 'utf8' }); + const real = r.stdout.trim(); + if (real && real.startsWith('/') && !fs.existsSync(path.join(sys, t))) fs.symlinkSync(real, path.join(sys, t)); + } + return path.join(f.root, 'bin') + path.delimiter + sys; +} + +test('a missing tool (curl, npm, systemctl, the admin wrapper) is refused up front: exit 2, nothing stopped, no misleading rollback', opts, () => { + for (const tool of ['curl', 'npm', 'systemctl', 'upstream-admin']) { + const f = fixture(); + f.publish({ 'server.js': '// v2\n' }); + fs.rmSync(path.join(f.root, 'bin', tool)); + const r = f.run([], { PATH: restrictedPath(f, []), UPSTREAM_ADMIN: tool === 'upstream-admin' ? 'no-such-admin' : path.join(f.root, 'bin', 'upstream-admin') }); + assert.equal(r.code, 2, tool + ': ' + r.all); + assert.match(r.err, new RegExp('missing on the PATH:.* ' + (tool === 'upstream-admin' ? 'no-such-admin' : tool)), tool); + assert.ok(!/ROLLBACK DID NOT RECOVER|rolling back/.test(r.all), tool + ': no rollback story'); + assert.equal(f.head(), f.old); + assert.deepEqual(f.calls(), [], tool + ': nothing ran'); + } +}); + +test('the credential check only refuses user:password@ / token@ in an http(s) authority, not ssh:// logins or an @ in a path', opts, () => { + const refused = ['https://jvanvik:glpat-secret@git.example.com/x.git', 'https://glpat-secret@git.example.com/x.git', 'http://u:p@127.0.0.1:1/x.git']; + for (const url of refused) { + const f = fixture(); + git(f.app, 'remote', 'set-url', 'origin', url); + const r = f.run(); + assert.equal(r.code, 2, url); + assert.match(r.err, /credentials/, url); + assert.ok(!r.all.includes('secret'), 'never echoed'); + } + // allowed: the script gets past the check and only then fails on the (unreachable) network, never with "credentials" + for (const url of ['ssh://git@127.0.0.1:1/jvanvik/Upstream.git', 'git@127.0.0.1:jvanvik/Upstream.git', 'https://127.0.0.1:1/a@b/c.git', 'https://127.0.0.1:1/jvanvik/Upstream.git']) { + const f = fixture(); + git(f.app, 'remote', 'set-url', 'origin', url); + const r = f.run([], { GIT_SSH_COMMAND: 'false' }); + assert.ok(!/credentials/.test(r.all), url + ': ' + r.all); + assert.match(r.err, /git fetch origin main failed/, url); + assert.equal(r.code, 1); + } +}); + +test('a SIGTERM while the service is stopped but before the merge starts it again on the untouched tree', opts, () => { + const f = fixture(); + f.publish({ 'server.js': '// v2\n' }); + // the admin wrapper (runs between stop and merge) sends TERM to the script + fs.writeFileSync(path.join(f.root, 'bin', 'upstream-admin'), '#!/bin/sh\necho "upstream-admin $*" >> "$STUB_DIR/calls.log"\nkill -TERM $PPID\nsleep 0\nexit 1\n', { mode: 0o755 }); + const r = f.run(); + assert.equal(r.code, 1, r.all); + assert.equal(f.head(), f.old, 'tree untouched'); + const sys = f.calls().filter((x) => x.startsWith('systemctl')).map((x) => x.split(' ')[1]); + assert.equal(sys.join(), 'stop,start', 'stopped, then started again: never left down'); + assert.equal(fs.existsSync(path.join(f.root, 'lock')), false); +}); + +test('a stop that fails refuses before anything is changed', opts, () => { + const f = fixture(); + f.publish({ 'server.js': '// v2\n' }); + fs.writeFileSync(path.join(f.stub, 'stop_fail'), ''); + const r = f.run(); + assert.equal(r.code, 1, r.all); + assert.match(r.err, /systemctl stop upstream failed/); + assert.equal(f.head(), f.old); + assert.equal(f.calls().some((x) => x.startsWith('upstream-admin') || x.startsWith('npm')), false); +}); + +test('--test as root runs npm ci / npm test as the service user (runuser) and never as root', opts, () => { + const f = fixture(); + f.publish({ 'server.js': '// v2\n' }); + // pretend to be root: id -u answers 0, and runuser is a stub that records who it switches to and then runs the command + fs.writeFileSync(path.join(f.root, 'bin', 'id'), '#!/bin/sh\n[ "$1" = "-u" ] && { echo 0; exit 0; }\nexec /usr/bin/id "$@"\n', { mode: 0o755 }); + fs.writeFileSync(path.join(f.root, 'bin', 'runuser'), '#!/bin/sh\necho "runuser $*" >> "$STUB_DIR/calls.log"\n[ "$1" = "-u" ] || exit 9\nshift 2\n[ "$1" = "--" ] && shift\nexec "$@"\n', { mode: 0o755 }); + fs.writeFileSync(path.join(f.root, 'bin', 'chown'), '#!/bin/sh\necho "chown $*" >> "$STUB_DIR/calls.log"\n', { mode: 0o755 }); + const r = f.run(['--test'], { UPSTREAM_ALLOW_NONROOT: '0', UPSTREAM_SERVICE_USER: 'svcuser' }); + assert.equal(r.code, 0, r.all); + const c = f.calls(); + assert.match(c[idx(c, 'runuser')], /^runuser -u svcuser -- env /); + assert.ok(idx(c, 'chown') >= 0 && idx(c, 'chown') < idx(c, 'runuser'), 'the copy is handed to the service user first'); + assert.ok(idx(c, 'runuser') < idx(c, 'systemctl stop'), 'before the service is touched'); + assert.equal(c.filter((x) => x.startsWith('runuser')).length, 1); +}); + +test('a red --test in the isolated copy leaves the live tree, the service and the snapshot dir alone', opts, () => { + const f = fixture(); + f.publish({ TESTFAIL: 'x' }, 'red'); + const r = f.run(['--test']); + assert.equal(r.code, 1, r.all); + assert.equal(f.head(), f.old); + assert.equal(fs.existsSync(path.join(f.app, 'TESTFAIL')), false); + assert.equal(fs.existsSync(f.backups), false, 'no snapshot was needed'); +}); diff --git a/test/economy-leaks.test.js b/test/economy-leaks.test.js new file mode 100644 index 0000000..b1de91f --- /dev/null +++ b/test/economy-leaks.test.js @@ -0,0 +1,173 @@ +'use strict'; +/* docs/BALANCE.md S2 (trade escrow refunds were clipped silently) and S4 (raid loot and the incumbent bonus were destroyed on + * arrival when the raiders' home Rack hall was full). Each test below fails on the code before the fix. Fake clock, in-memory db. */ +const test = require('node:test'); +const assert = require('node:assert'); +const T = require('./military-helpers'); +const { R, D, H } = T; +const { loadTown } = require('../server/state'); + +const capOf = (h, townId) => R.storageCap(loadTown(h.db, townId)); +const fieldsOff = (h, townId) => h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%'", townId); + +// ---------------------------------------------------------------- S4: loot +test('rules.lootSplit: a resource with no room at home is not taken and its share goes to the others', () => { + const rich = { fiber: 1000, hardware: 1000, capital: 1000 }; + assert.deepEqual(R.lootSplit(300, rich, { fiber: Infinity, hardware: Infinity, capital: Infinity }), { fiber: 100, hardware: 100, capital: 100 }); + assert.deepEqual(R.lootSplit(300, rich, { fiber: 1000, hardware: 0, capital: 1000 }), { fiber: 150, hardware: 0, capital: 150 }); + assert.deepEqual(R.lootSplit(300, rich, { fiber: 20, hardware: 0, capital: 0 }), { fiber: 20, hardware: 0, capital: 0 }, 'no more than the room, even if the raiders could carry more'); + assert.deepEqual(R.lootSplit(300, rich, { fiber: 50 }), { fiber: 50, hardware: 125, capital: 125 }, 'a missing key means no limit'); + assert.deepEqual(R.lootSplit(300, rich), { fiber: 100, hardware: 100, capital: 100 }, 'room is optional'); +}); + +function raid(homeStock) { + const h = T.setup(); + const att = T.addOperator(h, 'raider', { x: 5, y: 0, units: { script_crew: 40 } }); + const def = T.addOperator(h, 'target', { x: 9, y: 0, units: { soc_analyst: 20 }, infra: { rack_hall: 2 } }); + fieldsOff(h, att.townId); fieldsOff(h, def.townId); + h.db.run('UPDATE towns SET fiber = 600, hardware = 600, capital = 600 WHERE id = ?', def.townId); + h.db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', homeStock.fiber, homeStock.hardware, homeStock.capital, att.townId); + const sent = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'raid', toTownId: def.townId, units: { script_crew: 40 } }); + return { h, att, def, sent }; +} + +test('raid: loot is limited to what the home Rack hall can bank; the rest stays with the victim and the report says so (S4)', () => { + const probe = T.setup(); const cap = capOf(probe, T.addOperator(probe, 'p', { x: 5, y: 0 }).townId); + const { h, att, def, sent } = raid({ fiber: 100, hardware: cap, capital: cap - 30 }); // no room for Hardware, 30 for Capital + const defBefore = T.town(h, def.townId); + h.advanceTo(sent.arriveAt); + const rep = T.reportsOf(h, att.userId)[0].data; + assert.equal(rep.outcome, 'attacker_won'); + assert.equal(rep.loot.hardware, 0, 'nothing is taken that cannot be banked'); + assert.ok(rep.loot.capital <= 30 + 1e-9, 'Capital is limited to the 30 of room'); + assert.ok(rep.loot.fiber > 0, 'the carry goes to the resource that has room'); + assert.ok(rep.lootLeft.hardware > 0, 'the report says what was left behind for lack of room'); + const defAfter = T.town(h, def.townId); + assert.equal(defAfter.hardware, defBefore.hardware, 'the victim keeps what was not taken'); + const ret = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'"); + assert.deepEqual(JSON.parse(ret.cargo), rep.loot); + h.advanceTo(ret.arrive_at); + const back = T.notes(h, att.userId, 'movement_returned')[0]; + assert.ok(!back.cargoLost || Object.values(back.cargoLost).every((v) => v === 0), 'nothing is destroyed on arrival: ' + JSON.stringify(back.cargoLost)); + assert.ok(Math.abs(T.town(h, att.townId).hardware - cap) < 1e-6, 'hardware stays at the hall size'); +}); + +test('raid: two raids from one home that each see the same free room cannot both fill it; the later one is limited, nothing is destroyed on landing', () => { + const h = T.setup(); + const att = T.addOperator(h, 'raider', { x: 5, y: 0, units: { script_crew: 80 } }); + const def = T.addOperator(h, 'target', { x: 9, y: 0, units: { soc_analyst: 10 }, infra: { rack_hall: 2 } }); + fieldsOff(h, att.townId); fieldsOff(h, def.townId); + const cap = capOf(h, att.townId), room = 600, carry = room; + h.db.run('UPDATE towns SET fiber = 2000, hardware = 2000, capital = 2000 WHERE id = ?', def.townId); + h.db.run('UPDATE towns SET fiber = ?, hardware = ?, capital = ? WHERE id = ?', cap, cap, cap - room, att.townId); // room for ONE raid's worth, in Capital only (each raid alone could fill it) + const s1 = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'raid', toTownId: def.townId, units: { script_crew: 40 } }); + const s2 = h.run('sendMovement', { userId: att.userId, fromTownId: att.townId, type: 'raid', toTownId: def.townId, units: { script_crew: 40 } }); + h.advanceTo(Math.max(s1.arriveAt, s2.arriveAt)); + const reps = T.reportsOf(h, att.userId).map((r) => r.data).filter((d) => d.type === 'raid'); + assert.equal(reps.length, 2); + assert.ok(reps.every((r) => r.outcome === 'attacker_won'), 'both raids won (the test is about room, not combat)'); + const total = reps.reduce((a, r) => a + r.loot.capital, 0); + assert.ok(total <= carry + 1e-6, 'together they take no more than the home can bank: ' + total + ' vs ' + carry); + assert.ok(reps.some((r) => r.lootLeft && (r.lootLeft.fiber > 0 || r.lootLeft.hardware > 0)), 'the reports say what stayed with the victim'); + h.advance(2 * H); + assert.equal(T.notes(h, att.userId, 'movement_returned').length, 2); + for (const n of T.notes(h, att.userId, 'movement_returned')) assert.ok(!n.cargoLost || Object.values(n.cargoLost).every((v) => v === 0), 'nothing destroyed: ' + JSON.stringify(n.cargoLost)); +}); + +test('raid: with room everywhere the loot is the same even split as before and lootLeft is empty', () => { + const { h, att, sent } = raid({ fiber: 100, hardware: 100, capital: 100 }); + h.advanceTo(sent.arriveAt); + const rep = T.reportsOf(h, att.userId)[0].data; + assert.ok(rep.loot.fiber > 0 && rep.loot.fiber === rep.loot.hardware); + assert.deepEqual(rep.lootLeft, {}); +}); + +test('incumbent bonus is delivered in full even when the Hardware store is full (a one-time reward must not vanish at the door)', () => { + const h = T.setup({ seed: 99 }); + let site = null; + for (let x = -20; x <= 20 && !site; x++) for (let y = -20; y <= 20 && !site; y++) if (R.tileAt(h.world.seed, 50, x, y).type === 'incumbent' && Math.abs(x) + Math.abs(y) > 6) site = { x, y }; + const need = R.incumbentDefence(h.world.seed, site.x, site.y, 0); + const crews = Math.ceil(need / 40 * 1.6); + const a = T.addOperator(h, 'raider', { x: site.x - 3, y: site.y, units: { script_crew: crews } }); + fieldsOff(h, a.townId); + const cap = capOf(h, a.townId); + h.db.run('UPDATE towns SET fiber = 100, hardware = ?, capital = 100 WHERE id = ?', cap, a.townId); + const s = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'attack', x: site.x, y: site.y, units: { script_crew: crews } }); + h.advanceTo(s.arriveAt); + const ret = h.db.get("SELECT * FROM movements WHERE type = 'return' AND status = 'out'"); + h.advanceTo(ret.arrive_at); + assert.equal(T.town(h, a.townId).hardware, cap + D.INCUMBENT.hardwareBonus, 'the bonus sits on top of the full store (kept, it only stops growing)'); + const back = T.notes(h, a.userId, 'movement_returned')[0]; + assert.ok(!back.cargoLost || !back.cargoLost.hardware, 'and is not reported lost'); +}); + +// ---------------------------------------------------------------- S2: trade escrow +function poster(o) { + const h = T.setup(); + const a = T.addOperator(h, 'alice', { x: 5, y: 0, res: 100 }); + const b = T.addOperator(h, 'bob', { x: 9, y: 0 }); + const cap = capOf(h, a.townId); + h.db.run('UPDATE towns SET fiber = ?, hardware = 0, capital = 0 WHERE id = ?', o && o.fiber !== undefined ? o.fiber : cap - 420, a.townId); + return { h, a, b, cap }; +} +const offerOf = (h, a, amount) => h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'fiber', giveAmount: amount || 400, wantRes: 'hardware', wantAmount: 300, maxDistance: 30 }).offer; +const fiberNow = (h, townId) => R.resourcesAt(loadTown(h.db, townId), h.clock.now()).amounts.fiber; + +test('trade (S2): escrow keeps its room in the Rack hall, so a refund after the store refilled loses nothing and stores nothing extra', () => { + for (const how of ['cancel', 'expire']) { + const { h, a, cap } = poster(); + const offer = offerOf(h, a); + h.advance(30 * H); // production refills everything it may (the offer lives 48 h) + const before = fiberNow(h, a.townId); + assert.ok(Math.abs(before - (cap - 400)) < 1e-6, how + ': the stock stops 400 below the hall size while 400 are escrowed, got ' + before); + if (how === 'cancel') h.run('tradeCancel', { userId: a.userId, offerId: offer.id }); + else h.advanceTo(offer.expiresAt); + assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, how === 'cancel' ? 'cancelled' : 'expired'); + const after = fiberNow(h, a.townId); + assert.ok(Math.abs(after - (before + 400)) < 1e-6 && Math.abs(after - cap) < 1e-6, how + ': the whole escrow came back and exactly fills the hall: ' + after + ' / ' + cap); + assert.equal(T.notes(h, a.userId, 'trade_refund_clipped').length, 0, 'nothing was lost, so nothing is reported'); + } +}); + +test('trade (S2): several offers and other resources - the room is per resource and per open offer', () => { + const { h, a, cap } = poster({ fiber: 0 }); + h.db.run('UPDATE towns SET fiber = ?, hardware = ? WHERE id = ?', cap - 300, cap - 100, a.townId); + const o1 = offerOf(h, a, 400), o2 = offerOf(h, a, 300); + h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'hardware', giveAmount: 250, wantRes: 'fiber', wantAmount: 300, maxDistance: 30 }); + h.advance(30 * H); + const t = loadTown(h.db, a.townId); + assert.deepEqual(t.escrow, { fiber: 700, hardware: 250, capital: 0 }); + assert.equal(R.resourcesAt(t, h.clock.now()).caps.fiber, cap - 700); + h.run('tradeCancel', { userId: a.userId, offerId: o1.id }); + assert.ok(Math.abs(fiberNow(h, a.townId) - (cap - 300)) < 1e-6, 'the other offer still holds its 300'); + h.run('tradeCancel', { userId: a.userId, offerId: o2.id }); + assert.ok(Math.abs(fiberNow(h, a.townId) - cap) < 1e-6); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM notifications WHERE type = 'trade_refund_clipped'").n, 0); +}); + +test('trade (S2): accepting settles the poster under the reserved room; afterwards the room is free again', () => { + const { h, a, b, cap } = poster({ fiber: 0 }); + h.db.run('UPDATE towns SET fiber = ? WHERE id = ?', cap - 420, a.townId); + const offer = offerOf(h, a, 400); + h.advance(30 * H); + assert.ok(Math.abs(fiberNow(h, a.townId) - (cap - 400)) < 1e-6); + const acc = h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId }); + const stored = h.db.get('SELECT fiber FROM towns WHERE id = ?', a.townId).fiber; + assert.ok(Math.abs(stored - (cap - 400)) < 1e-6, 'the poster was settled at the moment the escrow left, under the reserved cap: ' + stored); + h.advanceTo(acc.arriveAt + 100 * H); + assert.ok(Math.abs(fiberNow(h, a.townId) - cap) < 1e-6, 'the hall fills up again once the escrow is gone'); +}); + +test('trade (S2): what cannot be refunded (Rack hall shot down meanwhile) is reported, never silent', () => { + const { h, a } = poster({ fiber: 3000 }); + const offer = offerOf(h, a, 400); + const total = () => h.db.get('SELECT fiber FROM towns WHERE id = ?', a.townId).fiber; + const before = total(); + T.setBuildings(h, a.townId, { rack_hall: 1 }); // cap 1000 << stock 2600 + const r = h.run('tradeCancel', { userId: a.userId, offerId: offer.id }); + assert.equal(r.returned.amount, 0, 'stock above the hall size is kept but a refund does not lift it further'); + assert.ok(Math.abs(total() - before) < 1e-6); + const note = T.notes(h, a.userId, 'trade_refund_clipped'); + assert.equal(note.length, 1); + assert.deepEqual([note[0].resource, note[0].lost, note[0].credited], ['fiber', 400, 0]); +}); diff --git a/test/endgame-garrison.test.js b/test/endgame-garrison.test.js new file mode 100644 index 0000000..9580a59 --- /dev/null +++ b/test/endgame-garrison.test.js @@ -0,0 +1,508 @@ +'use strict'; +/* Garrisons at backbone landing sites (docs/DECISIONS.md E6): members of the holding alliance station units in a site, the units defend it on top + * of its static defence, attacks resolve in arrival order (a lost wave kills a share of the garrison, the next wave faces less), a won attack + * wipes it and takes the site. Plus the edges: nobody but the holder can reinforce, units are never in two places, withdraw/recall while under + * attack, leaving the alliance, power. Fake clock, in-memory db; the world is moved to day 100 by advancing the clock. */ +const test = require('node:test'); +const assert = require('node:assert'); +const T = require('./military-helpers'); +const A = require('../server/alliances'); +const E = require('../server/endgame'); +const G = require('../server/military/garrison'); +const { createEndgameQueries } = require('../server/endgameQueries'); +const { loadTown } = require('../server/state'); +const { R, D, H } = T; +const DAY = 24 * H; + +function alliance(h, name, leader, members) { + const id = Number(h.db.run('INSERT INTO alliances (world_id, name, tag, size_cap, created_by, created_at) VALUES (?, ?, ?, 10, ?, ?)', h.worldId, name, name.slice(0, 3).toUpperCase(), leader.opId, h.clock.now()).lastInsertRowid); + A.addMember(h.db, id, leader.opId, 'leader', h.clock.now()); + for (const m of members || []) A.addMember(h.db, id, m.opId, 'member', h.clock.now()); + return id; +} +const err = (fn) => { try { fn(); } catch (e) { return e; } assert.fail('expected an error'); }; + +function world(day, o) { + const h = T.setup(Object.assign({ seed: 4242, radius: 50 }, o)); + h.advanceTo(h.world.start_at + Math.round(day * DAY / (h.world.speed || 1))); + h.eg = createEndgameQueries(h); + h.sites = R.backboneSites(h.world.seed, h.world.map_radius); + return h; +} +// An operator next to site `i` with plenty of power so that its units stay online; no production unless asked. +function near(h, name, i, o) { + const s = h.sites[i]; + const op = T.addOperator(h, name, Object.assign({ x: s.x - 4, y: s.y, power: 25 }, o || {})); + if (!(o && o.produce)) h.db.run("UPDATE buildings SET level = 0 WHERE town_id = ? AND key LIKE 'f%' AND key NOT IN ('f13','f14','f15','f16')", op.townId); + return op; +} +const siteOf = (h, i) => h.db.get('SELECT * FROM landing_sites WHERE world_id = ? AND idx = ?', h.worldId, i); +function hold(h, i, allianceId, opId) { + E.ensureSites(h.db, h.world, h.clock.now()); + h.db.run('UPDATE landing_sites SET holder_alliance_id = ?, holder_operator_id = ? WHERE idx = ?', allianceId, opId, i); +} +const sendTo = (h, who, i, type, units) => h.run('sendMovement', { userId: who.userId, fromTownId: who.townId, type, x: h.sites[i].x, y: h.sites[i].y, units }); +const staticHeld = (h, i, level, held) => R.backboneDefence(h.world.seed, h.sites[i].x, h.sites[i].y, R.worldAgeDays(h.world.start_at, h.clock.now(), h.world.speed), level || 0, held !== false); +const garrisonAt = (h, i) => { const s = siteOf(h, i); const out = {}; for (const g of G.groups(h.db, s.id)) for (const k of Object.keys(g.units)) out[k] = (out[k] || 0) + g.units[k]; return out; }; +// Every unit in the world, wherever it is: home, stationed in a POP, in a garrison, in a movement that has not arrived. +function totals(h) { + const out = {}; + const add = (u, n) => { out[u] = (out[u] || 0) + n; }; + for (const r of h.db.all('SELECT unit, SUM(count) AS n FROM town_units GROUP BY unit')) add(r.unit, r.n); + for (const r of h.db.all('SELECT unit, SUM(count) AS n FROM stationed GROUP BY unit')) add(r.unit, r.n); + for (const r of h.db.all('SELECT unit, SUM(count) AS n FROM site_stationed GROUP BY unit')) add(r.unit, r.n); + for (const m of h.db.all("SELECT units FROM movements WHERE status = 'out'")) { const u = JSON.parse(m.units); for (const k of Object.keys(u)) add(k, u[k]); } + return out; +} +const draw = (h, who) => loadTown(h.db, who.townId).unitDraw; +const lastReport = (h, who, type) => T.reportsOf(h, who.userId).filter((r) => r.type === type).pop(); + +// alice (leader) + alice2 (member) hold site 0 for ALP; bob + bob2 are BRA; 'loner' has no alliance +function scene(o) { + const h = world(100, o); + const s0 = h.sites[0]; + const a = near(h, 'alice', 0, { units: { soc_analyst: 600 } }); + const a2 = near(h, 'alice2', 0, { x: s0.x - 4, y: s0.y + 3, units: { blue_team: 100 } }); + const b = near(h, 'bob', 0, { x: s0.x + 4, y: s0.y }); + const b2 = near(h, 'bob2', 0, { x: s0.x + 4, y: s0.y + 3 }); + const loner = near(h, 'loner', 0, { x: s0.x, y: s0.y - 5, units: { soc_analyst: 10 } }); + const A1 = alliance(h, 'Alpha', a, [a2]), B1 = alliance(h, 'Bravo', b, [b2]); + hold(h, 0, A1, a.opId); + return Object.assign(h, { a, a2, b, b2, loner, A1, B1 }); +} + +// ---------------------------------------------------------------- pure rules + +test('rules: a held site is much weaker than an unheld one; battle = static + garrison; the static part never loses anything; transport capacity scales with speed', () => { + const seed = 4242, x = 10, y = 10; + const open = R.backboneDefence(seed, x, y, 100, 0, false), heldD = R.backboneDefence(seed, x, y, 100, 0, true); + assert.equal(R.backboneDefence(seed, x, y, 100, 0), open, 'unheld is the default (the opening scramble)'); + assert.ok(open > 5 * heldD && heldD > 0, 'held = ' + heldD + ', unheld = ' + open); + assert.ok(R.backboneDefence(seed, x, y, 100, 50, true) > heldD, 'node levels still raise it'); + + const grp = (n) => ({ id: 'g', units: { soc_analyst: n }, research: {} }); + const none = R.resolveBattle({ kind: 'attack', attackers: { units: { script_crew: 100 }, research: {} }, defenders: [], firewall: 0, staticDefence: 3000 }); + assert.equal(none.D, 3000); + assert.equal(none.defenderLossFraction, 0, 'no garrison, nothing to lose'); + assert.equal(none.attackerWins, true); + const b = R.resolveBattle({ kind: 'attack', attackers: { units: { script_crew: 100 }, research: {} }, defenders: [grp(100)], firewall: 0, staticDefence: 3000 }); + assert.equal(b.D, 3000 + 100 * 25, 'static + raw defence, no firewall, no base defence'); + assert.equal(b.attackerWins, false); + assert.ok(b.defenderLossFraction > 0 && b.defenderLossFraction < 1); + assert.equal(b.defenders[0].lost.soc_analyst, Math.round(100 * Math.pow(4000 / 5500, 1.5))); + const win = R.resolveBattle({ kind: 'attack', attackers: { units: { script_crew: 200 }, research: {} }, defenders: [grp(100)], firewall: 0, staticDefence: 3000 }); + assert.equal(win.attackerWins, true); + assert.equal(win.defenders[0].lost.soc_analyst, 100, 'a won attack wipes the garrison'); + // a POP battle is untouched by the new mode + const pop = R.resolveBattle({ kind: 'attack', attackers: { units: { script_crew: 100 }, research: {} }, defenders: [grp(100)], firewall: 0 }); + assert.equal(pop.D, (100 * 25 + D.MILITARY.defenceBase) * R.firewallMult(0)); + + assert.equal(R.transportCapacity(1), D.TRANSPORT.capacityPerLink); + assert.equal(R.transportCapacity(3), 3 * D.TRANSPORT.capacityPerLink); + assert.equal(R.transportCapacity(undefined), D.TRANSPORT.capacityPerLink); +}); + +// ---------------------------------------------------------------- stationing + +test('reinforce a site: only members of the holding alliance; the units leave home, join the garrison on arrival and draw their owner\'s power', () => { + const h = scene(); + const { a, a2, b, loner } = h; + T.giveUnits(h, b.townId, { soc_analyst: 20 }); + assert.equal(err(() => sendTo(h, b, 0, 'reinforce', { soc_analyst: 10 })).details.reason, 'not_holder', 'a rival cannot'); + assert.equal(err(() => sendTo(h, loner, 0, 'reinforce', { soc_analyst: 10 })).details.reason, 'not_holder', 'no alliance cannot'); + assert.equal(err(() => sendTo(h, a, 1, 'reinforce', { soc_analyst: 10 })).details.reason, 'not_holder', 'not a site your alliance holds'); + assert.equal(err(() => h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'reinforce', x: h.sites[0].x + 1, y: h.sites[0].y, units: { soc_analyst: 1 } })).code, 'invalid_target'); + + const before = totals(h); + const d0 = draw(h, a); + assert.equal(d0, 600); + const mv = sendTo(h, a, 0, 'reinforce', { soc_analyst: 400 }); + assert.equal(draw(h, a), 200, 'units on the road draw nothing'); + assert.equal(T.units(h, a.townId).soc_analyst, 200); + assert.equal(h.db.get('SELECT COUNT(*) AS n FROM site_stationed').n, 0); + assert.deepEqual(totals(h), before, 'in a movement, counted once'); + assert.equal(T.notes(h, a2.userId, 'backbone_incoming').length, 0, 'own members are not warned about the own reinforcement'); + h.advanceTo(mv.arriveAt); + assert.deepEqual(garrisonAt(h, 0), { soc_analyst: 400 }); + assert.equal(draw(h, a), 600, 'the owner pays for them again, nobody else'); + assert.equal(draw(h, a2), 100 * D.UNITS.blue_team.draw); + assert.equal(h.db.get('SELECT COUNT(*) AS n FROM stationed').n, 0, 'not a POP reinforcement'); + assert.deepEqual(totals(h), Object.assign({}, before), 'counted once'); + assert.equal(T.notes(h, a.userId, 'garrison_arrived').length, 1); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0); + // the POP view lists them (they draw this POP's power, so they must not just vanish from it) + const mu = h.queries.town(a.userId, a.townId).town.military.units; + assert.deepEqual(mu.garrisoned, [{ siteId: siteOf(h, 0).id, x: h.sites[0].x, y: h.sites[0].y, units: { soc_analyst: 400 } }]); + assert.equal(T.units(h, a.townId).soc_analyst, 200); + assert.deepEqual(h.queries.town(b.userId, b.townId).town.military.units.garrisoned, []); + + // a second member adds to the same site; groups are per owner POP + const mv2 = sendTo(h, a2, 0, 'reinforce', { blue_team: 100 }); + h.advanceTo(mv2.arriveAt); + assert.equal(G.groups(h.db, siteOf(h, 0).id).length, 2); + const view = h.eg.site(a.userId, siteOf(h, 0).id); + assert.equal(view.you.canReinforce, true); + assert.equal(view.garrison.length, 2); + assert.deepEqual(view.garrison.map((g) => g.mine), [true, false]); + assert.equal(view.defence.static, staticHeld(h, 0, 0)); + assert.equal(view.defence.garrison, 400 * 25 + 100 * 80); + assert.equal(view.defence.total, view.defence.static + view.defence.garrison); + assert.equal(h.eg.site(b.userId, siteOf(h, 0).id).garrison, undefined, 'the garrison is the holders\' business (a scan shows it)'); + assert.equal(h.eg.site(b.userId, siteOf(h, 0).id).you.canReinforce, false); +}); + +test('a scan of a held site shows the garrison once: defence = static + garrison, units not doubled', () => { + const h = scene(); + const { a, b } = h; + const mv = sendTo(h, a, 0, 'reinforce', { soc_analyst: 300 }); + h.advanceTo(mv.arriveAt); + T.giveUnits(h, b.townId, { port_scanner: 200 }); + const sc = sendTo(h, b, 0, 'scan', { port_scanner: 200 }); + assert.equal(T.notes(h, a.userId, 'backbone_incoming').length, 1, 'the holders are told something is coming (no type, no sender)'); + assert.deepEqual(Object.keys(T.notes(h, a.userId, 'backbone_incoming')[0]).sort(), ['arriveAt', 'index', 'siteId', 'x', 'y']); + h.advanceTo(sc.arriveAt); + const rep = lastReport(h, b, 'scan').data; + assert.equal(rep.success, true); + assert.deepEqual(rep.intel.garrison.units, { soc_analyst: 300 }); + assert.equal(rep.intel.garrison.power, 300 * 25); + assert.equal(rep.intel.static, staticHeld(h, 0, 0)); + assert.equal(rep.intel.defence, staticHeld(h, 0, 0) + 300 * 25); + assert.equal(rep.intel.holder.allianceId, h.A1); +}); + +// ---------------------------------------------------------------- the fight + +test('waves: a lost wave kills part of the garrison and nothing else, the next wave faces less and takes the site; the garrison is wiped, the site changes hands', () => { + const h = scene(); + const { a, b, b2 } = h; + const mv = sendTo(h, a, 0, 'reinforce', { soc_analyst: 400 }); + h.advanceTo(mv.arriveAt); + const S = staticHeld(h, 0, 0), G0 = 400 * 25; + // wave 1: more than the static part, less than static + garrison + const n1 = Math.ceil((S + 0.8 * G0) / 40); + assert.ok(n1 * 40 > S && n1 * 40 < S + G0); + T.giveUnits(h, b.townId, { script_crew: n1 }); + // wave 2 is sized for what is LEFT after wave 1 (computed from the rules), and must be smaller than the whole defence + const f1 = Math.pow((n1 * 40) / (S + G0), 1.5); + const left = 400 - Math.round(400 * f1); + const n2 = Math.ceil((S + left * 25) * 1.02 / 40); + assert.ok(n2 * 40 < S + G0, 'the second wave alone could not have taken the site'); + T.giveUnits(h, b2.townId, { script_crew: n2 }); + + const w1 = sendTo(h, b, 0, 'attack', { script_crew: n1 }); + const w2 = sendTo(h, b2, 0, 'attack', { script_crew: n2 }); + assert.ok(w1.arriveAt <= w2.arriveAt, 'bob first (the same distance, lower id first)'); + assert.equal(T.notes(h, a.userId, 'backbone_incoming').length, 2); + const unitsBefore = totals(h); + h.advanceTo(w1.arriveAt); + assert.equal(siteOf(h, 0).holder_alliance_id, h.A1, 'wave 1 lost'); + assert.deepEqual(garrisonAt(h, 0), { soc_analyst: left }, 'the garrison lost ratio^1.5 of its units'); + const r1 = lastReport(h, b, 'landing').data; + assert.equal(r1.outcome, 'defender_won'); + assert.equal(r1.power.static, S); + assert.equal(r1.power.garrison, G0); + assert.equal(r1.defender.garrison[0].lost.soc_analyst, 400 - left); + assert.equal(T.units(h, b.townId).script_crew, undefined, 'a lost attack loses everything'); + assert.equal(lastReport(h, a, 'landing').role, 'defender', 'the garrison owner gets the report'); + assert.equal(h.db.get('SELECT defense_points FROM operator_stats WHERE operator_id = ?', a.opId).defense_points > 0, true); + assert.equal(h.db.get('SELECT attack_points FROM operator_stats WHERE operator_id = ?', b.opId).attack_points > 0, true); + assert.equal(draw(h, a), 200 + left, 'the dead no longer draw power'); + + h.advanceTo(w2.arriveAt); + const site = siteOf(h, 0); + assert.equal(site.holder_alliance_id, h.B1, 'wave 2 took it'); + assert.equal(site.holder_operator_id, b2.opId); + assert.deepEqual(garrisonAt(h, 0), {}, 'a won attack wipes the garrison'); + const r2 = lastReport(h, b2, 'landing').data; + assert.equal(r2.outcome, 'attacker_won'); + assert.equal(r2.power.defence, S + left * 25); + assert.equal(T.notes(h, a.userId, 'backbone_lost').length, 1); + assert.equal(draw(h, a), 200, 'and the wiped ones neither'); + // nothing was created: units before = units after + the dead (units of the survivors are in movements) + const after = totals(h); + const dead = { soc_analyst: 400 - 0, script_crew: n1 + n2 }; + assert.equal(unitsBefore.soc_analyst - after.soc_analyst, 400, 'all 400 analysts are gone (lost in the two battles), none duplicated'); + assert.ok(unitsBefore.script_crew - after.script_crew <= dead.script_crew && unitsBefore.script_crew - after.script_crew >= n1, 'wave 1 died, wave 2 lost part of its crews'); + // the new holder can now garrison, the old one cannot + T.giveUnits(h, b.townId, { soc_analyst: 5 }); + assert.equal(err(() => sendTo(h, a, 0, 'reinforce', { soc_analyst: 1 })).details.reason, 'not_holder'); + assert.ok(sendTo(h, b, 0, 'reinforce', { soc_analyst: 5 }).movementId); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE status = 'failed'").n, 0); +}); + +test('an attack that beats the static part but not the garrison loses; without the garrison the same attack wins (withdraw at T-1)', () => { + const h = scene(); + const { a, b } = h; + const mv = sendTo(h, a, 0, 'reinforce', { soc_analyst: 400 }); + h.advanceTo(mv.arriveAt); + const S = staticHeld(h, 0, 0); + const n = Math.ceil(1.3 * S / 40); + assert.ok(n * 40 > S && n * 40 < S + 400 * 25); + T.giveUnits(h, b.townId, { script_crew: 2 * n }); + const atk = sendTo(h, b, 0, 'attack', { script_crew: n }); + const before = totals(h); + // alice calls the garrison home one millisecond before the attack arrives: the attack meets the static part only + h.advanceTo(atk.arriveAt - 1); + const wd = h.run('withdrawGarrison', { userId: a.userId, siteId: siteOf(h, 0).id, fromTownId: a.townId }); + assert.deepEqual(wd.units, { soc_analyst: 400 }); + assert.deepEqual(garrisonAt(h, 0), {}); + assert.equal(draw(h, a), 200, 'they stopped drawing at once'); + assert.deepEqual(totals(h), before, 'in the return movement, counted once'); + h.advanceTo(atk.arriveAt); + assert.equal(siteOf(h, 0).holder_alliance_id, h.B1, 'the same attack that would have lost took the site'); + assert.equal(lastReport(h, b, 'landing').data.defender.garrison.length, 0); + // the return leg survives the change of hands and brings every unit home + assert.equal(h.db.get("SELECT status FROM movements WHERE id = ?", wd.movementId).status, 'out'); + h.advanceTo(wd.arriveAt); + assert.equal(T.units(h, a.townId).soc_analyst, 600, 'nothing lost on the way home'); + assert.equal(draw(h, a), 600); + assert.equal(T.notes(h, a.userId, 'movement_returned').length, 1); +}); + +test('the other order: the attack arrives first, then a withdraw only gets the survivors, and after a wipe there is nothing to withdraw', () => { + const h = scene(); + const { a, a2, b, b2 } = h; + const mv = sendTo(h, a, 0, 'reinforce', { soc_analyst: 400 }); + h.advanceTo(mv.arriveAt); + const S = staticHeld(h, 0, 0); + const n = Math.ceil((S + 0.5 * 400 * 25) / 40); + T.giveUnits(h, b.townId, { script_crew: n }); + const atk = sendTo(h, b, 0, 'attack', { script_crew: n }); + h.advanceTo(atk.arriveAt); + const left = garrisonAt(h, 0).soc_analyst; + assert.ok(left > 0 && left < 400); + const siteId = siteOf(h, 0).id; + assert.equal(err(() => h.run('withdrawGarrison', { userId: a.userId, siteId, fromTownId: a.townId, units: { soc_analyst: 400 } })).code, 'not_enough_units', 'cannot call home more than there is'); + assert.equal(err(() => h.run('withdrawGarrison', { userId: a2.userId, siteId, fromTownId: a.townId })).code, 'not_found', 'only the owner can'); + assert.equal(err(() => h.run('withdrawGarrison', { userId: b.userId, siteId, fromTownId: b.townId })).code, 'not_enough_units', 'a POP with nothing there'); + const part = h.run('withdrawGarrison', { userId: a.userId, siteId, fromTownId: a.townId, units: { soc_analyst: 5 } }); + assert.deepEqual(part.units, { soc_analyst: 5 }); + assert.equal(garrisonAt(h, 0).soc_analyst, left - 5); + // the site is wiped by the next wave: a late withdraw finds nothing + const S1 = staticHeld(h, 0, 0); + const n2 = Math.ceil((S1 + (left - 5) * 25) * 1.05 / 40); + T.giveUnits(h, b2.townId, { script_crew: n2 }); + const atk2 = sendTo(h, b2, 0, 'attack', { script_crew: n2 }); + h.advanceTo(atk2.arriveAt); + assert.equal(siteOf(h, 0).holder_alliance_id, h.B1); + assert.equal(err(() => h.run('withdrawGarrison', { userId: a.userId, siteId, fromTownId: a.townId })).details.reason, 'nothing stationed'); + h.advance(DAY); + assert.equal(T.units(h, a.townId).soc_analyst, 200 + 5, 'only the withdrawn 5 came back; the rest died in the two battles'); +}); + +test('recall of a reinforcement within the window: nothing ever arrives in the garrison; a reinforcement that arrives after the site changed hands is turned back', () => { + const h = scene(); + const { a, a2, b } = h; + const before = totals(h); + const mv = sendTo(h, a, 0, 'reinforce', { soc_analyst: 100 }); + const rc = h.run('recallMovement', { userId: a.userId, movementId: mv.movementId }); + h.advanceTo(rc.arriveAt + 1); + assert.deepEqual(garrisonAt(h, 0), {}); + assert.deepEqual(totals(h), before); + assert.equal(T.units(h, a.townId).soc_analyst, 600); + + // alice2 lives further away: bob takes the site while her units are on the road + h.db.run("UPDATE operators SET alliance_id = alliance_id WHERE id = ?", a2.opId); + const late = sendTo(h, a2, 0, 'reinforce', { blue_team: 50 }); + T.giveUnits(h, b.townId, { script_crew: Math.ceil(staticHeld(h, 0, 0) * 1.2 / 40) }); + const atk = sendTo(h, b, 0, 'attack', { script_crew: Math.ceil(staticHeld(h, 0, 0) * 1.2 / 40) }); + assert.ok(atk.arriveAt < late.arriveAt, 'the attack gets there first'); + h.advanceTo(late.arriveAt); + assert.equal(siteOf(h, 0).holder_alliance_id, h.B1); + assert.deepEqual(garrisonAt(h, 0), {}, 'an ex-holder\'s units do not join the new holder\'s garrison'); + assert.equal(lastReport(h, a2, 'movement_failed').data.reason, 'not_holder'); + h.advance(DAY); + assert.equal(T.units(h, a2.townId).blue_team, 100, 'they came home'); +}); + +// ---------------------------------------------------------------- membership edges + +test('leaving or being kicked from the alliance, or the alliance disbanding, sends the garrison home; so does losing the POP it belongs to', () => { + const h = scene(); + const { a, a2, b } = h; + const m1 = sendTo(h, a, 0, 'reinforce', { soc_analyst: 300 }); + const m2 = sendTo(h, a2, 0, 'reinforce', { blue_team: 60 }); + h.advanceTo(Math.max(m1.arriveAt, m2.arriveAt)); + const before = totals(h); + assert.deepEqual(garrisonAt(h, 0), { soc_analyst: 300, blue_team: 60 }); + + // a2 leaves: only her units go home + h.run('allianceLeave', { userId: a2.userId, allianceId: h.A1 }); + assert.deepEqual(garrisonAt(h, 0), { soc_analyst: 300 }); + assert.deepEqual(totals(h), before, 'in a return movement'); + const rel = T.notes(h, a2.userId, 'garrison_released'); + assert.equal(rel.length, 1); + assert.equal(rel[0].reason, 'left_alliance'); + assert.deepEqual(rel[0].units, { blue_team: 60 }); + h.advance(DAY); + assert.equal(T.units(h, a2.townId).blue_team, 100); + + // a POP that changes hands: what it had in a site goes home to its OLD owner's other POP + const a3 = T.addTown(h, a, { n: 2 }); + const ctx = h.ctx(); + const m3 = h.run('sendMovement', { userId: a.userId, fromTownId: a.townId, type: 'reinforce', x: h.sites[0].x, y: h.sites[0].y, units: { soc_analyst: 50 } }); + h.advanceTo(m3.arriveAt); + assert.equal(G.ownedAt(h.db, siteOf(h, 0).id, a.townId).soc_analyst, 350); + const combat = require('../server/military/combat'); + const tb = loadTown(h.db, a.townId); + assert.ok(a3.townId); + combat.transferTown(h.ctx(), tb, { id: b.opId }, { id: a.opId }, h.clock.now()); + assert.deepEqual(garrisonAt(h, 0), {}, 'nothing is left standing for a POP that no longer belongs to its owner'); + const rel2 = T.notes(h, a.userId, 'garrison_released').pop(); + assert.equal(rel2.reason, 'town_lost'); + h.advance(DAY); + assert.equal(T.units(h, a3.townId).soc_analyst, 350, 'home to the old owner\'s remaining POP'); +}); + +test('disbanding the holding alliance sends every garrison home and leaves the level with the site', () => { + const h = scene(); + const { a, a2 } = h; + const m1 = sendTo(h, a, 0, 'reinforce', { soc_analyst: 300 }); + const m2 = sendTo(h, a2, 0, 'reinforce', { blue_team: 60 }); + h.advanceTo(Math.max(m1.arriveAt, m2.arriveAt)); + h.db.run('UPDATE landing_sites SET level = 7 WHERE idx = 0'); + const before = totals(h); + h.run('allianceDisband', { userId: a.userId, allianceId: h.A1 }); + assert.deepEqual(garrisonAt(h, 0), {}); + assert.equal(siteOf(h, 0).holder_alliance_id, null); + assert.equal(siteOf(h, 0).level, 7); + assert.deepEqual(totals(h), before); + assert.equal(T.notes(h, a.userId, 'garrison_released')[0].reason, 'alliance_dissolved'); + h.advance(DAY); + assert.equal(T.units(h, a.townId).soc_analyst, 600); + assert.equal(T.units(h, a2.townId).blue_team, 100); + assert.equal(h.db.get('SELECT COUNT(*) AS n FROM site_stationed').n, 0); +}); + +// ---------------------------------------------------------------- power + +test('power: garrison units draw their owner\'s power; with the owner POP out of power the group stops defending, and a won attack still wipes it', () => { + const h = scene(); + const { b } = h; + const s0 = h.sites[0]; + const weak = near(h, 'weak', 0, { x: s0.x - 6, y: s0.y - 3, power: 5, battery: 40, infra: { battery_bank: 1 }, units: { soc_analyst: 60 } }); + A.addMember(h.db, h.A1, weak.opId, 'member', h.clock.now()); + const mv = sendTo(h, weak, 0, 'reinforce', { soc_analyst: 60 }); + h.advanceTo(mv.arriveAt); + const town = loadTown(h.db, weak.townId); + assert.equal(town.unitDraw, 60, 'the garrison is the owner\'s draw'); + assert.ok(R.ratesPerHour(town).powerNet < 0, 'net power is negative: ' + JSON.stringify(R.ratesPerHour(town))); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM events WHERE type = 'powerCheck' AND status = 'pending' AND town_id = ?", weak.townId).n, 1, 'a power check is scheduled for the owner'); + const emptyAt = R.batteryEmptyAt(town, h.clock.now()); + assert.ok(emptyAt > h.clock.now()); + const S = staticHeld(h, 0, 0); + // online: the group defends + assert.equal(G.defenders(h.db, siteOf(h, 0).id, emptyAt - 1000).groups[0].online, true); + assert.equal(G.defenders(h.db, siteOf(h, 0).id, emptyAt - 1000).power, 60 * 25); + // dry: offline, no defence value, and an attack that beats the static part takes the site although the group is there + h.advanceTo(emptyAt + 5000); + assert.equal(T.notes(h, weak.userId, 'units_offline').length, 1); + const d = G.defenders(h.db, siteOf(h, 0).id, h.clock.now()); + assert.equal(d.groups[0].online, false); + assert.equal(d.power, 0); + const n = Math.ceil(1.1 * S / 40); + T.giveUnits(h, b.townId, { script_crew: n }); + const atk = sendTo(h, b, 0, 'attack', { script_crew: n }); + h.advanceTo(atk.arriveAt); + assert.equal(siteOf(h, 0).holder_alliance_id, h.B1, 'an attack that beats the static part only takes a site whose garrison is offline'); + const rep = lastReport(h, b, 'landing').data; + assert.equal(rep.power.garrison, 0); + assert.equal(rep.defender.garrison[0].offline, true); + assert.equal(G.ownedAt(h.db, siteOf(h, 0).id, weak.townId).soc_analyst || 0, 0, 'a won attack wipes offline units too'); +}); + +// ---------------------------------------------------------------- the opening scramble is unchanged + +test('an unheld site keeps its heavy static defence (the opening scramble), a held one drops to heldDefenceMult', () => { + const h = scene(); + const open = staticHeld(h, 1, 0, false), held = staticHeld(h, 1, 0, true); + assert.equal(open, R.backboneDefence(h.world.seed, h.sites[1].x, h.sites[1].y, 100, 0)); + assert.ok(open / held >= D.ENDGAME.defenceMult / D.ENDGAME.heldDefenceMult - 0.01); + // a scan of the unheld site 1 shows the heavy number, a scan of the held site 0 the light one + const c = near(h, 'scout', 1, { units: { port_scanner: 300 } }); + const mv = sendTo(h, c, 1, 'scan', { port_scanner: 300 }); + h.advanceTo(mv.arriveAt); + assert.equal(lastReport(h, c, 'scan').data.intel.defence, open); +}); + +test('power: decommission takes units out of the garrison, partly, until the draw fits the output', () => { + const h = scene(); + const s0 = h.sites[0]; + const weak = near(h, 'weak', 0, { x: s0.x - 6, y: s0.y - 3, power: 5, battery: 40, infra: { battery_bank: 1 }, units: { soc_analyst: 60 } }); + A.addMember(h.db, h.A1, weak.opId, 'member', h.clock.now()); + const mv = sendTo(h, weak, 0, 'reinforce', { soc_analyst: 60 }); + h.advanceTo(mv.arriveAt); + const emptyAt = R.batteryEmptyAt(loadTown(h.db, weak.townId), h.clock.now()); + h.advanceTo(emptyAt + 5000); + const since = h.db.get('SELECT offline_since FROM town_power WHERE town_id = ?', weak.townId).offline_since; + h.advanceTo(since + R.decommissionMs(1) + 1000); + const left = G.ownedAt(h.db, siteOf(h, 0).id, weak.townId).soc_analyst || 0; + assert.ok(left > 0 && left < 60, 'partly decommissioned: ' + left); + const t1 = loadTown(h.db, weak.townId); + const base = R.ratesPerHour(Object.assign({}, t1, { unitDraw: 0 })); + assert.ok(t1.unitDraw <= base.powerOut - base.powerDraw + 1e-9, 'the draw fits the output again'); + assert.equal(T.units(h, weak.townId).soc_analyst, undefined, 'it was the garrison that was decommissioned, nothing at home to take'); + assert.equal(T.notes(h, weak.userId, 'units_decommissioned').length, 1); +}); + +test('kicking a member sends her units home from the site', () => { + const h = scene(); + const { a, a2 } = h; + const m = sendTo(h, a2, 0, 'reinforce', { blue_team: 40 }); + h.advanceTo(m.arriveAt); + assert.deepEqual(garrisonAt(h, 0), { blue_team: 40 }); + h.run('allianceKick', { userId: a.userId, allianceId: h.A1, operatorId: a2.opId }); + assert.deepEqual(garrisonAt(h, 0), {}); + assert.equal(T.notes(h, a2.userId, 'garrison_released')[0].reason, 'left_alliance'); + h.advance(DAY); + assert.equal(T.units(h, a2.townId).blue_team, 100); +}); + +// ---------------------------------------------------------------- the capture shield + +test('a site that changed hands is shielded for captureShieldHours (world hours / speed): attacks are refused or turned back, scans and garrisons are not', () => { + const h = scene(); + const { a, b } = h; + const s0 = h.sites[0]; + const S = staticHeld(h, 0, 0); + const n = Math.ceil(1.3 * S / 40); + const c = near(h, 'charlie', 0, { x: s0.x, y: s0.y + 6, units: { script_crew: 4 * n, port_scanner: 5 } }); + alliance(h, 'Charlie', c); + T.giveUnits(h, b.townId, { script_crew: n }); + // charlie's strike is on the road when bob takes the site (she lives further away) + const early = sendTo(h, c, 0, 'attack', { script_crew: 2 * n }); + const atk = sendTo(h, b, 0, 'attack', { script_crew: n }); + assert.ok(atk.arriveAt < early.arriveAt); + h.advanceTo(atk.arriveAt); + const site = siteOf(h, 0); + assert.equal(site.holder_alliance_id, h.B1); + const until = R.siteShieldUntil(site.taken_at, 1); + assert.equal(until, site.taken_at + D.ENDGAME.captureShieldHours * H); + assert.equal(h.eg.status(a.userId, h.worldId).sites[0].shieldUntil, until); + // refused at the door ... + const e = err(() => sendTo(h, c, 0, 'attack', { script_crew: n })); + assert.equal(e.code, 'invalid_target'); + assert.equal(e.details.reason, 'site_shielded'); + assert.equal(e.details.until, until); + // ... and one already on the road is turned back (its units come home) + h.advanceTo(early.arriveAt); + assert.equal(siteOf(h, 0).holder_alliance_id, h.B1, 'the strike bounced'); + assert.equal(lastReport(h, c, 'movement_failed').data.reason, 'site_shielded'); + // scanning and garrisoning are fine during the shield + assert.ok(sendTo(h, c, 0, 'scan', { port_scanner: 5 }).movementId); + T.giveUnits(h, b.townId, { soc_analyst: 5 }); + assert.ok(sendTo(h, b, 0, 'reinforce', { soc_analyst: 5 }).movementId); + // the shield ends on time, to the millisecond + h.advanceTo(until - 1); + assert.equal(err(() => sendTo(h, c, 0, 'attack', { script_crew: n })).details.reason, 'site_shielded'); + h.advanceTo(until); + assert.ok(sendTo(h, c, 0, 'attack', { script_crew: n }).movementId); + // unheld sites never have one: the opening scramble is first come, first served + assert.ok(sendTo(h, c, 1, 'attack', { script_crew: n }).movementId); +}); + +test('the shield is world time: at speed 2 it lasts half as long', () => { + assert.equal(R.siteShieldUntil(1000, 1) - 1000, D.ENDGAME.captureShieldHours * H); + assert.equal(R.siteShieldUntil(1000, 2) - 1000, D.ENDGAME.captureShieldHours * H / 2); + assert.equal(R.siteShieldUntil(null, 1), 0); +}); diff --git a/test/review-fixes.test.js b/test/review-fixes.test.js index 033fa0a..c2fd322 100644 --- a/test/review-fixes.test.js +++ b/test/review-fixes.test.js @@ -31,6 +31,7 @@ test('trade legs cannot be recalled (either side could otherwise keep both halve for (const u of [a, b]) t.setBuilding(u.townId, 'internet_exchange', 3); const made = await t.api('/trade/offers', { method: 'POST', body: { townId: a.townId, giveRes: 'fiber', giveAmount: 400, wantRes: 'hardware', wantAmount: 300, maxDistance: 60 } }, a.token); assert.equal(made.status, 201, JSON.stringify(made.body)); + t.srv.db.run('UPDATE towns SET fiber = 0 WHERE id = ?', b.townId); // room for the goods (accept refuses a full hall) const acc = await t.api('/trade/offers/' + made.body.offer.id + '/accept', { method: 'POST', body: { townId: b.townId } }, b.token); assert.equal(acc.status, 201, JSON.stringify(acc.body)); const legs = t.srv.db.all("SELECT id, owner_id FROM movements WHERE type = 'transport' AND status = 'out'"); diff --git a/test/trade-api.test.js b/test/trade-api.test.js index 0faefda..4a6c9d6 100644 --- a/test/trade-api.test.js +++ b/test/trade-api.test.js @@ -43,6 +43,12 @@ test('trade API: post, list, take, mine, detail, cancel, errors', async () => { const one = await t.api('/trade/offers/' + id, {}, c.token); assert.equal(one.body.offer.status, 'open', 'open offers are public inside the world'); + // a full Rack hall cannot take the goods: refused up front instead of destroying them on arrival + t.srv.db.run('UPDATE towns SET fiber = 1000000 WHERE id = ?', b.townId); + const full = await t.api('/trade/offers/' + id + '/accept', { method: 'POST', body: { townId: b.townId } }, b.token); + assert.equal(full.status, 409); assert.equal(full.body.error.code, 'no_room_for_goods'); + assert.equal(t.srv.db.get('SELECT status FROM trade_offers WHERE id = ?', id).status, 'open', 'nothing happened'); + t.srv.db.run('UPDATE towns SET fiber = 0 WHERE id = ?', b.townId); const acc = await t.api('/trade/offers/' + id + '/accept', { method: 'POST', body: { townId: b.townId } }, b.token); assert.equal(acc.status, 201); assert.equal(acc.body.status, 'accepted'); diff --git a/test/trade-flow.test.js b/test/trade-flow.test.js index 584be79..2d2833f 100644 --- a/test/trade-flow.test.js +++ b/test/trade-flow.test.js @@ -174,10 +174,11 @@ test('trade: an offer expires after its ttl (divided by world speed) and returns test('trade: a delivery above the receiver\'s storage cap loses exactly the overflow (and says so); the rest is conserved', () => { const { h, a, b } = traders({ bInfra: { rack_hall: 1 } }); // cap 1000 - h.db.run('UPDATE towns SET fiber = 900 WHERE id = ?', b.townId); - const before = total(h); + h.db.run('UPDATE towns SET fiber = 500 WHERE id = ?', b.townId); const offer = post(h, a, a.townId); - const acc = h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId }); + const acc = h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId }); // room for the 400 at accept time ... + h.db.run('UPDATE towns SET fiber = 900 WHERE id = ?', b.townId); // ... but the hall fills up on the road + const before = total(h); h.advanceTo(acc.arriveAt); assert.equal(stock(h, b.townId).fiber, 1000); const arrived = T.notes(h, b.userId, 'transport_arrived')[0]; @@ -186,6 +187,22 @@ test('trade: a delivery above the receiver\'s storage cap loses exactly the over assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'completed'); }); +test('trade: accepting into a hall with no room for the goods is refused up front (no_room_for_goods); cargo already on its way counts', () => { + const { h, a, b } = traders({ bInfra: { rack_hall: 1 } }); // cap 1000 + h.db.run('UPDATE towns SET fiber = 900 WHERE id = ?', b.townId); + const offer = post(h, a, a.townId); // gives 400 fiber + const before = total(h); + const e = err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })); + assert.equal(e.code, 'no_room_for_goods'); + assert.equal(e.details.room, 100); + assert.equal(h.db.get('SELECT status FROM trade_offers WHERE id = ?', offer.id).status, 'open'); + assert.equal(h.db.get("SELECT COUNT(*) AS n FROM movements WHERE status = 'out'").n, 0, 'rolled back: no payment left either'); + assert.equal(total(h), before); + h.db.run('UPDATE towns SET fiber = 500 WHERE id = ?', b.townId); + h.db.run("INSERT INTO movements (world_id, owner_id, type, from_town_id, to_town_id, from_x, from_y, to_x, to_y, units, cargo, depart_at, arrive_at, status, extra, created_at) SELECT world_id, owner_id, 'transport', id, id, x, y, x, y, '{}', '{\"fiber\":200}', 0, 9e15, 'out', '{}', 0 FROM towns WHERE id = ?", b.townId); + assert.equal(err(() => h.run('tradeAccept', { userId: b.userId, offerId: offer.id, townId: b.townId })).code, 'no_room_for_goods', '500 + 200 on its way + 400 > 1000'); +}); + test('trade: a POP that changes hands voids its open offers; the escrow stays in the POP', () => { const { h, a, b } = traders(); const offer = post(h, a, a.townId); diff --git a/test/transport-speed.test.js b/test/transport-speed.test.js new file mode 100644 index 0000000..a1ee0d7 --- /dev/null +++ b/test/transport-speed.test.js @@ -0,0 +1,72 @@ +'use strict'; +/* Transport capacity scales with world speed (docs/BALANCE.md B7): trips are per sitting, not per hour, so a link carries + * capacityPerLink x speed. One function (rules.transportCapacity) is the only reader of the constant; commands, trade terms and the + * client's numbers (the `transport` block of a POP view) all go through it. Fake clock, in-memory db. */ +const test = require('node:test'); +const assert = require('node:assert'); +const T = require('./military-helpers'); +const { R, D } = T; +const err = (fn) => { try { fn(); } catch (e) { return e; } assert.fail('expected an error'); }; + +const CAP = D.TRANSPORT.capacityPerLink; + +test('transportCapacity: capacityPerLink x speed, read at call time', () => { + assert.equal(R.transportCapacity(1), CAP); + assert.equal(R.transportCapacity(3), 3 * CAP); + assert.equal(R.transportCapacity(0.5), Math.round(CAP / 2)); + assert.equal(R.transportCapacity(10), 10 * CAP); + assert.equal(R.transportCapacity(), CAP, 'no speed = 1x'); + const keep = D.TRANSPORT.capacityPerLink; + D.TRANSPORT.capacityPerLink = 250; + try { assert.equal(R.transportCapacity(4), 1000); } finally { D.TRANSPORT.capacityPerLink = keep; } +}); + +test('transportPlan and tradeTermsCheck use the world speed', () => { + const town = { speed: 3, buildings: { internet_exchange: { type: 'internet_exchange', level: 2 } }, res: { fiber: 9000, hardware: 9000, capital: 9000, battery: 0 }, updatedAt: 0, unitDraw: 0, footprint: 0 }; + town.buildings.rack_hall = { type: 'rack_hall', level: 20 }; + const plan = (n, speed) => R.transportPlan(Object.assign({}, town, { speed }), { fiber: n }, 0, 0); + assert.notEqual(plan(3 * CAP, 3).code, 'capacity_exceeded'); + assert.equal(plan(3 * CAP + 1, 3).code, 'capacity_exceeded'); + assert.equal(plan(3 * CAP + 1, 3).capacity, 3 * CAP); + assert.equal(plan(CAP + 1, 1).code, 'capacity_exceeded', 'a 1x world is as before'); + const terms = (n, speed) => R.tradeTermsCheck({ giveRes: 'fiber', giveAmount: n, wantRes: 'hardware', wantAmount: n, maxDistance: 10 }, speed); + assert.equal(terms(3 * CAP, 3).ok, true); + assert.equal(terms(3 * CAP + 1, 3).code, 'capacity_exceeded'); + assert.equal(terms(3 * CAP, 1).code, 'capacity_exceeded'); + assert.equal(terms(CAP).ok, true, 'speed defaults to 1'); +}); + +test('server: a 3x world sends, ships and trades up to three times the 1x capacity; the POP view reports the real number', () => { + const h = T.setup({ speed: 3 }); + const a = T.addOperator(h, 'sender', { x: 5, y: 0, infra: { internet_exchange: 2, rack_hall: 20 }, res: 20000 }); + const b = T.addOperator(h, 'receiver', { x: 9, y: 0, infra: { rack_hall: 20 } }); + const send = (n) => h.run('sendTransport', { userId: a.userId, fromTownId: a.townId, toTownId: b.townId, cargo: { fiber: n } }); + assert.equal(err(() => send(3 * CAP + 1)).code, 'capacity_exceeded'); + assert.equal(h.queries.town(a.userId, a.townId).town.military.transport.capacityPerLink, 3 * CAP); + const mv = send(3 * CAP); + assert.equal(mv.cargo.fiber, 3 * CAP); + const offer = h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'hardware', giveAmount: 2 * CAP, wantRes: 'capital', wantAmount: 2 * CAP, maxDistance: 30 }).offer; + assert.equal(offer.give.amount, 2 * CAP, 'an offer may fill a whole 3x transport'); + assert.equal(err(() => h.run('tradeOffer', { userId: a.userId, townId: a.townId, giveRes: 'hardware', giveAmount: 3 * CAP + 1, wantRes: 'capital', wantAmount: 3 * CAP + 1, maxDistance: 30 })).code, 'capacity_exceeded'); + // the same send in a 1x world is refused + const h1 = T.setup({ speed: 1 }); + const a1 = T.addOperator(h1, 'sender', { x: 5, y: 0, infra: { internet_exchange: 2, rack_hall: 20 }, res: 20000 }); + const b1 = T.addOperator(h1, 'receiver', { x: 9, y: 0 }); + assert.equal(err(() => h1.run('sendTransport', { userId: a1.userId, fromTownId: a1.townId, toTownId: b1.townId, cargo: { fiber: 3 * CAP } })).code, 'capacity_exceeded'); +}); + +test('no file outside rules.js and data.js reads TRANSPORT.capacityPerLink directly (a constant read bypasses the world speed)', () => { + const fs = require('fs'), path = require('path'); + const root = path.join(__dirname, '..'); + const hits = []; + const walk = (dir) => { + for (const f of fs.readdirSync(dir, { withFileTypes: true })) { + if (f.name === 'node_modules' || f.name === '.git' || f.name === 'test' || f.name === 'e2e' || f.name === 'docs') continue; + const p = path.join(dir, f.name); + if (f.isDirectory()) walk(p); + else if (/\.js$/.test(f.name) && /TRANSPORT\.capacityPerLink/.test(fs.readFileSync(p, 'utf8'))) hits.push(path.relative(root, p)); + } + }; + walk(root); + assert.deepEqual(hits.filter((p) => !/^public\/js\/(rules|data)\.js$/.test(p)), []); +}); diff --git a/tools/admin.js b/tools/admin.js index c2e1f56..9474c34 100644 --- a/tools/admin.js +++ b/tools/admin.js @@ -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': ' --yes mark a world ended (no new signups/joins)', + 'end-world': ' --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: ' 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)); +} diff --git a/tools/bot.js b/tools/bot.js index 27828dc..13a527e 100644 --- a/tools/bot.js +++ b/tools/bot.js @@ -19,6 +19,8 @@ * (a final push with high attention; default 0 = off, normal sessions only) --endgame-min-members N (default 3) * --field-policy P marginal (default: keep the production mix at the ratio the player spends, upgrade whatever lags) or balanced * (all fields level up together; a lower bound of player skill) + * --no-contest end game: no garrisons (holders do not station defenders at their site) and no coordinated waves (one striker + * per site, as before E6); pair with --set ENDGAME.heldDefenceMult=12 to get the pre-E6 world back * --no-adapt bots do not answer raids with more defence (default: after being hit a bot trains defence up to 1.25 x the * strongest attack it saw, for 5 days; an upper bound of how defenders react) * --sample-min N economy sampling interval (default 120) @@ -60,6 +62,7 @@ function parseArgs(argv) { case '--endgame-min-members': o.endgameMinMembers = num(a); break; case '--endgame-step-min': o.endgameStepMin = num(a); break; case '--no-adapt': o.adapt = false; break; + case '--no-contest': o.contest = false; break; case '--field-policy': o.fieldPolicy = need(i, a); i++; if (['marginal', 'balanced'].indexOf(o.fieldPolicy) < 0) throw new Error('--field-policy is marginal or balanced'); break; case '--set': o.set.push(need(i, a)); i++; break; case '--json': o.json = need(i, a); i++; break; diff --git a/tools/bot/bots.js b/tools/bot/bots.js index 2bedde6..1af22e7 100644 --- a/tools/bot/bots.js +++ b/tools/bot/bots.js @@ -93,7 +93,7 @@ class Bot { this.firstAllianceTry = 0; this.incCache = null; this.takeoverTargets = new Map(); - this.armyOverride = 0; this.egForce = null; + this.armyOverride = 0; this.egForce = null; this.egDefTarget = 0; } // ------------------------------------------------------------------ session schedule (human cadence) @@ -164,7 +164,7 @@ class Bot { if (!sec && this.egForce) for (const type of Object.keys(this.egForce)) if (view.level(t, type) < this.egForce[type]) out.push({ key: type, type }); // a store that keeps hitting its cap is the first thing a player fixes const cur = R.resourcesAt(t, now); - if (RES.every((r) => cur.amounts[r] >= 0.8 * cur.caps.fiber) && !busy.has('rack_hall') && view.level(t, 'rack_hall') < Math.min(20, Math.max(2, F + 1))) out.push({ key: 'rack_hall', type: 'rack_hall' }); + if (RES.every((r) => cur.amounts[r] >= 0.8 * R.storageCap(t)) && !busy.has('rack_hall') && view.level(t, 'rack_hall') < Math.min(20, Math.max(2, F + 1))) out.push({ key: 'rack_hall', type: 'rack_hall' }); const order = sec ? ['core_router', 'rack_hall', 'battery_bank'] : this.arch.order; for (const type of order) { const tgt = sec ? Math.min(this.target(type, F), 6) : this.target(type, F); @@ -186,7 +186,7 @@ class Bot { // level the other fields are at; substations only when power is short (or units are wanted). pickFieldMarginal(t, fields, now) { const rates = R.ratesPerHour(t); - const unitsWanted = this.arch.armyDays > 0 || this.arch.defDays > 0.5 || !!this.armyOverride; + const unitsWanted = this.arch.armyDays > 0 || this.arch.defDays > 0.5 || !!this.armyOverride || !!this.egDefTarget; const lowest = (type) => fields.filter((f) => f.type === type && f.level < 20).sort((a, b) => a.level - b.level || (a.key < b.key ? -1 : 1))[0]; if (rates.powerNet < 4 + 0.04 * rates.powerOut && (unitsWanted || rates.powerNet < 2)) { const s = lowest('substation'); @@ -209,7 +209,7 @@ class Bot { const w = this.arch.weights; const rates = R.ratesPerHour(t); const power = rates.powerNet; - const unitsWanted = this.arch.armyDays > 0 || this.arch.defDays > 0.5 || !!this.armyOverride; + const unitsWanted = this.arch.armyDays > 0 || this.arch.defDays > 0.5 || !!this.armyOverride || !!this.egDefTarget; const lag = fields.filter((f) => f.level === F); if (!lag.length) return null; // power first when it is short and units are on the way @@ -248,7 +248,7 @@ class Bot { const pending = view.pendingBuilds(t.id); if (pending.length >= R.queueSlots(t)) break; const cur = R.resourcesAt(t, now); - const cap = cur.caps.fiber; + const cap = R.storageCap(t); const overflow = RES.some((r) => cur.amounts[r] >= 0.9 * cap); let acted = false; const list = this.wishes(t, now, new Set(pending.map((p) => p.key))); @@ -615,7 +615,7 @@ class Bot { if (lvl < 1) continue; let t = t0; const cur = R.resourcesAt(t, now); - const cap = cur.caps.fiber; + const cap = R.storageCap(t); const fill = {}; for (const r of RES) fill[r] = cur.amounts[r] / cap; const sorted = RES.slice().sort((a, b) => fill[b] - fill[a]); const surplus = sorted[0], deficit = sorted[2]; @@ -638,9 +638,9 @@ class Bot { // post one of our own (one open offer per POP at a time) const open = db.get("SELECT COUNT(*) AS n FROM trade_offers WHERE town_id = ? AND status = 'open'", t.id).n; if (open >= 1) continue; - const give = Math.min(D.TRANSPORT.capacityPerLink, Math.floor((cur.amounts[surplus] - 0.4 * cap) * 0.6)); + const give = Math.min(R.transportCapacity(this.sim.world.speed), Math.floor((cur.amounts[surplus] - 0.4 * cap) * 0.6)); if (give < 100) continue; - const want = Math.min(D.TRANSPORT.capacityPerLink, Math.max(50, Math.floor(give * (0.9 + this.rng() * 0.2)))); + const want = Math.min(R.transportCapacity(this.sim.world.speed), Math.max(50, Math.floor(give * (0.9 + this.rng() * 0.2)))); const r = this.call('tradeOffer', { townId: t.id, giveRes: surplus, giveAmount: give, wantRes: deficit, wantAmount: want, maxDistance: Math.max(10, Math.min(reach, 40)) }); if (r.ok) this.log.offers += 1; } diff --git a/tools/bot/collector.js b/tools/bot/collector.js index e0a5317..18be4fc 100644 --- a/tools/bot/collector.js +++ b/tools/bot/collector.js @@ -24,12 +24,12 @@ class Collector { this.unitsLost = {}; // unit -> count, every way of losing units that the ledger knows about this.unitsConsumed = {}; // crews/teams used up (not battle losses) this.byType = {}; // report type -> count - this.battles = { raid: { n: 0, att: 0, loot: 0, lootRes: { fiber: 0, hardware: 0, capital: 0 }, attLost: 0, defLost: 0 }, attack: { n: 0, att: 0, loot: 0, attLost: 0, defLost: 0 }, takeover: { n: 0, att: 0, loot: 0, attLost: 0, defLost: 0 } }; + this.battles = { raid: { n: 0, att: 0, loot: 0, lootRes: { fiber: 0, hardware: 0, capital: 0 }, lootLeft: { fiber: 0, hardware: 0, capital: 0 }, emptyWins: 0, attLost: 0, defLost: 0 }, attack: { n: 0, att: 0, loot: 0, attLost: 0, defLost: 0 }, takeover: { n: 0, att: 0, loot: 0, attLost: 0, defLost: 0 } }; this.raidSamples = []; // { loot, attLostValue, defLostValue, A, D, win, targetAgeDays, undefended } this.takeovers = { attempted: 0, dropped: 0, blocked: {}, captured: 0, loyaltyDropped: 0 }; this.scans = { n: 0, ok: 0, failed: 0, detected: 0, revealed: 0 }; this.incumbent = { n: 0, wins: 0, hardware: 0, attLostValue: 0 }; - this.landing = { n: 0, taken: 0, attLostValue: 0 }; + this.landing = { n: 0, taken: 0, attLostValue: 0, vsHeld: 0, vsHeldTaken: 0, vsGarrison: 0, garrisonLostValue: 0, garrisonLost: {}, attackPower: 0, defencePower: 0 }; this.movementFailed = {}; this.settles = { ok: 0 }; this.siege = { n: 0, levels: 0 }; @@ -37,6 +37,7 @@ class Collector { this.notes = {}; // notification type -> count this.cargoLostTotal = { fiber: 0, hardware: 0, capital: 0 }; this.cargoLostEvents = 0; + this.cargoLostBy = {}; // where the overflow happened: transport_arrived | raid_return | link_return -> { fiber, hardware, capital, n } this.decommissioned = {}; this.unitsOfflineNotes = 0; this.opCreated = new Map(); @@ -68,17 +69,25 @@ class Collector { default: break; } } - const rows = db.all("SELECT id, type, payload FROM notifications WHERE id > ? AND type IN ('transport_arrived','movement_returned','units_decommissioned','units_offline') ORDER BY id", this.noteCursor); + const rows = db.all("SELECT id, type, payload FROM notifications WHERE id > ? AND type IN ('transport_arrived','movement_returned','units_decommissioned','units_offline','trade_refund_clipped') ORDER BY id", this.noteCursor); for (const n of rows) { this.noteCursor = n.id; const p = JSON.parse(n.payload); bump(this.notes, n.type); if (n.type === 'units_decommissioned') { addInto(this.decommissioned, p.units); addInto(this.unitsLost, p.units); } else if (n.type === 'units_offline') this.unitsOfflineNotes += 1; + else if (n.type === 'trade_refund_clipped') { ledger.sinkClip[p.resource] += p.lost; ledger.clipEvents += 1; } else if (p.cargoLost) { let any = false; for (const r of RES) if (p.cargoLost[r]) { this.cargoLostTotal[r] += p.cargoLost[r]; ledger.sinkLost[r] += p.cargoLost[r]; any = true; } - if (any) { ledger.lostEvents += 1; this.cargoLostEvents += 1; } + if (any) { + ledger.lostEvents += 1; this.cargoLostEvents += 1; + let where = n.type; + if (n.type === 'movement_returned') { const m = db.get('SELECT m.extra, pm.type AS ptype, pm.to_town_id AS ptown FROM movements m LEFT JOIN movements pm ON pm.id = m.parent_id WHERE m.id = ?', p.movementId); where = m && JSON.parse(m.extra || '{}').link ? 'link_return' : (m && m.ptype && !m.ptown ? 'site_return' : 'raid_return'); } + const by = this.cargoLostBy[where] || (this.cargoLostBy[where] = { fiber: 0, hardware: 0, capital: 0, n: 0 }); + for (const r of RES) by[r] += p.cargoLost[r] || 0; + by.n += 1; + } } } // notifications are numbered independently of the filter above: move the cursor past rows we skipped @@ -100,7 +109,7 @@ class Collector { const loot = lootValue(d.loot); if (win) b.att += 1; b.loot += loot; b.attLost += attLostVal; b.defLost += defLostVal; - if (kind === 'raid') addInto(b.lootRes, d.loot); + if (kind === 'raid') { addInto(b.lootRes, d.loot); addInto(b.lootLeft, d.lootLeft || {}); if (win && !loot) b.emptyWins += 1; } const aId = d.attacker.operator.id, dId = d.defender.operator.id; const a = this.op(aId), df = this.op(dId); if (kind === 'raid') { a.raids += 1; if (win) a.raidWins += 1; a.raidLoot += loot; a.raidLostValue += attLostVal; } @@ -144,6 +153,12 @@ class Collector { const lost = (d.attacker.units && d.attacker.units.lost) || {}; this.landing.attLostValue += unitsValue(lost); addInto(this.unitsLost, lost); + // contests (E6): attacks on a HELD site, those that met a garrison, and what the garrison lost (units stationed at a site die in these reports) + if (d.site && d.site.holder) { this.landing.vsHeld += 1; if (d.taken) this.landing.vsHeldTaken += 1; this.landing.firstVsHeldAt = this.landing.firstVsHeldAt || d.arrivedAt; this.landing.lastVsHeldAt = d.arrivedAt; } + const gar = (d.defender && d.defender.garrison) || []; + if (gar.some((g) => Object.keys(g.sent || {}).length)) this.landing.vsGarrison += 1; + for (const g of gar) { addInto(this.unitsLost, g.lost || {}); addInto(this.landing.garrisonLost, g.lost || {}); this.landing.garrisonLostValue += unitsValue(g.lost || {}); } + if (d.power) { this.landing.attackPower += d.power.attack || 0; this.landing.defencePower += d.power.defence || 0; } } } diff --git a/tools/bot/endgame.js b/tools/bot/endgame.js index 6003eb0..da51f2b 100644 --- a/tools/bot/endgame.js +++ b/tools/bot/endgame.js @@ -4,16 +4,24 @@ * backbone, coordinated through a plan kept in memory (what an alliance would agree in its chat): * * 1. site the site that is cheapest to take for the alliance (static defence, a little distance weight) - * 2. striker ONE member with an Ops lab trains an army whose attack beats the site's defence on its own (every attack is - * resolved separately against the full static defence, so attacks cannot be added up) and attacks - * 3. holders once the alliance holds a site every member ships its spare Fiber/Hardware/Capital to it (transport links, 500 - * each), anyone starts the next Backbone node level when the stockpile pays for it + * 2. striker a site with NO garrison has only a static defence that waves cannot wear down (nothing to kill), so ONE member + * with an Ops lab trains an army whose attack beats it on its own and attacks + * assault a site WITH a garrison (E6) is worn down by waves: every member with an Ops lab trains crews towards a share of + * what the alliance needs (about 1.15 x static + 2.2 x garrison), and once a war game over the members' real armies + * (rules.resolveBattle, wave by wave, the garrison shrinking by the real loss law) says the last wave takes the site, + * the plan says GO and every member with an army sends it at its next sitting (arrival order is the real one) + * 3. holders once the alliance holds a site every member ships its spare Fiber/Hardware/Capital to it (transport links, + * rules.transportCapacity each), anyone starts the next Backbone node level when the stockpile pays for it, and + * (contest, unless --no-contest) members station their defenders in the site and train more, towards what the + * strongest rival alliance could throw at it (the holders scout their rivals; bots read it from the db) * * Everything goes through the normal commands; the plan only decides who does what. */ const D = require('../../public/js/data.js'); const R = require('../../public/js/rules.js'); const { DAY, HOUR } = require('./util'); +const ATTACK_UNITS = ['script_crew', 'botnet']; +const DEFENDERS = ['blue_team', 'soc_analyst']; // movable defenders (honeypots are fixed) const RES = D.RESOURCES; const EG = D.ENDGAME; @@ -22,7 +30,9 @@ function createEndgame(sim) { const E = require('../../server/endgame'); const A = require('../../server/alliances'); const M = require('../../server/military/movements'); - const log = { opened: null, plans: 0, strikes: 0, strikeWins: 0, shipments: 0, shipped: { fiber: 0, hardware: 0, capital: 0 }, builds: 0, buildErrors: {}, strikeSkips: {}, firstCapture: null, shipLinks: 0, wins: null }; + const G = require('../../server/military/garrison'); + const contest = sim.opts.contest !== false; + const log = { assaults: 0, assaultGo: 0, assaultSkips: {}, garrisoned: 0, garrisonSends: 0, garrisonPeak: 0, garrisonTrained: 0, opened: null, plans: 0, strikes: 0, strikeWins: 0, shipments: 0, shipped: { fiber: 0, hardware: 0, capital: 0 }, builds: 0, buildErrors: {}, strikeSkips: {}, firstCapture: null, shipLinks: 0, wins: null }; const plans = sim.alliancePlans; const bump = (o, k) => { o[k] = (o[k] || 0) + 1; }; @@ -44,7 +54,14 @@ function createEndgame(sim) { return E.siteStates(sim.db, sim.world, now).map(({ site, row }) => row || { id: null, idx: site.index, x: site.x, y: site.y, holder_alliance_id: null, level: 0, build_to: null, fiber: 0, hardware: 0, capital: 0 }); } - const defenceAt = (s, at) => R.backboneDefence(sim.world.seed, s.x, s.y, E.ageDays(sim.world, at), s.level); + // What a site is worth at `at`: its static defence (heavy while nobody holds it, light once an alliance does) and its garrison. + function siteDefence(s, at) { + const held = !!s.holder_alliance_id; + const staticDef = R.backboneDefence(sim.world.seed, s.x, s.y, E.ageDays(sim.world, at), s.level || 0, held); + const g = s.id ? G.defenders(sim.db, s.id, at) : { groups: [], power: 0 }; + return { staticDef, garrison: g.power, groups: g.groups, total: staticDef + g.power }; + } + const defenceAt = (s, at) => siteDefence(s, at).total; function choose(plan, allianceId, now) { const c = centroid(allianceId); @@ -106,18 +123,106 @@ function createEndgame(sim) { const row = siteRows(now).find((r) => r.idx === plan.site.idx); plan.siteHeld = !!(row && row.holder_alliance_id === allianceId); - if (plan.siteHeld) { hold(bot, towns, row, now); return; } - // not ours yet: the striker prepares and attacks, the others carry on with their economy - bot.egForce = null; - if (plan.striker === bot.idx) strike(bot, main, plan, row, now); + if (plan.siteHeld) { bot.armyOverride = 0; hold(bot, towns, row, now); return; } + // not ours yet. A site with a garrison is worn down by waves (assault), one without has a static defence that only a single + // army can beat (striker); the other members carry on with their economy + bot.egForce = null; bot.egDefTarget = 0; + const site = row || { id: null, idx: plan.site.idx, x: plan.site.x, y: plan.site.y, level: 0, holder_alliance_id: null }; + const flight = R.movementMs(R.distance(main.x, main.y, site.x, site.y), { script_crew: 1 }, sim.world.speed); + const d = siteDefence(site, now + flight); + const shielded = E.shieldUntil(site, sim.world) > now + flight; // just taken: nothing can be attacked until the shield is down + if (contest && d.garrison > 0) { assault(bot, towns, plan, site, d, allianceId, now, shielded); return; } + bot.armyOverride = 0; + if (plan.striker === bot.idx) strike(bot, main, plan, row, now, shielded); + } + + // ---- assault: every member trains towards a share, the plan says GO when the war game over the real armies says the site falls + const sumRes = (u) => ATTACK_UNITS.reduce((a, k) => a + (u[k] || 0), 0); + + // Production share of one member inside its alliance (what it can carry of the army the alliance needs). + function shareOf(bot, allianceId) { + let mine = 0, all = 0; + for (const m of members(allianceId)) { + const t = sim.view.towns(m.operatorId)[0]; + if (!t) continue; + const r = R.ratesPerHour(t); + const v = (m.archetype === 'turtle' ? 0.3 : 1) * (r.fiber + r.hardware + r.capital); + all += v; if (m === bot) mine = v; + } + return all > 0 ? mine / all : 0; + } + + // Every POP of the alliance with attackers at home, as armies { townId, opId, bot, units, research, flightMs, attack }, nearest first. + function armies(allianceId, site, now) { + const out = []; + for (const m of members(allianceId)) { + for (const t of sim.view.towns(m.operatorId)) { + if (!R.unitsOnline(t, now)) continue; + const home = sim.view.home(t.id); + const units = {}; + for (const u of ATTACK_UNITS) if (home[u] > 0) units[u] = home[u]; + if (!sumRes(units)) continue; + const research = sim.view.researchLevels(t.id); + const attack = R.attackPower(units, research); + if (attack < 400) continue; + out.push({ townId: t.id, opId: m.operatorId, units, research, attack, flightMs: R.movementMs(R.distance(t.x, t.y, site.x, site.y), units, sim.world.speed) }); + } + } + return out.sort((a, b) => a.flightMs - b.flightMs || a.townId - b.townId); + } + + // The war game: the armies arrive in this order, one battle each, against the static part (x margin) and the garrison, which shrinks + // by the real loss law. -> number of waves it takes, or 0 when the last wave still loses. + function wargame(list, d, margin) { + let groups = d.groups.filter((g) => g.online).map((g) => ({ id: g.id, units: Object.assign({}, g.units), research: g.research })); + for (let i = 0; i < list.length; i++) { + const b = R.resolveBattle({ kind: 'attack', attackers: { units: list[i].units, research: list[i].research }, defenders: groups, firewall: 0, staticDefence: d.staticDef * margin }); + if (b.attackerWins) return i + 1; + groups = groups.map((g) => { const r = b.defenders.find((x) => x.id === g.id); return { id: g.id, units: r ? r.survivors : g.units, research: g.research }; }); + } + return 0; + } + + function assault(bot, towns, plan, site, d, allianceId, now, shielded) { + const view = sim.view; + const main = towns[0]; + // training: this member's share of ~1.15 x static + 2.2 x garrison (a lost wave only kills ratio^1.5 of the garrison) + const need = 1.15 * d.staticDef + 2.2 * d.garrison; + const research = view.researchLevels(main.id); + const mult = R.researchMult(R.researchLevel(research, 'script_crew', 'attack')); + bot.egForce = { ops_lab: 6, research_lab: 5, noc: 1 }; + bot.armyOverride = Math.ceil(need * shareOf(bot, allianceId) / (R.unitDef('script_crew').attack * mult)); + if (shielded) { bump(log.assaultSkips, 'shielded'); return; } + // GO? evaluated at most every 3 hours per alliance + if (!plan.go || now > plan.go.until) { + plan.go = null; + if (!plan.checkedAt || now - plan.checkedAt >= 3 * HOUR) { + plan.checkedAt = now; + const list = armies(allianceId, site, now); + const waves = list.length ? wargame(list, d, 1.15) : 0; + if (waves) { plan.go = { until: now + 30 * HOUR, towns: new Set(list.map((a) => a.townId)), waves, planned: list.length }; log.assaultGo += 1; } + else bump(log.assaultSkips, list.length ? 'army_short' : 'no_army'); + } + } + if (!plan.go) return; + for (const t of towns) { + if (!plan.go.towns.has(t.id)) continue; + plan.go.towns.delete(t.id); + const home = view.home(t.id); + const units = {}; + for (const u of ATTACK_UNITS) if (home[u] > 0) units[u] = home[u]; + if (!sumRes(units)) continue; + const r = bot.call('sendMovement', { fromTownId: t.id, type: 'attack', x: site.x, y: site.y, units }); + if (r.ok) { log.assaults += 1; log.strikes += 1; } else bump(log.strikeSkips, r.code); + } } // ---- striker - function strike(bot, main, plan, row, now) { + function strike(bot, main, plan, row, now, shielded) { const view = sim.view; const site = row || { x: plan.site.x, y: plan.site.y, level: 0 }; const flight = R.movementMs(R.distance(main.x, main.y, site.x, site.y), { script_crew: 1 }, sim.world.speed); - const dv = defenceAt({ x: site.x, y: site.y, level: site.level || 0 }, now + flight); + const dv = siteDefence({ x: site.x, y: site.y, level: site.level || 0, id: site.id, holder_alliance_id: site.holder_alliance_id }, now + flight).total; const research = view.researchLevels(main.id); const mult = R.researchMult(R.researchLevel(research, 'script_crew', 'attack')); const need = Math.ceil(1.12 * dv / (R.unitDef('script_crew').attack * mult)); @@ -125,7 +230,8 @@ function createEndgame(sim) { bot.armyOverride = need; const home = view.home(main.id); const attack = armyAttack(main, home, research); - if (attack >= 1.08 * dv) { + if (shielded) bump(log.strikeSkips, 'shielded'); + else if (attack >= 1.08 * dv) { const units = {}; for (const u of ['script_crew', 'botnet']) if (home[u]) units[u] = home[u]; const r = bot.call('sendMovement', { fromTownId: main.id, type: 'attack', x: site.x, y: site.y, units }); @@ -133,9 +239,70 @@ function createEndgame(sim) { } else bump(log.strikeSkips, 'army_short'); } + // ---- garrison (holders): what could the strongest rival throw, keep that much defence in the site + function rivalThreat(allianceId, now) { + const plan = plans.get(allianceId); + if (plan.threatAt && now - plan.threatAt < 4 * HOUR) return plan.threat; + let best = 0; + const byAlliance = new Map(); + for (const b of sim.bots) { + const op = sim.view.operator(b.operatorId); + if (!op || !op.alliance_id || op.alliance_id === allianceId) continue; + let v = 0; + for (const t of sim.view.towns(b.operatorId)) { + const home = sim.view.home(t.id); + const units = {}; + for (const u of ATTACK_UNITS) if (home[u] > 0) units[u] = home[u]; + v += R.attackPower(units, sim.view.researchLevels(t.id)); + } + for (const m of sim.view.outgoing(b.operatorId)) { const u = JSON.parse(m.units || '{}'); v += R.attackPower({ script_crew: u.script_crew || 0, botnet: u.botnet || 0 }, {}); } + byAlliance.set(op.alliance_id, (byAlliance.get(op.alliance_id) || 0) + v); + } + for (const [aid, v] of byAlliance) { + if (A.memberCount(sim.db, aid) < sim.opts.endgameMinMembers) continue; + const rel = A.relationBetween(sim.db, allianceId, aid); + if (rel === 'nap' || rel === 'confed') continue; + best = Math.max(best, v); + } + plan.threatAt = now; plan.threat = best; + return best; + } + + function garrison(bot, towns, row, now, allianceId) { + const view = sim.view; + const d = siteDefence(row, now); + const threat = rivalThreat(allianceId, now); + const goal = Math.max(1.1 * threat, 1.5 * d.staticDef); // total defence in the site the alliance wants (static + garrison) + const share = shareOf(bot, allianceId); + const mine = G.ofTown(sim.db, towns[0].id); + const main = towns[0]; + // the garrison this member should keep: its share of (goal - static) + const want = Math.max(0, (goal - d.staticDef) * share); + bot.egDefTarget = want; + bot.egForce = { noc: 5, research_lab: 3 }; // blue teams need them + const have = R.defencePower(mine, {}) + R.defencePower(view.home(main.id), {}) + bot.queuedDefence(main); + if (have < want) { + const unit = R.unitMissing(main, 'blue_team').length === 0 ? 'blue_team' : 'soc_analyst'; + const n = bot.trainSome(main, unit, Math.ceil((want - have) / R.unitDef(unit).defence), now, false); + log.garrisonTrained += n || 0; + } + // send every movable defender at home into the site (the member keeps none at home for the site) + for (const t of towns) { + const home = view.home(t.id); + const units = {}; + for (const u of DEFENDERS) if (home[u] > 0) units[u] = home[u]; + if (!Object.keys(units).length) continue; + if (!R.unitsOnline(t, now)) continue; + const r = bot.call('sendMovement', { fromTownId: t.id, type: 'reinforce', x: row.x, y: row.y, units }); + if (r.ok) { log.garrisonSends += 1; log.garrisoned += Object.keys(units).reduce((a, k) => a + units[k], 0); } else bump(log.assaultSkips, 'garrison_' + r.code); + } + log.garrisonPeak = Math.max(log.garrisonPeak, siteDefence(row, now).garrison); + } + // ---- holders: ship and build function hold(bot, towns, row, now) { const view = sim.view; + if (contest) garrison(bot, towns, row, now, row.holder_alliance_id); // start the next level when the stockpile pays for it if (!row.build_to && row.level < EG.maxLevel) { const cost = R.backboneCost(row.level + 1); @@ -157,9 +324,9 @@ function createEndgame(sim) { for (let i = 0; i < lvl; i++) { if (M.activeLinks(sim.db, t.id) >= lvl) break; const cur = R.resourcesAt(t, now); - const cap = cur.caps.fiber; + const cap = R.storageCap(t); const cargo = {}; - let room = D.TRANSPORT.capacityPerLink; + let room = R.transportCapacity(sim.world.speed); const order = RES.slice().sort((a, b) => want[b] - want[a]); for (const r of order) { const spare = Math.max(0, cur.amounts[r] - 0.12 * cap); @@ -206,7 +373,7 @@ function createEndgame(sim) { for (const r of sim.db.all('SELECT town_id, unit, count FROM town_units')) { (perTown[r.town_id] = perTown[r.town_id] || {})[r.unit] = r.count; } let maxPopAttack = 0; for (const id of Object.keys(perTown)) maxPopAttack = Math.max(maxPopAttack, R.attackPower(perTown[id], {})); - const bestDefence = sites.filter((x) => x.level > 0).reduce((m, x) => Math.max(m, R.backboneDefence(sim.world.seed, x0(x).x, x0(x).y, E.ageDays(world, now), x.level)), 0); + const bestDefence = sim.db.all('SELECT * FROM landing_sites WHERE world_id = ? AND level > 0', sim.world.id).reduce((m, r) => Math.max(m, siteDefence(r, now).total), 0); const daysSinceOpen = Math.max(1e-9, (now - sim.t0) / DAY - (log.opened || 0)); const shippedTotal = RES.reduce((s, r) => s + log.shipped[r], 0); const perDay = shippedTotal / daysSinceOpen; @@ -216,6 +383,12 @@ function createEndgame(sim) { open: true, ageDays: age, openedAtSimDay: log.opened, plans: log.plans, strikes: log.strikes, strikeSkips: log.strikeSkips, landingReports: sim.col.landing, shipments: log.shipments, shippedTotal, shipped: log.shipped, maxPopAttackNoResearch: Math.round(maxPopAttack), bestHeldSiteDefenceNow: bestDefence, shippedPerSimDay: Math.round(perDay), buildsStarted: log.builds, buildErrors: log.buildErrors, sites, bestLevel, remainingToLevel100: remaining, remainingTotal: remainTotal, simDaysToFinishAtThisRate: perDay > 0 ? Math.round(remainTotal / perDay) : null, + contest: { + enabled: contest, assaultGo: log.assaultGo, assaultsSent: log.assaults, assaultSkips: log.assaultSkips, garrisonSends: log.garrisonSends, garrisonedUnits: log.garrisoned, garrisonTrained: log.garrisonTrained, + garrisonPeakPower: Math.round(log.garrisonPeak), garrisonNow: sites.map((x) => { const row = sim.db.get('SELECT id FROM landing_sites WHERE world_id = ? AND idx = ?', sim.world.id, x.idx); return row ? Math.round(G.defenders(sim.db, row.id, now).power) : 0; }), + attacksOnHeld: sim.col.landing.vsHeld, heldTaken: sim.col.landing.vsHeldTaken, metGarrison: sim.col.landing.vsGarrison, garrisonLostValue: Math.round(sim.col.landing.garrisonLostValue), + firstAttackOnHeldDay: sim.col.landing.firstVsHeldAt ? Math.round((sim.col.landing.firstVsHeldAt - sim.t0) / DAY * 10) / 10 : null, lastAttackOnHeldDay: sim.col.landing.lastVsHeldAt ? Math.round((sim.col.landing.lastVsHeldAt - sim.t0) / DAY * 10) / 10 : null, + }, winner: world.winner_alliance_id ? { allianceId: world.winner_alliance_id, tag: world.winner_tag, wonAtSimDay: (world.won_at - sim.t0) / DAY } : null, worldStatus: world.status, towns: links, }; } diff --git a/tools/bot/ledger.js b/tools/bot/ledger.js index e09cf4a..8fb9d92 100644 --- a/tools/bot/ledger.js +++ b/tools/bot/ledger.js @@ -13,7 +13,8 @@ * bookings (db.tx is tapped too), so only committed settles count. Caps are already inside the stored numbers. * sinks build/train/research costs (from the command results), Backbone node levels (from landing_sites), cargo that * did not fit the Rack hall (`cargoLost` in notifications), trade escrow refunds clipped by the Rack hall cap - * (tap on the refund statement) + * (booked from `trade_refund_clipped` notifications: with escrow reserving its room in the Rack hall this is only a hall that was + * shot down below stock + escrow in the meantime, so it is 0 in normal runs) * * Anything else is DRIFT: a leak or a duplication in the server (or a missing sink here). Drift is printed and fails the run. * @@ -28,8 +29,6 @@ const zero = () => ({ fiber: 0, hardware: 0, capital: 0 }); const addRes = (a, b) => { for (const r of RES) a[r] += (b && b[r]) || 0; return a; }; const SETTLE_SQL = 'UPDATE towns SET fiber = ?, hardware = ?, capital = ?, battery = ?, footprint = ?, res_at = ?, loyalty = ?, loyalty_at = ? WHERE id = ?'; -const REFUND_RE = /^UPDATE towns SET (fiber|hardware|capital) = \? WHERE id = \?$/; -const CLOSE_PREFIX = 'UPDATE trade_offers SET status = ?, closed_at = ? WHERE id = ?'; class Ledger { constructor(db) { @@ -38,11 +37,10 @@ class Ledger { this.sinkCosts = zero(); // build / train / research (command results) this.sinkLost = zero(); // cargoLost notifications this.lostEvents = 0; - this.sinkClip = zero(); // trade refund clipped by the Rack hall cap + this.sinkClip = zero(); // trade refund that did not fit (trade_refund_clipped notifications) this.clipEvents = 0; this.sourceStart = zero(); // operators' start stock this.stack = []; - this.closing = null; this.t = { settles: 0 }; this.installed = false; } @@ -63,20 +61,6 @@ class Ledger { if (sql === SETTLE_SQL) { const prev = db.get('SELECT fiber, hardware, capital FROM towns WHERE id = ?', p[8]); if (prev) self.book({ fiber: p[0] - prev.fiber, hardware: p[1] - prev.hardware, capital: p[2] - prev.capital }, zero(), 0); - } else if (sql === CLOSE_PREFIX) { - self.closing = p[2]; - } else { - const m = REFUND_RE.exec(sql); - if (m && self.closing !== null) { - const prev = db.get('SELECT ' + m[1] + ' AS v FROM towns WHERE id = ?', p[1]); - const off = db.get('SELECT give_amount, give_res FROM trade_offers WHERE id = ?', self.closing); - if (prev && off && off.give_res === m[1]) { - const credit = p[0] - prev.v; - const clip = Math.max(0, off.give_amount - credit); - if (clip > 1e-9) { const c = zero(); c[m[1]] = clip; self.book(zero(), c, 1); } - } - self.closing = null; - } } return run(sql, ...p); }; @@ -157,6 +141,7 @@ function aliveUnits(db) { const add = (k, n) => { out[k] = (out[k] || 0) + n; }; for (const r of db.all('SELECT unit, SUM(count) AS n FROM town_units GROUP BY unit')) add(r.unit, r.n); for (const r of db.all('SELECT unit, SUM(count) AS n FROM stationed GROUP BY unit')) add(r.unit, r.n); + for (const r of db.all('SELECT unit, SUM(count) AS n FROM site_stationed GROUP BY unit')) add(r.unit, r.n); // garrisons at landing sites (E6) for (const m of db.all("SELECT units FROM movements WHERE status = 'out' AND units != '{}'")) { const u = JSON.parse(m.units); for (const k of Object.keys(u)) add(k, u[k]); } return out; } diff --git a/tools/bot/report.js b/tools/bot/report.js index df46145..c0e395a 100644 --- a/tools/bot/report.js +++ b/tools/bot/report.js @@ -79,6 +79,7 @@ function render(s, opts) { const t = s.trade; out.push('offers by status: ' + Object.entries(t.byStatus).map(([k, v]) => k + ':' + v.n).join(' ') + ', completed volume ' + fmt(t.volumeCompleted) + ', completed give/want ratio p10/50/90 ' + pc(t.ratio, 'p10') + '/' + pc(t.ratio, 'p50') + '/' + pc(t.ratio, 'p90')); out.push('transport overflow lost (' + t.cargoLostEvents + ' deliveries): ' + JSON.stringify(t.cargoLost) + ', trade refunds clipped by the Rack hall cap (' + t.clipEvents + '): ' + JSON.stringify(t.refundClipped)); + out.push(' overflow by place: ' + Object.entries(t.cargoLostBy || {}).map(([k, v]) => k + ' ' + v.n + 'x (' + fmt(v.fiber) + '/' + fmt(v.hardware) + '/' + fmt(v.capital) + ')').join(', ')); const a = s.alliances; out.push('alliances ' + a.count + ', members p10/50/90 ' + pc(a.members, 'p10') + '/' + pc(a.members, 'p50') + '/' + pc(a.members, 'p90') + ' (max ' + a.membersMax + '), operators in an alliance ' + a.inAlliance + '/' + a.operators + ', relations ' + JSON.stringify(a.relations) + ', proposals ' + JSON.stringify(a.proposals)); @@ -90,7 +91,8 @@ function render(s, opts) { out.push('opened at simulated day ' + fmt(e.openedAtSimDay, 1) + ' (world age now ' + fmt(e.ageDays, 0) + '), alliance plans ' + e.plans + ', strikes sent ' + e.strikes + ' (landing reports ' + e.landingReports.n + ', taken ' + e.landingReports.taken + ', units lost value ' + fmt(e.landingReports.attLostValue) + '), strike blockers ' + JSON.stringify(e.strikeSkips)); out.push('shipments ' + e.shipments + ' carrying ' + fmt(e.shippedTotal) + ' (F ' + fmt(e.shipped.fiber) + ' H ' + fmt(e.shipped.hardware) + ' C ' + fmt(e.shipped.capital) + '), ' + fmt(e.shippedPerSimDay) + ' per simulated day; node levels started ' + e.buildsStarted + ' ' + JSON.stringify(e.buildErrors)); out.push(table(e.sites.map((x) => [x.idx, x.holder || '-', x.level, x.takenAt === null ? '-' : fmt(x.takenAt, 1), x.contributors, fmt(x.shippedIn.fiber + x.shippedIn.hardware + x.shippedIn.capital), fmt(x.shippedPerDay), x.daysToLevel100 === null ? '-' : x.daysToLevel100, fmt(x.stock.fiber + x.stock.hardware + x.stock.capital)]), ['site', 'holder', 'node level', 'taken (day)', 'contributors', 'shipped in', 'shipped/day', 'days to lvl 100 at that rate', 'stockpile now'])); - out.push('largest army (attack, before research) any single POP holds: ' + fmt(e.maxPopAttackNoResearch) + ' against the defence of the best built-up site now: ' + fmt(e.bestHeldSiteDefenceNow) + ' (one attack is one movement from one POP, so attacks cannot be added up)'); + if (e.contest) out.push('contest (E6, garrisons) ' + (e.contest.enabled ? 'on' : 'OFF') + ': attacks on HELD sites ' + e.contest.attacksOnHeld + ' (taken ' + e.contest.heldTaken + ', met a garrison ' + e.contest.metGarrison + '), first/last on day ' + e.contest.firstAttackOnHeldDay + '/' + e.contest.lastAttackOnHeldDay + '; assaults GO ' + e.contest.assaultGo + ', armies sent ' + e.contest.assaultsSent + ' ' + JSON.stringify(e.contest.assaultSkips) + '; garrison sends ' + e.contest.garrisonSends + ' (' + e.contest.garrisonedUnits + ' units), trained ' + e.contest.garrisonTrained + ', peak power ' + fmt(e.contest.garrisonPeakPower) + ', now per site ' + JSON.stringify(e.contest.garrisonNow) + ', garrison units lost (value) ' + fmt(e.contest.garrisonLostValue)); + out.push('largest army (attack, before research) any single POP holds: ' + fmt(e.maxPopAttackNoResearch) + ' against the whole defence (static + garrison) of the best built-up site now: ' + fmt(e.bestHeldSiteDefenceNow) + ' (one attack is one movement from one POP; a garrison is worn down by several waves, a static defence only by one army that beats it)'); out.push('best node level ' + e.bestLevel + '; still to ship for level 100 from there (per resource) ' + fmt(e.remainingToLevel100.fiber) + '; world ' + e.worldStatus + (e.winner ? ', WINNER ' + e.winner.tag + ' on day ' + fmt(e.winner.wonAtSimDay, 1) : ', no winner')); } } diff --git a/tools/bot/sim.js b/tools/bot/sim.js index 37f8472..8b7faaa 100644 --- a/tools/bot/sim.js +++ b/tools/bot/sim.js @@ -148,7 +148,7 @@ async function runSim(o) { for (const row of db.all('SELECT * FROM towns ORDER BY id')) { const t = S.townFromRow(db, row, world); const cur = R.resourcesAt(t, now); - const cap = cur.caps.fiber; + const cap = R.storageCap(t); acc.towns += 1; for (const r of RES) { acc.stock[r] += cur.amounts[r]; acc.prod[r] += cur.rates[r]; } const fills = RES.map((r) => cur.amounts[r] / cap); diff --git a/tools/bot/stats.js b/tools/bot/stats.js index 223ba67..23ed3c4 100644 --- a/tools/bot/stats.js +++ b/tools/bot/stats.js @@ -106,7 +106,7 @@ function build(x) { const undefended = samples.filter((s) => s.undefended); const combat = { reports: col.byType, - raids: { n: raid.n, wins: raid.att, winRate: raid.n ? raid.att / raid.n : null, lootTotal: round(raid.loot, 0), lootRes: raid.lootRes, lootPerRaid: percentiles(lootPerRaid, [10, 50, 90]), attackerLostValue: round(raid.attLost, 0), defenderLostValue: round(raid.defLost, 0), + raids: { n: raid.n, wins: raid.att, winRate: raid.n ? raid.att / raid.n : null, lootTotal: round(raid.loot, 0), lootRes: raid.lootRes, lootLeft: raid.lootLeft, emptyWins: raid.emptyWins, lootPerRaid: percentiles(lootPerRaid, [10, 50, 90]), attackerLostValue: round(raid.attLost, 0), defenderLostValue: round(raid.defLost, 0), lootPerLostValue: raid.attLost > 0 ? round(raid.loot / raid.attLost, 2) : null, undefendedShare: samples.length ? round(undefended.length / samples.length, 3) : null, undefendedLoot: round(sum(undefended.map((s) => s.loot)), 0), lootOverLossValue: percentiles(ratio, [10, 50, 90]), targetAge: ageBuckets, attackOverDefence: percentiles(samples.filter((s) => s.D > 0).map((s) => s.A / s.D), [10, 50, 90]) }, attacks: col.battles.attack, takeoverBattles: col.battles.takeover, takeovers: col.takeovers, siege: col.siege, @@ -117,7 +117,7 @@ function build(x) { // ---- trade, alliances const tradeRows = db.all('SELECT status, COUNT(*) AS n, SUM(give_amount) AS give, SUM(want_amount) AS want FROM trade_offers GROUP BY status'); const trade = { byStatus: Object.fromEntries(tradeRows.map((r) => [r.status, { n: r.n, give: r.give, want: r.want }])), refundClipped: ledger.sinkClip, clipEvents: ledger.clipEvents, - cargoLost: col.cargoLostTotal, cargoLostEvents: col.cargoLostEvents }; + cargoLost: col.cargoLostTotal, cargoLostEvents: col.cargoLostEvents, cargoLostBy: col.cargoLostBy }; const completed = db.all("SELECT give_res, give_amount, want_res, want_amount FROM trade_offers WHERE status = 'completed'"); trade.volumeCompleted = sum(completed.map((r) => r.give_amount + r.want_amount)); trade.ratio = percentiles(completed.map((r) => r.give_amount / r.want_amount), [10, 50, 90]);