No description
  • Rust 67%
  • TypeScript 23.1%
  • Svelte 8.8%
  • Shell 0.7%
  • Dockerfile 0.2%
  • Other 0.2%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Napat Srichan 2795efb7b1
All checks were successful
CI / Rust (fmt, check, test) (push) Successful in 3m25s
CI / Web (Bun: check, test, build) (push) Successful in 28s
feat: add singleplayer practice mode against the core solver
Server: the additive `client.createSolo` message creates and immediately
starts a match with the caller in seat 0 and a virtual computer seat in
seat 1. The hub solves with `solve_for_player` (fixed 250k-node budget,
top_n 1, exchange when no placement), applies the move through
`apply_action`, and broadcasts ordinary events/state at the next match
version. `server.matchStart` gains an additive `solo` marker (also on
resume). Solo matches persist with kind "solo"; the computer seat has no
guest, connection, or reconnect token, and restore finishes an interrupted
computer turn before the hub accepts connections.

Web: add the `/solo` practice page, Practice nav and lobby entry, Computer
labels and practice badges, a New practice match link, a mock-transport
fixture for local development, and reducer/app-client coverage.

Docs: record the round-3 contract and decision (R3-D1 / R3-S1), document the
solver's server use, and update the README status.
2026-11-01 16:14:07 -08:00
.github/workflows refactor!: remove the developer debug surface 2026-11-01 14:53:12 -08:00
core feat: move the workspace to edition 2024 2026-10-31 17:40:01 -07:00
docs feat: add singleplayer practice mode against the core solver 2026-11-01 16:14:07 -08:00
scripts chore(r2): finalize round-2 records and switch web toolchain to Bun 2026-10-27 00:59:12 -07:00
server feat: add singleplayer practice mode against the core solver 2026-11-01 16:14:07 -08:00
web feat: add singleplayer practice mode against the core solver 2026-11-01 16:14:07 -08:00
.dockerignore chore(p4): Docker, Compose, CI, and operations docs 2026-10-13 01:14:24 -07:00
.gitignore docs(next-iteration): mark F0-F6 done, document debug envs, record execution status 2026-10-13 22:20:32 -07:00
Cargo.lock chore(deps): sqlx 0.9 and argon2 0.6 2026-10-31 17:42:45 -07:00
Cargo.toml feat: move the workspace to edition 2024 2026-10-31 17:40:01 -07:00
compose.yaml chore(p4): Docker, Compose, CI, and operations docs 2026-10-13 01:14:24 -07:00
Dockerfile chore(p4): Docker, Compose, CI, and operations docs 2026-10-13 01:14:24 -07:00
Makefile refactor!: remove the developer debug surface 2026-11-01 14:53:12 -08:00
README.md feat: add singleplayer practice mode against the core solver 2026-11-01 16:14:07 -08:00
rustfmt.toml feat: move the workspace to edition 2024 2026-10-31 17:40:01 -07:00

Numtiles

Numtiles is an online A-Math-style number tile game for two players. This repository is a monorepo:

Path Package Purpose
core/ numtiles-core Authoritative game rules library (Rust).
server/ numtiles-server HTTP/WebSocket match server (Rust, Axum + Tokio).
web/ numtiles-web SvelteKit client (TypeScript).
docs/ — Product, engine, contract, and rules documentation.
scripts/ — Local development helpers (PostgreSQL).

The documentation map starts at docs/README.md. The game/rule source of truth is docs/rules.md; the frozen core/server/web contracts are in docs/contracts.md; operations and deployment are in docs/operations.md. The reasoning behind the current behavior — decisions, rejected options, and the one open decision — is in docs/decisions.md.

Status: the confirmed scope is implemented — the 100-tile rulebook with the official 15×15 premium map, the authoritative Rust engine, the online server with PostgreSQL persistence, and the SvelteKit client. The follow-on work packages are also implemented: optional accounts (P1), read-only match review (P2), server hardening (P3), and Docker/Compose + CI operations (P4). Round 2 implements the product answers: five of the six open behaviors are resolved and one is deferred (see Round-2 decisions); timed-turn expiry remains explicitly unimplemented. Round 3 adds singleplayer practice: the additive client.createSolo message starts a match against the core solver on the server, and the web client exposes it at /solo (see docs/decisions.md R3-D1).

Architecture and authority

  • core is the single source of truth for rules. It has no networking, storage, or process-global randomness. All randomness enters through TileDrawSource.
  • server is the only authority allowed to change a match. It owns guest identities, private rooms, matchmaking, live delivery, and persistence. It calls core for every accepted action.
  • web presents and submits intents. It may preview, but it never computes an authoritative score or decides legality.
  • Privacy: a PlayerView contains only the viewer's own rack plus public board/scores. The opponent's rack and the bag are never sent to a browser or exposed by a persistence query that feeds a client.

