diff --git a/docs/game/HOSTING.md b/docs/game/HOSTING.md index d736c33..8c2713b 100644 --- a/docs/game/HOSTING.md +++ b/docs/game/HOSTING.md @@ -18,12 +18,13 @@ A mode is a JSON document, at most 8 KiB: ```json { - "schema": "wikideck.mode/1", + "schema": "wikideck.mode/2", "id": "trending", "version": 1, "name": "Trending", "description": "Live Wikipedia pageview trends power cards up or down.", "tags": ["live-data"], + "engine": "editwar", "rules": { "trendUp": 25, "trendDown": -25 }, "cards": { "preset": "trending", "percentPerPoint": 25, "maxBonus": 3, "penalise": true }, "decks": { "kind": "starter" }, @@ -33,12 +34,14 @@ A mode is a JSON document, at most 8 KiB: | Field | Meaning | |---|---| +| `schema` | `wikideck.mode/2`. Night 1 documents (`wikideck.mode/1`) are rejected with a message saying what to change. | +| `engine` | Required: `editwar` (the Night 1 simultaneous-reveal game, `shared/game`) or `duel` (the Night 2 Magic-style duel, `shared/duel`). Duel modes only allow `constructed` and `draft` with `source: "collections"`: every card is one the players own. | | `id`, `version` | Lowercase slug and a version integer. Bump `version` whenever the rules change, so old match records and leaderboards stay attributable (`#@`). | | `name`, `description`, `tags` | Plain text only: no control characters or `<` `>`. | | `rules` | **Overrides** on top of the engine's `DEFAULT_RULESET` (see `docs/game/ENGINE_API.md`). Objects merge one level deep; arrays and numbers replace. The merged result then goes through the engine's strict `parseRuleset`, so the engine alone decides what's legal (bounded turns, Topics, deck sizes, known keywords and portals only; see DESIGN.md §9 for the keys). | | `cards` | A card-mapping **preset** from a fixed list. `standard` leaves cards as dealt. `live` freezes each card's live trend arrow (DESIGN §1.6, using the ruleset's `trendUp`/`trendDown`) at match start. `trending` does the same and also adds a bounded power bonus from the live pageview trend. The mode only picks a preset and tunes its bounded numbers. | -| `decks` | `starter` (everyone gets a seeded starter deck), `draft` (snake draft from a host-seeded pool of preview cards) or `constructed` (bring your own; see "Not yet" below). | -| `limits` | Concurrency and lobby expiry for this mode on this host. `turnSeconds` only applies to engines without their own turn timer; with tonight's engine, the ruleset's `turnSeconds` (plus 5 s network grace) is the timer. | +| `decks` | `constructed` (each player submits exactly `deckSize` NFT token ids they own; the host verifies ownership and confirmations on the chain, `minConfirmations` default 1, and builds every card from its block), `starter` (Edit War only: a seeded starter deck) or `draft` (snake draft; `source: "preview"` uses preview cards, Edit War only; `source: "collections"` pools both players' owned cards for that match only, and both must own at least `deckSize`). | +| `limits` | Concurrency and lobby expiry for this mode on this host. `rated: true` moves Elo (start 1200, K 24) when both seats are eom.dev accounts; `accountsOnly: true` refuses guest seats (owned-card modes always do). `turnSeconds` only applies to engines without their own turn timer; with tonight's engine, the ruleset's `turnSeconds` (plus 5 s network grace) is the timer. | The schema is strict: unknown fields are rejected, as are prototype keys (`__proto__`, `constructor`, `prototype`) anywhere in the document, nesting deeper than two @@ -46,6 +49,15 @@ levels inside `rules`, more than 48 rule keys, and oversized strings and arrays. **never** evaluates, imports or runs anything another peer sends. Nothing in a mode can name a file, a URL, a script or a function. +### Seats, invites, quick match and polling (Night 2) + +- **Seats:** `POST /modes/:id/lobbies`, `POST /lobbies/:id/join` and `POST /modes/:id/quick` take `{idToken, deck?, private?}` for an eom.dev account (the Dex ID token may also be sent as `Authorization: Bearer `), or `{name, secret}` for a guest in Edit War modes. The reply is `{lobbyId, seat, token, invite, playerId}`; `token` is the seat bearer for every later call. Account player ids are `sha256("acct:" + iss + "\n" + sub)`. +- **Invites:** every lobby gets a 12-character `invite` code. `private: true` hides it from `/lobbies` and quick match. `GET /invites/:code` describes it and `POST /invites/:code/join` joins it (SPA link: `/play/invite/`). +- **Quick match:** `POST /modes/:id/quick` joins the oldest open public lobby someone else opened (`matched: true`), or opens one (`matched: false`) to poll. +- **Polling:** every lobby view has a `version`. `GET /lobbies/:id?v=` answers **204** while nothing changed. Poll; never hold requests open (the node caps concurrent `/api` requests). +- **Ladder:** `GET /modes/:id/ladder` (same as `/leaderboard`): entries carry `rating` (Elo, or null if unrated) plus W/L/D. +- **Records:** `GET /matches/:id` has the seed, rules, both decks (as the engine cards), every action, `engine`, `rated`, and for constructed modes `tokens` (the NFT ids each seat played), so the recap can replay the match. + ## 2. Running your own modes Configure modes with environment variables on your node: @@ -255,10 +267,9 @@ be pinned in consensus. ## Not yet -- `constructed` decks of **owned NFTs**: the policy exists, but tonight the host deals - starter decks for it. Playing with your own cards needs a wallet-signed ownership proof - for the lobby (and then the engine's `cardFromStats`). That's a follow-up once accounts and - wallet linking (#7) settle. +- `constructed` decks of **owned NFTs** are verified on the hosting node only, against its + own account store (Night 2). Playing them on a *peer* needs a wallet-signed deck claim, + because accounts are per node; that's a follow-up. - `trending` never calls Wikipedia when a match starts. The node warms a cache-only trend store in the background, one page every 20 s (configurable, never faster than 15 s), through its existing enrichment cache (6 h TTL), starting with the preview-card pages. A card whose page isn't warm yet gets no bonus. This diff --git a/server/game/config.ts b/server/game/config.ts index b6393cb..60d0467 100644 --- a/server/game/config.ts +++ b/server/game/config.ts @@ -3,7 +3,7 @@ * environment and files; nothing here is learned from peers. * * WIKIDECK_MODES comma list of built-in mode ids and/or JSON file paths - * (default "classic"; "none" hosts nothing but still discovers) + * (default DEFAULT_MODES; "none" hosts nothing but still discovers) * WIKIDECK_MODES_DIR optional directory: every *.json in it is a mode * WIKIDECK_GAME_OPERATOR name shown as "Hosted by ..." (default: the origin's host name) * WIKIDECK_GAME_NOTE optional short note shown with the host @@ -17,11 +17,13 @@ import { HostIdentitySchema, MAX_MODES_PER_NODE, parseModeJson, type HostIdentit import { parsePeerOrigins } from './discovery.ts'; export const BUILTIN_MODES_DIR = fileURLToPath(new URL('./modes/', import.meta.url)); -export const BUILTIN_MODE_IDS = ['classic', 'trending', 'draft'] as const; +/** Duel (Night 2): classic, draft, trending. Edit War (Night 1): edit-war, edit-war-draft, edit-war-trending. */ +export const BUILTIN_MODE_IDS = ['classic', 'trending', 'draft', 'edit-war', 'edit-war-trending', 'edit-war-draft'] as const; +export const DEFAULT_MODES = 'classic,draft,trending,edit-war'; export function loadModes(env: NodeJS.ProcessEnv = process.env): ModeDocument[] { const modes: ModeDocument[] = []; - const spec = (env.WIKIDECK_MODES ?? 'classic').trim(); + const spec = (env.WIKIDECK_MODES ?? DEFAULT_MODES).trim(); if (spec !== 'none') for (const item of spec.split(',').map(s => s.trim()).filter(Boolean)) { if ((BUILTIN_MODE_IDS as readonly string[]).includes(item)) modes.push(readMode(join(BUILTIN_MODES_DIR, `${item}.json`))); else if (item.endsWith('.json')) modes.push(readMode(resolve(item))); diff --git a/server/game/duel-binding.ts b/server/game/duel-binding.ts new file mode 100644 index 0000000..07c4348 --- /dev/null +++ b/server/game/duel-binding.ts @@ -0,0 +1,51 @@ +/** + * Binds the mode host to the Night 2 duel engine (shared/duel; DUEL_API.md "Host binding"). + * + * Cards: an owned NFT (`ChainCard`, built by ownership.ts from its block) becomes a `DuelCard` + * through ONE function, `toDuelCard`, shared by the host and the collection API, so PvP, the + * deck builder and the browser bot all see the same card. The card profile (P31 classes, + * categories, description, links) comes from testnet-ops' frozen IdentityStore (#68). On a + * miss it is derived from what the chain itself carries (weaker typing), and nothing is + * fetched inline: no Wikimedia call ever happens at deck validation or match time. + */ +import { derive, type DuelCard } from '../../shared/duel/derive.ts'; +import { profileFromSources } from '../../shared/duel/profile.ts'; +import { toProfile, type IdentityStore } from './identity.ts'; +import type { ChainCard, EnginePort } from './engine-port.ts'; + +export type DuelCardSources = { + /** Frozen per-token identities (server/game/identity.ts). */ + identity?: Pick; +}; + +type AnyPort = EnginePort; + +/** The single ChainCard → DuelCard conversion. Deterministic for a given block and identity. */ +export function toDuelCard(card: ChainCard, sources: DuelCardSources = {}): DuelCard { + const article = card.article as { pageId: number; title: string; extract: string; revisionId: number } | undefined; + const statsSnapshot = card.statsSnapshot as { pageBytes: number; languageCount: number; stats: any } | undefined; + if (!article || !statsSnapshot) throw new Error(`Card ${card.tokenId} has no on-chain article or stats snapshot`); + const frozen = sources.identity?.get(card.tokenId); + const profile = frozen ? toProfile(frozen) : profileFromSources({ enrichment: { + description: null, wikidataId: null, categories: [], revisionId: article.revisionId ?? null } as any }); + return derive({ tokenId: card.tokenId, article, statsSnapshot }, profile as any); +} + +/** Wrap duel-core's `duelEnginePort` with what the host adds: owned-card building and the copy limit. */ +export function duelBinding(port: AnyPort, sources: DuelCardSources = {}): AnyPort { + return { + ...port, + fromChain: (_rules, card) => toDuelCard(card, sources), + copyLimit: rules => (rules as { maxCopiesPerPage?: number }).maxCopiesPerPage ?? 4, + }; +} + +/** + * The duel engine, if this build has it (`duelEnginePort` from shared/duel/index.ts, the engine + * alpha). Null before that lands: duel modes are then skipped at startup with a log line. + */ +export async function loadDuelEngine(sources: DuelCardSources = {}): Promise { + const mod = await import('../../shared/duel/index.ts') as Record; + const port = mod.duelEnginePort as AnyPort | undefined; + return port && typeof port.createMatch === 'function' ? duelBinding(port, sources) : null; +} diff --git a/server/game/engine-port.ts b/server/game/engine-port.ts index 74b50b7..8d0cd53 100644 --- a/server/game/engine-port.ts +++ b/server/game/engine-port.ts @@ -40,4 +40,32 @@ export interface EnginePort