Compare commits

..
Author SHA1 Message Date
claudeandClaude Opus 5.5 79041990ed duel-core: ConnectKeys qid/cites for claim-based Linked; seed secrecy rule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:10:16 -05:00
claudeandClaude Opus 5.5 5d5eaa5488 duel-core: adopt duel-cards card/effect shape and DUEL_DESIGN log kinds
Connected computed by the engine from frozen connect keys; tokens, fight,
multi-target plays, locationsPerTurn, timeoutsToConcede.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:49:52 -05:00
claudeandClaude Opus 5.5 4daf87edde duel-core: monotonic attack/block declarations; optional permanent counters
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:36:41 -05:00
claudeandClaude Opus 5.5 5365611c4a duel-core: shared/duel contracts (types, ruleset) and DUEL_API.md
Refs #55.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:35:37 -05:00
11 changed files with 637 additions and 612 deletions
+89
View File
@@ -0,0 +1,89 @@
# WikiDeck Duel: engine API (v1, Night 2)
Owner: **duel-core** (claude/wikideck#55). Rules: `docs/game/DUEL_DESIGN.md` (duel-design). This file: how code talks to the engine.
- Types: `shared/duel/types.ts`. Ruleset: `shared/duel/ruleset.ts`. Function surface: `DuelEngineApi` in `shared/duel/index.ts`, implemented by `shared/duel/engine.ts` (engine-alpha PR).
- `shared/game/` (Edit War) is untouched. Change requests: comment on #55 with `[from <agent>]`.
## Principles
- **Pure and deterministic.** `(rules, decks, seed, actions)` → identical state and log. RNG: `shared/game/rng.ts` (mulberry32); its uint32 state lives in `DuelState.rng`.
- **Plain JSON.** `DuelState` round-trips through `JSON.stringify`/`parse`; `serialize`/`deserialize` are thin wrappers.
- **Clone-on-apply.** `applyAction` never mutates its input and throws on an illegal action.
- **Atomic actions.** `legalActions(state, seat)` is small, and `[]` for the seat that is not to act. The host checks an action by deep-equal against that list (`concede` and `timeout` excepted).
- **Off-chain.** Matches never move or burn cards. Cards arrive derived and frozen; the engine does no I/O.
## Cards (`DuelCard`)
Built by duel-cards (`derive()`), frozen by the host at match start. Shape agreed with duel-cards on #55.
| Field | Notes |
|---|---|
| `cardId` | unique in a deck (NFT tokenId; sample id in sims; `token:` for tokens) |
| `pageId`, `revisionId?`, `title`, `description?` | `pageId` matches Linked pairs; `revisionId` for recap references |
| `type`, `subtype?` | `Figure` · `Location` · `Event` · `Institution` · `Doctrine` |
| `portal` | `Arts, Earth, History, Science, Society, Neutral`; no deckbuilding restriction |
| `cost` | 1–6 (Locations 1–3) |
| `power`, `toughness` | Figures: body. Locations: 0 / Garrison (0 = can't block). Others: `null` or 0 |
| `keywords` | ≤ `maxKeywords` (2). Figures only |
| `territory?` | Location: +N max Citations while controlled (total from all sources ≤ `territoryCap`) |
| `effects` | `EffectSpec[]` (below), ≤ 4 |
| `rulesText`, `flavor` | display only |
| `connect?` | `{countries, centuries, links, p31}` frozen claims; the engine computes Connected |
| `rarity?`, `deriveVersion?`, `token?` | |
### Keywords (DUEL_DESIGN §4), as the engine applies them
- **Protected**: can't be the target of Events or Doctrines an opponent controls (abilities of other permanents and combat still apply).
- **Featured**: can be blocked only by Featured, Translated or Multilingual Figures.
- **Multilingual**: can block Featured; can't be blocked by Local Figures.
- **Translated**: can block Featured.
- **Legacy**: when destroyed, its controller draws a card.
- **Well-sourced**: prevent the first 1 damage dealt to it each turn.
- **Stub**: at the start of your turn, a +1/+1 counter, up to `stubMax` (2).
- **Local**: +1/+1 while you control a Location sharing a `connect.countries` value.
- **Trending** (Trending mode, set by the host via `applyLive`): no Pending review, +`trendingPower`/+0.
### Effects (`EffectSpec`)
`{ trigger, op, target?, amount?, power?, toughness?, duration?, token?, condition?, grant?, template? }`
- **Triggers:** `onPlay` (Event resolves; on a permanent same as `onEnter`), `onEnter`, `onAttack`, `onDestroyed`, `startOfTurn`, `onCombatDamageToPlayer` (on a Figure, or on a Doctrine for its attached Figure), `static`.
- **Ops:** `damage`, `damageEach`, `createToken`, `pump`, `fight`, `draw`, `attach`, `gainLife`, `drain`, `destroy`, `bounce`, `tap`.
- **Targets:** chosen: `figure`, `figureOrLocation`, `ownFigure`, `opponentFigure`, `anyTarget`; automatic: `each`, `self`, `attached`, `ownFigures`, `opponentFigures`, `opponent`, `controller`. Defaults: damage → `anyTarget`, pump → `self`, draw/gainLife/createToken → `controller`, drain → `opponent`.
- **Chosen targets:** each `onPlay`/`onEnter` effect with a chosen target consumes the next entry of `play.targets`, in effect order; `legalActions` enumerates the combinations. An Event or Doctrine with no legal target can't be played; a Figure/Location/Institution enters and its targeted effect fizzles (`targets` omitted).
- **fight:** the previous chosen target in the same card (else the source permanent) and this target deal damage equal to their power to each other. T6 = `[{op:'pump', target:'ownFigure', power:k, toughness:0}, {op:'fight', target:'opponentFigure'}]`.
- **Doctrine:** its `attach` effect's target is the Figure it attaches to (`ownFigure` for T11, `figure` for T12). Its `static` effects with `target: 'attached'` apply to that Figure; `condition.samePortal` on a Doctrine means "other Figures you control of the attached Figure's Portal". When the Figure leaves, the Doctrine is Deleted.
- **static pump** applies while the source is in play; conditions use **printed** power (no feedback loops). `condition.connected` = the affected Figure is Connected to the source (T9).
- **createToken:** `amount` tokens of `token` (a fresh `DuelCard` with `token: true`, uid `t:<n>`); `condition.maxTokens` = only if you control fewer tokens than that. Tokens leaving play cease to exist.
- Triggers resolve immediately: the active player's first, then in entry order.
## Rules (defaults: `DEFAULT_DUEL_RULESET`; details in DUEL_DESIGN §2)
- 40-card decks (`deckSize`), ≤ 4 per `pageId`, unique `cardId`s, no tokens. 20 Notability. Drawing from an empty library loses (`libraryEmpty: 'lose'`; `'reshuffle'` and `'fatigue'` exist as data).
- Opening hand 7. Up to `mulligans` (1): shuffle in, draw 7, then on `keep` put one card per mulligan on the bottom (the last in hand order). Seat 0 decides first, then seat 1.
- First player (from the seed) skips their first draw.
- **Turn:** refresh (base max +1 to 10, plus Territory ≤ 2; refill; untap; Pending review ends; Stub and `startOfTurn` triggers) → draw → **main** → **attack** → **block** → damage → end (damage and "until end of turn" clear; discard down to `handSize` 7, **highest cost first**, automatically).
- Locations: `locationsPerTurn` (1), can't attack. Garrison Locations (toughness > 0) block as 0-power.
- Combat: attack the opponent only; each blocker blocks one attacker, at most one blocker per attacker; simultaneous damage; destroy triggers after all combat damage. No trample, first strike, stack or instants.
- **Connected** (engine, from `connect`, tiers in `connectedTiers`): Linked (either `links` contains the other's `pageId`, or either `cites` contains the other's `qid`), Compatriot (shared country), Contemporary (shared century, different types), Kin (shared P31, not Q5/Q16521). A Figure gets the single best bonus among other permanents its controller controls: `+linkedBonus` (2) if Linked, else `+connectedBonus` (1). Logged once (`connected`). Opposing Connected pairs are logged once as `rivalry`.
- **Timeouts:** `timeout` passes (mulligan: keep; main/attack: end the turn without attacking; block: confirm current blocks). `timeoutsToConcede` (3) consecutive timeouts by one seat lose (`reason: 'timeout'`).
- `turnCap` (null by default): after that many total turns, higher Notability wins, then higher total power in play, then the second player.
## Phases and actions
| Phase | Who acts | Listed actions |
|---|---|---|
| `mulligan` | seat 0 until ready, then seat 1 | `keep`, `mulligan` |
| `main` | active | `play {uid, targets?}`, `endPhase` |
| `attack` | active | `toggleAttacker {uid}` (untapped, not Pending review, not yet declared), `confirmAttack` |
| `block` | defender | `block {blocker, attacker}` (unassigned blocker, unblocked attacker, evasion allowing), `confirmBlocks` |
| any | either seat | `concede` (not listed) |
| any | host, for the seat to act | `timeout` (not listed) |
Declarations are **monotonic** (no un-declare), so every turn has a bounded number of actions; UIs stage choices locally and send them on confirm. If the defender has no legal block, damage resolves at `confirmAttack` with no block phase. `confirmAttack` with no attackers ends the turn.
## Views and log
- `viewFor(state, seat): PlayerView`: your hand; the opponent's hand and library **sizes** only; both graveyards; the battlefield with current power/toughness, keywords and Connected badge; combat; `toAct`; `version`; `result`. Never the RNG or library order.
- **The seed is secret until the match ends.** `seed` plus the deck lists reproduce every shuffle, so the host never sends `seed` or `rng` (or the raw `DuelState`) to clients before `gameOver`. Live log rendering picks template variants from a derived `storySeed = sha256(seed + ':story')`.
- `state.log` is omniscient (server, and the recap after the match). Clients get **`logFor(state, seat)`**: the opponent's `draw` events have no `card`. Every other event is public information.
- Every event has `seq` and `turn`. `CardRef` carries `uid, cardId, title, pageId, type` plus `power`/`toughness` right after the event.
- Kinds (DUEL_DESIGN §10 names): `start, mulligan, keep, turnStart, draw, deploy, cast, adopt, tokenCreated, connected, rivalry, effect, attack, block, effectDamage, combatDamage, playerDamage, lifeGain, destroyed, bounced, discard, fatigue, concede, timeout, gameOver`. `destroyed` = the recap's casualties. Prose templates live with duel-design / ui-pvp, not in the engine.
## Host binding
`duelEnginePort` (engine.ts) is structurally an `EnginePort<DuelRuleset, DuelCard, DuelState, DuelAction>` (`server/game/engine-port.ts`; `shared/` doesn't import `server/`, so host-pvp types it there). `concedeAction`, `timeoutAction`, `turnSeconds`, `turnOf`, `applyLive` included. `starterDeck` and `previewPool` throw: there are no starters (BRIEF decision 2); draft pools come from both players' collections.
## Stability
These types are the contract for duel-cards, host-pvp, ui-duel, ui-pvp and sim-balance. Additive changes (optional fields, new log kinds) can land with the engine; breaking ones get a `[duel-core] contract change` comment on #55 first.
-67
View File
@@ -1,67 +0,0 @@
# Night 2 private testnet: how to test (testnet-ops, #63)
**Testnet only, LAN only, on poweredge-r350.** It is never mainnet and never the live `wikideck` namespace.
## Nodes
| node | URL | game modes (env from Night 1 #22) |
|---|---|---|
| node-a | http://192.168.1.32:3101 | classic, trending |
| node-b | http://192.168.1.32:3102 | draft |
| node-c | http://192.168.1.32:3103 | classic, draft, trending |
- **Autodeploy:** the nodes follow `night/2026-11-17`. A loop on r350 (`deploy/night/autodeploy.sh`, in a dedicated detached worktree) polls the branch every 3 min.
- On a new head it rebuilds the image and restarts node-a, then b, then c, each after the previous one passes `/healthz`.
- While any match or lobby is live it defers, for up to 15 min.
- Lobbies are in memory, so a deploy that does go through ends games in progress. After night-lead merges, wait about 5 min, or check that all three nodes report the new head, before you start an end-to-end run.
- Ledgers persist in the Docker volumes across deploys.
## Test wallets
Four disposable wallets: **alice**, **bob**, **carol** and **dave**.
| wallet | address | cards (confirmed) |
|---|---|---|
| alice | `ff9273368c225698d8ae34430800cfe30b10a1c3d8c21091d42960493db556df` | see #63 |
| bob | `80f17f10ca782efd16783d10d71ce43b2993aadccda36dbd0364dee1921cbc22` | see #63 |
| carol | `f2d908633c4313bd77e86650c13d11ac3e7e656223ebe881cc34ffba3f3e0524` | leftovers |
| dave | `02bb97f202e1616ab97b45e8938e384dcbf622a0b44a7f4c1589f44236d3ccef` | leftovers |
- Confirmed at height 91: **alice 41, bob 40**, carol 5, dave 5. Block #92 came from the Android emulator (#59).
- alice and bob were consolidated to 40 cards each with on-chain NFT transfers from carol and dave, so **production `deckSize` 40 works on the testnet** and no lower-deckSize test mode is needed.
- **The encrypted browser backups are in a comment on #63**, not in git.
- Backup password: `wikideck-night-testnet`. It is **public and testnet-only**: never reuse it, and never put a real secret next to it.
- Anyone who can read this repo's issues can open these wallets. Keep them on the LAN-only testnet, and never send them anything of value.
- Re-check counts at any time: `GET http://192.168.1.32:3101/api/decks/<address>?offset=0&limit=24` (pages of 24, follow `next`).
### Load a wallet in the browser
**First make the node origins a secure context** (found by night-review on #63).
- `http://192.168.1.32:310x` is plain HTTP on a LAN address, so the browser leaves `crypto.subtle` undefined. Open wallet then fails with "Cannot read properties of undefined (reading 'digest')" or "Wallet storage unavailable".
- **Chrome/Chromium:** open `chrome://flags/#unsafely-treat-insecure-origin-as-secure`, add `http://192.168.1.32:3101,http://192.168.1.32:3102,http://192.168.1.32:3103`, then relaunch.
- **Command line:** `--unsafely-treat-insecure-origin-as-secure=http://192.168.1.32:3101,http://192.168.1.32:3102,http://192.168.1.32:3103 --user-data-dir=<fresh profile dir>`.
- **Playwright:** use the full `chromium` channel. The headless shell ignores this flag.
- **SSH tunnel to `localhost`:** this also works for the wallet, but it breaks the Dex callback URLs, so you can't do the login/link step that way.
- **Firefox** has no per-origin equivalent.
Use a separate browser profile per player, because a browser holds one wallet per origin.
1. Open a node URL, then **Open wallet**.
2. **Recover from a local backup**: choose the backup JSON file (save it from the #63 comment as `alice.backup.json`), and enter the backup password above.
3. Set a new local encryption password (at least 12 characters, anything testnet-only), then confirm it.
4. The wallet dialog should show the address above and its confirmed card count.
### eom.dev login (Dex)
- There is no new Dex config tonight. The existing `wikideck` client already allows the 3101–3103 callbacks.
- Log in with **Log in with eom.dev**, then unlock the wallet and press **Link wallet …** to link it to the account.
- PvP seats are keyed to the account, and ownership is checked on the server against the account's linked wallets. So for a two-player run you need **two eom.dev accounts**, one with alice linked and one with bob. Which accounts to use is night-lead's call (see #53/#63). Never use a real person's account without their OK.
## Mining on the testnet
- Mining isn't needed for tests. Only run a miner if night-lead asks for more blocks, or to confirm transfers.
- `deploy/night/testnet.sh mine N [workers]` runs the native multi-worker miner in a container named `wikideck-night-miner` (at most 4 workers on r350).
- Every template costs Wikipedia requests on the node, so it is paced by `MIN_GAP`.
- **testnet-ops stops any miner by 01:55** (`docker rm -f wikideck-night-miner`). The nodes stay up.
- **Difficulty (for mobile mining, #59):** at block ~90, an accepted block took between about 2 K and 130 K hashes. That is up to ~8 min at the 4-worker r350 rate of ~250 H/s. One light-mode thread on the emulator is far slower, so expect a long wait per block, with high variance.
## Card identity pre-bake (engineer WS E)
- `server/game/identity.ts` is a persistent per-token store (`node:sqlite`). It freezes each card's off-chain identity at first sight and never rewrites it. The identity covers P31/P279 classes, description, categories, countries, years, coordinates and outlink pageIds. Its fields match duel-cards' `CardProfile` (#70), and `toProfile()` returns that view.
- `scripts/night2/prebake-identity.ts --node <url> [--store <file>] [--cards <cached.json> ...]` reads the canonical chain from one node and freezes what the cached card files know. The store defaults to `$WIKIDECK_DATA_DIR/card-identity.sqlite` (`identityStoreFile()`), and hosts should open it at the same path.
- It **never calls Wikimedia itself**.
- Live facts arrive only through the wikimedia team's client on its `background` lane (#62), once that client has merged.
- Cards that are still unknown stay unfrozen and are retried on a later run.
-56
View File
@@ -1,56 +0,0 @@
// testnet-ops (engineer WS E): pre-bake frozen card identities for every card on a chain.
//
// node --experimental-strip-types scripts/night2/prebake-identity.ts --node http://192.168.1.32:3101 \
// --store $WIKIDECK_DATA_DIR/card-identity.sqlite [--cards docs/game/card-sample.json] [--batch 50]
//
// - Reads the canonical chain from ONE node (GET /api/summary, then /api/canonical pages), so every
// card is built from its mint block, never from client JSON.
// - Facts come ONLY from cached card files (`--cards`, repeatable). This script never calls
// Wikipedia or Wikidata itself. Live facts must go through the wikimedia team's process-wide client
// on its `background` lane (server/wikimedia, #62); that IdentitySource plugs into `prebake()` in
// server/game/identity.ts once it has merged. Until then, unknown cards are left unfrozen and are
// picked up by a later run.
// - Idempotent and freeze-at-first-sight: already frozen tokens are skipped and never rewritten.
import { readFileSync } from 'node:fs';
import { parseArgs } from 'node:util';
import { IdentityStore, cachedSource, identityStoreFile, prebake, type ChainArticle } from '../../server/game/identity.ts';
const { values } = parseArgs({ options: {
node: { type: 'string', default: 'http://192.168.1.32:3101' },
store: { type: 'string', default: identityStoreFile() },
cards: { type: 'string', multiple: true, default: ['docs/game/card-sample.json'] },
batch: { type: 'string', default: '50' },
} });
const nodeUrl = new URL(values.node!);
if (!['http:', 'https:'].includes(nodeUrl.protocol)) throw new Error('--node must be an http(s) WikiDeck node URL');
if (/wikipedia\.org|wikidata\.org|wikimedia\.org/i.test(nodeUrl.hostname)) throw new Error('--node must be a WikiDeck node, not Wikimedia');
async function get<T>(path: string): Promise<T> {
const r = await fetch(new URL(path, nodeUrl), { signal: AbortSignal.timeout(30000), redirect: 'error' });
if (!r.ok) throw new Error(`${path}: HTTP ${r.status}`);
return await r.json() as T;
}
type Block = { tokenId: string; article: { pageId: number; title: string; revisionId?: number } };
async function chainArticles(): Promise<ChainArticle[]> {
const { tip } = await get<{ tip: string }>('/api/summary');
const out: ChainArticle[] = [];
for (let offset: number | null = 0; offset !== null;) {
const page: { blocks: Block[]; next: number | null } = await get(`/api/canonical?tip=${tip}&offset=${offset}&limit=16`);
for (const b of page.blocks) if (b.article && b.tokenId)
out.push({ tokenId: b.tokenId, pageId: b.article.pageId, title: b.article.title, revisionId: b.article.revisionId ?? null });
offset = page.next;
}
return out;
}
const cards = values.cards!.flatMap(f => {
const d = JSON.parse(readFileSync(f, 'utf8'));
return Array.isArray(d) ? d : d.cards ?? [];
});
const articles = await chainArticles();
const store = new IdentityStore(values.store!);
try {
const report = await prebake(store, cachedSource(cards), articles, { batchSize: Number(values.batch) });
console.log(JSON.stringify({ node: nodeUrl.origin, chainCards: articles.length, cachedCards: cards.length, ...report, stored: store.count() }));
} finally { store.close(); }
-113
View File
@@ -1,113 +0,0 @@
// Live IdentitySource for server/game/identity.ts (engineer WS E, data §3).
//
// Every request goes through the process-wide polite Wikimedia client on the **background** lane:
// - the page enrichment (description, wikidataId, categories) via `enrichment.getBackground()`,
// which also feeds the disk cache card faces use;
// - one `wbgetentities&props=claims` per batch of at most 50 items;
// - one `wbgetentities&props=labels` per 50 class ids still missing a label.
// That is about 2 Wikidata requests per 50 new cards, plus one cached enrichment per card.
// Outlinks (prop=links, data §4) are not fetched tonight: they cost about 1.2 requests per card,
// and Connected falls back to its other tiers without them.
//
// The profile itself is built by duel-cards' pure `profileFromSources()` (shared/duel/profile.ts, #70),
// so the frozen identity and what derive() reads cannot drift apart. That module, and the client
// (server/wikimedia, #73), are injected structurally, so this file has no import from unmerged PRs.
// Wiring, once both have merged:
// wikimediaIdentitySource({ client: wikimediaClient, enrichment: wikipediaEnrichment,
// profile: await import('../../shared/duel/profile.ts') })
// Any transport failure leaves the affected cards unknown (undefined), so they are retried later,
// never frozen half-empty.
import type { PageEnrichment } from '../../shared/enrichment.ts';
import type { ChainArticle, IdentityFacts, IdentitySource, WikidataClass } from './identity.ts';
/** Structural slices of server/wikimedia/client.ts (#73) and shared/duel/profile.ts (#70). */
export type BackgroundRequest = { lane: 'background'; timeoutMs: number; cache?: { ttlMs: number; maxBytes?: number } };
export type WikidataEntity = { id?: string; claims?: Record<string, readonly {
rank?: string; mainsnak?: { snaktype?: string; datavalue?: { type?: string; value?: unknown } } }[]> };
export type ProfileLike = { wikidataId: string | null; description: string | null; categories: readonly string[];
instanceOf: readonly WikidataClass[]; subclassOf?: readonly WikidataClass[]; countries?: readonly string[];
years?: readonly number[]; died?: boolean; links?: readonly number[]; cites?: readonly string[]; fetchedRevisionId?: number };
export type ProfileBuilder = {
wikidataEntityParams(qids: readonly string[]): Record<string, string>;
wikidataLabelParams(qids: readonly string[]): Record<string, string>;
classIdsOf(entity: WikidataEntity | null | undefined): string[];
profileFromSources(src: { enrichment: PageEnrichment; entity?: WikidataEntity | null; labels?: Readonly<Record<string, string>> }): ProfileLike;
};
export type IdentitySourceDeps = {
enrichment: { getBackground(pageId: number): Promise<PageEnrichment> };
client: { request(url: URL, options: BackgroundRequest): Promise<{ response: Response }> };
profile: ProfileBuilder;
};
const WIKIDATA_API = 'https://www.wikidata.org/w/api.php';
const MAX_BYTES = 4 * 1024 * 1024;
const CACHE = { ttlMs: 7 * 24 * 60 * 60 * 1000, maxBytes: MAX_BYTES };
async function wikidata(client: IdentitySourceDeps['client'], params: Record<string, string>): Promise<Record<string, unknown>> {
const url = new URL(WIKIDATA_API);
for (const [k, v] of Object.entries(params)) url.searchParams.set(k, v);
const { response } = await client.request(url, { lane: 'background', timeoutMs: 15000, cache: CACHE });
if (!response.ok) { await response.body?.cancel(); throw new Error(`Wikidata HTTP ${response.status}`); }
const text = await response.text();
if (text.length > MAX_BYTES) throw new Error('Wikidata response too large');
const body = JSON.parse(text) as { entities?: Record<string, unknown> | unknown[] };
const entities = body.entities ?? {};
// formatversion=2 returns an object keyed by id; tolerate an array too.
return Array.isArray(entities)
? Object.fromEntries(entities.filter(e => e && typeof (e as { id?: unknown }).id === 'string').map(e => [(e as { id: string }).id, e]))
: entities as Record<string, unknown>;
}
const chunks = <T>(xs: T[], n: number) => Array.from({ length: Math.ceil(xs.length / n) }, (_, i) => xs.slice(i * n, i * n + n));
export function wikimediaIdentitySource(deps: IdentitySourceDeps): IdentitySource {
const { classIdsOf, profileFromSources, wikidataEntityParams, wikidataLabelParams } = deps.profile;
return {
kind: 'wikimedia',
async lookup(articles: ChainArticle[]) {
const out = new Map<number, IdentityFacts | undefined>(articles.map(a => [a.pageId, undefined]));
// 1. Enrichment, one page at a time (the client paces it); failures stay unknown.
const enriched = new Map<number, PageEnrichment>();
for (const a of articles) {
try { enriched.set(a.pageId, await deps.enrichment.getBackground(a.pageId)); } catch { /* retry later */ }
}
// 2. Claims for every item we know, in batches of ≤ 50.
const qids = [...new Set([...enriched.values()].map(e => e.wikidataId).filter((q): q is string => !!q && /^Q\d+$/.test(q)))];
const entities = new Map<string, WikidataEntity>();
let claimsFailed = false;
for (const batch of chunks(qids, 50)) {
try { for (const [id, e] of Object.entries(await wikidata(deps.client, wikidataEntityParams(batch)))) entities.set(id, e as WikidataEntity); }
catch { claimsFailed = true; }
}
// 3. English labels for the P31/P279 classes.
const classIds = [...new Set([...entities.values()].flatMap(e => classIdsOf(e)))];
const labels: Record<string, string> = {};
let labelsFailed = false;
for (const batch of chunks(classIds, 50)) {
try {
for (const [id, e] of Object.entries(await wikidata(deps.client, wikidataLabelParams(batch)))) {
const v = (e as { labels?: { en?: { value?: unknown } } }).labels?.en?.value;
if (typeof v === 'string') labels[id] = v;
}
} catch { labelsFailed = true; }
}
// 4. Freeze only complete profiles: a card whose item couldn't be read stays unknown.
for (const a of articles) {
const e = enriched.get(a.pageId);
if (!e) continue;
const qid = e.wikidataId && /^Q\d+$/.test(e.wikidataId) ? e.wikidataId : null;
const entity = qid ? entities.get(qid) : null;
if (qid && !entity && claimsFailed) continue; // item not read: retry later
if (entity && labelsFailed) continue; // class labels not read: retry later
const p = profileFromSources({ enrichment: e, entity: entity ?? null, labels });
out.set(a.pageId, {
fetchedRevisionId: p.fetchedRevisionId ?? null, wikidataId: p.wikidataId, description: p.description,
categories: [...p.categories], instanceOf: [...p.instanceOf], subclassOf: [...(p.subclassOf ?? [])],
countries: [...(p.countries ?? [])], years: [...(p.years ?? [])], died: p.died === true,
links: [...(p.links ?? [])], cites: [...(p.cites ?? [])],
});
}
return out;
},
};
}
-204
View File
@@ -1,204 +0,0 @@
// Card identity (engineer WS E, data review §3): the off-chain, mutable facts about a card's article
// (P31/P279 classes, a few Wikidata claims, categories, outlinks) frozen ONCE per tokenId, the first time
// the card is seen, so that a later Wikipedia/Wikidata edit can never retype a card someone owns.
//
// - On-chain data (article, statsSnapshot) stays the source of truth for everything it covers.
// - Identities are never fetched at match time. They are pre-baked in the background
// (scripts/night2/prebake-identity.ts), from cached data or through an injected IdentitySource that
// must use the process-wide Wikimedia client on its `background` lane. This file performs no I/O
// besides the sqlite store and never calls fetch itself.
// - First write wins: `freeze` never overwrites an existing record (data §3 "freeze at first sight").
import { DatabaseSync } from 'node:sqlite';
import { createHash } from 'node:crypto';
import { join, resolve } from 'node:path';
export const IDENTITY_VERSION = 1;
/** Where hosts keep the store: next to the ledger, `$WIKIDECK_DATA_DIR/card-identity.sqlite` (default ./data). */
export function identityStoreFile(env: NodeJS.ProcessEnv = process.env): string {
return join(env.WIKIDECK_DATA_DIR ?? resolve('data'), 'card-identity.sqlite');
}
/** Same shape as shared/duel/classify.ts `WikidataClass` (duel-cards, #70). */
export type WikidataClass = { id: string; label: string };
/**
* A frozen card identity. Its profile fields are structurally the `CardProfile` that duel-cards'
* `derive()` reads (shared/duel/classify.ts), so `toProfile(identity)` can be passed straight in.
*/
export type CardIdentity = {
version: typeof IDENTITY_VERSION;
tokenId: string;
pageId: number;
title: string;
/** article.revisionId from the mint block. */
mintRevisionId: number | null;
/** The live revision the off-chain facts were read from (data §3; may differ from the mint revision). */
fetchedRevisionId: number | null;
wikidataId: string | null;
wikidataRev: number | null;
/** Wikipedia short description. */
description: string | null;
/** Non-hidden category titles without the "Category:" prefix, sorted. */
categories: string[];
/** P31 (instance of). */
instanceOf: WikidataClass[];
/** P279 of the item, or its P31 classes' superclasses, nearest first. */
subclassOf: WikidataClass[];
/** P17 / P27 country Q-ids, sorted. */
countries: string[];
/** Years from P569/P570/P571/P580/P585 (negative = BCE), sorted. */
years: number[];
/** P570 (date of death) present. */
died: boolean;
/** P625 or prop=coordinates, [lat, lon]. */
coords: [number, number] | null;
/** ns0 outlinks as pageIds, sorted, deduplicated (Connected, Linked tier). Empty when unknown. */
links: number[];
/** Item Q-ids cited by the frozen claims (P17, P27, P131, P361, P106, ...). */
cites: string[];
/** sha256 of `links`, so match records can log a short fingerprint. */
linksHash: string;
/** Where the facts came from: an offline cache (e.g. card-sample.json) or a live background fetch. */
source: 'cache' | 'wikimedia';
frozenAt: string;
};
/** What a source knows about an article; any field may be missing. */
export type IdentityFacts = Partial<Pick<CardIdentity, 'fetchedRevisionId' | 'wikidataId' | 'wikidataRev' | 'description'
| 'categories' | 'instanceOf' | 'subclassOf' | 'countries' | 'years' | 'died' | 'coords' | 'links' | 'cites'>>;
/** The minimum the chain tells us about a card (built from its mint block, never from client JSON). */
export type ChainArticle = { tokenId: string; pageId: number; title: string; revisionId?: number | null };
/**
* A source of identity facts. A live implementation must route every request through the shared
* Wikimedia client on the background lane (never the mint or interactive lanes) and batch where it
* can. Returning `undefined` for a page means "unknown for now": nothing is frozen and it is retried
* on a later run.
*/
export interface IdentitySource {
readonly kind: CardIdentity['source'];
lookup(articles: ChainArticle[]): Promise<Map<number, IdentityFacts | undefined>>;
}
export function linksHash(links: readonly number[]): string {
return createHash('sha256').update(JSON.stringify(links)).digest('hex');
}
const QID = /^Q\d+$/;
const uniqStrings = (xs: readonly unknown[] | undefined) => [...new Set((xs ?? []).filter((x): x is string => typeof x === 'string'))].sort();
const uniqInts = (xs: readonly unknown[] | undefined) =>
[...new Set((xs ?? []).filter((x): x is number => Number.isSafeInteger(x)))].sort((a, b) => a - b);
const classes = (xs: readonly WikidataClass[] | undefined) =>
(xs ?? []).filter(c => c && QID.test(c.id)).map(c => ({ id: c.id, label: typeof c.label === 'string' ? c.label : '' }));
/** Pure: build a frozen identity from chain data plus whatever facts a source returned. */
export function buildIdentity(article: ChainArticle, facts: IdentityFacts, source: CardIdentity['source'], now: Date): CardIdentity {
const links = uniqInts(facts.links);
const coords = facts.coords && facts.coords.length === 2 && facts.coords.every(Number.isFinite) ? [facts.coords[0], facts.coords[1]] as [number, number] : null;
return {
version: IDENTITY_VERSION,
tokenId: article.tokenId,
pageId: article.pageId,
title: article.title,
mintRevisionId: article.revisionId ?? null,
fetchedRevisionId: facts.fetchedRevisionId ?? null,
wikidataId: facts.wikidataId && QID.test(facts.wikidataId) ? facts.wikidataId : null,
wikidataRev: facts.wikidataRev ?? null,
description: typeof facts.description === 'string' ? facts.description : null,
categories: uniqStrings(facts.categories),
instanceOf: classes(facts.instanceOf),
subclassOf: classes(facts.subclassOf),
countries: uniqStrings(facts.countries),
years: uniqInts(facts.years),
died: facts.died === true,
coords,
links,
cites: uniqStrings(facts.cites).filter(q => QID.test(q)),
linksHash: linksHash(links),
source,
frozenAt: now.toISOString(),
};
}
/** The duel-cards `CardProfile` view of an identity (structural; no import, so no stacked PR). */
export function toProfile(i: CardIdentity) {
return { wikidataId: i.wikidataId, description: i.description, categories: i.categories, instanceOf: i.instanceOf,
subclassOf: i.subclassOf, countries: i.countries, years: i.years, died: i.died, links: i.links, cites: i.cites,
...(i.fetchedRevisionId != null ? { fetchedRevisionId: i.fetchedRevisionId } : {}) };
}
/** Persistent per-token identity store. Records are immutable once written. */
export class IdentityStore {
readonly #db: DatabaseSync;
constructor(file: string) {
this.#db = new DatabaseSync(file);
this.#db.exec(`CREATE TABLE IF NOT EXISTS card_identity (
token_id TEXT PRIMARY KEY, page_id INTEGER NOT NULL, version INTEGER NOT NULL, body TEXT NOT NULL)`);
}
get(tokenId: string): CardIdentity | undefined {
const row = this.#db.prepare('SELECT body FROM card_identity WHERE token_id = ?').get(tokenId) as { body: string } | undefined;
return row ? JSON.parse(row.body) as CardIdentity : undefined;
}
has(tokenId: string): boolean { return this.get(tokenId) !== undefined; }
/** Freeze at first sight: returns the stored record, which is the earlier one if it already existed. */
freeze(identity: CardIdentity): CardIdentity {
this.#db.prepare('INSERT OR IGNORE INTO card_identity (token_id, page_id, version, body) VALUES (?, ?, ?, ?)')
.run(identity.tokenId, identity.pageId, identity.version, JSON.stringify(identity));
return this.get(identity.tokenId)!;
}
/** Freeze several in one transaction (one fsync per batch, not per card). */
freezeMany(identities: CardIdentity[]): void {
this.#db.exec('BEGIN');
try { for (const i of identities) this.freeze(i); this.#db.exec('COMMIT'); }
catch (e) { this.#db.exec('ROLLBACK'); throw e; }
}
count(): number { return (this.#db.prepare('SELECT COUNT(*) AS n FROM card_identity').get() as { n: number }).n; }
all(): CardIdentity[] {
return (this.#db.prepare('SELECT body FROM card_identity ORDER BY token_id').all() as { body: string }[]).map(r => JSON.parse(r.body));
}
close() { this.#db.close(); }
}
export type PrebakeReport = { seen: number; alreadyFrozen: number; frozen: number; unknown: number };
/**
* Freeze identities for every card not yet in the store, asking the source in batches. The caller
* controls pacing (batch size, and the source's client controls request rate).
*/
export async function prebake(store: IdentityStore, source: IdentitySource, articles: ChainArticle[],
opts: { batchSize?: number; now?: () => Date } = {}): Promise<PrebakeReport> {
const batchSize = Math.max(1, Math.min(50, opts.batchSize ?? 50)), now = opts.now ?? (() => new Date());
const seenTokens = new Set<string>(), todo: ChainArticle[] = [];
let alreadyFrozen = 0;
for (const a of articles) {
if (seenTokens.has(a.tokenId)) continue;
seenTokens.add(a.tokenId);
if (store.has(a.tokenId)) alreadyFrozen++; else todo.push(a);
}
let frozen = 0, unknown = 0;
for (let i = 0; i < todo.length; i += batchSize) {
const batch = todo.slice(i, i + batchSize), facts = await source.lookup(batch), ready = [];
for (const a of batch) {
const f = facts.get(a.pageId);
if (!f) { unknown++; continue; }
ready.push(buildIdentity(a, f, source.kind, now()));
}
store.freezeMany(ready); frozen += ready.length;
}
return { seen: seenTokens.size, alreadyFrozen, frozen, unknown };
}
/** Offline source: facts from an already-cached card file such as docs/game/card-sample.json. */
export function cachedSource(cards: readonly { pageId: number; wikidataId?: string | null; revisionId?: number | null;
description?: string | null; instanceOf?: WikidataClass[]; categories?: string[] }[]): IdentitySource {
const byPage = new Map(cards.map(c => [c.pageId, c]));
return {
kind: 'cache',
async lookup(articles) {
return new Map(articles.map(a => {
const c = byPage.get(a.pageId);
return [a.pageId, c ? { fetchedRevisionId: c.revisionId ?? null, wikidataId: c.wikidataId ?? null,
description: c.description ?? null, instanceOf: c.instanceOf ?? [], categories: c.categories ?? [] } : undefined];
}));
},
};
}
+35
View File
@@ -0,0 +1,35 @@
/**
* WikiDeck Duel public API. Spec: docs/game/DUEL_API.md.
* Contracts PR: types and ruleset only. engine.ts (createDuel, legalActions,
* applyAction, viewFor, logFor, replay, ...) lands in the engine alpha PR and
* implements DuelEngineApi below; build against that interface until then.
*/
export * from './types.ts';
export * from './ruleset.ts';
import type { DuelAction, DuelCard, DuelResult, DuelRuleset, DuelState, LogEvent, PlayerView, Seat } from './types.ts';
/** The engine's function surface (implemented by shared/duel/engine.ts). All pure; inputs are never mutated. */
export interface DuelEngineApi {
/** Throws if the deck is illegal: size ≠ deckSize, duplicate cardId, > maxCopiesPerPage of one pageId, bad stats, > maxKeywords. */
validateDeck(rules: DuelRuleset, cards: DuelCard[]): void;
/** Shuffle both decks from `seed`, deal opening hands, phase 'mulligan'. */
createDuel(rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string): DuelState;
/** Atomic legal actions for `seat`; [] if `seat` is not the one to act (concede is always accepted by applyAction but not listed). */
legalActions(state: DuelState, seat: Seat): DuelAction[];
/** Returns a new state. Throws on an illegal action. */
applyAction(state: DuelState, seat: Seat, action: DuelAction): DuelState;
/** Seat that must act now, or null when over. Mulligan: the lowest seat not yet ready. */
toAct(state: DuelState): Seat | null;
isOver(state: DuelState): boolean;
result(state: DuelState): DuelResult | null;
viewFor(state: DuelState, seat: Seat): PlayerView;
/** Per-seat log: the opponent's draws (and other hidden-zone cards) are masked. */
logFor(state: DuelState, seat: Seat): LogEvent[];
/** Deterministic: same inputs → identical state (and log). */
replay(rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string, actions: { seat: Seat; action: DuelAction }[]): DuelState;
serialize(state: DuelState): string;
deserialize(text: string): DuelState;
/** Current power/toughness of a permanent after counters, buffs, statics and Connected. */
statsOf(state: DuelState, uid: string): { power: number; toughness: number };
}
+76
View File
@@ -0,0 +1,76 @@
/**
* Duel ruleset: every rule number as data (BRIEF "Game rules core").
* parseDuelRuleset() is the only way untrusted JSON (mode files, peer hosts)
* becomes a DuelRuleset. Night 1 Edit War rulesets are rejected cleanly.
*/
import { z } from 'zod';
import type { DuelRuleset } from './types.ts';
const int = (min: number, max: number) => z.number().int().min(min).max(max);
export const DuelRulesetSchema = z.object({
engine: z.literal('duel'),
version: z.string().min(1).max(16),
deckSize: int(1, 60),
maxCopiesPerPage: int(1, 60),
startingLife: int(1, 100),
openingHand: int(0, 10),
handSize: int(1, 15),
mulligans: int(0, 3),
firstPlayerDraws: z.boolean(),
maxCitations: int(1, 20),
citationsPerTurn: int(1, 5),
territoryCap: int(0, 10),
locationsPerTurn: int(0, 10),
libraryEmpty: z.enum(['lose', 'reshuffle', 'fatigue']),
maxKeywords: int(0, 4),
stubMax: int(0, 10),
trendingPower: int(0, 5),
connectedTiers: z.array(z.enum(['Linked', 'Compatriot', 'Contemporary', 'Kin'])).max(4)
.refine(v => new Set(v).size === v.length, 'Duplicate tier'),
connectedBonus: int(0, 5),
linkedBonus: int(0, 5),
turnSeconds: int(5, 600),
bankSeconds: int(0, 3600),
timeoutsToConcede: int(1, 20),
turnCap: int(2, 200).nullable(),
}).strict();
export const DEFAULT_DUEL_RULESET: DuelRuleset = Object.freeze({
engine: 'duel',
version: 'duel-1',
deckSize: 40,
maxCopiesPerPage: 4,
startingLife: 20,
openingHand: 7,
handSize: 7,
mulligans: 1,
firstPlayerDraws: false,
maxCitations: 10,
citationsPerTurn: 1,
territoryCap: 2,
locationsPerTurn: 1,
libraryEmpty: 'lose',
maxKeywords: 2,
stubMax: 2,
trendingPower: 1,
connectedTiers: ['Linked', 'Compatriot', 'Contemporary', 'Kin'],
connectedBonus: 1,
linkedBonus: 2,
turnSeconds: 60,
bankSeconds: 300,
timeoutsToConcede: 3,
turnCap: null,
}) as DuelRuleset;
/** Validate a full ruleset. Throws (ZodError) on anything invalid or unknown. */
export function parseDuelRuleset(value: unknown): DuelRuleset {
return DuelRulesetSchema.parse(value) as DuelRuleset;
}
/** Merge a partial override (a mode file's `rules`) onto the defaults, then validate. */
export function mergeDuelRuleset(overrides: unknown, base: DuelRuleset = DEFAULT_DUEL_RULESET): DuelRuleset {
if (overrides === undefined || overrides === null) return parseDuelRuleset(structuredClone(base));
if (typeof overrides !== 'object' || Array.isArray(overrides)) throw new TypeError('Ruleset overrides must be an object');
return parseDuelRuleset({ ...structuredClone(base), ...(overrides as Record<string, unknown>) });
}
+397
View File
@@ -0,0 +1,397 @@
/**
* WikiDeck Duel: the Magic-style 40-card engine (off-chain). Contract types.
* Spec: docs/game/DUEL_API.md (rules: docs/game/DUEL_DESIGN.md). Owner: duel-core (claude/wikideck#55).
*
* Everything here is plain JSON data: DuelState round-trips through
* JSON.stringify/parse with no loss (no Maps, classes or functions).
* shared/game/ (Edit War) is a separate engine and is not affected.
*/
import type { RngState } from '../game/rng.ts';
export type Seat = 0 | 1;
export const SEATS: readonly Seat[] = [0, 1];
// ---------------------------------------------------------------------------
// Cards (derived by duel-cards in shared/duel/derive.ts; the engine never re-derives)
// ---------------------------------------------------------------------------
export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
export const CARD_TYPES: readonly CardType[] = ['Figure', 'Location', 'Event', 'Institution', 'Doctrine'];
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
export const PORTALS: readonly Portal[] = ['Arts', 'Earth', 'History', 'Science', 'Society', 'Neutral'];
/** Card keywords (DUEL_DESIGN §4), ≤ ruleset.maxKeywords per card. 'Trending' is granted by Trending mode only. */
export type Keyword = 'Protected' | 'Featured' | 'Legacy' | 'Multilingual' | 'Translated' | 'Well-sourced' | 'Stub' | 'Local' | 'Trending';
export const KEYWORDS: readonly Keyword[] = ['Protected', 'Featured', 'Legacy', 'Multilingual', 'Translated', 'Well-sourced', 'Stub', 'Local', 'Trending'];
/** Connected tiers (DUEL_DESIGN §6). The engine computes them from `connect`. */
export type ConnectedTier = 'Linked' | 'Compatriot' | 'Contemporary' | 'Kin';
export const CONNECTED_TIERS: readonly ConnectedTier[] = ['Linked', 'Compatriot', 'Contemporary', 'Kin'];
/** Frozen claims used for Connected (no I/O during a match). */
export interface ConnectKeys {
/** P17/P27 values (Q-ids or labels; compared as strings). */
countries: string[];
/** From P569/P570/P571/P580/P585, e.g. 19 for the 1800s. */
centuries: number[];
/** Outlink pageIds (cached), plus pageIds the card's claims cite. */
links: number[];
/** P31 Q-ids. Q5 (human) and Q16521 (taxon) never count for Kin. */
p31: string[];
/** The card's own Q-id, and the Q-ids its claims cite: Linked if either cites the other (DUEL_DESIGN §6). */
qid?: string;
cites?: string[];
}
/** When an effect runs. Sorcery speed only: there is no stack and no response window. */
export type EffectTrigger =
| 'onPlay' // an Event resolves (on a permanent: same as onEnter)
| 'onEnter' // this permanent enters the battlefield
| 'onAttack' // this Figure is declared as an attacker (resolves at confirmAttack)
| 'onDestroyed' // this permanent is destroyed (after all combat damage)
| 'startOfTurn' // its controller's refresh step, in entry order
| 'onCombatDamageToPlayer' // this Figure (or the Figure this Doctrine is attached to) deals combat damage to a player
| 'static'; // continuous while on the battlefield
/** Effect ops the interpreter knows. duel-cards builds the 12 templates (DUEL_DESIGN §5) from these. */
export type EffectOp =
| 'damage' // `amount` to each target (Figure, Location or player)
| 'damageEach' // `amount` to every Figure and Location (target narrows: 'ownFigures' / 'opponentFigures')
| 'createToken' // `amount` (default 1) copies of `token` under the controller; condition.maxTokens limits
| 'pump' // +power/+toughness (negative allowed); duration 'turn' | 'permanent'; as static: while the source is in play
| 'fight' // the previous chosen target (else this permanent) and this target deal damage equal to their power to each other
| 'draw' // controller draws `amount`
| 'attach' // Doctrine: attach to the target Figure (defines the Doctrine's target)
| 'gainLife' // controller gains `amount` Notability
| 'drain' // opponent loses `amount`, controller gains `amount`
| 'destroy' // destroy target permanent
| 'bounce' // return target permanent to its owner's hand
| 'tap'; // tap target permanent
export type TargetSpec =
// chosen (each consumes one entry of play.targets, in effect order)
| 'figure' // any Figure
| 'figureOrLocation' // any Figure or Location
| 'ownFigure' // a Figure you control
| 'opponentFigure' // a Figure you don't control
| 'anyTarget' // any Figure, Location or player
// automatic
| 'each' // every Figure and Location
| 'self' // this permanent
| 'attached' // the Figure this Doctrine is attached to
| 'ownFigures' // every Figure you control
| 'opponentFigures' // every Figure you don't control
| 'opponent' // the opposing player
| 'controller'; // you
export interface TokenSpec { name: string; power: number; toughness: number; portal: Portal }
export interface EffectSpec {
trigger: EffectTrigger;
op: EffectOp;
/** Default per op: damage → 'anyTarget'; pump → 'self'; draw/gainLife/createToken → 'controller'; drain → 'opponent'. */
target?: TargetSpec;
amount?: number;
/** pump: +power/+toughness (default: amount/amount). */
power?: number;
toughness?: number;
/** pump/grant outside static: 'turn' (default) or 'permanent'. */
duration?: 'turn' | 'permanent';
token?: TokenSpec;
condition?: {
/** Only affects Figures with printed power ≤ maxPower. */
maxPower?: number;
/** Only Figures of the source's Portal (for a Doctrine: the attached Figure's Portal), excluding that card itself. */
samePortal?: boolean;
/** Only Figures Connected to the source. */
connected?: boolean;
/** createToken: only if the controller controls fewer than this many tokens. */
maxTokens?: number;
};
/** Keywords granted to the affected Figures (static: while in play; otherwise for `duration`). */
grant?: Keyword[];
/** Template id (T1–T12) for rules text and log wording. */
template?: string;
}
/**
* A card as the engine sees it, frozen at match start. The host builds these
* from the chain via duel-cards' derive(); the engine trusts them.
*/
export interface DuelCard {
/** Unique within one deck: the NFT tokenId (or a sample id in sims; `token:` ids for tokens). */
cardId: string;
pageId: number | null;
revisionId?: number;
title: string;
/** Wikidata description ("American actor (1909–1994)"), for log first mentions. */
description?: string;
type: CardType;
/** e.g. 'conflict', 'election', 'organisation', 'pathology'. */
subtype?: string | null;
portal: Portal;
cost: number;
/** Figures: the body. Locations: power 0, toughness = Garrison (0 = can't block). Others: null or 0. */
power: number | null;
toughness: number | null;
keywords: Keyword[];
/** Locations: +N max Citations while controlled (all sources together ≤ territoryCap). */
territory?: number;
effects: EffectSpec[];
/** Deterministic rules text (shared/duel/text.ts). Display only. */
rulesText: string;
/** First sentence of article.extract (else description). Display only. */
flavor: string;
connect?: ConnectKeys;
rarity?: 'Common' | 'Rare' | 'Epic' | 'Legendary';
deriveVersion?: string;
/** Tokens are created in play and never in decks. */
token?: boolean;
}
// ---------------------------------------------------------------------------
// Ruleset (all numbers are data; parseDuelRuleset in ruleset.ts validates)
// ---------------------------------------------------------------------------
export type LibraryEmpty = 'lose' | 'reshuffle' | 'fatigue';
export interface DuelRuleset {
engine: 'duel';
version: string;
deckSize: number; // 40
maxCopiesPerPage: number; // 4
startingLife: number; // 20 Notability
openingHand: number; // 7
handSize: number; // 7: hand limit at end of turn (DUEL_DESIGN `handLimit`); excess discarded highest cost first
mulligans: number; // 1: shuffle, draw openingHand, bottom one per mulligan taken
firstPlayerDraws: boolean; // false
maxCitations: number; // 10
citationsPerTurn: number; // 1
territoryCap: number; // 2
locationsPerTurn: number; // 1
libraryEmpty: LibraryEmpty; // 'lose'
maxKeywords: number; // 2
stubMax: number; // 2: max Stub counters
trendingPower: number; // 1: Trending gets +N/+0
connectedTiers: ConnectedTier[]; // all four; cut tiers by removing them
connectedBonus: number; // 1
linkedBonus: number; // 2
turnSeconds: number; // 60
bankSeconds: number; // 300
timeoutsToConcede: number; // 3 consecutive timeouts lose
/** Optional: after this many turns in total, higher Notability wins, then higher power in play, then the second player. */
turnCap: number | null;
}
// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------
/** 'mulligan' → 'main' → 'attack' → ('block' if attackers can be blocked) → next turn. Refresh, draw, damage and end are automatic. */
export type Phase = 'mulligan' | 'main' | 'attack' | 'block' | 'over';
/** One physical card in a match. `uid` is unique per match ("0:12" = seat 0, deck index 12; "t:3" = token); actions use uids. */
export interface CardInstance {
uid: string;
owner: Seat;
card: DuelCard;
}
export interface Permanent extends CardInstance {
controller: Seat;
tapped: boolean;
/** "Pending review": entered this turn, can't attack. */
sick: boolean;
damage: number;
/** Stub +1/+1 counters. */
counters: number;
/** Permanent pump modifiers. */
permPower: number;
permToughness: number;
/** Until-end-of-turn modifiers. */
tempPower: number;
tempToughness: number;
/** Keywords granted until end of turn / permanently by non-static effects. */
tempKeywords: Keyword[];
permKeywords: Keyword[];
/** Doctrines: uid of the Figure they're attached to. */
attachedTo?: string;
/** Well-sourced: prevention already used this turn. */
shielded: boolean;
/** Entry order (trigger order). */
entered: number;
/** Connected bonus already logged. */
connectedLogged: boolean;
}
export interface PlayerState {
life: number;
/** Citations available this turn. */
citations: number;
/** Base max (rises by citationsPerTurn to maxCitations). */
baseCitations: number;
library: CardInstance[]; // top = index 0. Hidden.
hand: CardInstance[]; // hidden from the opponent
graveyard: CardInstance[]; // "Deleted", public
mulligansTaken: number;
ready: boolean;
locationsThisTurn: number;
/** Remaining time bank in seconds (the host decrements it). */
bankSeconds: number;
/** Consecutive timeouts. */
timeouts: number;
/** libraryEmpty 'fatigue': damage of the last empty draw. */
fatigue: number;
}
export interface CombatState {
attackers: string[];
/** blocker uid → attacker uid. */
blocks: Record<string, string>;
}
export type EndReason = 'life' | 'library' | 'concede' | 'timeout' | 'turnCap';
export interface DuelResult {
winner: Seat | null; // null = draw
reason: EndReason;
}
export interface DuelState {
engine: 'duel';
rules: DuelRuleset;
seed: string;
rng: RngState;
/** 1-based, counts both players' turns. 0 during mulligans. */
turn: number;
active: Seat;
firstSeat: Seat;
phase: Phase;
players: [PlayerState, PlayerState];
battlefield: Permanent[];
combat: CombatState;
log: LogEvent[];
result: DuelResult | null;
/** Increments on every applied action (host polling: unchanged → 204). */
version: number;
/** Counters for token uids and entry order. */
nextToken: number;
nextEntry: number;
}
// ---------------------------------------------------------------------------
// Actions (atomic; legalActions enumerates them; [] for the seat not to act)
// ---------------------------------------------------------------------------
export type TargetRef = { kind: 'card'; uid: string } | { kind: 'player'; seat: Seat };
export type DuelAction =
| { type: 'keep' }
| { type: 'mulligan' }
/** targets: one per chosen-target effect, in effect order (Doctrine: its 'attach' target). Omitted when none. */
| { type: 'play'; uid: string; targets?: TargetRef[] }
| { type: 'endPhase' } // main → attack
| { type: 'toggleAttacker'; uid: string } // declare one more attacker (monotonic)
| { type: 'confirmAttack' } // no attackers → end turn
| { type: 'block'; blocker: string; attacker: string } // defender, monotonic
| { type: 'confirmBlocks' } // damage, then end of turn
| { type: 'concede' } // any time, either seat (not listed)
| { type: 'timeout' }; // host-only, for the seat that must act (not listed)
// ---------------------------------------------------------------------------
// Log (encyclopedic; clients get logFor(state, seat); state.log is omniscient)
// ---------------------------------------------------------------------------
/** A card in the log. power/toughness: current values right after the event (Figures and Garrisons on the battlefield). */
export interface CardRef { uid: string; cardId: string; title: string; pageId: number | null; type: CardType; power?: number; toughness?: number }
export type LogEvent = { seq: number; turn: number } & (
| { kind: 'start'; firstSeat: Seat }
| { kind: 'mulligan'; seat: Seat }
| { kind: 'keep'; seat: Seat; handSize: number }
| { kind: 'turnStart'; seat: Seat; citations: number; life: [number, number] }
/** card is omitted in the opponent's logFor (hidden draw). */
| { kind: 'draw'; seat: Seat; card?: CardRef }
/** A Figure, Location or Institution entered. */
| { kind: 'deploy'; seat: Seat; card: CardRef }
/** An Event resolved. */
| { kind: 'cast'; seat: Seat; card: CardRef; targets: TargetRef[] }
/** A Doctrine was attached. */
| { kind: 'adopt'; seat: Seat; card: CardRef; to: CardRef }
| { kind: 'tokenCreated'; seat: Seat; card: CardRef; source: CardRef }
| { kind: 'connected'; seat: Seat; card: CardRef; with: CardRef; tier: ConnectedTier; via: string; bonus: number }
/** Rivalry (log only): two opposing permanents are Connected. */
| { kind: 'rivalry'; card: CardRef; with: CardRef; tier: ConnectedTier; via: string }
/** Any resolved effect (wording key: template). Damage and life changes follow as their own events. */
| { kind: 'effect'; seat: Seat; source: CardRef; op: EffectOp; template?: string; targets: TargetRef[] }
| { kind: 'attack'; seat: Seat; attackers: CardRef[] }
| { kind: 'block'; seat: Seat; blocks: { blocker: CardRef; attacker: CardRef }[] }
/** Damage to a permanent from an effect / from combat. */
| { kind: 'effectDamage'; source: CardRef; target: CardRef; amount: number }
| { kind: 'combatDamage'; source: CardRef; target: CardRef; amount: number }
/** Damage or life loss to a player. source null = fatigue. */
| { kind: 'playerDamage'; source: CardRef | null; seat: Seat; amount: number; life: number; combat: boolean }
| { kind: 'lifeGain'; source: CardRef; seat: Seat; amount: number; life: number }
| { kind: 'destroyed'; card: CardRef; owner: Seat }
| { kind: 'bounced'; card: CardRef; owner: Seat }
| { kind: 'discard'; seat: Seat; card: CardRef }
| { kind: 'fatigue'; seat: Seat; amount: number }
| { kind: 'concede'; seat: Seat }
| { kind: 'timeout'; seat: Seat }
| { kind: 'gameOver'; winner: Seat | null; reason: EndReason; life: [number, number] }
);
export type LogKind = LogEvent['kind'];
// ---------------------------------------------------------------------------
// Views (what one seat may see; bots and UI get only this)
// ---------------------------------------------------------------------------
export interface PermanentView {
uid: string;
owner: Seat;
controller: Seat;
card: DuelCard;
tapped: boolean;
sick: boolean;
damage: number;
counters: number;
attachedTo?: string;
/** Current values after counters, pumps, statics, Connected and Trending. */
power: number;
toughness: number;
keywords: Keyword[];
/** Active Connected bonus, if any (for the card face). */
connected?: { with: string; tier: ConnectedTier; via: string; bonus: number };
}
export interface SideView {
seat: Seat;
life: number;
citations: number;
maxCitations: number;
handSize: number;
librarySize: number;
graveyard: CardInstance[];
bankSeconds: number;
ready: boolean;
mulligansTaken: number;
}
export interface PlayerView {
engine: 'duel';
seat: Seat;
turn: number;
active: Seat;
phase: Phase;
/** Seat that must act now (null when over). */
toAct: Seat | null;
you: SideView & { hand: CardInstance[] };
opponent: SideView;
battlefield: PermanentView[];
combat: CombatState;
result: DuelResult | null;
version: number;
rules: DuelRuleset;
}
+40
View File
@@ -0,0 +1,40 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { DEFAULT_DUEL_RULESET, mergeDuelRuleset, parseDuelRuleset, CARD_TYPES, KEYWORDS } from '../shared/duel/index.ts';
import { DEFAULT_RULESET } from '../shared/game/index.ts';
test('duel default ruleset matches the BRIEF', () => {
const rules = parseDuelRuleset({ ...DEFAULT_DUEL_RULESET });
assert.equal(rules.deckSize, 40);
assert.equal(rules.startingLife, 20);
assert.equal(rules.maxCitations, 10);
assert.equal(rules.handSize, 7);
assert.equal(rules.openingHand, 7);
assert.equal(rules.mulligans, 1);
assert.equal(rules.libraryEmpty, 'lose');
assert.equal(rules.firstPlayerDraws, false);
assert.equal(rules.turnSeconds, 60);
assert.equal(rules.bankSeconds, 300);
assert.equal(rules.turnCap, null);
assert.equal(rules.territoryCap, 2);
});
test('duel ruleset merges overrides and rejects unknown keys', () => {
assert.equal(mergeDuelRuleset({ deckSize: 20 }).deckSize, 20);
assert.equal(mergeDuelRuleset({ turnCap: 30 }).turnCap, 30);
assert.throws(() => mergeDuelRuleset({ topicCount: 3 }));
assert.throws(() => mergeDuelRuleset({ libraryEmpty: 'shrug' }));
assert.throws(() => mergeDuelRuleset({ deckSize: 0 }));
assert.throws(() => mergeDuelRuleset([1]));
});
test('Night 1 Edit War rulesets are rejected cleanly', () => {
assert.throws(() => parseDuelRuleset(DEFAULT_RULESET));
});
test('card types and keywords are the BRIEF set', () => {
assert.deepEqual([...CARD_TYPES], ['Figure', 'Location', 'Event', 'Institution', 'Doctrine']);
for (const k of ['Protected', 'Featured', 'Translated', 'Legacy', 'Stub', 'Well-sourced', 'Multilingual', 'Local']) {
assert.ok((KEYWORDS as readonly string[]).includes(k), k);
}
});
-82
View File
@@ -1,82 +0,0 @@
// testnet-ops: live identity source over a FAKE Wikimedia client. Zero network calls.
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { wikimediaIdentitySource } from '../server/game/identity-source.ts';
import { IdentityStore, prebake, toProfile } from '../server/game/identity.ts';
import type { BackgroundRequest, ProfileBuilder } from '../server/game/identity-source.ts';
// A minimal stand-in for shared/duel/profile.ts (#70), so this test needs no unmerged module.
const ids = (e: any, p: string): string[] => (e?.claims?.[p] ?? []).map((s: any) => s.mainsnak?.datavalue?.value?.id).filter(Boolean);
const yrs = (e: any, p: string): number[] => (e?.claims?.[p] ?? []).map((s: any) => Number(/^[+-]0*(\d+)-/.exec(s.mainsnak?.datavalue?.value?.time ?? '')?.[1])).filter(Boolean);
const profile: ProfileBuilder = {
wikidataEntityParams: q => ({ action: 'wbgetentities', ids: [...q].sort().join('|'), props: 'claims', format: 'json', formatversion: '2' }),
wikidataLabelParams: q => ({ action: 'wbgetentities', ids: [...q].sort().join('|'), props: 'labels', languages: 'en', format: 'json', formatversion: '2' }),
classIdsOf: e => [...new Set([...ids(e, 'P31'), ...ids(e, 'P279')])].sort(),
profileFromSources: ({ enrichment, entity, labels = {} }) => ({
wikidataId: enrichment.wikidataId, description: enrichment.description, categories: enrichment.categories,
instanceOf: ids(entity, 'P31').map(id => ({ id, label: labels[id] ?? id })), countries: ids(entity, 'P27'),
years: [...yrs(entity, 'P569'), ...yrs(entity, 'P570')], died: ids(entity, 'P570').length > 0 || yrs(entity, 'P570').length > 0,
fetchedRevisionId: enrichment.revisionId }),
};
const enrichmentFor = (pageId: number, wikidataId: string | null) => ({
pageId, title: `Page ${pageId}`, description: `desc ${pageId}`, wikidataId, revisionId: 1000 + pageId, pageBytes: 1,
languageCount: 1, languagesTruncated: false, categories: ['Living people', '1948 births'], categoriesTruncated: false,
fetchedAt: '2026-11-17T00:00:00Z',
pageviews: { status: 'unavailable', months: [], latestMonth: '2026-10', total: null, dailyAverage: null, trendPercent: null },
}) as any;
const claim = (id: string) => ({ rank: 'normal', mainsnak: { snaktype: 'value', datavalue: { type: 'wikibase-entityid', value: { id } } } });
const time = (t: string) => ({ rank: 'normal', mainsnak: { snaktype: 'value', datavalue: { type: 'time', value: { time: t } } } });
function fakeClient(opts: { failClaims?: boolean } = {}) {
const calls: { url: URL; options: BackgroundRequest }[] = [];
return { calls, async request(url: URL, options: BackgroundRequest) {
calls.push({ url, options });
const props = url.searchParams.get('props'), ids = url.searchParams.get('ids')!.split('|');
if (props === 'claims' && opts.failClaims) return { response: new Response('busy', { status: 503 }), signal: new AbortController().signal, fromCache: false };
const entities = Object.fromEntries(ids.map(id => [id, props === 'claims'
? { id, claims: { P31: [claim('Q5')], P27: [claim('Q30')], P569: [time('+1948-01-02T00:00:00Z')], P570: [time('+2001-01-01T00:00:00Z')] } }
: { id, labels: { en: { value: id === 'Q5' ? 'human' : `label ${id}` } } }]));
return { response: Response.json({ entities }), signal: new AbortController().signal, fromCache: false };
} };
}
test('every request is on the background lane, batched, and the frozen identity is derive-ready', async () => {
const realFetch = globalThis.fetch;
globalThis.fetch = (() => { throw new Error('network call in test'); }) as typeof fetch;
const dir = mkdtempSync(join(tmpdir(), 'identity-src-'));
try {
const client = fakeClient();
const source = wikimediaIdentitySource({ client, profile, enrichment: { async getBackground(id) { return enrichmentFor(id, `Q${id}`); } } });
const store = new IdentityStore(join(dir, 'id.sqlite'));
const articles = [1, 2, 3].map(i => ({ tokenId: String(i).repeat(64), pageId: i, title: `Page ${i}`, revisionId: i }));
const r = await prebake(store, source, articles);
assert.deepEqual(r, { seen: 3, alreadyFrozen: 0, frozen: 3, unknown: 0 });
assert.ok(client.calls.every(c => c.options.lane === 'background'));
assert.ok(client.calls.every(c => c.url.hostname === 'www.wikidata.org'));
assert.deepEqual(client.calls.map(c => c.url.searchParams.get('props')), ['claims', 'labels']);
assert.equal(client.calls[0].url.searchParams.get('ids'), 'Q1|Q2|Q3');
const one = store.get('1'.repeat(64))!;
assert.equal(one.source, 'wikimedia');
assert.deepEqual(one.instanceOf, [{ id: 'Q5', label: 'human' }]);
assert.deepEqual(one.countries, ['Q30']);
assert.deepEqual(one.years, [1948, 2001]);
assert.equal(one.died, true);
assert.equal(one.fetchedRevisionId, 1001);
assert.equal(toProfile(one).description, 'desc 1');
store.close();
} finally { globalThis.fetch = realFetch; rmSync(dir, { recursive: true, force: true }); }
});
test('a failed claims request leaves cards unknown so they are retried, never frozen half-empty', async () => {
const source = wikimediaIdentitySource({ client: fakeClient({ failClaims: true }), profile,
enrichment: { async getBackground(id) { if (id === 9) throw new Error('throttled'); return enrichmentFor(id, id === 8 ? null : `Q${id}`); } } });
const got = await source.lookup([7, 8, 9].map(i => ({ tokenId: String(i).repeat(64), pageId: i, title: `P${i}` })));
assert.equal(got.get(7), undefined); // has an item, claims failed → retry
assert.equal(got.get(9), undefined); // enrichment failed → retry
assert.equal(got.get(8)?.wikidataId, null); // no Wikidata item at all → enrichment-only profile is final
assert.deepEqual(got.get(8)?.instanceOf, []);
});
-90
View File
@@ -1,90 +0,0 @@
// testnet-ops: card identity freeze-at-first-sight and pre-bake. Zero network calls.
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { identityStoreFile, IdentityStore, buildIdentity, cachedSource, linksHash, prebake, toProfile,
type ChainArticle, type IdentitySource } from '../server/game/identity.ts';
const sample = JSON.parse(readFileSync(new URL('../docs/game/card-sample.json', import.meta.url), 'utf8')).cards as any[];
const now = () => new Date('2026-11-17T22:00:00Z');
function tmpStore() {
const dir = mkdtempSync(join(tmpdir(), 'identity-'));
return { store: new IdentityStore(join(dir, 'identity.sqlite')), done: () => rmSync(dir, { recursive: true, force: true }) };
}
const art = (c: any, i: number): ChainArticle => ({ tokenId: i.toString(16).padStart(64, '0'), pageId: c.pageId, title: c.title, revisionId: c.revisionId });
test('no fetch: pre-bake from the cached sample freezes every sample card', async () => {
const realFetch = globalThis.fetch;
globalThis.fetch = (() => { throw new Error('network call in test'); }) as typeof fetch;
const { store, done } = tmpStore();
try {
const articles = sample.map(art);
const r = await prebake(store, cachedSource(sample), articles, { now });
assert.deepEqual(r, { seen: sample.length, alreadyFrozen: 0, frozen: sample.length, unknown: 0 });
const salah = store.get(articles[sample.findIndex(c => c.title === 'Salahuddin of Aceh')].tokenId)!;
assert.equal(salah.wikidataId, 'Q4264920');
assert.deepEqual(salah.instanceOf, [{ id: 'Q5', label: 'human' }]);
assert.equal(salah.source, 'cache');
assert.ok(salah.categories.includes('Sultans of Aceh'));
assert.equal(salah.description, 'Sultan of Aceh (1530–1537/9)');
const profile = toProfile(salah);
assert.deepEqual(profile.instanceOf, [{ id: 'Q5', label: 'human' }]);
assert.equal(profile.fetchedRevisionId, 1358732737);
} finally { globalThis.fetch = realFetch; store.close(); done(); }
});
test('freeze at first sight: a later, different profile never overwrites the stored one', async () => {
const { store, done } = tmpStore();
try {
const a = art(sample[0], 1);
const first = store.freeze(buildIdentity(a, { instanceOf: [{ id: 'Q5', label: 'human' }] }, 'cache', now()));
const second = store.freeze(buildIdentity(a, { instanceOf: [{ id: 'Q515', label: 'city' }] }, 'wikimedia', new Date()));
assert.deepEqual(second, first);
assert.equal(store.get(a.tokenId)!.instanceOf[0].id, 'Q5');
const again = await prebake(store, cachedSource(sample), [a, a], { now });
assert.deepEqual(again, { seen: 1, alreadyFrozen: 1, frozen: 0, unknown: 0 });
} finally { store.close(); done(); }
});
test('unknown pages are not frozen, so a later run can retry them', async () => {
const { store, done } = tmpStore();
try {
const stranger: ChainArticle = { tokenId: 'f'.repeat(64), pageId: 999999999, title: 'Not in sample', revisionId: 1 };
const r = await prebake(store, cachedSource(sample), [stranger], { now });
assert.deepEqual(r, { seen: 1, alreadyFrozen: 0, frozen: 0, unknown: 1 });
assert.equal(store.has(stranger.tokenId), false);
} finally { store.close(); done(); }
});
test('sources are asked in bounded batches and identities persist across reopen', async () => {
const dir = mkdtempSync(join(tmpdir(), 'identity-'));
try {
const calls: number[] = [];
const source: IdentitySource = { kind: 'wikimedia', async lookup(batch) {
calls.push(batch.length);
return new Map(batch.map(a => [a.pageId, { links: [7, 3, 3, 1.5], coords: [1, 2] as [number, number], cites: ['Q30', 'bad'], years: [1948, -44], died: true }]));
} };
let store = new IdentityStore(join(dir, 'id.sqlite'));
await prebake(store, source, sample.slice(0, 12).map(art), { batchSize: 5, now });
assert.deepEqual(calls, [5, 5, 2]);
store.close();
store = new IdentityStore(join(dir, 'id.sqlite'));
const one = store.get(art(sample[3], 3).tokenId)!;
assert.deepEqual(one.links, [3, 7]);
assert.equal(one.linksHash, linksHash([3, 7]));
assert.deepEqual(one.cites, ['Q30']);
assert.deepEqual(one.years, [-44, 1948]);
assert.equal(one.died, true);
assert.deepEqual(one.coords, [1, 2]);
assert.equal(one.mintRevisionId, sample[3].revisionId);
assert.equal(store.count(), 12);
store.close();
} finally { rmSync(dir, { recursive: true, force: true }); }
});
test('the store file lives under WIKIDECK_DATA_DIR, next to the ledger', () => {
assert.equal(identityStoreFile({ WIKIDECK_DATA_DIR: '/srv/wd' }), join('/srv/wd', 'card-identity.sqlite'));
assert.ok(identityStoreFile({}).endsWith(join('data', 'card-identity.sqlite')));
});