diff --git a/docs/game/HOSTING.md b/docs/game/HOSTING.md index 8c2713b..49aa7a3 100644 --- a/docs/game/HOSTING.md +++ b/docs/game/HOSTING.md @@ -56,6 +56,8 @@ a file, a URL, a script or a function. - **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. +- **Duel cards:** `server/game/duel-binding.ts` `toDuelCard` is the one path from an owned NFT to a duel card, for matches and for `GET /api/game/collection` card faces. It uses the frozen card identity (`/card-identity.sqlite`, testnet-ops' pre-bake) when present. Otherwise it types the card from what its block carries (the extract's first sentence, then the mint-time category), with no fetch. So a card's *collection* type can change **once**, when its identity is first frozen. Matches never change: the record stores the derived cards. Run the identity pre-bake before opening a node to PvP. +- **Clock:** duel turns get `turnSeconds` (+5 s grace) plus a per-seat `bankSeconds` bank; seat views carry `clock: {turnStartedAt, turnMs, bankMs}`. - **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 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..8a9f019 --- /dev/null +++ b/server/game/duel-binding.ts @@ -0,0 +1,86 @@ +/** + * 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 { classify } from '../../shared/duel/classify.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; + +/** + * Generic type hints from the mint-time `article.category` (server/wiki.ts `category()`), used + * only when neither a frozen identity nor the extract's first sentence types the card. They are + * class words, not facts about the subject, and never reach the Connected keys. + */ +const CATEGORY_HINTS: Readonly> = { + People: 'person', Nature: 'organism', Space: 'astronomical object', History: 'event', Science: 'concept', Culture: 'organization', +}; + +/** First sentence of the on-chain extract, as a description-like signal for the classifier. */ +function firstSentence(extract: string): string { + const text = extract.replace(/\s+/g, ' ').trim(); + return (/^.*?[.!?](?=\s|$)/.exec(text)?.[0] ?? text).slice(0, 300); +} + +/** + * The single ChainCard → DuelCard conversion. Deterministic for a given block and identity. + * Miss path (no frozen identity yet): classify from what the block itself carries, the extract's + * first sentence, then the mint-time category hint. No fetch; card faces stay real data only. + */ +export function toDuelCard(card: ChainCard, sources: DuelCardSources = {}): DuelCard { + const article = card.article as { pageId: number; title: string; extract: string; revisionId: number; category?: string } | 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 chain = { tokenId: card.tokenId, article, statsSnapshot }; + const frozen = sources.identity?.get(card.tokenId); + if (frozen) return derive(chain, toProfile(frozen) as any); + const base = profileFromSources({ enrichment: { + description: null, wikidataId: null, categories: [], revisionId: article.revisionId ?? null } as any }); + const sentence = firstSentence(article.extract ?? ''); + let profile = { ...base, description: sentence || null }; + if (classify(profile).source === 'fallback') { + const hint = CATEGORY_HINTS[article.category ?? '']; + if (hint) profile = { ...profile, instanceOf: [{ id: '', label: hint }] }; + } + const out = derive(chain, profile as any); + // The sentence is the flavour text already; it is not a Wikidata short description. + delete (out as { description?: string }).description; + out.connect = { ...out.connect, p31: out.connect.p31.filter(id => id !== '') }; + (out as { typedBy?: string }).typedBy = 'fallback'; + return out; +} + +/** 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, + // BRIEF "Clock": 60 s per turn plus a 5-minute bank, both ruleset data. + bankSeconds: rules => (rules as { bankSeconds?: number }).bankSeconds ?? 0, + }; +} + +/** + * 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 8d0cd53..53c7a06 100644 --- a/server/game/engine-port.ts +++ b/server/game/engine-port.ts @@ -32,6 +32,8 @@ export interface EnginePort= 0) void this.takePick(l, l.draft.order[l.draft.turn]!, idx).catch(() => { l.phase = 'expired'; }); } else if (l.phase === 'playing' && l.state !== undefined && now - (l.turnStartedAt ?? l.lastMove) > this.turnMs(l)) { const waiting = ([0, 1] as Seat[]).filter(s => engine.legalActions(l.state, s).length > 0); - if (engine.timeoutAction) { + // Past the turn timer, a lone waiting seat spends its bank before it times out. + const bank = waiting.length === 1 && l.bank ? l.bank[waiting[0]!] : 0; + if (now - (l.turnStartedAt ?? l.lastMove) <= this.turnMs(l) + bank) { /* still on the bank */ } + else if (engine.timeoutAction) { // The engine decides what a timeout means (auto-commit, AFK forfeit); it is logged and replayable. - for (const s of waiting) if (l.phase === 'playing') this.apply(l, s, engine.timeoutAction(s)); + for (const s of waiting) if (l.phase === 'playing') { if (l.bank) l.bank[s] = 0; this.apply(l, s, engine.timeoutAction(s)); } l.turnStartedAt = now; } else if (waiting.length === 1) this.finish(l, waiting[0] === 0 ? 1 : 0, 'timeout'); else this.finish(l, null, 'abandoned'); @@ -437,6 +443,8 @@ export class ModeHost { l.state = engine.createMatch(l.rules, mapped, l.seed); l.phase = 'playing'; l.startedAt = l.lastMove = l.turnStartedAt = this.now(); + const bankSeconds = engine.bankSeconds?.(l.rules); + if (bankSeconds !== undefined && bankSeconds > 0) l.bank = [bankSeconds * 1000, bankSeconds * 1000]; l.turn = engine.turnOf?.(l.state); delete l.draft; this.bump(l); @@ -471,7 +479,14 @@ export class ModeHost { l.lastMove = this.now(); this.bump(l); const turn = engine.turnOf?.(l.state); - if (turn !== l.turn) { l.turn = turn; l.turnStartedAt = l.lastMove; } + if (turn !== l.turn) { + // The seat that ended the turn pays any time over the turn timer from its bank. + if (l.bank && l.turnStartedAt !== undefined) { + const over = l.lastMove - l.turnStartedAt - this.turnMs(l); + if (over > 0) l.bank[seat] = Math.max(0, l.bank[seat] - over); + } + l.turn = turn; l.turnStartedAt = l.lastMove; + } if (engine.isOver(l.state)) { const r = engine.result(l.state); this.finish(l, r.winner, reason ?? r.reason ?? 'complete'); } else if (l.actions.length >= 2000) this.finish(l, null, 'action-limit'); } diff --git a/server/game/index.ts b/server/game/index.ts index cb0dffe..7d667df 100644 --- a/server/game/index.ts +++ b/server/game/index.ts @@ -4,7 +4,7 @@ */ import { join } from 'node:path'; import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; -import type express from 'express'; +import express from 'express'; import { loadModes, hostIdentity, gamePeers } from './config.ts'; import { ModeDiscovery } from './discovery.ts'; import { ModeHost } from './host.ts'; @@ -13,7 +13,10 @@ import { MatchStore } from './store.ts'; import type { EnginePort, OwnershipPort } from './engine-port.ts'; import type { EngineId } from '../../shared/game/modes.ts'; import { TrendCache } from './trends.ts'; -import type { OwnershipDeps } from './ownership.ts'; +import { loadDuelEngine, toDuelCard } from './duel-binding.ts'; +import { collectionRouter } from './collection.ts'; +import { IdentityStore } from './identity.ts'; +import { collection, resolveDeck, verifyAccount, type OwnershipDeps } from './ownership.ts'; type Enrichment = { get(pageId: number): Promise<{ pageviews: { trendPercent: number | null } }> }; @@ -29,8 +32,19 @@ export async function gameRouter(options: { dataDir: string | null; enrichment?: env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean }): Promise { const env = options.env ?? process.env; const engine = options.engine ?? (await import('./engine-binding.ts')).engineBinding; - const engines = { editwar: engine, ...options.engines }; - const modes = loadModes(env); + const engines: Partial>> = { editwar: engine, ...options.engines }; + // Frozen card identities (testnet-ops #68) give duel cards their P31 typing. Opened once, here, + // and shared by the duel engine binding and the collection API's card faces. + const identity = options.dataDir ? new IdentityStore(join(options.dataDir, 'card-identity.sqlite')) : undefined; + if (!engines.duel) { + const duel = await loadDuelEngine({ identity }); + if (duel) engines.duel = duel; + } + const modes = loadModes(env).filter(m => { + if (engines[m.engine]) return true; + console.warn(`Game modes: skipping "${m.id}": engine "${m.engine}" is not in this build`); + return false; + }); // Trends come from a slowly warmed, cache-only store: never a Wikipedia call per match. let trends: TrendCache | undefined; if (options.enrichment && modes.some(m => m.cards.preset === 'trending')) { @@ -47,14 +61,30 @@ export async function gameRouter(options: { dataDir: string | null; enrichment?: } if (options.warmTrends !== false) trends.start(); } - const host = new ModeHost({ identity: hostIdentity(env), modes, engines, ownership: options.ownershipPort, + const ownership = options.ownershipPort ?? (options.ownership ? ownershipPortFrom(options.ownership) : undefined); + const host = new ModeHost({ identity: hostIdentity(env), modes, engines, ownership, store: new MatchStore(options.dataDir ? join(options.dataDir, 'game') : null), liveData: trends ? async pageId => trends!.get(pageId) : undefined }); const discovery = new ModeDiscovery({ peers: gamePeers(env) }); if (options.dataDir) persistLive(host, join(options.dataDir, 'game'), options.handleSignals !== false); const timer = setInterval(() => host.sweep(), 5_000); timer.unref(); - return createGameRouter(host, discovery); + const game = createGameRouter(host, discovery); + if (!options.ownership) return game; + // GET /api/game/collection (#57), with each card's DuelCard face from the same toDuelCard the host uses. + const router = express.Router(); + router.use('/collection', collectionRouter({ ...options.ownership, duelCard: c => toDuelCard(c, { identity }) })); + router.use(game); + return router; +} + +/** The async port the host calls, over ownership.ts's pure functions (#57). */ +export function ownershipPortFrom(deps: OwnershipDeps): OwnershipPort { + return { + verifyAccount: idToken => verifyAccount(deps, idToken), + resolveDeck: (account, tokenIds, opts) => resolveDeck(deps, account, tokenIds, opts), + collection: account => collection(deps, account), + }; } const MAX_LIVE_BYTES = 32 * 1024 * 1024; diff --git a/server/game/modes/classic.json b/server/game/modes/classic.json index a7d79ea..422fbab 100644 --- a/server/game/modes/classic.json +++ b/server/game/modes/classic.json @@ -1,24 +1,27 @@ { "schema": "wikideck.mode/2", - "id": "classic", "version": 1, - "name": "Classic", - "description": "The base WikiDeck rules with starter decks. Cards use their at-mint snapshot stats.", - "tags": [ - "base", - "starter" - ], - "engine": "editwar", + "engine": "duel", "rules": {}, + "id": "classic", + "name": "Classic", + "description": "The ranked duel: bring 40 cards you own (at most 4 of one article). 20 Notability each, Citations rise by 1 a turn to 10. Cards use their at-mint snapshot.", + "tags": [ + "ranked", + "constructed" + ], "cards": { "preset": "standard" }, "decks": { - "kind": "starter" + "kind": "constructed", + "minConfirmations": 3 }, "limits": { "maxConcurrentMatches": 32, "turnSeconds": 90, - "lobbyMinutes": 15 + "lobbyMinutes": 15, + "rated": true, + "accountsOnly": true } } diff --git a/server/game/modes/draft.json b/server/game/modes/draft.json index 13543c7..0a6ecd7 100644 --- a/server/game/modes/draft.json +++ b/server/game/modes/draft.json @@ -1,30 +1,29 @@ { "schema": "wikideck.mode/2", - "id": "draft", "version": 1, - "name": "Snake Draft", - "description": "Both players snake-draft 10-card decks from one shared, host-seeded pool of 30 preview cards, then play the base rules with a 4-card opening hand. Nobody brings cards, so everyone starts even.", + "engine": "duel", + "rules": {}, + "id": "draft", + "name": "Draft", + "description": "Both players must own 40 cards. 100 cards are drawn from both collections and snake-drafted into two 40-card decks, for this match only: nothing moves on-chain.", "tags": [ "draft", - "no-collection" + "collections" ], - "engine": "editwar", - "rules": { - "deckSize": 10, - "openingHand": 4 - }, "cards": { "preset": "standard" }, "decks": { "kind": "draft", - "source": "preview", - "poolSize": 30, - "pickSeconds": 30 + "source": "collections", + "poolSize": 100, + "pickSeconds": 20 }, "limits": { "maxConcurrentMatches": 16, "turnSeconds": 90, - "lobbyMinutes": 15 + "lobbyMinutes": 15, + "rated": false, + "accountsOnly": true } } diff --git a/server/game/modes/edit-war-draft.json b/server/game/modes/edit-war-draft.json new file mode 100644 index 0000000..5bec5b4 --- /dev/null +++ b/server/game/modes/edit-war-draft.json @@ -0,0 +1,30 @@ +{ + "schema": "wikideck.mode/2", + "id": "edit-war-draft", + "version": 1, + "name": "Edit War: Snake Draft", + "description": "Both players snake-draft 10-card decks from one shared, host-seeded pool of 30 preview cards, then play the base rules with a 4-card opening hand. Nobody brings cards, so everyone starts even.", + "tags": [ + "draft", + "no-collection" + ], + "engine": "editwar", + "rules": { + "deckSize": 10, + "openingHand": 4 + }, + "cards": { + "preset": "standard" + }, + "decks": { + "kind": "draft", + "source": "preview", + "poolSize": 30, + "pickSeconds": 30 + }, + "limits": { + "maxConcurrentMatches": 16, + "turnSeconds": 90, + "lobbyMinutes": 15 + } +} diff --git a/server/game/modes/edit-war-trending.json b/server/game/modes/edit-war-trending.json new file mode 100644 index 0000000..f89777b --- /dev/null +++ b/server/game/modes/edit-war-trending.json @@ -0,0 +1,30 @@ +{ + "schema": "wikideck.mode/2", + "id": "edit-war-trending", + "version": 1, + "name": "Edit War: Trending", + "description": "Live Wikipedia pageview trends matter both ways: cards get the live trend arrow (up at +25%, down at -25%, where the base rules ignore falls), plus +1 power per 25% rise and -1 per 25% fall, capped at 3 either way.", + "tags": [ + "live-data", + "starter" + ], + "engine": "editwar", + "rules": { + "trendUp": 25, + "trendDown": -25 + }, + "cards": { + "preset": "trending", + "percentPerPoint": 25, + "maxBonus": 3, + "penalise": true + }, + "decks": { + "kind": "starter" + }, + "limits": { + "maxConcurrentMatches": 32, + "turnSeconds": 90, + "lobbyMinutes": 15 + } +} diff --git a/server/game/modes/edit-war.json b/server/game/modes/edit-war.json new file mode 100644 index 0000000..f74a4b8 --- /dev/null +++ b/server/game/modes/edit-war.json @@ -0,0 +1,24 @@ +{ + "schema": "wikideck.mode/2", + "id": "edit-war", + "version": 1, + "name": "Edit War", + "description": "The base WikiDeck rules with starter decks. Cards use their at-mint snapshot stats.", + "tags": [ + "base", + "starter" + ], + "engine": "editwar", + "rules": {}, + "cards": { + "preset": "standard" + }, + "decks": { + "kind": "starter" + }, + "limits": { + "maxConcurrentMatches": 32, + "turnSeconds": 90, + "lobbyMinutes": 15 + } +} diff --git a/server/game/modes/trending.json b/server/game/modes/trending.json index 751d0f6..77dc3ae 100644 --- a/server/game/modes/trending.json +++ b/server/game/modes/trending.json @@ -1,30 +1,27 @@ { "schema": "wikideck.mode/2", - "id": "trending", "version": 1, + "engine": "duel", + "rules": {}, + "id": "trending", "name": "Trending", - "description": "Live Wikipedia pageview trends matter both ways: cards get the live trend arrow (up at +25%, down at -25%, where the base rules ignore falls), plus +1 power per 25% rise and -1 per 25% fall, capped at 3 either way.", + "description": "Bring 40 cards you own. Live Wikipedia pageview momentum, frozen when the match starts, marks rising articles Trending (DUEL_DESIGN). Unranked.", "tags": [ "live-data", - "starter" + "constructed" ], - "engine": "editwar", - "rules": { - "trendUp": 25, - "trendDown": -25 - }, "cards": { - "preset": "trending", - "percentPerPoint": 25, - "maxBonus": 3, - "penalise": true + "preset": "live" }, "decks": { - "kind": "starter" + "kind": "constructed", + "minConfirmations": 1 }, "limits": { "maxConcurrentMatches": 32, "turnSeconds": 90, - "lobbyMinutes": 15 + "lobbyMinutes": 15, + "rated": false, + "accountsOnly": true } } diff --git a/server/testnet/http.ts b/server/testnet/http.ts index 71ed2a6..08b5239 100644 --- a/server/testnet/http.ts +++ b/server/testnet/http.ts @@ -19,7 +19,6 @@ import { trustedProxies, operationsPort, startOperations } from '../operations.t import { accountVerifier, createAccountRouter } from '../account/router.ts'; import { AccountStore } from '../account/store.ts'; import { DexKeys, oidcConfig } from '../account/oidc.ts'; -import { collectionRouter } from '../game/collection.ts'; const root = fileURLToPath(new URL('../../', import.meta.url)); assertLaunchAllowed(); @@ -157,7 +156,7 @@ app.post('/p2p/transaction',workLimit,async(req,res)=>{ const oidc=oidcConfig(), dexKeys=new DexKeys(oidc), accounts=new AccountStore(resolve(dataDir,'accounts.sqlite')); const ownership={ledger,accounts,verifyIdToken:accountVerifier(oidc,dexKeys,accounts)}; app.use('/api/account',createAccountRouter({config:oidc,keys:dexKeys,store:accounts})); -app.use('/api/game/collection',collectionRouter(ownership)); +// GET /api/game/collection is mounted inside gameRouter (it shares the card identity store). app.use('/api/game',await (await import('../game/index.ts')).gameRouter({dataDir,enrichment:wikipediaEnrichment,ownership})); app.use(['/api','/p2p'],(_req,res)=>{res.status(404).json({error:'Unknown testnet endpoint'});}); app.use(express.static(resolve(root,'dist'))); diff --git a/tests/host-pvp-binding.test.ts b/tests/host-pvp-binding.test.ts new file mode 100644 index 0000000..79d8a1a --- /dev/null +++ b/tests/host-pvp-binding.test.ts @@ -0,0 +1,185 @@ +// host-pvp (#56) part 2: the duel binding, ChainCard → DuelCard, the ownership adapter and +// built-in duel modes. Uses docs/game/card-sample.json only: zero network calls. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import express from 'express'; +import { derive } from '../shared/duel/derive.ts'; +import { sampleInputs, type SampleCard } from '../shared/duel/sample.ts'; +import * as duelApi from '../shared/duel/index.ts'; +import { buildIdentity, toProfile } from '../server/game/identity.ts'; +import { toDuelCard, duelBinding } from '../server/game/duel-binding.ts'; +import { gameRouter, ownershipPortFrom } from '../server/game/index.ts'; +import { ModeHost } from '../server/game/host.ts'; +import { MatchStore } from '../server/game/store.ts'; +import { parseMode, MODE_SCHEMA_VERSION } from '../shared/game/modes.ts'; +import { loadModes } from '../server/game/config.ts'; +import type { ChainCard, EnginePort, OwnershipPort } from '../server/game/engine-port.ts'; + +const SAMPLE = (JSON.parse(readFileSync(new URL('../docs/game/card-sample.json', import.meta.url), 'utf8')) as { cards: SampleCard[] }).cards; + +/** A ChainCard as ownership.ts builds it from a block, here from a sample card. */ +function chainCard(s: SampleCard, owner = 'wallet'): ChainCard { + const { chain } = sampleInputs(s); + return { tokenId: chain.tokenId, owner, confirmations: 5, pageId: s.pageId, title: s.title, revisionId: s.revisionId, + article: { ...chain.article, url: `https://en.wikipedia.org/?curid=${s.pageId}` }, + statsSnapshot: { ...chain.statsSnapshot, revisionId: s.revisionId } }; +} + +test('host-pvp binding: toDuelCard uses the frozen identity, deterministically', () => { + const s = SAMPLE[0]!; + const card = chainCard(s); + const ident = buildIdentity({ tokenId: card.tokenId, pageId: s.pageId, title: s.title, revisionId: s.revisionId }, + { description: s.description, wikidataId: s.wikidataId, categories: s.categories, instanceOf: s.instanceOf } as any, + 'cache', new Date('2026-11-17T00:00:00Z')); + const identity = { get: (t: string) => (t === card.tokenId ? ident : undefined) }; + const a = toDuelCard(card, { identity }); + assert.deepEqual(a, derive(sampleInputs(s).chain, toProfile(ident) as any), 'same as derive(chain, frozen profile)'); + assert.deepEqual(toDuelCard(card, { identity }), a, 'deterministic'); + // A miss falls back to what the chain carries: still a legal card, no fetch. + const fallback = toDuelCard(card, {}); + assert.equal(fallback.pageId, s.pageId); + assert.ok(fallback.cost >= 1 && fallback.cost <= 6); + assert.throws(() => toDuelCard({ ...card, article: undefined }), /no on-chain article/); +}); + +test('host-pvp binding: the ownership adapter passes the account and options through', async () => { + const seen: unknown[] = []; + const deps = { + ledger: { nft: () => undefined, deck: () => ({ tip: 't', total: 0, next: null, nfts: [] }), summary: () => ({ tip: 't', height: 1 }) }, + accounts: { wallets: (sub: string) => { seen.push(sub); return []; } }, + verifyIdToken: async (t: string) => { if (t !== 'a.b.c') throw Object.assign(new Error('Token expired'), { status: 401 }); + return { sub: 'alice', issuer: 'https://dex.test', name: 'Alice', username: 'alice' }; }, + }; + const port: OwnershipPort = ownershipPortFrom(deps as any); + const acct = await port.verifyAccount('a.b.c'); + assert.equal(acct.sub, 'alice'); + await assert.rejects(port.verifyAccount('x.y.z'), (e: any) => e.status === 401); + assert.deepEqual(await port.collection(acct), []); + await assert.rejects(port.resolveDeck(acct, ['a'.repeat(64)], { deckSize: 40, maxCopiesPerPage: 4, minConfirmations: 1 }), + (e: any) => e.status >= 400 && e.status < 500); + assert.ok(seen.includes('alice')); +}); + +test('host-pvp binding: built-in duel modes parse; Edit War ids moved to edit-war*', () => { + const modes = loadModes({}); + assert.deepEqual(modes.map(m => [m.id, m.engine]), [['classic', 'duel'], ['draft', 'duel'], ['trending', 'duel'], ['edit-war', 'editwar']]); + const classic = modes[0]!; + assert.equal(classic.limits.rated, true); + assert.equal(classic.decks.kind, 'constructed'); + const draft = modes[1]!; + assert.ok(draft.decks.kind === 'draft' && draft.decks.source === 'collections' && draft.decks.poolSize >= 80); +}); + +test('host-pvp binding: duel modes are skipped (not fatal) when the build has no duel engine', async () => { + const hasEngine = typeof (duelApi as Record).duelEnginePort?.createMatch === 'function'; + const app = express(); + app.use('/api/game', await gameRouter({ dataDir: null, warmTrends: false, handleSignals: false, + env: { WIKIDECK_MODES: 'classic,edit-war', PUBLIC_ORIGIN: 'http://127.0.0.1:3101', WIKIDECK_GAME_PEERS: '' } })); + const server = app.listen(0); + try { + const list = await (await fetch(`http://127.0.0.1:${(server.address() as any).port}/api/game/modes`)).json(); + assert.deepEqual(list.modes.map((m: any) => m.mode.id), hasEngine ? ['classic', 'edit-war'] : ['edit-war']); + } finally { server.close(); } +}); + +const realPort = (duelApi as Record).duelEnginePort as EnginePort | undefined; + +test('host-pvp binding: two scripted players finish a hosted 40-card duel on the real engine', { skip: !realPort && 'duel engine alpha not merged yet' }, async () => { + const engine = duelBinding(realPort!); + const alice = SAMPLE.slice(0, 40).map(s => chainCard(s, 'wallet-alice')); + const bob = SAMPLE.slice(40, 80).map(s => chainCard(s, 'wallet-bob')); + const owned: Record = { alice, bob }; + const ownership: OwnershipPort = { + verifyAccount: async t => ({ sub: String(t), issuer: 'https://dex.test', name: String(t) }), + resolveDeck: async (a, ids) => (ids as string[]).map(id => { const c = owned[a.sub]!.find(x => x.tokenId === id); + if (!c) throw Object.assign(new Error('not yours'), { status: 403 }); return c; }), + collection: async a => owned[a.sub] ?? [], + }; + const mode = parseMode({ schema: MODE_SCHEMA_VERSION, engine: 'duel', id: 'classic', version: 1, name: 'Classic', description: 'x', + decks: { kind: 'constructed', minConfirmations: 1 }, limits: { rated: true } }); + const host = new ModeHost({ identity: { origin: 'http://node.test', operator: 'T' }, modes: [mode], engines: { duel: engine }, + ownership, store: new MatchStore(null) }); + const a = await host.createLobby('classic', { idToken: 'alice', deck: alice.map(c => c.tokenId) }); + const b = await host.join(a.lobbyId, { idToken: 'bob', deck: bob.map(c => c.tokenId) }); + await assert.rejects(host.join(a.lobbyId, { idToken: 'bob', deck: bob.map(c => c.tokenId) }), /no longer open/); + const tokens = [a.token, b.token]; + for (let i = 0; i < 4000; i++) { + const v = host.view(a.lobbyId, a.token) as any; + if (v.phase !== 'playing') break; + let moved = false; + for (const t of tokens) { + const sv = host.view(a.lobbyId, t) as any; + if (sv.legalActions?.length) { await host.act(a.lobbyId, t, sv.legalActions[i % sv.legalActions.length]); moved = true; break; } + } + assert.ok(moved, 'someone can always act'); + } + const end = host.view(a.lobbyId, a.token) as any; + assert.equal(end.phase, 'finished'); + const rec = host.matchRecord(end.matchId); + assert.equal(rec.decks[0]!.length, 40); + assert.equal(rec.engine, 'duel'); + // Anyone can audit: replaying the record reproduces the result. + const api = duelApi as Record; + if (typeof api.replay === 'function') { + const replayed = api.replay(rec.rules, rec.decks, rec.seed, rec.actions); + assert.equal(api.result(replayed)?.winner ?? null, rec.winner); + } +}); + +test('host-pvp binding: gameRouter mounts GET /collection when ownership deps are given', async () => { + const deps = { + ledger: { nft: () => undefined, deck: () => ({ tip: 't', total: 0, next: null, nfts: [] }), summary: () => ({ tip: 't', height: 1 }) }, + accounts: { wallets: () => [] }, + verifyIdToken: async (t: string) => { if (t !== 'a.b.c') throw Object.assign(new Error('Token expired'), { status: 401 }); + return { sub: 'alice', issuer: 'https://dex.test', name: 'Alice', username: 'alice' }; }, + }; + const app = express(); + app.use('/api/game', await gameRouter({ dataDir: null, warmTrends: false, handleSignals: false, ownership: deps as any, + env: { WIKIDECK_MODES: 'edit-war', PUBLIC_ORIGIN: 'http://127.0.0.1:3101', WIKIDECK_GAME_PEERS: '' } })); + const server = app.listen(0); + try { + const base = `http://127.0.0.1:${(server.address() as any).port}/api/game`; + assert.equal((await fetch(`${base}/collection`)).status, 401); + const ok = await fetch(`${base}/collection`, { headers: { authorization: 'Bearer a.b.c' } }); + assert.equal(ok.status, 200); + assert.deepEqual((await ok.json()).cards, []); + assert.equal((await fetch(`${base}/modes`)).status, 200, 'the game routes still answer'); + } finally { server.close(); } +}); + +/** server/wiki.ts's mint-time category(), reproduced for the sample (it is not exported). */ +function mintCategory(title: string, categories: string[]): string { + const text = `${title} ${categories.join(' ')}`.toLowerCase(); + if (/astronom|planet|space|galax|moon|star\b/.test(text)) return 'Space'; + if (/animal|plant|species|ocean|biolog|mollusc/.test(text)) return 'Nature'; + if (/births|deaths|people|scientist/.test(text)) return 'People'; + if (/physic|chem|math|science|technolog/.test(text)) return 'Science'; + if (/histor|ancient|archaeolog|empire/.test(text)) return 'History'; + return 'Culture'; +} + +test('host-pvp binding: without a frozen identity, cards are typed from on-chain data, not all Doctrine (night-review P1)', () => { + const types: Record = {}; + for (const s of SAMPLE) { + const c = chainCard(s); + (c.article as any).category = mintCategory(s.title, s.categories); + const d = toDuelCard(c, {}); + types[d.type] = (types[d.type] ?? 0) + 1; + assert.equal(d.typedBy, 'fallback'); + assert.equal(d.description, undefined, 'no fabricated short description'); + assert.ok(!d.connect.p31.includes(''), 'hints never become Connected keys'); + } + assert.ok((types.Doctrine ?? 0) < SAMPLE.length / 2, JSON.stringify(types)); + assert.ok((types.Figure ?? 0) >= 40, JSON.stringify(types)); + // The extract's first sentence wins over the category hint. + const s = SAMPLE[0]!; + const battle = chainCard(s); + (battle.article as any).extract = 'The Battle of Somewhere was a battle fought in 1548. It was long.'; + (battle.article as any).category = 'People'; + assert.equal(toDuelCard(battle, {}).type, 'Event'); + const pol = chainCard(s); + (pol.article as any).extract = 'Jane Doe is an American politician.'; + (pol.article as any).category = 'Culture'; + assert.equal(toDuelCard(pol, {}).type, 'Figure'); +}); diff --git a/tests/host-pvp-host.test.ts b/tests/host-pvp-host.test.ts index 795648a..1d5b957 100644 --- a/tests/host-pvp-host.test.ts +++ b/tests/host-pvp-host.test.ts @@ -342,3 +342,28 @@ test('host-pvp: seeded shuffle is deterministic and a permutation', () => { assert.notDeepEqual(seededShuffle(xs, 's'), seededShuffle(xs, 't')); assert.deepEqual([...seededShuffle(xs, 's')].sort((a, b) => a - b), xs); }); + +test('host-pvp: a slow seat spends its time bank before it times out', async () => { + let now = 1_000_000; + // Stub turns are simultaneous; a 10 s turn plus a 30 s bank, timeouts from the engine. + const timed: EnginePort = { ...duelStub, turnSeconds: () => 10, bankSeconds: () => 30, turnOf: (s: any) => s.turn, + timeoutAction: () => ({ type: 'play', card: 0 }) }; + const own = fakeOwnership(); + const host = new ModeHost({ identity, modes: [duelMode()], engines: { duel: timed }, ownership: own.port, + store: new MatchStore(null), now: () => now }); + const a = await host.createLobby('duel-classic', { idToken: 'id-alice', deck: deckOf('alice') }); + const b = await host.join(a.lobbyId, { idToken: 'id-bob', deck: deckOf('bob') }); + await host.act(a.lobbyId, a.token, (host.view(a.lobbyId, a.token) as any).legalActions[0]); // alice moves, bob stalls + const clock = (host.view(a.lobbyId, b.token) as any).clock; + assert.deepEqual(clock.bankMs, [30_000, 30_000]); + assert.equal(clock.turnMs, 15_000, 'turn timer includes 5 s network grace'); + now += 15_000 + 20_000; // past the turn timer, inside bob's bank + host.sweep(); + assert.equal((host.view(a.lobbyId, b.token) as any).state.turn, 0, 'bob is still on his bank'); + now += 11_000; // bank exhausted + host.sweep(); + const v = host.view(a.lobbyId, b.token) as any; + assert.equal(v.state.turn, 1, 'timeout applied'); + assert.equal(v.clock.bankMs[1], 0); + assert.equal(v.clock.bankMs[0], 30_000); +}); diff --git a/tests/modes-api.test.ts b/tests/modes-api.test.ts index bfd0628..e52e130 100644 --- a/tests/modes-api.test.ts +++ b/tests/modes-api.test.ts @@ -44,16 +44,16 @@ async function playToEnd(base: string, lobby: string, tokens: string[]) { } test('modes api: three example modes over HTTP with the real engine', { timeout: 60_000 }, async () => { - const node = await serve({ WIKIDECK_MODES: 'classic,trending,draft', PUBLIC_ORIGIN: 'http://127.0.0.1:3101', + const node = await serve({ WIKIDECK_MODES: 'edit-war,edit-war-trending,edit-war-draft', PUBLIC_ORIGIN: 'http://127.0.0.1:3101', WIKIDECK_GAME_OPERATOR: 'Node A', WIKIDECK_GAME_PEERS: '' }, { get: async (pageId: number) => ({ pageviews: { trendPercent: pageId % 3 === 0 ? 80 : -30 } }) }); try { const list = (await call(node.base, '/api/game/modes')).json; ModeListSchema.parse(list); - assert.deepEqual(list.modes.map((m: any) => m.mode.id), ['classic', 'trending', 'draft']); + assert.deepEqual(list.modes.map((m: any) => m.mode.id), ['edit-war', 'edit-war-trending', 'edit-war-draft']); assert.equal(list.host.operator, 'Node A'); - for (const id of ['classic', 'trending']) { + for (const id of ['edit-war', 'edit-war-trending']) { const a = await call(node.base, `/api/game/modes/${id}/lobbies`, alice); assert.equal(a.status, 201); const b = await call(node.base, `/api/game/lobbies/${a.json.lobbyId}/join`, bob); @@ -71,7 +71,7 @@ test('modes api: three example modes over HTTP with the real engine', { timeout: } // Draft: 20 snake picks, 10-card decks. - const a = (await call(node.base, '/api/game/modes/draft/lobbies', alice)).json; + const a = (await call(node.base, '/api/game/modes/edit-war-draft/lobbies', alice)).json; const b = (await call(node.base, `/api/game/lobbies/${a.lobbyId}/join`, bob)).json; const tokens = [a.token, b.token]; let picks = 0; @@ -95,7 +95,7 @@ test('modes api: three example modes over HTTP with the real engine', { timeout: const after = (await call(node.base, '/api/game/modes')).json; assert.equal(after.matchesHosted, 3); - const board = (await call(node.base, '/api/game/modes/draft/leaderboard')).json; + const board = (await call(node.base, '/api/game/modes/edit-war-draft/leaderboard')).json; assert.equal(board.entries.length, 2); assert.equal((await call(node.base, '/api/game/modes/nope/leaderboard')).status, 404); assert.equal((await call(node.base, '/api/game/lobbies/zzz')).status, 404); @@ -103,15 +103,15 @@ test('modes api: three example modes over HTTP with the real engine', { timeout: }); test('modes api: a node lists its peers\' modes and ranks hosts by matches hosted', { timeout: 30_000 }, async () => { - const peerB = await serve({ WIKIDECK_MODES: 'draft,classic', PUBLIC_ORIGIN: 'http://b.invalid', WIKIDECK_GAME_OPERATOR: 'Node B' }); - const nodeA = await serve({ WIKIDECK_MODES: 'classic', PUBLIC_ORIGIN: 'http://a.invalid', WIKIDECK_GAME_OPERATOR: 'Node A', + const peerB = await serve({ WIKIDECK_MODES: 'edit-war-draft,edit-war', PUBLIC_ORIGIN: 'http://b.invalid', WIKIDECK_GAME_OPERATOR: 'Node B' }); + const nodeA = await serve({ WIKIDECK_MODES: 'edit-war', PUBLIC_ORIGIN: 'http://a.invalid', WIKIDECK_GAME_OPERATOR: 'Node A', WIKIDECK_GAME_PEERS: `${peerB.base},http://127.0.0.1:1`, WIKIDECK_ALLOW_PRIVATE_PEERS: '1' }); try { // One match on B so it leads the host leaderboard. - const a = (await call(peerB.base, '/api/game/modes/draft/lobbies', alice)).json; + const a = (await call(peerB.base, '/api/game/modes/edit-war-draft/lobbies', alice)).json; const b = (await call(peerB.base, `/api/game/lobbies/${a.lobbyId}/join`, bob)).json; await call(peerB.base, `/api/game/lobbies/${a.lobbyId}/resign`, {}, b.token); // during the draft: not a match - const c = (await call(peerB.base, '/api/game/modes/classic/lobbies', alice)).json; + const c = (await call(peerB.base, '/api/game/modes/edit-war/lobbies', alice)).json; const d = (await call(peerB.base, `/api/game/lobbies/${c.lobbyId}/join`, bob)).json; assert.equal((await call(peerB.base, `/api/game/lobbies/${c.lobbyId}/resign`, {}, d.token)).json.outcome.winner, 0); const resigned = (await call(peerB.base, `/api/game/lobbies/${c.lobbyId}`, undefined, c.token)).json; @@ -122,7 +122,7 @@ test('modes api: a node lists its peers\' modes and ranks hosts by matches hoste assert.equal(net.peers.length, 2); assert.equal(net.peers[0].ok, true); assert.equal(net.peers[0].list.host.origin, peerB.base, 'origin pinned to the fetched peer'); - assert.equal(net.peers[0].list.modes[0].mode.id, 'draft'); + assert.equal(net.peers[0].list.modes[0].mode.id, 'edit-war-draft'); assert.equal(net.peers[1].ok, false); const hosts = (await call(nodeA.base, '/api/game/hosts/leaderboard')).json.hosts; assert.deepEqual(hosts.map((h: any) => [h.operator, h.matchesHosted]), [['Node B', 1], ['Node A', 0]]);