outpost/AGENTS.md
coyotte508 54ec844c33 Rebuild exact game states for BGS undo and replays
BGS saves what the engine's `replay(data, { to })` returns: undo against bots,
admin and batch replays. It replayed the log for display, without drawing from
the decks or advancing the PRNG, so a restored game kept its initial decks
(cards duplicated between hands and decks), rewound the random counter and
lost the players' auto-pass and production settings.

Given the seed, `replay` now re-applies the logged moves from `initGame`,
replays automatic choices as recorded and checks every regenerated entry
against the saved log, refusing rather than rewriting a history it cannot
reproduce (e.g. after a drop). Current names, settings and drops are kept;
secret-stripped logs still use the display replay. Engine 0.10.26.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 12:06:25 +02:00

10 KiB
Raw Permalink Blame History

AGENTS.md

Guidance for AI agents and contributors working in this repository.

What this is

Unofficial open-source implementation of the board game Outpost (1991, James Hlavaty) for boardgamers.space (BGS). Two packages: packages/engine (outpost-engine, rules + BGS wrapper) and packages/viewer (outpost-viewer, Svelte 5 browser UI). See README.md for the full picture, including the rules set implemented (Expert Rules v1.32) and the known data deviations (some production deck distributions are inferred, not confirmed).

Conventions

  • ESM everywhere: "type": "module" in every package. TS imports use explicit .js extensions in the engine (moduleResolution: nodenext) and no extension in the viewer (moduleResolution: bundler) — follow the local pattern of each package.
  • Node >= 24 (engines field, .nvmrc), pnpm 11 workspaces (pnpm-workspace.yaml).
  • TypeScript strict, including noUncheckedIndexedAccess. Code must pass pnpm tsc (engine tsc --noEmit, viewer svelte-check) with zero errors.
  • No comments by default — write self-explanatory code; comment only the non-obvious "why" (e.g. a BGS contract quirk, a rules edge case). No emojis in code or docs.
  • Formatting: oxfmt (.oxfmtrc.json) — tabs for indentation (tabWidth 2), 120-column lines, Svelte formatting enabled. Run pnpm fmt to format, pnpm fmt:check in CI. Linting: oxlint (.oxlintrc.json) with curly: all — always brace if/for/ while bodies. Run pnpm lint.
  • Tests: colocated *.spec.ts next to engine sources, run with node --test against compiled output (pnpm --filter outpost-engine test compiles to dist-test/ first). Use node:assert/strict.
  • Dependencies: pin exact versions; verify a version exists (npm view <pkg> version) before adding it. Keep the dependency list minimal.

Engine specifics

  • In-place state mutation is intentional. applyMove / dropPlayer mutate the passed GameState and return it, matching BGS/take6 engine semantics (the game-server JSON-serializes the state between calls). Illegal moves must throw before any mutation — validation runs first. Never mutate-then-throw.
  • The game state must stay JSON-serializable at all times (no functions, no class instances, no Map/Set) because BGS round-trips it through JSON.parse(JSON.stringify(...)).
  • All randomness goes through the seeded PRNG (src/prng.ts); the seed arrives via init. Never use Math.random in the engine — replay determinism depends on it. Randomness is drawn as seedrandom(seed:counter) with the counter stored in the state, so nothing needs to persist PRNG internals.
  • The wrapper boundary deep-validates untrusted input. wrapper.move receives raw network JSON; applyMove runs sanitizeMove (src/sanitize.ts) which rebuilds the move as a fresh literal with only whitelisted fields, strict type checks and bounded arrays — this protects both interpretation and the log (moves are stored verbatim in state.log).
  • Hidden information: stripSecret hides the seed (it derives all deck orders), deck values, other players' hand values (v = -1), and produced card values in round log entries. logSlice applies the same treatment. When writing features, never leak deck contents or opponents' card values into what a client can see.
  • Replay (src/replay.ts) rebuilds state from the log without consuming randomness: "round" log entries carry purchase order, market, supply and production draws, and a replayMode flag (src/moves.ts) makes round transitions and affordability checks inert so a stripped log replays into a stripped state.
  • Rollbacks (src/rebuild.ts): BGS saves what wrapper.replay returns (undo against bots, admin and batch replays), so given the seed it re-applies the logged moves from initGame to rebuild the exact state (decks, discards, PRNG counter) and checks each regenerated entry against the recorded one, throwing rather than rewriting history. Automatic choices must stay in the log (auto-passes in info.autoPassed, Mega choices as moves); names, settings and drops are not logged and are taken from the current state.
  • packages/engine/wrapper.ts is the BGS Engine API contract: keep the exported names and signatures in sync with the platform's app/types/engine.ts. dist/wrapper.js must exist after build (it is the registered entryPoint).
  • Production deck data (src/data.ts) reproduces the published card counts; treat it as rules data, not creative content. See README.md "Data notes / deviations" before changing distributions — it also lists the rules not yet implemented (mega production cards).