Prerequisites

  • Rust 1.98+ and Cargo
  • Bun 1.4+ (the web runtime, package manager, and test/build tool)
  • PostgreSQL 18 (optional; the server runs in memory when DATABASE_URL is unset). Nix users can get it with nix-shell -p postgresql.

Rust workspace

Run from the repository root:

cargo fmt --all -- --check   # formatting
cargo check --workspace      # type/compile check
cargo test --workspace       # unit + integration tests

Run a deterministic two-player self-play game (both seats use the core solver):

cargo run --release -p numtiles-core --example selfplay -- \
  --seed 1 --max-nodes 5000000

core/examples/selfplay.rs applies every recommendation through the authoritative engine, verifies the solver's claimed score against the engine's turn score, and reports per-move node counts and wall time.

Record a fixed position corpus, then benchmark solver variants on identical positions:

cargo run --release -p numtiles-core --example selfplay -- \
  --seed 1 --max-nodes 5000000 --games 5 \
  --record-actions /tmp/numtiles-corpus --quiet

cargo run --release -p numtiles-core --example bench_corpus -- \
  --dir /tmp/numtiles-corpus --budgets 200000,1000000,5000000 \
  --csv /tmp/bench.csv --samples 3 --warmup 1

bench_corpus replays the recorded actions through the engine and solves every pre-action position at each budget, so pruning/search-order changes are measured on a fixed corpus rather than on divergent self-play games.

--samples N (default 3, at least 1) is the number of timed solves per position and budget, and --warmup N (default 1) the number of untimed solves before them. Every timed solve of a position must return an identical full SolveResult (including alternatives and exchange) or the run panics. The defaults therefore solve each position and budget 4 times (1 warmup + 3 samples), so a run takes about four times as long as a single pass; use --samples 1 --warmup 0 for a quick pass. The CSV and summary report median, p95, min and max latency.

Play two solver seats against each other and save a complete replay file:

cargo run --release -p numtiles-core --example replay_demo -- \
  --seed 1 --nodes-p0 1000000 --nodes-p1 1000000 \
  --out /tmp/numtiles-replay.json

core/src/replay.rs stores the initial racks and bag order plus every accepted action in a versioned JSON format; Replay::verify replays it through the engine. Replay files contain private state (both racks and the bag) and must not be served to clients. See docs/replay.md.

Web client

Run from web/:

bun install --frozen-lockfile   # install dependencies from bun.lock
bun run check    # svelte-check + strict TypeScript
bun run build    # production build
bun run dev      # local dev server
bun run test     # vitest unit tests

Singleplayer practice

The web client has a Practice page (/solo) backed by the additive client.createSolo message. The server creates a normal match with the caller in seat 0 and a virtual computer seat in seat 1, then plays the computer's turns with the core solver (docs/solver.md). The computer's moves are validated and scored by the same engine and arrive as ordinary server.events + server.state frames, so the client never computes legality or scores. Practice matches are persisted, resumable, and reviewable like two-player matches. See docs/contracts.md §11 and docs/decisions.md (R3-D1).

Start the server (below) and open /solo (also linked from the lobby). The in-memory development fixture answers client.createSolo too, so the page works without a backend, but only a real server plays the solver.

Running the server with PostgreSQL

The server reads its bind address from NUMTILES_BIND_ADDR (default 127.0.0.1:3000) and its connection string from DATABASE_URL. When DATABASE_URL is set it connects, applies versioned migrations, and restores active matches after a restart; otherwise it runs in memory (development only).

# Start a throwaway local PostgreSQL and run the DB-gated tests.
scripts/pg-dev.sh

# Or run any command against a throwaway cluster:
scripts/pg-dev.sh cargo test -p numtiles-server

# Start the server against a database (migrations run automatically):
DATABASE_URL=postgres://numtiles@127.0.0.1:55432/numtiles \
  cargo run -p numtiles-server
curl -i http://127.0.0.1:3000/health

scripts/pg-dev.sh re-executes itself under nix-shell -p postgresql, starts a cluster in target/pgdata (override with NUMTILES_PGDATA/NUMTILES_PGPORT), exports DATABASE_URL, and stops the cluster on exit. Any PostgreSQL 18 instance works equally well; set DATABASE_URL yourself and run cargo test --workspace.

The WebSocket endpoint is GET /ws; the message envelope and all message types are frozen in docs/contracts.md §11.

One developer-tooling variable is accepted, inert unless set: NUMTILES_RNG_SEED (a u64 that makes per-match tile draws reproducible). Leave it unset outside development; see docs/operations.md.

Accounts, review, and hardening

  • Accounts (P1). POST /auth/register, /auth/login, /auth/logout, and GET /auth/me add optional accounts on top of the guest identity. An account recovers the same guest (and its active matches/reconnect tokens) on another device; guest display-name semantics and game rules are unchanged. See docs/contracts.md §14.
  • Match review (P2). GET /matches/{matchId}/review returns the retained history: public board, scores, status, seat labels, the ordered action log, and the additive publicEvents stream (round 2) — never racks, bag order, or rackDrawn/rackReturned tile identities. The client route is /review/[matchId]. See §15.
  • Hardening (P3). Per-connection rate limiting, JSON 404s, WebSocket frame caps, input validation, graceful shutdown, and an aggregate Prometheus GET /metrics endpoint. See §16.