Viewer specifics

  • Svelte 5 runes mode only: $state, $derived, $props, $effect. No legacy export let, no $: reactive statements.
  • The viewer uses @boardgamers/protocol for registration, validated events, and chat. registerViewer exposes window.outpost.launch(); its returned emitter is driven by BGS or the standalone dev harness. Do not add another postMessage bridge.
  • Keep everything asset-free: cards and tokens are pure CSS. Theme tokens live in src/lib/theme.css.
  • The BGS host measures body.scrollHeight — normal top-down document flow, no vertical centering tricks.
  • wrapper.currentPlayer returns an array of seats whenever several players act at once (discard phase, fastBid auctions); the dev backend (and any future integration) must handle both shapes.
  • Responsive layout (App.svelte): mobile is one column ordered action bar → own panel → market → other players → event log (the action bar is sticky, see ActionBar.svelte); desktop is a two-column grid with the players grid + market on the left and a sticky action-bar/log sidebar on the right. Child-component roots (.banner, .market, .panel, LogFeed's .side) need :global() to be targeted from App.svelte (Svelte scoped styles).

Workflow

pnpm install
pnpm dev      # viewer dev server + mock backend harness
pnpm fmt      # oxfmt format (tabs, 120 cols)
pnpm lint     # oxlint (curly rule)
pnpm tsc      # engine tsc + viewer svelte-check
pnpm test     # engine tests
pnpm build    # engine dist/ + viewer dist/ (iife + css)
pnpm check    # fmt:check + lint + tsc + test + build

Run pnpm check before committing. Commit with clear messages. The repo lives on Codeberg (origin = codeberg.org/boardgamers/outpost); push main directly (git pull --rebase first if behind), no PR workflow. CI runs as a Forgejo Actions workflow (.forgejo/workflows/ci.yml).

The dev harness (pnpm dev) is a hot-seat vs bots: ?players=N&seed=S&auto=1& delay=ms&fastBid=1 (auto = bots also play your seat).

Deploying to BGS (prod)

Publishing goes through the BGS admin API with an admin token (bgs_admin_..., sent as Authorization: Bearer <token>; only valid under /api/admin/* and the token needs the gameinfo grant). Base URL: https://admin.boardgamers.space/api. Never commit a token; take it from the environment ($BGS_ADMIN_TOKEN).

Outpost is registered as game outpost, version doc 1, engine entryPoint dist/wrapper.js. Ongoing games are pinned to the game version integer but hot-swap the engine package on that doc, so re-uploading the engine upgrades the running games within ~60 s (the game-server install cron). Upgrade the engine and viewer together — the move format couples them.

AUTH="Authorization: Bearer $BGS_ADMIN_TOKEN"
BASE=https://admin.boardgamers.space/api/admin/gameinfo/outpost

# 0. Bump packages/engine/package.json version, then:
pnpm check && (cd packages/engine && pnpm pack)

# 1. Engine: raw npm-pack tgz body. Reads name/version from the tarball,
#    stores it on S3 and $sets engine.package (incl. url) on the doc itself.
curl -X POST "$BASE/1/engine" -H "$AUTH" \
	-H "Content-Type: application/octet-stream" \
	--data-binary @packages/engine/outpost-engine-<version>.tgz

# 2–3. Upload the complete viewer folder and activate after verification.
# Use the publisher from your BGS checkout (not this game repository):
node /path/to/boardgamers/scripts/publish-viewer.mjs --game outpost --version 1 \
  --dir packages/viewer/dist --entry outpost-viewer.iife.js --style outpost-viewer.css \
  --token /path/to/admin-token --record /tmp/outpost-release.json --apply --activate
# This includes language JSON and sets scriptBytes. BGS compresses uploads itself.

# 4. Verify: engine.package.version and viewer.url on the doc.
curl "$BASE/1" -H "$AUTH"

Step 1 alone is enough for an engine-only fix (no PUT needed). A brand-new game version integer ($BASE/2) instead leaves ongoing games on the old code forever.

Rules page (CMS)

The public rules page (/page/outpost/rules) is a CMS doc in the pages collection, not a repo file. Edit it via the admin API (same token; the gameinfo:outpost grant covers pages named outpost:*):

curl "https://admin.boardgamers.space/api/page/outpost:rules"   # read (public)
curl -X PUT "https://admin.boardgamers.space/api/admin/page/outpost:rules/en" \
	-H "$AUTH" -H "Content-Type: application/json" \
	--data-binary @payload.json   # { "title": "Outpost rules", "content": "<markdown>" }

Game-creation options (e.g. fastBid) are declared in the options array on the gameinfo doc (same GET/PUT flow as step 3); option values are captured on the game doc at creation, so editing the declaration never affects ongoing games. Expansions use the native BGS mechanism: declared as expansions: [{ name, label }] on the gameinfo doc, the chosen names arrive in wrapper.init's expansions: string[] param and the wrapper maps kicker onto the internal options.kicker flag (also kept working for games created back when it was a checkbox option).

BGS publication and Git delivery

Whenever changes are published to BGS, commit the corresponding source, tests, dependency/lockfile changes and version bumps, then push them to this repository's main or master release branch in the same task. A BGS upload or a push only to a feature branch does not complete delivery. This is standing authorization to commit and push published changes without asking for separate confirmation.

Fetch and integrate the latest release-branch changes, run the relevant repository checks, and push without force. Update any public mirrors required by this repo's existing workflow too. Keep credentials, generated artifacts excluded by the repo, and unrelated unfinished work out of the commit. Verify the remote branch contains the delivered commit and report any blocker instead of claiming delivery.