Docker and Compose

A Dockerfile builds the numtiles-server binary in a multi-stage image (runtime contains only the server). compose.yaml runs PostgreSQL 18 (named volume + healthcheck) plus the server wired to it via DATABASE_URL:

docker compose up --build
docker compose up -d db      # database only

Environment variables, migrations, health, deployment, and shutdown behavior are documented in docs/operations.md.

Verification

cargo fmt --all -- --check
cargo check --workspace
cargo test --workspace            # core engine, server flows, persistence
( cd web && bun install --frozen-lockfile && bun run check && bun run test && bun run build )
DATABASE_URL=... cargo test --workspace   # enables the DB-gated tests
scripts/verify.sh --require-db            # DB-gated tests are mandatory

A Makefile wraps the common Rust and web commands (make verify), and scripts/verify.sh runs the same verification list (DATABASE_URL=... scripts/verify.sh enables the DB-gated tests; make verify-db = scripts/verify.sh --require-db fails when DATABASE_URL is unset or unreachable). CI (.github/workflows/ci.yml) runs the same checks on a self-hosted Forgejo forgejo-runner, not GitHub-hosted runners — the runner constraints that shape the workflow are recorded in docs/operations.md. The web job uses Bun (oven-sh/setup-bun + bun.lock) instead of Node/npm, plus an explicit DB-gated step.

Round-2 decisions

The six behaviors that were open are now answered by the product owner and recorded in docs/decisions.md (R2-D1…R2-D11); the implementable result is in docs/contracts.md §12–§15.

# Behavior Result
1 Ready-confirmation expiry Resolved — a prompt lasts until the room owner exits; no TTL.
2 Timed per-turn expiry Deferred — still tracked and displayed, not enforced.
3 Private room / invite-link expiry Resolved — until the owner exits; the code is freed then.
4 Matchmaking queue across restart Resolved — no persistence; the client re-sends client.joinQueue.
5 Reconnect credential format/rotation Resolved — Option A: opaque 256-bit token per match seat, match lifetime, never public.
6 Queued guest on disconnect Resolved — removed on the guest's last disconnect.

What changed in the product surface:

  • Owner exit. client.leaveRoom { matchId } is added (§11). Leaving a private room as the owner closes it and frees the code; the other seat gets server.error {code:"room_closed"}, which is terminal. The owner's last tab closing does the same — presence is the fallback, and there is no timer.
  • Public pairing. server.matchFound {matchId, settings, ready} replaces the old reuse of server.room with an empty code plus server.queue{matched}. The client shows a dedicated ready page; public matches stay untimed.
  • History. GET /matches/{id}/review gains an additive publicEvents stream (per-action scores, board, bingo, exchanges as counts only) so a reload can rebuild the game. Racks, bag order, and rack-draw tile identities are never stored or returned.
  • Guest-name auth race (§3.2) is fixed: setDisplayName re-sends client.hello on an open socket, so create-room no longer races the name.
  • CI proves the DB-gated suites run: a fail-fast SELECT 1 probe gates cargo test --workspace.
  • Bun is the web toolchain (install/check/test/build) and CI runtime. bun.lock is committed, CI uses oven-sh/setup-bun with no actions/setup-node, and the previous Node-download timeout cannot recur.

Each entry in docs/decisions.md records the answer, the reasoning, and the options that were rejected.

Roadmap

  • Round 3 adds singleplayer practice (R3-D1): a server-driven computer seat backed by the core solver, exposed as client.createSolo and the /solo web page. The solver budget is a fixed policy; difficulty selection and hints are not implemented.
  • Round 2 applies these answers (R2-D1…R2-D11); the record is docs/decisions.md.
  • Open: timed per-turn expiry (R2-D2) — deferred, so there is no deadline sweeper, no timeout action, and no automatic forfeit; the TODO(decision) marker stays and the options are recorded in docs/decisions.md.
  • Solver integration: the move solver (docs/solver.md) is a core API used by the self-play, benchmark, and replay examples, by tests, and (round 3) by the server's singleplayer practice seat. There is still no hint/analysis message in docs/contracts.md and no /solve endpoint, so client-side solving or hints would first need bag_remaining added to the contract.
  • No production web adapter yet: web/ builds with @sveltejs/adapter-auto, so a generic Node target is produced and the client is not part of the server image or Compose stack. Choosing a concrete adapter and host is recorded as a deliberately unmade deployment decision in docs/operations.md.
  • Known limitations by design: matchmaking queues and pre-start rooms are in-memory only (a restart empties them; clients rejoin), and account sessions live until logout.
  • The round-1 iteration (F0–F6) is complete; its engineering decisions (D1, D2, seams S1–S5) are recorded in docs/decisions.md.