Compare commits

...
Author SHA1 Message Date
claudeanderic dbb89ce9c5 Night 2: 40-card Magic-style duel, PvP with owned decks, polite Wikimedia client, Android mining (#23)
Night 2 (2026-11-17), from the `claude/wikideck` fork's `night/2026-11-17` branch. It follows Night 1 (#22).

## What's in it
- **Duel engine** (fork #72, #80): 40-card decks of cards you own, Notability/Citations, keywords, effects T1–T12, Connected, a hidden-information-safe `viewFor`/`logFor`, and replay. Balance v1 tuning (#84) gives the first player about 51%.
- **Card profiles** (#70, #82): Figure, Location, Event, Institution or Doctrine, plus stats, keywords and rules text, all derived from real article data. Templates only.
- **Design and story** (#66, #69, #83): DUEL_DESIGN.md, plus the match log and the encyclopedic "Battle of X (2026)" recap.
- **PvP** (#74, #77, #81, #76, #85):
  - The server checks ownership, and 40-card eligibility is enforced.
  - Modes: Classic (ranked), Draft and Trending.
  - Invites, quick match, Elo, a ladder and recap pages. Online matches render on the duel board.
- **Duel board UI** (#79): MTG-style card faces and combat declaration, built for 360 px first.
- **Polite Wikimedia client** (#73, #75): throttled, cached and identified requests, the mint-path fix, and a prefetch pool.
- **Android mining** (#78): native RandomX, as a sideload build. The emulator mined a testnet block.
- **Testnet ops** (#67, #68).

PR numbers refer to `claude/wikideck`.

## Status
- **Tests:** 423, of which 422 pass, 0 fail and 1 is skipped. The build is OK (`node:24-alpine`, `--network none`).
- **Testnet:** running this commit (036489c) on r350.
- **Untouched:** no changes to `server/testnet/consensus.ts`, `randomx.ts`, `native/` or the mainnet compose.
- **Review:** night-review reviewed fork #66–#79. #80–#85 came from the agents' unfinished branches and were not reviewed.
- **Known gaps:**
  - The PvP end-to-end test hasn't been run (it needs two eom.dev accounts).
  - Bot matches aren't reachable from Play.
  - Card identity pre-bake hasn't been done.
  - The RandomX verifier latch (`server/testnet/randomx.ts:140`) is still open.

This PR is for Eric to merge.

🤖 Generated with [Claude Code](https://claude.com/claude-code)Reviewed-on: WikiDeck/wikideck#23

Co-authored-by: Claude <claude@eom.dev>
2026-11-18 18:12:24 +00:00
151 changed files with 26435 additions and 360 deletions
+4
View File
@@ -28,3 +28,7 @@ dist-ssr
*.njsproj
*.sln
*.sw?
# Native RandomX engine for the app (scripts/build-randomx-android.sh)
native/build-android-*/
android/app/src/main/jniLibs/
+7
View File
@@ -16,6 +16,13 @@ android {
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
packagingOptions {
jniLibs {
// The RandomX engine (jniLibs/<abi>/libwikideck_randomx.so) is an executable, not a JNI library.
// Android may exec it only from the extracted nativeLibraryDir, so keep legacy extraction.
useLegacyPackaging true
}
}
buildTypes {
release {
minifyEnabled false
@@ -1,5 +1,14 @@
package dev.eom.wikideck;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {}
public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
// Local plugins must be registered before the bridge starts.
registerPlugin(MinerPlugin.class);
super.onCreate(savedInstanceState);
}
}
@@ -0,0 +1,264 @@
package dev.eom.wikideck;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Build;
import android.os.PowerManager;
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
/**
* Native RandomX engine for the WikiDeck app (sideload build only, see docs/night2/MOBILE_MINING.md).
*
* The plugin only runs the pinned `wikideck-randomx` executable (shipped as jniLibs/<abi>/libwikideck_randomx.so)
* in LIGHT mode and speaks its line protocol (docs/randomx-native.md). It never sees wallet keys: the WebView builds
* the work blob, signs the block claim with the web wallet, and submits it to the node. This class also enforces the
* device safeguards: engines are killed when the app goes to the background, on battery saver, when the device is
* hot, or when the battery is low and not charging. Each stop is reported to the WebView as a `halted` event.
*/
@CapacitorPlugin(name = "WikiDeckMiner")
public class MinerPlugin extends Plugin {
private static final String BINARY = "libwikideck_randomx.so";
private static final int MAX_THREADS = 4;
/** At or above Android's THERMAL_STATUS_MODERATE we stop. */
private static final int THERMAL_LIMIT = 2;
/** Battery temperature limit in tenths of a degree Celsius. */
private static final int BATTERY_TEMP_LIMIT = 400;
private static final int LOW_BATTERY_PERCENT = 20;
private static final Pattern HEX = Pattern.compile("^[0-9a-f]+$");
private final List<Engine> engines = new ArrayList<>();
private BroadcastReceiver receiver;
private Object thermalListener;
/** One long-lived engine process with exactly one outstanding command (it is strictly request/response). */
private static final class Engine {
final Process process;
final OutputStream in;
final BufferedReader out;
final ExecutorService worker = Executors.newSingleThreadExecutor();
Engine(Process process) {
this.process = process;
this.in = process.getOutputStream();
this.out = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.US_ASCII));
}
String command(String line) throws Exception {
in.write((line + "\n").getBytes(StandardCharsets.US_ASCII));
in.flush();
String reply = out.readLine();
if (reply == null) throw new Exception("RandomX engine exited");
return reply;
}
void kill() {
worker.shutdownNow();
try { in.close(); } catch (Exception ignored) { }
process.destroy();
try { if (!process.waitFor(1, TimeUnit.SECONDS)) process.destroyForcibly(); } catch (InterruptedException ignored) { }
}
}
private File binary() {
return new File(getContext().getApplicationInfo().nativeLibraryDir, BINARY);
}
@Override
public void load() {
receiver = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) { checkAndHalt(); }
};
IntentFilter filter = new IntentFilter();
filter.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
getContext().registerReceiver(receiver, filter);
if (Build.VERSION.SDK_INT >= 29) {
PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
PowerManager.OnThermalStatusChangedListener l = status -> checkAndHalt();
pm.addThermalStatusListener(l);
thermalListener = l;
}
}
@Override
protected void handleOnPause() {
halt("background");
super.handleOnPause();
}
@Override
protected void handleOnDestroy() {
halt("closed");
try { getContext().unregisterReceiver(receiver); } catch (Exception ignored) { }
if (Build.VERSION.SDK_INT >= 29 && thermalListener != null) {
PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
pm.removeThermalStatusListener((PowerManager.OnThermalStatusChangedListener) thermalListener);
}
super.handleOnDestroy();
}
/** Current device state and, if mining must not run, the reason. */
private JSObject conditionsObject() {
PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Intent battery = getContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int temp = battery == null ? -1 : battery.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
int level = battery == null ? -1 : battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = battery == null ? -1 : battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int plugged = battery == null ? 0 : battery.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
int percent = level >= 0 && scale > 0 ? Math.round(100f * level / scale) : -1;
int thermal = Build.VERSION.SDK_INT >= 29 ? pm.getCurrentThermalStatus() : 0;
boolean powerSave = pm.isPowerSaveMode();
String block = null;
if (powerSave) block = "battery-saver";
else if (thermal >= THERMAL_LIMIT) block = "thermal";
else if (temp >= BATTERY_TEMP_LIMIT) block = "battery-hot";
else if (plugged == 0 && percent >= 0 && percent < LOW_BATTERY_PERCENT) block = "battery-low";
JSObject o = new JSObject();
o.put("powerSave", powerSave);
o.put("thermalStatus", thermal);
o.put("batteryTempC", temp < 0 ? null : temp / 10.0);
o.put("batteryPercent", percent);
o.put("charging", plugged != 0);
o.put("cores", Runtime.getRuntime().availableProcessors());
o.put("abi", Build.SUPPORTED_ABIS.length > 0 ? Build.SUPPORTED_ABIS[0] : "unknown");
o.put("engineInstalled", binary().canExecute());
o.put("blocked", block);
return o;
}
private void checkAndHalt() {
String block = conditionsObject().getString("blocked");
if (block != null) halt(block);
}
private synchronized void halt(String reason) {
if (engines.isEmpty()) return;
for (Engine e : engines) e.kill();
engines.clear();
JSObject event = new JSObject();
event.put("reason", reason);
notifyListeners("halted", event);
}
@PluginMethod
public void conditions(PluginCall call) {
call.resolve(conditionsObject());
}
/** Runs upstream's known-vector test (Hash test 1a/2a) on this device. */
@PluginMethod
public void selfTest(PluginCall call) {
new Thread(() -> {
try {
Process p = new ProcessBuilder(binary().getAbsolutePath(), "--self-test").redirectErrorStream(true).start();
p.getOutputStream().close();
StringBuilder text = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8));
for (String line; (line = r.readLine()) != null && text.length() < 2000; ) text.append(line).append('\n');
boolean done = p.waitFor(120, TimeUnit.SECONDS);
if (!done) p.destroyForcibly();
JSObject o = new JSObject();
o.put("ok", done && p.exitValue() == 0);
o.put("output", text.toString().trim());
call.resolve(o);
} catch (Exception e) {
call.reject("Self-test failed to run: " + e.getMessage());
}
}).start();
}
/** Starts 1..4 light-mode engines (more than 2 only while charging) (each needs about 256 MiB). Refuses if a safeguard is active. */
@PluginMethod
public synchronized void start(PluginCall call) {
int threads = call.getInt("threads", 1);
if (threads < 1 || threads > MAX_THREADS || threads > Runtime.getRuntime().availableProcessors()) { call.reject("threads must be 1 to " + MAX_THREADS + " and at most the core count"); return; }
String block = conditionsObject().getString("blocked");
if (block == null && threads > 2 && !conditionsObject().getBool("charging")) block = "max-needs-charging";
if (block != null) { call.reject("Mining is paused: " + block, block); return; }
if (!engines.isEmpty()) { for (Engine e : engines) e.kill(); engines.clear(); }
try {
for (int i = 0; i < threads; i++) {
// No arguments = LIGHT mode. `--fast` (about 2 GiB) is never used on phones.
Process p = new ProcessBuilder(binary().getAbsolutePath()).redirectError(ProcessBuilder.Redirect.to(new File("/dev/null"))).start();
engines.add(new Engine(p));
}
} catch (Exception e) {
for (Engine en : engines) en.kill();
engines.clear();
call.reject("Could not start the RandomX engine: " + e.getMessage());
return;
}
JSObject o = new JSObject();
o.put("threads", threads);
call.resolve(o);
}
@PluginMethod
public synchronized void stop(PluginCall call) {
for (Engine e : engines) e.kill();
engines.clear();
call.resolve();
}
/**
* One bounded batch on engine `lane`: `mine <key> <blob> <target> <nonceOffset> <maxAttempts>`.
* Resolves {found:false} on exhaustion or {found:true, hash, nonce} (nonce as a decimal string).
*/
@PluginMethod
public void mine(PluginCall call) {
String key = call.getString("key", ""), blob = call.getString("blob", ""), target = call.getString("target", "");
int lane = call.getInt("lane", 0), offset = call.getInt("nonceOffset", -1), attempts = call.getInt("maxAttempts", 0);
if (key.length() != 64 || target.length() != 64 || blob.length() < 2 || blob.length() > 16384 || blob.length() % 2 != 0
|| !HEX.matcher(key).matches() || !HEX.matcher(target).matches() || !HEX.matcher(blob).matches()
|| offset < 0 || offset + 8 > blob.length() / 2 || attempts < 1 || attempts > 10000) {
call.reject("Invalid mining request");
return;
}
final Engine engine;
synchronized (this) {
if (lane < 0 || lane >= engines.size()) { call.reject("Miner is not running", "stopped"); return; }
engine = engines.get(lane);
}
String line = "mine " + key + " " + blob + " " + target + " " + offset + " " + attempts;
try {
engine.worker.execute(() -> {
try {
String reply = engine.command(line);
JSObject o = new JSObject();
if (reply.equals("exhausted")) {
o.put("found", false);
} else {
String[] parts = reply.split(" ");
if (parts.length != 3 || !parts[0].equals("found") || parts[1].length() != 64 || !HEX.matcher(parts[1]).matches()
|| !parts[2].matches("^[0-9]{1,20}$")) throw new Exception("Malformed engine reply");
o.put("found", true);
o.put("hash", parts[1]);
o.put("nonce", parts[2]);
}
call.resolve(o);
} catch (Exception e) {
call.reject("Miner stopped: " + e.getMessage(), "stopped");
}
});
} catch (Exception e) {
call.reject("Miner is not running", "stopped");
}
}
}
+5 -1
View File
@@ -1,11 +1,15 @@
#!/bin/sh
# Build the WikiDeck debug APK against the private Night-1 testnet.
# Needs ANDROID_HOME and a JDK 21 (JAVA_HOME). Output: android/app/build/outputs/apk/debug/app-debug.apk
# Needs ANDROID_HOME (with an NDK and CMake for the RandomX engine) and a JDK 21 (JAVA_HOME). Output: android/app/build/outputs/apk/debug/app-debug.apk
set -eu
cd "$(dirname "$0")/.."
export VITE_WIKIDECK_NETWORK="${VITE_WIKIDECK_NETWORK:-testnet}"
export VITE_WIKIDECK_GENESIS_TIME="${VITE_WIKIDECK_GENESIS_TIME:-1792411200}"
export VITE_NODE_URL="${VITE_NODE_URL:-http://192.168.1.32:3101}"
# Native RandomX engine (jniLibs/<abi>/libwikideck_randomx.so); built once, reused after (scripts/build-randomx-android.sh).
for abi in ${ABIS:-arm64-v8a x86_64}; do
[ -x "android/app/src/main/jniLibs/$abi/libwikideck_randomx.so" ] || ABIS="$abi" sh scripts/build-randomx-android.sh
done
npm run build
npx cap sync android
cd android && ./gradlew --no-daemon -q assembleDebug
+1 -1
View File
@@ -16,7 +16,7 @@ A 3-node **testnet-only** fixture on poweredge-r350. It is reachable on the LAN
- `compose.lan.yaml` also sets, per node:
- `WIKIDECK_USER_AGENT`, a Wikimedia-policy UA with a project URL (#19). Without it, Wikipedia returned 429 to our egress and templates failed.
- the game-mode env from #22: A = classic and trending, B = draft, C = all three.
- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-16 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves.
- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-17 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves.
- `testnet.sh` has `up`, `mine N [workers]`, `status` and `down`. Run it from the repo root on a checkout of the integration branch. `up` rebuilds the image from that checkout; the ledgers persist in the named volumes.
Never point this at mainnet or the live `wikideck` namespace.
+1 -1
View File
@@ -6,7 +6,7 @@
# because lobbies are in memory and a restart ends games in progress.
# Head detection uses the public Gitea API, which also works where SSH auth isn't available.
set -u
BRANCH=${BRANCH:-night/2026-11-16}
BRANCH=${BRANCH:-night/2026-11-17}
API=${API:-https://gitea.eom.dev/api/v1/repos/claude/wikideck}
INTERVAL=${INTERVAL:-180}
LOG=${LOG:-/tmp/wikideck-night-autodeploy.log}
+8
View File
@@ -1,12 +1,16 @@
# sim-testnet override: publish the fixture on r350's LAN address only (not 0.0.0.0).
# WIKIDECK_USER_AGENT identifies the testnet to Wikimedia (UA policy; no personal contact info).
# Game-mode env (modes team, #6) is inert until night/modes/hosting merges.
# WIKIDECK_WIKIMEDIA_NODES_PER_IP / WIKIDECK_OPERATOR_CONTACT (#62): the 3 nodes share one egress IP, so the
# polite client splits its rate and daily cap 3 ways. Inert until the wikimedia client merges.
services:
node-a:
ports: !override ["192.168.1.32:3101:3001"]
environment:
PUBLIC_ORIGIN: http://192.168.1.32:3101
WIKIDECK_USER_AGENT: &ua WikiDeck-testnet/0.1 (https://gitea.eom.dev/claude/wikideck; private testnet)
WIKIDECK_WIKIMEDIA_NODES_PER_IP: &perip "3"
WIKIDECK_OPERATOR_CONTACT: &contact https://gitea.eom.dev/claude/wikideck
WIKIDECK_MODES: classic,trending
WIKIDECK_GAME_OPERATOR: Testnet A
WIKIDECK_GAME_PEERS: http://192.168.1.32:3102,http://192.168.1.32:3103
@@ -15,6 +19,8 @@ services:
environment:
PUBLIC_ORIGIN: http://192.168.1.32:3102
WIKIDECK_USER_AGENT: *ua
WIKIDECK_WIKIMEDIA_NODES_PER_IP: *perip
WIKIDECK_OPERATOR_CONTACT: *contact
WIKIDECK_MODES: draft
WIKIDECK_GAME_OPERATOR: Testnet B
WIKIDECK_GAME_PEERS: http://192.168.1.32:3101,http://192.168.1.32:3103
@@ -23,6 +29,8 @@ services:
environment:
PUBLIC_ORIGIN: http://192.168.1.32:3103
WIKIDECK_USER_AGENT: *ua
WIKIDECK_WIKIMEDIA_NODES_PER_IP: *perip
WIKIDECK_OPERATOR_CONTACT: *contact
WIKIDECK_MODES: classic,trending,draft
WIKIDECK_GAME_OPERATOR: Testnet C
WIKIDECK_GAME_PEERS: http://192.168.1.32:3101,http://192.168.1.32:3102
+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. Balance levers (data only): `firstPlayerDraws`, and `secondPlayerCitations` (extra Citations on the second player's first turn; default 1 from balance v1, #64).
- **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` (default 40 total turns from balance v1, #64; `null` = none): 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.
+124
View File
@@ -0,0 +1,124 @@
# WikiDeck Duel: balance report
**Owner:** sim-balance (issue #64). **Rules:** `docs/game/DUEL_DESIGN.md`, `docs/night2/BRIEF.md`.
Every proposal here is **data only**: ruleset keys (`shared/duel` ruleset) or derivation table values (`DERIVE_RULES`). No code changes are proposed in this file.
## How to reproduce
```
# Node 24 (node:24-alpine on r350/inspiron). At most 4 workers on r350 (Night 1 ran out of memory).
npx tsx scripts/sim/duel-run.ts --engine duel --matches 3000 --workers 4 --mix default \
--out ../sim-out/duel --label base --sha $(git rev-parse --short HEAD)
# Ruleset overrides as JSON (shallow-merged into the duel ruleset):
npx tsx scripts/sim/duel-run.ts --engine duel --rules '{"startingLife":18}' --label life18 ...
```
- **Card pool:** the 236 real cards in `docs/game/card-sample.json`, derived by duel-cards (`shared/duel/sample.ts`, `docs/game/duel-card-sample.json`). No chain, no network.
- **Decks:** 120 decks of exactly 40 unique cards (each NFT once), sampled without replacement (`scripts/sim/duel-decks.ts`). Half are uniform random; the rest are skewed archetypes: Figure-, Doctrine-, Event-, Location- and Institution-heavy, low curve and high curve.
- **Bots** (`shared/bots/duel-bots.ts`): `heuristic` (greedy plays on a material evaluation, rule-based attacks and blocks), `mc`/`mc-lite` (shallow Monte Carlo over heuristic rollouts, re-sampling hidden cards on every rollout, so it is not clairvoyant), `greedy` (one-ply) and `random`. Bots see only `viewFor` of their seat.
- **Balance stats use bot-symmetric games only** (both seats the same bot). Mixed pairs measure skill.
- **Card win rate** = win rate of the seat that played the card, in games where only one side played it. It has a positive baseline (winners play more cards), so compare cards against each other and against the "all plays" baseline, not against 50%.
- **Minutes** are a model, not a measurement: 10 s per turn plus 4 s per atomic action (each play, attacker toggle, block and confirm).
- **Connected pair rate** = share of all 27,730 sample pairs with any Connected tier (`connectedTier`).
## Targets
| Metric | Target | Source |
|---|---|---|
| First-player win rate | 48–54% | DUEL_DESIGN §2.6 (issue #64 asks 48–52%) |
| Median game length | 8–12 turns each, 8–15 minutes | issue #64 |
| Stalls | < 5% reach turn 20 each | DUEL_DESIGN §2.6 |
| Connected | 15–30% of pairs | BRIEF |
| Famous cards | bigger and pricier, not strictly better: fame vs win rate r ≈ 0 within a cost | BRIEF |
## Balance v1 (00:05, from the v1 runs below)
**Ship as ruleset defaults (`DEFAULT_DUEL_RULESET`, data only):**
| Key | From | To | Why |
|---|---|---|---|
| `secondPlayerCitations` | 0 | **1** | First player 60.1% → **54.7%** [53–57] (v1-cand, n≈2700). The edge is tempo, and this is the only lever that moved it. |
| `turnCap` | null | **40** (20 each) | Games past 20 turns each 3.4% → **0%**. 3.9% of games are decided at the cap; median and p90 unchanged (8 / 12). |
v1-cand (both changes, 3000 matches, engine 4623930 + duel-cards 067de83): first player 54.7% [53–57], turns each 6 / 8 / 12, est. minutes median 7.9 / p90 13.5, 0 library-outs, Connected 17.2% of pairs.
The first-player rate sits at the top edge of DUEL_DESIGN's 48–54% band (issue #64 asked for 48–52%). `secondPlayerCitations: 2` was not tested; duel-design prefers to accept ~54% over a 2-Citation swing.
**Landed:** duel-core set both as `DEFAULT_DUEL_RULESET` values on `engine-wip` 0eb80d2. night-review's random-play soak there (300 matches) gives a first-player rate of 51.0%, down from 62.7%, with 0 leaks, exact replay, and `turnCap` ending forced stalls at turn 40. duel-design recorded both in DUEL_DESIGN v1.3 (#66).
**Not shipped, with the evidence:**
- Second seat +1 opening card: no effect (60.7%); the mulligan and the 7-card hand limit absorb it.
- `garrisonStep` 15: Location-heavy decks +4 pts, but games get longer (p90 14, 4.5% past 20 turns).
- `territoryCap` 3, `locationsPerTurn` 2, `stubMax` 1, `startingLife` 16/24: ≤ ±3 pts on first player or Location decks.
- `libraryEmpty: reshuffle`: games stretch out (the run didn't finish in 9 min); BRIEF keeps the MTG rule.
- `firstPlayerDraws: true`: worsens the edge (+1.7 pts).
**Open for v1.1: Locations.** Location-heavy decks win ~17–21% in every variant, and Location cards are the weakest type (47–48%). The T2 rider "When this enters, draw a card" (v1-cand-ld) raises the Location card to 51.7% but does **not** help Location-heavy decks (16.5%), pushes the first player back to 58.4%, and brings back library-outs (117 of 3000). It needs another lever first, e.g. the conditional version ("if you already control 2 or more Locations") or a Location body (`garrisonStep`) change, tested together with spc1. Since random collections are ~32% Locations, this matters for real players.
**Healthy, leave alone:** Connected (17.2% of pairs, fires on 28% of plays, inside 15–30%). Famous cards are bigger, not strictly better: fame vs card win rate r = 0.10–0.20 overall, ≈0 or negative within a cost. Keywords all net positive; Featured strongest, kept per duel-design.
## Frozen head (01:15)
**Not run.** At the 01:15 freeze `night/2026-11-17` was still at 2af2e7f: no PR had merged all night (night-lead unreachable, see #53), so there was no frozen head containing the duel engine. The reference result is therefore **v1-cand at engine-wip 4623930 + duel-cards 067de83 (not frozen head)**. At 01:16 the newest unmerged heads were: engine-wip 0eb80d2 (balance v1 as defaults), duel-cards 5076299, duel-adapter d97cbc2. Once they merge, re-run with no overrides:
```
npx tsx scripts/sim/duel-run.ts --engine duel --workers 4 --mix fast --matches 3000 --label frozen --sha $(git rev-parse --short HEAD)
```
## Results
### v1 runs: engine-wip 4623930 + duel-cards 067de83 (Doctrines working)
Run by ui-duel on inspiron-3670 with this harness (duel-adapter acd2c49/7102239), Node 24, 4 workers, `--mix fast`, 120 decks. Not yet the frozen head; see "Frozen head" below.
| Run | Overrides | n | First player (sym) | Turns each p10/med/p90 | >20 turns each | Library-out | Loc-heavy | Doc-heavy | Fig-heavy |
|---|---|---|---|---|---|---|---|---|---|
| v1-base | `{}` | 3000 | **60.1%** [58–62] | 6 / 8 / 12 | 3.4% | 2.0% | 20.5% | 42.8% | 66.6% |
| v1-spc1 | `{"secondPlayerCitations":1}` | 1500 | **54.4%** [52–57] | 6 / 8 / 12 | 3.9% | 2.2% | 20.8% | 45.9% | 63.0% |
| v1-extra1 | second seat +1 opening card (sim-only hook) | 1500 | 60.7% [58–63] | 6 / 8 / 12 | 3.6% | 2.3% | 16.8% | 52.9% | 64.7% |
| v1-garr15 | derive `garrisonStep` 15 | 1500 | 58.5% [56–61] | 6 / 8 / 14 | 4.5% | 2.3% | 24.9% | 45.3% | 65.3% |
| v1-terr3 | `{"territoryCap":3}` | 1500 | 59.7% [57–62] | 6 / 8 / 12 | 3.0% | 1.9% | 21.3% | 49.4% | 64.7% |
| v1-cap40 | `{"turnCap":40}` | 1500 | 60.2% [58–63] | 6 / 8 / 12 | 0.0% | 0 (turnCap 3.1%) | 19.8% | 48.3% | 65.9% |
| **v1-cand** (3000) | `{"secondPlayerCitations":1,"turnCap":40}` | 3000 | **54.7%** [53–57] | 6 / 8 / 12 | 0.0% | 0 (turnCap 3.9%) | 17.9% | 41.7% | 64.2% |
| v1-cand-ld (3000) | v1-cand + every Location "When this enters, draw a card" | 3000 | 58.4% [57–60] | 6 / 8 / 12 | 0.0% | 3.9% (turnCap 0.4%) | 16.5% | 39.0% | 62.5% |
| v1-combo | garr15 + `{"secondPlayerCitations":1,"territoryCap":3,"turnCap":40}` | 1500 | **52.8%** [50–55] | 6 / 8 / 13 | 0.0% | 0 (turnCap 4.4%) | 21.3% | 43.0% | 61.8% |
Card type WR (seat that played it), v1-base → v1-combo: Doctrine 55.8 → 56.4, Event 51.1 → 51.8, Figure 58.8 → 58.4, Institution 53.1 → 52.8, Location 48.1 → 48.0. Est. minutes v1-combo 5.6 / 8.4 / 14.9.
v1-base other numbers: est. minutes 5.4 / 7.9 / 13.2; Connected 17.2% of pairs, 28.1% of plays (6.96 per game); fame vs card WR r = 0.20 (top vs bottom decile 62.1% vs 53.6%, both above the played-card baseline); card type WR Doctrine 55.8%, Event 51.1%, Location 48.1%.
### Old-tree sweep (engine 5cd0ffb + duel-cards ae14bc7, Doctrines inert): relative effects only
| Run | Overrides | First player | Turns each p10/med/p90 | >20 turns | Loc-heavy | Doc-heavy | Fig-heavy |
|---|---|---|---|---|---|---|---|
| alpha-base (4000) | `{}` | 57.8% [56–59] | 6 / 8 / 21 | 10.3% | 23.2% | 29.5% | 73.1% |
| p1draws | `{"firstPlayerDraws":true}` | 59.5% [57–62] | 6 / 8 / 19 | 9.4% | 24 | 27 | 74 |
| life24 | `{"startingLife":24}` | 55.0% [52–58] | 6 / 9 / 24 | 12.2% | 21.8% | 29.7% | 72.3% |
| life16 | `{"startingLife":16}` | 57.3% [55–60] | 5 / 8 / 16 | 7.7% | 27.9% | 29.1% | 68.2% |
| terr3 | `{"territoryCap":3}` | 56.0% [53–59] | 6 / 8 / 18 | 9.3% | 23.9% | 30.2% | 71.1% |
| loc2 | `{"locationsPerTurn":2}` | 55.1% [52–58] | 6 / 8 / 20 | 9.8% | 24.4% | 29.1% | 71.1% |
| stub1 | `{"stubMax":1}` | 55.0% [52–58] | 6 / 8 / 17 | 7.7% | 20.3% | 30.8% | 68.2% |
| reshuffle | `{"libraryEmpty":"reshuffle"}` | stopped after 9 min: games stretch out | | | | | |
### Baseline, engine alpha (duel-core `engine-wip` 5cd0ffb + duel-cards ae14bc7, merged locally). Not the frozen head.
> **Superseded:** at duel-cards ae14bc7 Doctrines attached but gave no ±k (fixed in 067de83). Doctrine numbers below are therefore wrong, and everything else is slightly off. See the v1 runs.
4000 matches, `--mix fast` (90% heuristic mirrors, 5% heuristic vs random, 5% heuristic vs greedy), 120 decks, 0 engine errors.
| Metric | Value | Target |
|---|---|---|
| First-player win rate | **57.8%** [56–59] | 48–52% |
| Turns each p10 / median / p90 | 6 / **8** / 21 | 8–12 |
| Est. minutes p10 / median / p90 | 5.6 / 8.6 / 20.3 | 8–15 |
| Games past 20 turns each | **10.3%** | < 5% |
| Library-out losses | 7.2% (70% of the long games) | |
| Connected pair rate / fires per play | 17.2% / 28% | 15–30% |
| Fame vs card WR within each cost | r = −0.24, −0.65, −0.54, +0.12, −0.14, +0.07 (costs 1–6) | ≈ 0 |
| heuristic vs greedy / random | 72.9% / 95.1% | |
**Findings**
1. **First-player edge is tempo.** 68.5% in games under 7 turns each, 57% at 7–9, ~54% in longer games. `firstPlayerDraws: true` raises it to 59.5% (1500 matches), so the edge needs compensation for the second seat, not a draw change.
2. **Deck composition dominates.** Win rate vs decks without the tag: Figure-heavy 73%, random 67%, high-curve 46%, Event-heavy 44%, Institution-heavy 37%, low-curve 35%, Doctrine-heavy 30%, Location-heavy **23%**. By card type (seat that played it): Figure 58.8%, Institution 51.3%, Event 50.2%, Doctrine 47.3%, Location 47.1%. Every one of the 8 bottom cards is a Location: past the 2-Territory cap a Location is only a 0/1–0/4 Garrison. Random collections are ~32% Locations (75 of 236), so this matters for real players, who can't choose what they mine.
3. **Famous cards are not strictly better.** Within a cost, fame and win rate are uncorrelated or negative (the keyword tax). Cost-6 cards win 61% when played, but that includes a survivorship effect (you only reach 6 Citations in longer games you're still in).
4. **Keywords are all net positive.** When played: Featured 67.6%, Multilingual 67.6%, Well-sourced 59.6%, Protected 59.2%, Translated 59.0%, Legacy 58.6%, Stub 58.2%, Local 54.6%, none 48.6%. Featured is the strongest relative to its tax.
5. **Long games** are not mainly Location decks: past 20 turns each in 16% of low-curve games, 13% random, 11% Location-heavy, 3% Event-, Institution-heavy and high-curve. Boards stall and decks run out.
Caveats: the heuristic bot may under-use Doctrines and Events, and may be too cautious to attack into walls (the MC-mirror check was stopped, see below), so the Doctrine/Event numbers and the stall rate are upper bounds on the problem.
The sweep on r350 was stopped at 23:00 when r350 ran out of memory; ui-duel re-ran it on inspiron (tables above).
+279
View File
@@ -0,0 +1,279 @@
# WikiDeck Duel: design v1
**Status:** v1.3, Night 2 (2026-11-17): v1 plus night-review's nits on PR #66, duel-cards' implementation choices from PR #70, and the balance v1 rules `secondPlayerCitations` 1 and `turnCap` 40 (#64). Owner: duel-design (issue #60).
**Base:** `docs/night2/BRIEF.md` (Eric's locked decisions). Where this file and BRIEF disagree, BRIEF wins. Reviews used: designer (rules), data §2–4 (derivation), critic S7 (tone).
**Consumers:** duel-core (`shared/duel/` engine and `types.ts`), duel-cards (`classify/derive/effects/text.ts`), sim-balance (bots, `DUEL_BALANCE.md`), ui-duel / ui-pvp (faces, recap), host-pvp (rulesets).
Every number in this file is a **ruleset key or a derivation table value**, not code. sim-balance tunes them in data-only PRs.
---
## 1. The game in one paragraph
Two players each bring **40 cards they own on-chain**. Each card is a Wikipedia article turned into a Magic-style card by fixed rules over real data. You start at **20 Notability**. Every turn your **Citations** (mana) maximum rises by one. You deploy Figures, attack with them, block with yours, cast Events, adopt Doctrines onto Figures. The first player to 0 Notability, or unable to draw, loses. The match is written up afterwards as an encyclopedic "Battle of X (2026)" page.
---
## 2. Rules
### 2.1 Decks and eligibility (BRIEF decisions 1–2)
| Key | Default | Rule |
|---|---|---|
| `deckSize` | **40** | Exactly this many cards. Every card is an NFT the player owns (server-verified by `ownership.ts`). No Basics, loaners, proxies or tokens in decks. |
| `maxCopiesPerPage` | **4** | Different mints of the same `pageId` may appear up to 4 times (each mint once: it is unique). |
| colour/Portal rules | none | Any mix of Portals. |
| Eligibility | owns ≥ `deckSize` | Below it, the UI shows "23 / 40 cards" and how to mine. No practice with borrowed cards. Bot matches need eligibility too. |
Testnet end-to-end mode files may lower `deckSize`. Production stays at 40.
### 2.2 Setup
- **Notability** (life): `startingLife` **20**. At 0 you lose.
- **Empty library:** drawing from an empty library loses (`libraryEmpty: 'lose'`).
- **Opening hand:** `openingHand` **7**. One mulligan (`mulligans: 1`): shuffle, draw 7, put 1 on the bottom.
- **First player** (seeded coin flip) skips their first draw.
- **Second player** gets +1 Citation maximum on their first turn only (`secondPlayerCitations` **1**). Balance v1: this moved the first-player win rate from 60.1% to 54.4% in 1,500 heuristic-mirror matches (engine 4623930, #64). Neither an extra opening card (washed out by the mulligan and the hand limit) nor `firstPlayerDraws` worked.
### 2.3 Turn structure: refresh → draw → main → combat → end
1. **Refresh.** Citation maximum +1 (to `maxCitations` **10**), plus Territory (§2.5). Citations refill to the maximum. Your permanents untap. "Pending review" ends for your Figures. Start-of-turn triggers (Stub, Institutions) resolve in the order the permanents entered.
2. **Draw** 1 card.
3. **Main.** Play cards in any order while you can pay their cost in Citations: Figures, Locations (one per turn: `locationsPerTurn` 1), Institutions, Doctrines (attach to a Figure), Events (resolve immediately).
4. **Combat** (§2.4).
5. **End.** Damage on permanents clears. "Until end of turn" effects end. Discard down to `handLimit` **7** (the player chooses; bots discard highest cost first).
**Zones.** Library and hand are hidden (a hand's size is public). The battlefield and **Deleted** (the graveyard) are **public**: a discarded card is revealed and named once it reaches Deleted.
There is **no second main phase, no stack, no priority and nothing at instant speed.** Events are sorcery-speed. Triggers resolve immediately, in a fixed order: the active player's first, in the order the cards entered.
### 2.4 Combat
- **Attack:** the active player chooses any untapped Figures without Pending review and taps them. They attack the opponent only, never permanents.
- **Block:** the defender assigns **at most one blocker per attacker**, and each blocker blocks one attacker. Untapped Figures and Garrison Locations may block. Evasion (Featured) restricts who may block: **a Garrison Location can't block a Featured attacker** (only Featured, Translated or Multilingual Figures can).
- **Damage:** simultaneous. A blocked pair deal their power to each other. An unblocked attacker deals its power to the defending player's Notability.
- A permanent with damage ≥ toughness is **destroyed** (goes to the Deleted pile, the graveyard). Destroy triggers (Legacy) fire after all combat damage.
- No trample, no first strike, no deathtouch, no lifelink in v1.
### 2.5 Card types (BRIEF; classifier in data §1, built by duel-cards)
| Type | MTG analogue | Rules |
|---|---|---|
| **Figure** | creature | Power/toughness. Enters with **Pending review** (summoning sickness): can't attack until your next turn. |
| **Location** | land-ish permanent | Cost `ceil(derivedCost/2)` (1–3). **Territory:** +1 Citation maximum while you control it; at most **+2 in total** from Territory (`territoryCap` 2). **Garrison 0/T:** can block like a 0-power Figure (T = 1 + floor(pct_depth / 25), so 1–4). Can't attack. Damage clears at end of turn as usual; a Location destroyed in a block goes to Deleted. One per turn. |
| **Event** | sorcery | Resolves at once, then goes to Deleted. |
| **Institution** | artifact | A permanent with a static or triggered ability. |
| **Doctrine** | Aura | **Adopt:** attach to target Figure (yours or the opponent's for negative Doctrines). If the Figure leaves play, the Doctrine goes to Deleted. |
Classification order (duel-cards owns it): P31 → P279 anchor classes → P31 label regex (`^human$`, fixing the `\bhuman\b` bug) → categories → description → **Doctrine**. The derived profile is **frozen** the first time a card is seen.
### 2.6 Clock and length
- `turnSeconds` **60** per turn plus `bankSeconds` **300** per player. The turn timer runs first; when it expires, the player's bank drains; when the bank is also empty, the turn passes (`timeout` action). The bank does not refill. Three timeouts in a row concede.
- **`turnCap` 40** (20 turns each, balance v1). At the cap the higher Notability wins, then the higher total power in play, then the second player. In sims it decides about 4% of games and removes every game past 20 turns each, without moving the median.
- **Sim targets** (agreed with sim-balance, #64): median 8–12 turns each; first-player win rate 48–54%; < 5% of games past 20 turns each. **Balance v1 result** (`secondPlayerCitations` 1 + `turnCap` 40; 3,000 heuristic-mirror matches, engine 4623930, duel-cards 067de83; run by ui-duel for sim-balance, #64): first player **54.7%** [53–57], turns each 6 / 8 / 12, 0% past 20, about 8 minutes median.
### 2.7 Determinism
All randomness (shuffles, coin flip, template variants) comes from the match seed via `shared/game/rng.ts`. The same seed and actions always replay to the same state, log and recap.
---
## 3. Derivation summary (duel-cards implements; data §2)
- **Percentiles** `pct_a`, `pct_d`, `pct_r` from the sample cut points (DESIGN.md §1.1 counting). **fame** = mean of the three, rounded.
- **Cost** 1–6 by `costThresholds` [26, 39, 51, 63, 78].
- **Figure body budget** P+T = [3, 4, 6, 8, 10, 12] for cost 1–6 (MTG vanilla curve). Subtract **1 per taxed keyword** (§4). At cost 1, a second taxed keyword is skipped, so a body never drops below 1/1. Then `power = clamp(round(budget × pct_a / (pct_a + pct_d)), 1, budget − 1)`, toughness = the rest. Famous cards are bigger and pricier, never more efficient.
- **Magnitude** for non-Figures: `k = ceil(cost / 2)` (1–3).
- **Portal** (faction): Arts, Earth, History, Science, Society, or Neutral, scored by regex hits (designer §3.2); ties go to the type default (Figure → Society, Location → Earth, Event → History, Institution → Arts, Doctrine → Science). No deckbuilding restriction.
- **Flavour text:** first sentence of on-chain `article.extract`; if absent (the sample has none), the Wikidata `description`; if that is empty too, none.
---
## 4. Keywords (10)
Eight card keywords, each triggered only by real data and applied **to Figures only**, at most **2 per card** in the priority order below. Plus two rules keywords. Thresholds are measured on the 236-card sample (86 Figures); sim-balance may move them.
| # | Keyword | Trigger (real data) | Rules text | Body tax | Rate among Figures |
|---|---|---|---|---|---|
| 1 | **Protected** | category `Living people` | Can't be the target of Events or Doctrines an opponent controls. | 1 | 38% |
| 2 | **Featured** (flying) | pct_attention ≥ 85 | Can't be blocked except by Featured, Translated or Multilingual Figures. | 1 | 15% |
| 3 | **Legacy** | a `<year> deaths` category (or P570 in the frozen profile) | When this is destroyed, draw a card. | 1 | 33% |
| 4 | **Multilingual** | pct_reach ≥ 90 | Can block Featured Figures. Can't be blocked by Local Figures. | 1 | ~5% |
| 5 | **Translated** (reach) | 75 ≤ pct_reach < 90 | Can block Featured Figures. | 0 | 19% |
| 6 | **Well-sourced** | pct_depth ≥ 85 | Prevent the first 1 damage that would be dealt to this each turn. | 1 | ~13% before cap |
| 7 | **Stub** | pageBytes < 3000 or a `…stubs` category | At the start of your turn, put a +1/+1 counter on this, to a maximum of 2. | 0 | 33% |
| 8 | **Local** | raw reach = 0 (no other language editions) | Gets +1/+1 while you control a Compatriot Location (same P17). | 0 | 7% before cap |
| 9 | **Connected** | the card pair's frozen claims and links (§6) | +1/+1 while you control another card Connected to it; +2/+2 if Linked. | – | target 15–30% of pairs |
| 10 | **Trending** (haste) | Trending mode only: frozen live ▲ (trend ≥ +25% and daily ≥ 20) | Can attack the turn it enters. Gets +1/+0. | – | ~2% of cards |
Rule words that are not keywords: **Pending review** (summoning sickness), **Territory**, **Garrison**, **Adopt**, **Deleted** (the graveyard).
Notes:
- Protected deliberately sits first: living people are the most targeted, and the rule that matters most for them is mechanical, not a tone rule. It doesn't stop combat.
- Multilingual and Translated are two bands of the same reach axis, so a card never has both.
- A card's face shows at most 2 keyword words; the reminder text is behind a tap.
---
## 5. Effect templates (12, MTG register)
Subtype regexes run over the frozen P31/P279 labels, then the description, then categories. First match wins, in the order listed. `k = ceil(cost/2)`.
| # | Type / subtype | Trigger regex (labels, description) | Rules text |
|---|---|---|---|
| T1 | Figure | (all Figures) | Vanilla body + keywords. No other text. |
| T2 | Location | (all Locations) | Territory. Garrison 0/T. |
| T3 | Event: conflict | `battle\|war\|siege\|annexation\|protest\|riot\|uprising\|massacre\|coup` | Deal k+1 damage to target Figure or Location. |
| T4 | Event: disaster | `storm\|nor.easter\|cyclone\|hurricane\|earthquake\|flood\|tornado\|wildfire\|eruption\|famine\|epidemic` | Deal k−1 damage (minimum 1) to each Figure and each Location. |
| T5 | Event: election | `election\|referendum\|straw poll` | Create k 1/1 Society Figure tokens named Elected Member. |
| T6 | Event: sport | `match\|final\|season\|tournament\|championship\|grand prix\|race` | Target Figure you control gets +k/+0 until end of turn, then fights target Figure you don't control. |
| T7 | Event: default (period, ceremony, scandal, other) | anything else | Draw k cards. |
| T8 | Institution: organisation | `company\|organi[sz]ation\|party\|agency\|studio\|military\|university\|diocese\|council\|band\|musical group\|association\|business\|school\|college\|institute\|manufacturer` | Cost ≥ 4: "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member." Cost ≤ 3: "When this enters, create a 1/1 Figure token named Staff Member." |
| T9 | Institution: creative work | `film\|album\|song\|book\|novel\|series\|video game\|painting\|software\|typeface\|newspaper\|magazine` | When this enters, draw a card. Figures you control that are Connected to this get +1/+1. |
| T10 | Institution: team, award, vehicle, other | anything else | Figures you control with power 2 or less get +1/+0. |
| T11 | Doctrine: Adopt | (all non-Pathology Doctrines) | Attach to target Figure you control. It gets +k/+k. Rider by subtype, checked in the order pathology (→ T12) > language/software > mathematics, so "functional programming language" is not maths: mathematics → "and has Well-sourced"; language/software → "Whenever it deals combat damage to a player, draw a card"; ideology/religion → "Other Figures you control of its Portal get +1/+0"; otherwise none. |
| T12 | Doctrine: Pathology | `disease\|clinical sign\|pathogen\|syndrome\|disorder\|toxin\|poison` | Attach to target Figure. It gets −k/−k. |
Elected Member tokens are Society; Staff Member tokens have no Portal ("1/1 Figure token"). Tokens are not cards: they never appear in decks, are created only by T5/T8, and are removed when they leave play. Token names are fixed generic strings, never real people.
Rules-text style:
- Second person, present tense, MTG terse register: "Deal 3 damage to target Figure."
- Card names appear in rules text only as "this" (never the article title), so text stays the same length on a 360 px face.
- No adjectives, no puns, no exclamation marks.
---
## 6. Connected (data §4 tiers)
Computed by the host at match start from frozen card profiles. No network calls during a match; the edge list is written into the match record.
| Tier | Test | Bonus | Cut order |
|---|---|---|---|
| **Linked** | either article links to the other (cached outlinks), or one card's claims cite the other's Q-id | +2/+2 | keep |
| **Compatriot** | share a P17 (country) or P27 (citizenship) value | +1/+1 | keep |
| **Contemporary** | same century from P569/P570/P571/P580/P585, **only between different types** | +1/+1 | cut 4th (BRIEF) |
| **Kin** | same P31 class, excluding Q5 human and Q16521 taxon | +1/+1 | cut 4th (BRIEF) |
- A Figure gets the **single best** bonus among its Connected cards you control (no stacking): +2/+2 if any is Linked, else +1/+1.
- A Connected creative-work Institution (T9) gives its +1/+1 on top.
- **Target:** 15–30% of random card pairs connected (text proxies measured 21.5% for country OR century). If sims show more, drop the noisiest keys first (P17 = United States, then France); if fewer, add P131.
- The card shows why: "Connected — *Pathrail Mosque* (country: Bangladesh)".
- **Rivalry** (log only): when two opposing cards are Connected, the log may note it once (§8.3). No mechanical effect.
---
## 7. Modes (on the duel engine)
| Mode | Decks | Notes |
|---|---|---|
| **Classic** | constructed from your own 40+ owned cards | Ranked (Elo, keyed to the eom.dev account). Invite links and quick match. |
| **Bot** | your own 40 | Only for eligible players. Not ranked. |
| **Draft** | both players eligible | Pool drawn from both players' collections (e.g. 30 cards from each, shuffled into one pool). Snake-pick until each has `deckSize`. Drafted cards are used for that match only; nothing moves on-chain. Ownership is credited in the recap ("from the collection of bob"). |
| **Trending** | any | Live pageview trend from the daily cache, frozen at match start: ▲ (≥ +25%, daily ≥ 20) gives Trending (haste, +1/+0); ▼ (≤ −50%, daily ≥ 20) gives −1/−0. Cut 3rd. |
| **House rules** | peer-hosted | Data-only, versioned schema. Keys: `deckSize`, `maxCopiesPerPage`, `startingLife`, `openingHand`, `mulligans`, `maxCitations`, `territoryCap`, `handLimit`, `turnSeconds`, `bankSeconds`, `turnCap`, `secondPlayerCitations`, `connectedTiers`, `keywordThresholds`. Night 1 mode files are rejected cleanly with a message. |
---
## 8. Tone and story text
### 8.1 Tone rules (BRIEF decision 5, critic S7)
1. **Lean in.** Living people, tragedies, wars, disasters, crimes, diseases and dictators are ordinary cards with full mechanics. No `solemn` flags, no special cases, no softened verbs. "Casualties" is fine. A protester shot in 1970 is a 6/3 with Legacy like anything else.
2. **Deadpan.** The text takes itself completely seriously. It **never winks** and **never comments on the matchup** ("in a surprising twist", "unlikely", "ironically" are banned). The comedy lives in the nouns: "*Heart rot* was adopted by *Tom Ewell*."
3. **Encyclopedic texture.** Past tense, third person, passive where Wikipedia would use it, dates and turn numbers, and `[n]` citations linking each card's real article at its revision.
4. **No adjectives about cards or players** (no "brutal", "heroic", "humiliating", "bloodiest"). Mechanical verbs only: deployed, attacked, blocked, was destroyed, was adopted by, took N damage, was cited.
5. **Never invent facts about real people.** All generated text is a deterministic template filled **only** with real card data (title, description, dates, categories, revision id) and real match data (turn, players, numbers). No LLM prose. No made-up quotes, crimes, acts, motives or feelings. The template verbs describe **game events of the card**, and every narrative paragraph is framed as a WikiDeck engagement; the footer says so.
6. **Allowed real data in text:** title, Wikidata `description`, birth/death years parsed from the description or frozen claims, the first extract sentence (flavour), Portal, type. Nothing else about a person.
7. **Dull guard:** 3–4 synonymous variants per event, chosen by the match seed (§8.2).
| DO | DON'T |
|---|---|
| "Turn 6. *Zbyszek Godlewski* (6/3) attacked. *Pallas's cat* (5/5) blocked. *Zbyszek Godlewski* was destroyed.[3][4]" | "Godlewski got mauled by a cat lol" |
| "The *April 2021 nor'easter* dealt 1 damage to each Figure. *Dichromorpha viridis* was destroyed.[5][6]" | "Mother Nature wiped out the poor grasshopper!" |
| "*Heart rot* was adopted by *Tom Ewell*, which became a 2/2.[7][8]" | "Ewell caught a tree disease, how embarrassing" (adjective + invented claim) |
| "The **Battle of Pathrail Mosque (2026)** was a WikiDeck engagement fought on 17 November 2026 between the forces of alice and bob." | "the bloodiest battle in WikiDeck history" |
### 8.2 Match-log templates (`shared/duel/story/log.ts`)
- One template group per engine `LogEvent` kind, each with **3–4 variants**. Variant = `rng(seed, turn, eventIndex) mod n`, using the match seed, so `replay` regenerates the log exactly.
- First mention of a card in a match adds its description in parentheses: "*Tom Ewell* (American actor, 1909–1994)". Later mentions use the title only.
- Each first mention of a card assigns it the next reference number `[n]`; later mentions reuse it.
- `logFor(seat)` hides the opponent's hand: their draws read "bob drew a card." and mulligans are not named. Discards are named, because Deleted is public (§2.3).
| Event | Variants (`{card}` italic, `{player}` the seat name) |
|---|---|
| deploy (Figure/Location/Institution) | "{player} deployed {card}." · "{card} was deployed by {player}." · "{player} brought {card} into play." · "{card} entered play under {player}." |
| event cast | "{player} cited {card}." · "{card} was cited by {player}." · "{player} invoked {card}." |
| adopt | "{doctrine} was adopted by {figure}, which became a {p}/{t}." · "{figure} adopted {doctrine} and became a {p}/{t}." · "{player} attached {doctrine} to {figure} ({p}/{t})." |
| attack | "{card} ({p}/{t}) attacked." · "{player} sent {card} ({p}/{t}) into combat." · "{card} ({p}/{t}) advanced on {opponent}." |
| block | "{blocker} ({p}/{t}) blocked {attacker}." · "{attacker} was blocked by {blocker} ({p}/{t})." · "{blocker} ({p}/{t}) intercepted {attacker}." |
| player damage | "{opponent} lost {n} Notability ({life} remaining)." · "{card} dealt {n} damage to {opponent}, leaving {life} Notability." · "{opponent}'s Notability fell to {life}." |
| destroyed | "{card} was destroyed." · "{card} was moved to Deleted." · "{card} was removed from play." · "{card} did not survive the turn." |
| effect damage | "{source} dealt {n} damage to {target}." · "{target} took {n} damage from {source}." · "{source} inflicted {n} damage on {target}." |
| token created | "{source} produced {n} {token}." · "{n} {token} were created by {source}." · "{source} created {n} {token}." |
| draw (own) | "{player} drew {card}." · "{card} was drawn." · "{player} added {card} to their hand." |
| draw (hidden) | "{player} drew a card." · "{player} drew {n} cards." |
| Connected | "{a} and {b} were Connected ({reason})." · "{a} was Connected to {b} through {reason}." · "Records link {a} and {b} ({reason})." |
| discard | "{player} discarded {card}." · "{card} was discarded by {player}." · "{player} moved {card} from hand to Deleted." |
| rivalry (opposing Connected pair, once) | "{a} and {b} are both listed under {reason}." · "{a} and {b} share {reason}." · "The two sides were linked through {reason}." |
| turn start | "Turn {n}." (fixed) |
| game over | "{loser} was nominated for deletion. The result was **delete**." · "{loser} was reduced to 0 Notability. {winner} won." · "{winner} won on turn {n}." · (library) "{loser} could not draw a card and lost." · (concede) "{loser} withdrew." |
### 8.3 Battle recap (`shared/duel/story/recap.ts`)
A deterministic function `recap(matchRecord) → RecapDoc` (structured data; ui-pvp renders it). Inputs are the match record only: seed, players, decks' frozen card profiles, the event list, the date. No network, no clock.
**Title:** "{Prefix} {Name} ({year})"
- **Name:** the winner's highest-cost Location that entered play; else the loser's; else the highest-cost Event cast in the match; else the winner's highest-cost card deployed; ties broken by first played. Living people and tragedies are eligible like any card ("Battle of Zbyszek Godlewski (2026)" is valid).
- **Prefix:** "Skirmish at" (≤ 6 turns each), "Battle of" (7–12), "Siege of" (≥ 13). For a Figure name: "Battle of" becomes "{Name} campaign" (no prefix).
- **Year:** the match date's year (2026).
**Infobox:**
| Field | Value |
|---|---|
| Date | the match date, "17 November 2026" |
| Location | the Name card if it's a Location, else "WikiDeck host {hostName}" |
| Result | "Decisive {winner} victory" (margin ≥ 10 Notability) · "Pyrrhic {winner} victory" (winner ≤ 3) · "{winner} victory" · "{winner} victory by withdrawal" (concession/timeout) · "{winner} victory by attrition" (empty library) · "Victory by decision" (turn cap) |
| Belligerents | the two seat names (account display names) |
| Commanders | each side's highest-cost Figure deployed |
| Strength | cards deployed per side ("14 cards") |
| Casualties and losses | cards destroyed per side, count, then the titles |
**Sections:**
1. **Lead** (1 paragraph): "The {title} was a WikiDeck engagement fought on {date} between the forces of {a} and {b}. It lasted {n} turns and ended in {result-lowercase}.[1]" + one sentence on the first Figure deployed: "Contemporary accounts note the deployment of {card} in the {ordinal} turn.[n]"
2. **Background:** each side's Portal mix ("History was the largest Portal in the force of alice (eleven of twenty cards played)").
3. **Course of the battle:** the 3–5 largest Notability swings and every destroyed card with cost ≥ 4, in turn order, as log sentences (variants from §8.2, but seeded with `seed ⊕ 'recap'` so the recap doesn't repeat the log word for word).
4. **Aftermath:** final Notability, turns, rating change if ranked.
5. **See also:** Connected pairs and rivalries.
6. **References:** every card played by either side, in first-mention order: "{n}. ^ "{title}". Wikipedia. Revision {revisionId}. Minted as token {tokenId}." linking `https://en.wikipedia.org/w/index.php?title={title}&oldid={revisionId}`.
**Branding and footer:** WikiDeck masthead, never the Wikipedia/Wikimedia name or logo. Footer: "This page records a WikiDeck match. Card names refer to Wikipedia articles; the events described are game events." Shareable at `/recap/{matchId}`.
---
## 9. Worked examples (12 cards from `docs/game/card-sample.json`)
Computed with the rules above (data §2 budget, §4 keyword priority, §5 templates) by a script over the sample, and checked by hand. duel-cards' implementation (PR #70) agrees on all 12, with the two Portal corrections now applied (#9, #11). Flavour is the `description` because the sample has no extracts. Final numbers come from duel-cards' implementation; if they differ, the implementation and its golden test win and this table is updated.
| # | Card | Derivation | Card |
|---|---|---|---|
| 1 | **Marc Fesneau** (living person) | P31 human → Figure. "politician" → Society. pct 76/68/63 → fame 69 → cost 5, budget 10. Living people → Protected (−1) → 9 split 76:68 → 5/4. | **Marc Fesneau** · 5 · Figure — Society · **5/4** · *Protected.* "French politician (born 1971)." |
| 2 | **Tom Ewell** | human → Figure, Arts. 94/83/93 → fame 90 → cost 6, budget 12. Featured (−1), Legacy (−1); Multilingual dropped by the cap. 10 → 5/5. | **Tom Ewell** · 6 · Figure — Arts · **5/5** · *Featured. Legacy.* "American actor (1909–1994)." |
| 3 | **Zbyszek Godlewski** (killed at a 1970 protest) | human → Figure, History. 77/48/78 → fame 68 → cost 5. Legacy (1970 deaths, −1), Translated (pct_r 78, 0). 9 split 77:48 → 6/3. | **Zbyszek Godlewski** · 5 · Figure — History · **6/3** · *Legacy. Translated.* "Polish protester (1952–1970)." |
| 4 | **Pallas's cat** | taxon → Figure, Earth. 99/97/99 → fame 98 → cost 6. Featured (−1), Multilingual (−1); Well-sourced dropped. 10 → 5/5. | **Pallas's cat** · 6 · Figure — Earth · **5/5** · *Featured. Multilingual.* "Species of small wild cat." |
| 5 | **Dichromorpha viridis** | taxon → Figure, Earth. 58/3/53 → fame 38 → cost 2, budget 4. Stub (1,347 bytes, untaxed). Split clamps to 3/1. | **Dichromorpha viridis** · 2 · Figure — Earth · **3/1** · *Stub.* "Species of grasshopper." |
| 6 | **Monoid** (maths) | no P31; category "Algebraic structures" → Doctrine, Science. fame 96 → cost 6, k = 3. Maths rider. | **Monoid** · 6 · Doctrine — Science · Attach to target Figure you control. It gets +3/+3 and has Well-sourced. "Algebraic structure with an associative operation and an identity element." |
| 7 | **Heart rot** (disease) | P31 plant disease → Doctrine, Pathology (T12). Science. fame 68 → cost 5, k = 3. | **Heart rot** · 5 · Doctrine — Science · Attach to target Figure. It gets −3/−3. "Fungal disease of trees." |
| 8 | **April 2021 nor'easter** (disaster) | P31 nor'easter → Event, disaster (T4). Earth. fame 50 → cost 3, k = 2. | **April 2021 nor'easter** · 3 · Event — Earth · Deal 1 damage to each Figure and each Location. "Slow-moving nor'easter in April 2021." |
| 9 | **2025 Tehreek-e-Labbaik Pakistan protests** (conflict) | P31 protest → Event, conflict (T3). Society (protest/riot hits outnumber "war"). fame 64 → cost 5, k = 3. | **2025 Tehreek-e-Labbaik Pakistan protests** · 5 · Event — Society · Deal 4 damage to target Figure or Location. "Gaza war protests in Pakistan." |
| 10 | **1954 Gold Coast general election** | P31 legislative election → Event, election (T5). Society. fame 45 → cost 3, k = 2. | **1954 Gold Coast general election** · 3 · Event — Society · Create two 1/1 Society Figure tokens named Elected Member. *(no flavour: empty description)* |
| 11 | **Pathrail Mosque** | P31 mosque → Location, Society ("mosque" hits in P31, the description and two categories outnumber 15th-century + Sultanate). fame 49 → cost 3 → Location cost 2. pct_d 54 → Garrison 0/3. | **Pathrail Mosque** · 2 · Location — Society · Territory. Garrison 0/3. "Mosque in Faridpur, Bangladesh." |
| 12 | **Tatsunoko Production** | P31 animation studio → Institution, organisation (T8). Arts. fame 93 → cost 6. | **Tatsunoko Production** · 6 · Institution — Arts · At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member. "Japanese animation studio." |
Interactions these cards show:
- *Heart rot* on *Marc Fesneau* is illegal (Protected stops opponents' Doctrines). On *Tom Ewell* it makes a 2/2 Featured Legacy.
- *Monoid* on *Dichromorpha viridis* makes a 6/4 Well-sourced Stub that keeps growing to 8/6.
- *April 2021 nor'easter* destroys *Dichromorpha viridis* and both Elected Members, and leaves *Pathrail Mosque* at 0/3 with 1 damage.
- *Pathrail Mosque* and *2025 Tehreek-e-Labbaik Pakistan protests* are not Compatriots (Bangladesh vs Pakistan); *Pathrail Mosque* and *Zbyszek Godlewski* are not Contemporary (15th vs 20th century).
Sample log:
> Turn 5. alice deployed *Zbyszek Godlewski* (Polish protester, 1952–1970).[1]
> Turn 6. bob cited the *April 2021 nor'easter* (Slow-moving nor'easter in April 2021).[2] The *April 2021 nor'easter* dealt 1 damage to *Zbyszek Godlewski*.
> Turn 7. *Zbyszek Godlewski* (6/3) attacked. *Pallas's cat* (5/5) blocked *Zbyszek Godlewski*.[3] *Zbyszek Godlewski* was destroyed. alice drew a card.
---
## 10. Hand-offs
- **duel-core:** §2 rules and ruleset keys; `LogEvent` kinds needed by §8.2 (deploy, cast, adopt, attack, block, playerDamage, destroyed, effectDamage, tokenCreated, draw, connected, turnStart, gameOver with reason `life|library|concede|timeout|turnCap`). Each event carries card ids, P/T after the event, and Notability where relevant.
- **duel-cards:** §3 derivation, §4 thresholds and priority, §5 templates T1–T12, §6 tiers; the §9 table as golden tests.
- **sim-balance:** §2.6 targets; tune `keywordThresholds`, `connectedTiers`, T4's k−1, the Stub cap and the T8 token rate; report the first-player win rate and the cost-6 dominance check.
- **ui-pvp:** renders `RecapDoc` from §8.3.
## 11. Open questions for the sim (not blockers)
1. Disaster T4 at k−1 may be weak against 40-card boards; try k.
2. Stub at +2 counters on cheap bodies may be too strong (33% of Figures); try max 1.
3. **Locations (balance v1 finding):** Location-heavy decks win ~20% and Locations are the weakest cards. `territoryCap` 3, `locationsPerTurn` 2 and `garrisonStep` 15 move them ±3 points at most. Tested and **rejected for v1**: a T2 rider "When this enters, draw a card". It lifts the Location card (47 → 52%) but not Location-heavy decks (18 → 17%), pushes the first player back to 58.4%, and brings back library-out losses. Open for v1.1: a lever that helps Location-heavy decks without extra card flow, e.g. Territory that scales (+1 Citation per two Locations) or Garrison Locations that can block Featured.
+20 -7
View File
@@ -18,12 +18,13 @@ A mode is a JSON document, at most 8 KiB:
```json
{
"schema": "wikideck.mode/1",
"schema": "wikideck.mode/2",
"id": "trending",
"version": 1,
"name": "Trending",
"description": "Live Wikipedia pageview trends power cards up or down.",
"tags": ["live-data"],
"engine": "editwar",
"rules": { "trendUp": 25, "trendDown": -25 },
"cards": { "preset": "trending", "percentPerPoint": 25, "maxBonus": 3, "penalise": true },
"decks": { "kind": "starter" },
@@ -33,12 +34,14 @@ A mode is a JSON document, at most 8 KiB:
| Field | Meaning |
|---|---|
| `schema` | `wikideck.mode/2`. Night 1 documents (`wikideck.mode/1`) are rejected with a message saying what to change. |
| `engine` | Required: `editwar` (the Night 1 simultaneous-reveal game, `shared/game`) or `duel` (the Night 2 Magic-style duel, `shared/duel`). Duel modes only allow `constructed` and `draft` with `source: "collections"`: every card is one the players own. |
| `id`, `version` | Lowercase slug and a version integer. Bump `version` whenever the rules change, so old match records and leaderboards stay attributable (`<origin>#<id>@<version>`). |
| `name`, `description`, `tags` | Plain text only: no control characters or `<` `>`. |
| `rules` | **Overrides** on top of the engine's `DEFAULT_RULESET` (see `docs/game/ENGINE_API.md`). Objects merge one level deep; arrays and numbers replace. The merged result then goes through the engine's strict `parseRuleset`, so the engine alone decides what's legal (bounded turns, Topics, deck sizes, known keywords and portals only; see DESIGN.md §9 for the keys). |
| `cards` | A card-mapping **preset** from a fixed list. `standard` leaves cards as dealt. `live` freezes each card's live trend arrow (DESIGN §1.6, using the ruleset's `trendUp`/`trendDown`) at match start. `trending` does the same and also adds a bounded power bonus from the live pageview trend. The mode only picks a preset and tunes its bounded numbers. |
| `decks` | `starter` (everyone gets a seeded starter deck), `draft` (snake draft from a host-seeded pool of preview cards) or `constructed` (bring your own; see "Not yet" below). |
| `limits` | Concurrency and lobby expiry for this mode on this host. `turnSeconds` only applies to engines without their own turn timer; with tonight's engine, the ruleset's `turnSeconds` (plus 5 s network grace) is the timer. |
| `decks` | `constructed` (each player submits exactly `deckSize` NFT token ids they own; the host verifies ownership and confirmations on the chain, `minConfirmations` default 1, and builds every card from its block), `starter` (Edit War only: a seeded starter deck) or `draft` (snake draft; `source: "preview"` uses preview cards, Edit War only; `source: "collections"` pools both players' owned cards for that match only, and both must own at least `deckSize`). |
| `limits` | Concurrency and lobby expiry for this mode on this host. `rated: true` moves Elo (start 1200, K 24) when both seats are eom.dev accounts; `accountsOnly: true` refuses guest seats (owned-card modes always do). `turnSeconds` only applies to engines without their own turn timer; with tonight's engine, the ruleset's `turnSeconds` (plus 5 s network grace) is the timer. |
The schema is strict: unknown fields are rejected, as are prototype keys
(`__proto__`, `constructor`, `prototype`) anywhere in the document, nesting deeper than two
@@ -46,6 +49,17 @@ levels inside `rules`, more than 48 rule keys, and oversized strings and arrays.
**never** evaluates, imports or runs anything another peer sends. Nothing in a mode can name
a file, a URL, a script or a function.
### Seats, invites, quick match and polling (Night 2)
- **Seats:** `POST /modes/:id/lobbies`, `POST /lobbies/:id/join` and `POST /modes/:id/quick` take `{idToken, deck?, private?}` for an eom.dev account (the Dex ID token may also be sent as `Authorization: Bearer <jwt>`), or `{name, secret}` for a guest in Edit War modes. The reply is `{lobbyId, seat, token, invite, playerId}`; `token` is the seat bearer for every later call. Account player ids are `sha256("acct:" + iss + "\n" + sub)`.
- **Invites:** every lobby gets a 12-character `invite` code. `private: true` hides it from `/lobbies` and quick match. `GET /invites/:code` describes it and `POST /invites/:code/join` joins it (SPA link: `/play/invite/<code>`).
- **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=<version>` 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 (`<dataDir>/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
Configure modes with environment variables on your node:
@@ -255,10 +269,9 @@ be pinned in consensus.
## Not yet
- `constructed` decks of **owned NFTs**: the policy exists, but tonight the host deals
starter decks for it. Playing with your own cards needs a wallet-signed ownership proof
for the lobby (and then the engine's `cardFromStats`). That's a follow-up once accounts and
wallet linking (#7) settle.
- `constructed` decks of **owned NFTs** are verified on the hosting node only, against its
own account store (Night 2). Playing them on a *peer* needs a wallet-signed deck claim,
because accounts are per node; that's a follow-up.
- `trending` never calls Wikipedia when a match starts. The node warms a cache-only trend
store in the background, one page every 20 s (configurable, never faster than 15 s), through its existing enrichment cache (6 h TTL),
starting with the preview-card pages. A card whose page isn't warm yet gets no bonus. This
+73
View File
@@ -0,0 +1,73 @@
# Ownership and collection API (Night 2, #57)
Server-side checks that a player owns the cards they play. Off-chain only: nothing here moves, burns or locks a card, and nothing changes consensus.
## The rules (ruleset data)
| Key | Default | Meaning |
|---|---|---|
| `deckSize` | 40 | A constructed deck has exactly this many cards. A testnet mode file may lower it. |
| `maxCopiesPerPage` | 4 | The MTG-style copy limit. Cards minted from the same Wikipedia `pageId` are separate cards, but at most this many go in one deck. |
| `minConfirmations` | 1 | The confirmations each card's mint block needs. Rated play uses `RATED_MIN_CONFIRMATIONS` = 3. |
## `server/game/ownership.ts` (used by the PvP host)
```ts
verifyAccount(deps, idToken: unknown): Promise<Account>
resolveDeck(deps, account, tokenIds: unknown, opts?: Partial<OwnershipRules>): Promise<ChainCard[]>
collection(deps, account, opts?: { minConfirmations?: number }): Promise<ChainCard[]>
```
- **`deps`** is `{ ledger, accounts, verifyIdToken }`. In production, `server/testnet/http.ts` builds it from the node's `Ledger`, the shared `AccountStore`, and `accountVerifier()` from `server/account/router.ts`. It passes the result to `gameRouter({ ownership })`.
- **`resolveDeck`** accepts token ids only, never card JSON. For each card it checks:
- the card is on the canonical chain (`ledger.nft()`);
- its current owner (after transfers) is one of the account's linked wallets;
- it has enough confirmations;
- the deck size and copy limit.
Each card is rebuilt from its own block (`article` and `statsSnapshot`). The cards come back in the order given.
- **Errors** are thrown as `DeckError { code, status, tokenIds, pageId? }`. `tokenIds` lists every offending card of that class.
| `code` | `status` |
|---|---|
| `auth` | 401 |
| `size` | 400 |
| `duplicate-token` | 400 |
| `unknown-token` (not on chain, or malformed) | 400 |
| `not-owned` (includes "no linked wallet") | 403 |
| `unconfirmed` | 400 |
| `copy-limit` | 400 |
`OwnershipUnavailable` (503) means Dex is unreachable or the chain tip kept moving during a read.
- **`collection`** pages `ledger.deck()` (24 per page) across every linked wallet at one canonical tip, restarting if the tip moves. There is no 128-block snapshot cap.
## `GET /api/game/collection`
`Authorization: Bearer <Dex ID token>` (the same token as `/api/account/me`). Optional: `?minConfirmations=N`.
```ts
{
tip, wallets: string[],
deckSize: 40, copyLimit: 4, maxCopiesPerPage: 4, minConfirmations: 1,
owned: number, // confirmed cards across all linked wallets
playable: number, // Σ min(copies, copyLimit) per pageId
needed: number, // max(0, deckSize - playable)
eligible: boolean, // playable >= deckSize
cards: ChainCard[] // tokenId, owner, confirmations, pageId, title, revisionId, url, extract, imageUrl?,
// height, blockHash, createdAt, powHash, article, statsSnapshot
}
```
| Case | Response |
|---|---|
| No linked wallets | 200 with `cards: []` and `needed: 40` |
| Missing or invalid token | 401 |
| Dex unreachable | 503 |
| Bad query | 400 |
The UI shows `playable / deckSize`, for example "23 / 40 cards", and how to mine.
## Not covered (known gaps)
- **Peer hosts.** Account stores are per node, and a Dex token sent to a peer could be replayed elsewhere (engineer review §2, G6). This API is for the self-hosted node only. The stretch fix is a wallet-signed deck claim.
- **Plausibility of minted stats** (G5): `pageId` → `title` and `revisionId` → `size` are not cross-checked yet.
File diff suppressed because it is too large Load Diff
+144
View File
@@ -0,0 +1,144 @@
# WikiDeck Night 2: design brief (locked decisions)
**Night 2:** 2026-11-17, 21:30 to **02:00 EST, hard stop**.
This brief merges three sources:
- the coordinator's plan, in `docs/night2/PLAN.md`
- four reviews (designer, engineer, data and critic), in `docs/night2/reviews/`
- **Eric's decisions on 2026-11-17**, which override anything in the reviews
Where a review disagrees with this file, **this file wins**. Where this file is silent, follow the reviews, in this order:
1. engineer, for architecture
2. designer, for rules
3. data, for derivation
4. critic, for process
## Eric's decisions (non-negotiable)
1. **A full 40-card, Magic-style game.**
- A deck is exactly 40 cards, and every card in it is an NFT the player owns.
- There are no loaners, Basics, filler or proxies.
2. **Players can't play until they own enough cards.**
- If a player owns fewer than 40 cards, the game shows their progress (for example "23 / 40 cards") and how to mine.
- There is no "practice with borrowed cards".
- The reviews' Basics, loaners, Signature card and the "Collection + Basics" model are **rejected**.
3. **PvP is first-class.** Bot matches exist, but only for eligible players.
4. **The mobile app must be able to mine.**
- Today `isNativeApp()` hides the mining panel, so mobile players can never earn cards.
- Fix it in the Android app.
- Write in `docs/night2/MOBILE_MINING.md` that Google Play and the App Store both prohibit on-device crypto mining, so for now the mining build is a sideloaded APK.
5. **Tone: lean in, Cards Against Humanity style.**
- Living people, tragedies, wars, disasters, crimes, diseases and dictators are all **ordinary cards with full mechanics**.
- There are no `solemn` flags, no special-casing and no softened verbs.
- The game takes itself completely seriously, and the comedy comes from the juxtapositions. Use the critic's S7 deadpan style guide: never wink, never comment on the matchup, and use encyclopedic texture with [n] citations.
- "Casualties" is fine.
- **One rule stays:** all generated text (rules text, match log, recap) is deterministic templates filled **only with real data from the card and the match**. Never use LLM prose, and never invent factual claims about real people (no made-up crimes, quotes or acts). Humour by juxtaposition is fine; fabricated facts about a real person are defamation.
6. **iOS is paused.** Don't touch `ios/` or the macOS VM.
7. **Wikimedia politeness by default** (the engineer's §4 and the data analyst's §5), including the mint-path bug (§9 below).
## Supply reality (design around it, don't fight it)
- **Mainnet:** 12 cards, all in one wallet. Consensus mints at most about 96 cards a day, network-wide. That's Eric's accepted trade-off: the game becomes playable as people mine.
- **Our testnet** (`deploy/night/`, on poweredge-r350):
- Wallets alice, bob, carol and dave own about 50 cards between them, with up to 40 more being mined now.
- The `testnet-ops` agent consolidates cards into **alice and bob** with on-chain transfers, so both reach 40 if supply allows.
- Deck size is **ruleset data** (`deckSize`, default 40). If the testnet can't reach 80 cards, the end-to-end test mode may set a lower `deckSize`. That's a testnet mode file only; production stays at 40.
- **Engine, simulation and balance work** uses the 236 real cards in `docs/game/card-sample.json` as the card pool. Build 40-card random decks from it. This needs no chain.
## Game rules core (designer §2, adapted to 40 cards)
- **Life:** each player starts with 20 Notability; at 0 you lose. Drawing from an empty library loses (the MTG rule). These are ruleset keys.
- **Opening:** hands of 7, with one mulligan (shuffle, draw 7, bottom 1). The first player skips their first draw.
- **Turn:** refresh, draw, main, combat, end.
- **Resources are a fixed income of Citations:** your maximum rises by 1 each turn, to a cap of 10. There are no land cards, so no land screw.
- Locations ramp at most +2 in total.
- Hand limit is 7.
- **Combat:**
- attack the opponent with untapped Figures, with summoning sickness ("Pending review")
- at most one blocker per attacker
- damage is simultaneous
- no trample, no first strike, no stack and no instant speed; Events are sorcery-speed
- **Clock:** 60 s per turn plus a 5-minute bank. No turn cap is required. If the sims show stalls, add `turnCap` as a ruleset key.
- **Card types** (designer §3 and data §1):
- **Figure:** a creature
- **Location:** a permanent with Territory or Garrison
- **Event:** sorcery-speed
- **Institution:** an artifact
- **Doctrine:** an Aura that attaches to a Figure, so *Tetrated dodecahedron* can buff *Cho Yang-ho*
- Classify with data §1's P31 → P279 anchor classes, falling back to categories, then the description, then Doctrine.
- Fix the `\bhuman\b` → People bug.
- Freeze each card's derived profile the first time the card is seen.
- **Factions ("Portals"):** designer §3.2. There are no colour restrictions in deckbuilding.
- **Stats:** data §2. Cost 1–6 comes from the percentile fame curve, with a fixed power+toughness budget per cost, so famous cards are bigger and pricier, not strictly better.
- **Keywords:** designer §3.4 and data §2, at most 2 per card, each triggered by real data:
- Protected
- Featured
- Translated
- Legacy
- Stub
- Well-sourced
- Multilingual
- Local
- **Connected:** the data team's tiers (data §4): Linked, Compatriot, Contemporary and Kin, from cached Wikidata claims and links.
- It gives +1/+1, or +2/+2 for a direct link.
- Aim for it to fire in 15–30% of pairs, tuned in the simulator.
- **Flavour text:** the first sentence of the on-chain `article.extract`.
## Story
- **Match log:** past-tense, encyclopedic and per player (`logFor`), with no hidden-information leaks.
- **Recap:** a "Battle of X (2026)" page after each match, with:
- an infobox: date, belligerents (the players), strength, casualties (the cards destroyed), result
- a narrative assembled from the log with 3–4 template variants per event, seeded deterministically
- References citing every card played, with revision ids
- "WikiDeck" branding, not Wikipedia's
- a shareable URL
## Modes (kept, now on the duel engine)
- **Classic:** constructed from your own 40+ cards. It's ranked.
- **Draft:** both players must be eligible. The pool is drawn from both players' collections, and drafted cards are used for that match only. Nothing moves on-chain.
- **Trending:** live pageview momentum changes stats (designer §5), from a daily refreshed cache.
- **Peer-hosted house rules:** stay data-only, with a versioned schema. Night 1 mode files are rejected cleanly.
## PvP (engineer §3)
- **Seats and ownership:**
- Seats are tied to eom.dev accounts (Dex) and their linked wallets.
- The host verifies **ownership on the server** (`ownership.ts`, using `ledger.nft()`) and builds each card from the chain.
- **Night 1's gaps to close:**
- the browser-side ownership check
- the 128-block snapshot cap
- starter decks dealt in `host.ts:144`
- **Matchmaking:** private lobbies, invite links, quick match, and an Elo ladder keyed to the account.
- **Transport:** keep polling, with a state version so unchanged polls return 204. Don't use long-polling.
## Wikimedia (engineer §4 and data §5)
**One process-wide client:**
- 1 request per second, burst 3, 1 request in flight per host
- priority lanes: mint, then interactive, then background
- `maxlag=5`
- honour `Retry-After`
- a circuit breaker after 3 consecutive 429s
- a daily cap
- a sqlite cache on disk with ETags
- a User-Agent with an operator contact (a config key that operators must set; the testnet uses the project URL)
**The mint path changes transport only:** request parameters stay byte-identical, and the cache is never used for mint data.
**Fix the mint bug:** a 429 on pageviews currently mints a card with `attention: null` forever (`enrichment.ts:145-164`). Fail and retry instead.
**Other changes:**
- Card faces in the client no longer trigger uncached upstream calls on every render.
- An article prefetch pool for mining templates (data §8).
**Tests make zero network calls.**
## Cut order if late
1. the Elo ladder (keep W/L)
2. quick match (keep invites)
3. Trending's live stats
4. the Kin and Contemporary tiers of Connected
5. recap polish (keep the plain log)
**Never cut:**
- the duel core
- 40-card owned-deck validation on the server
- PvP over invite links
- the Wikimedia client and mint fix
- mobile mining
- the recap (the story is the point)
+88
View File
@@ -0,0 +1,88 @@
# WikiDeck Night 2: team handbook
Read this whole file, then `docs/night2/BRIEF.md` (the locked design decisions). Then read the review sections your issue names in `docs/night2/reviews/`.
**Window:** 2026-11-17 21:30 until **02:00 EST, hard stop**.
**Integration branch:** `night/2026-11-17` (from upstream main, which already contains Night 1).
**Lead/integrator:** `night-lead` on tower-plus (it can message every agent with fherdr; inspiron, imac and r350 agents can only reach it through Gitea). The coordinator is Eric's Claude session on tower-plus.
**Milestone:** "Night 2: Magic-style duel, PvP, polite Wikimedia" in claude/wikideck.
**Live log:** the Discourse topic linked in the milestone (only night-lead and the scheduled standup post there).
## Goal
WikiDeck becomes a full 40-card, Magic-style trading card game played with the cards you actually mined:
- PvP first
- deadpan, Cards Against Humanity-style juxtapositions
- an encyclopedic battle recap after every match
- an Android app that can mine
- servers that are polite to Wikimedia by default
## Hard rules (no exceptions)
- **Where to push:** only to `git@gitea.eom.dev:claude/wikideck.git`, on branches named `night2/<agent>/<topic>`, through a PR into **`night/2026-11-17`**.
- Never push to `WikiDeck/wikideck`, `main` or the Night 1 branch.
- Only `night-lead` merges, using squash.
- **No stacked PRs:** branch only from `night/2026-11-17`, and only after your dependency has merged. If you need unmerged code, stub the interface.
- **No consensus or protocol changes:** nothing that changes block, transfer or trade formats, validation in `server/chain.ts`, `server/testnet/consensus.ts` or `shared/protocol.ts`, or what a mint fetches and stores. The game runs **off-chain**, and matches never move or burn cards.
- **Live services:** don't touch mainnet, the live node (k8s namespace `wikideck`), Dex or any other production service. The testnet is private, on poweredge-r350 (`deploy/night/README.md`).
- **iOS is paused:** don't touch `ios/` or the macOS VM.
- **Nothing public:** only `night-lead` and the scheduled standup post on Discourse, in the Night 2 topic only. No purchases, sign-ups or secrets in git.
- **The printer and CNC:** inspiron-3670 drives a 3D printer and a CNC router. Never start, resume or send a print or cut.
- **Wikimedia:** tests make **zero** network calls. Don't script loops against Wikipedia or Wikidata. Use `docs/game/card-sample.json` and cached data. Our IP was rate-limited on Night 1.
- **Git identity** in every clone:
```
git config user.name Claude
git config user.email claude@eom.dev
git config commit.gpgsign false
```
End commit messages with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
- **Before opening a PR:** run `npm test` and `npm run build` on **Node 24**. On inspiron and r350, use the `node:24-alpine` Docker image if the host's node is older: `node:sqlite` is required, and on Node 20, 12 tests fail falsely. Don't add npm dependencies; ask night-lead.
- **Tests go in** `tests/<agent>-*.test.ts` (top level).
- **Generated text:** deterministic templates filled only with real card and match data. No LLM prose, and no invented facts about real people (BRIEF, decision 5). Otherwise, lean in: no softening of tragedies or living people.
## How we coordinate
**Gitea is the shared brain.** The machines don't share a filesystem.
- **Your issue is your inbox.**
- Prefix every comment with `[<agent>]`.
- Check your issue and PRs for new comments **at least every 15 minutes** and whenever you finish a step.
- **Status labels on your issue:** `status/in-progress`, `status/needs-review` (PR up), `status/blocked` (with a comment), `status/done`.
- **Need another team?** Comment on their issue with `[from <you>]`.
- **Contracts beat conversations.** Interfaces are files on the integration branch, e.g. `shared/duel/types.ts` and `docs/game/DUEL_API.md`. Read them before asking.
- **Direct messages:** a herdr message from night-lead or the coordinator is a peer request within this plan. Act on it.
- **Stuck for more than 10 minutes?** Label `status/blocked`, comment, and move on to something else.
## Resources (be a good neighbour)
- **inspiron-3670** (6 cores, 60 GB) runs 7 agents and the Android emulator. Wrap heavy commands in `flock /tmp/night-heavy.lock <cmd>` (npm ci, builds, gradle, docker build).
- **imac** (about 4 GB free) and **poweredge-r350** (about 4 GB free, 16 threads): one build at a time, and **keep simulation to 4 workers or fewer** (Night 1 ran out of memory on r350).
- **Avoid permission prompts:** nobody answers them. Don't chain `cd <dir> && <write>`; use absolute paths or `git -C`. Keep one purpose per shell command.
## Timeline (EST)
| Time | Milestone |
|---|---|
| 21:30 | Kickoff. Preflight: Gitea MCP works, Node 24, clone. Comment `starting` on your issue. |
| **22:15** | **Contracts merged:** `shared/duel/types.ts` and `docs/game/DUEL_API.md` (duel-core), plus `docs/game/DUEL_DESIGN.md` v1 (duel-design: keywords, text templates and tone, with BRIEF.md as the base). The `ownership.ts` signature is agreed by 22:00. |
| 23:15 | Engine alpha. The simulation starts. The UI plays against a bot. |
| 00:00 | Wikimedia client merged. Host binds the duel. The PvP UI is wired to the host. |
| 00:45 | Balance v1 (tuning is data-only). Mobile mining runs in the emulator. |
| **01:15** | **Code freeze:** fixes only. Balance re-runs on the frozen head SHA. QA runs PvP end to end on the testnet with alice and bob. |
| 01:45 | Final report comment on every issue. night-lead writes `docs/night2/REPORT.md` and opens the upstream PR (never merges it). |
| **02:00** | **Stop.** Push, comment, exit. |
## Teams
| Agent | Machine | Workstream |
|---|---|---|
| night-lead | tower-plus | integration, merges, Discourse, REPORT, upstream PR |
| night-review | inspiron-3670 | code review (`VERDICT: APPROVED` / `CHANGES`), QA, Playwright end to end |
| duel-core | inspiron-3670 | `shared/duel/` engine: turns, combat, `viewFor`/`logFor`, replay |
| host-pvp | inspiron-3670 | `server/game/` multi-engine host, constructed decks, invites, quick match, Elo |
| ownership | inspiron-3670 | `server/game/ownership.ts` and `collection.ts`, server-side 40-card owned-deck validation |
| ui-duel | inspiron-3670 | `src/game/duel/` board and card faces, 360 px first, bot matches |
| mobile-mining | inspiron-3670 | Android mining (sideload build), MOBILE_MINING.md |
| duel-design | imac | DUEL_DESIGN.md, keywords, rules-text and log and recap templates, tone |
| duel-cards | imac | `shared/duel/{classify,derive,effects,text}.ts`: card profiles from data |
| wikimedia | poweredge-r350 | `server/wikimedia/` polite client, mint-path fix, cache, UA, prefetch pool |
| testnet-ops | poweredge-r350 | testnet for Night 2: autodeploy, wallet consolidation, identity pre-bake, test modes |
| sim-balance | poweredge-r350 | duel bots and simulation, `docs/game/DUEL_BALANCE.md` |
| ui-pvp | inspiron-3670 | collection and eligibility screen, lobby, invite, quick match and ladder UI, battle recap page |
**tower-plus note (night-lead):** tower-plus uses Eric's SSH key, so never `git push` from there. Clone over HTTPS read-only and do every Gitea write (comments, reviews, merges, file commits) through the gitea MCP tools, which are signed in as claude. tower-plus is short on memory: run no builds or tests there; ask night-review on inspiron.
+78
View File
@@ -0,0 +1,78 @@
# Mobile mining (Android, sideload build)
**Status (Night 2, 2026-11-17):** it works. The emulator mined and got testnet block #92 accepted with the in-app native RandomX engine (see "Results tonight"). Issue: claude/wikideck#59.
BRIEF decision 4: the mobile app must be able to mine, because otherwise mobile players can never earn the 40 owned cards a deck needs. Night 1's `isNativeApp()` hid the mining panel and the app had no miner at all.
## App stores: why this is a sideloaded APK
**Google Play and the Apple App Store both prohibit on-device cryptocurrency mining**, so the mining build cannot ship through either store. It is distributed as a sideloaded APK only.
- **Google Play**, Developer Program Policy, *Device and Network Abuse*: "We don't allow apps that mine cryptocurrency on devices." Apps that *remotely manage* mining that happens elsewhere are allowed.
- **Apple**, App Review Guidelines **3.1.5(b)(ii) Cryptocurrencies, Mining**: "Apps may not mine for cryptocurrencies unless the processing is performed off device (e.g. cloud-based mining)." Guideline 2.4.2 also bans unrelated background processes such as mining.
A WikiDeck block is a RandomX proof-of-work that mints an NFT on WikiDeck's own chain. That is cryptocurrency mining under both policies, whatever the reward looks like. Re-check the policy wording before any store submission; these quotes are from memory, not verified tonight (tests and agents make no web calls).
## How it works
```
WebView (React) Native (Java, Capacitor plugin "WikiDeckMiner")
src/MobileMiningPanel.tsx consent, intensity, stats
src/mobile-miner.ts same loop as server/testnet/miner.ts
POST /api/mining/template {owner, publicKey} ──► node (picks the article and stats; the phone never calls Wikipedia)
build blob = sha256(headerMessage) || nonceLE8
WikiDeckMiner.mine(lane, key, blob, target, 32, 16) ──► MinerPlugin.java ──stdin/stdout──► libwikideck_randomx.so
(the pinned native/ engine, LIGHT mode, line protocol)
found → hash, tokenId (mintId), sign(blockClaimMessage) with the web wallet
POST /api/blocks ──► node validates as usual
```
- **Same engine as desktop.** `native/` (RandomX v1.2.1, pinned SHA `102f8acf…`) is cross-compiled with the Android NDK by `scripts/build-randomx-android.sh` for `arm64-v8a` and `x86_64` (the emulator). It is packaged as `jniLibs/<abi>/libwikideck_randomx.so`: an executable named like a library, so Android extracts it to `nativeLibraryDir`, the one place an app may `exec` from (`useLegacyPackaging true` in `android/app/build.gradle`). The binaries are build outputs, so they're gitignored, and `android/build-debug.sh` builds them when they're missing.
- **Light mode only** (256 MiB cache per engine process). Fast mode (about 2 GiB) is never started on a phone: the plugin runs the binary with no arguments.
- **Known-vector check on the device.** Before the first start in each session, the app runs `libwikideck_randomx.so --self-test` (upstream Hash test 1a/2a). If the hash doesn't match, mining is disabled. A wrong hash would get every block rejected.
- **Keys never leave the web wallet.** The plugin only receives the public work (key, blob, target). The WebView builds and signs the block with the existing wallet code (`src/wallet.ts` `sign`). The private key and backup password are never passed to native code or to the node.
- **No protocol, consensus or server changes.** `src/mobile-miner.ts` rebuilds `miningBlob` and `mintId` with Web Crypto. `tests/mobile-mining-miner.test.ts` checks that they're byte-identical to `server/testnet/consensus.ts` and that the consensus validator accepts the assembled block.
- **Testnet only tonight.** In a mainnet build (`IS_MAINNET`), the panel only says mainnet mining isn't enabled. The debug build points at the private testnet `http://192.168.1.32:3101`.
## Safeguards
| Safeguard | How |
|---|---|
| Explicit consent | An unchecked consent box ("uses this phone's CPU and battery and can make it warm"). Start stays disabled until it's ticked. The choice is stored locally (`wikideck.mobileMining.consent.v1`). |
| Intensity | Low (1 thread, rests 400 ms between 16-hash batches), **Normal (1 thread, default)**, High (2 threads, about 512 MiB, offered only on 4+ cores). |
| Foreground only | `MinerPlugin.handleOnPause` kills the engines as soon as the activity pauses, and the WebView also stops on `visibilitychange`. There is no foreground service, no wake lock and no background mining. The web wallet also locks when the app is hidden. |
| Battery saver | `PowerManager.isPowerSaveMode()`, checked before start, every 2 s while mining, and on `ACTION_POWER_SAVE_MODE_CHANGED`. |
| Heat | `PowerManager.getCurrentThermalStatus() >= THERMAL_STATUS_MODERATE` (API 29+, with a listener), or a battery temperature of 40 °C or more (`ACTION_BATTERY_CHANGED`). |
| Low battery | Below 20 % while not charging. |
| Visible activity | Live hashrate, hashes tried, the block height being mined, accepted blocks, battery % and °C, and the self-test result. |
| Wallet change | If the wallet locks or changes, mining stops, so it never keeps mining to an old address. |
Each automatic stop shows its reason ("Paused: battery saver is on"). Mining never restarts by itself: the player taps Start again.
**Wallet idle lock:** a found block must be signed by the unlocked wallet, and the wallet locks after 5 minutes without taps. While mining is active (which means foreground and consented), each status update calls `touchWallet()` to keep the session alive. The 4-hour absolute limit and lock-on-hide still apply. night-review accepted this trade-off on PR #78. The session can't stay unlocked in the background: hiding the app locks the wallet, and `handleOnPause` halts mining, so the keep-alive applies only to consented foreground mining. Eric may prefer a stricter rule, such as re-prompting for the password when a block is found.
## Measured hashrate (emulator)
Measured on inspiron-3670 (6 cores, shared with ~7 agents), using the AVD `wikideck` (Android 15, x86_64 google_apis, KVM, `-cores 4`, 2 GB RAM):
| Measurement | Result |
|---|---|
| Known vector (`--self-test`), x86_64 | passed, 1.45 s including the 256 MiB cache init |
| Known vector, arm64-v8a (through the emulator's ARM translation) | passed |
| Raw engine, 1 process, 2000 hashes | about 53 s → **~37 H/s per thread** |
| In the app, Max (4 threads) | **~125 H/s** shown in the panel, with 4 engine processes at ~260 MB RSS each |
Light mode is about 10× slower per thread than desktop fast mode. At tonight's testnet target (`00002514…`, about 452 K expected hashes), 125 H/s means **one block per hour on average**, with high variance. On a real phone, expect roughly 20–60 H/s per big core (not measured tonight: no device).
## Results tonight
Verified in the emulator with the debug APK (`~/worker/jobs/night/mobile-mining/apk/wikideck-mining-testnet-debug.apk` on inspiron):
- The APK contains `lib/{arm64-v8a,x86_64}/libwikideck_randomx.so`. The app runs the self-test before its first start ("known vector OK"), then mines on the testnet (:3101) with live hashrate and block height.
- **Every safeguard halts the engines** (the engine process count drops to 0, and the panel shows the reason):
- thermal: `cmd thermalservice override-status 3` → "Paused: the device is warm"
- battery saver (unplugged, `settings put global low_power 1`) → "Paused: battery saver is on"
- low battery (`dumpsys battery set level 15`, unplugged) → halted (Android's low-battery dialog paused the activity first)
- background (HOME) → "Paused: the app went to the background"; the web wallet locks too, so restarting needs an unlock
- Max intensity is refused while unplugged
- **Accepted block:** at 22:37 EST the emulator (Max, ~136 H/s, 4 light threads) mined **testnet block #92** ("International FJ"; block `edaf8ac3…a8cb0`, NFT `acf778b1…7ee58`) to the in-app wallet `3b2362c7…5e054`. All three nodes (:3101–:3103) accepted it as their tip. That one was lucky: about 41 K hashes against ~452 K expected.
![Emulator panel after the accepted block](mobile-mining-accepted.jpg)
## Options for Eric
1. **Keep it sideload-only** (what exists now). Publish a signed release APK from a WikiDeck download page with clear battery and heat copy. This needs a release keystore (not in git) and an "unknown sources" install guide. F-Droid is a possible channel, but its anti-features policy would flag it, and its build server needs a reproducible NDK build.
2. **Store builds without mining.** Ship the store APK/AAB and the iOS app without the engine (a build flag that drops jniLibs and the panel), with the panel replaced by "Mine on desktop, or with the sideload app", plus a remote-management view of a desktop miner (allowed by Google's policy).
3. **Make mobile mining worthwhile.** Phones in light mode are roughly 10× slower per core than desktop fast mode. Options that need **consensus changes** (out of scope tonight): a lower-difficulty mobile lane, or pooled/shared mining where a phone's partial shares earn a card.
4. **Later engineering:** a JNI wrapper instead of exec (needed if a future Android blocks exec from `nativeLibraryDir`), an arm64 device test on real hardware, and battery-drain measurements.
+120
View File
@@ -0,0 +1,120 @@
# WikiDeck Night 2: proposed game redesign (for review)
Status: **draft, under review.** Written by the coordinator on 2026-11-17 from Eric's feedback on Night 1's game, Edit War. Night 2 runs unattended on 2026-11-17 from 21:30 to 02:00 EST.
## Eric's feedback on Edit War (the requirements)
1. **Real cards:** a player's deck is made of the cards they actually mined and own. Loaners existed for the demo; the real game uses real cards.
2. **PvP:** players must be able to play each other, not only the AI. Hosted lobbies exist (`src/game/OnlinePlay.tsx`, `server/game/host.ts`) but are buried.
3. **Story:** Edit War "doesn't really tell much of a story with the actual cards".
4. **Feel:** Magic: The Gathering is the model for how it should feel.
5. **Modes:** keep the different modes (classic, draft, trending); Eric likes them.
6. **Tone:** "The fact that I can use a Tetrated Dodecahedron in a game with Barack Obama is funny. Lean into this. The game should take itself seriously, but the end result is going to be entertaining for this reason." (Eric's original v2 post also mentions using his *Tetrated dodecahedron* card to buff his *Cho Yang-ho* card, and node operators running house rules.)
7. **Wikipedia limits:** our servers must respect Wikimedia rate limits by default instead of getting cut off. Night 1 hit HTTP 429 from our shared IP.
8. **iOS:** paused (Apple licence acceptance). Out of scope.
## Hard constraints
- **Consensus is fixed:**
- No changes to the chain, block format, mint stats snapshot or consensus files (see `docs/night/BOUNDARIES.md`).
- Everything game-related is derived off-chain from what a card already holds.
- **Where work happens:** in the `claude/wikideck` fork, through reviewed PRs. Eric merges upstream.
- **No live deployment:** don't touch mainnet or the live node at wikideck.eom.dev.
- **Budget:** 4.5 hours, about 10 agents across 4 machines (tower-plus, imac, inspiron-3670, poweredge-r350). Night 1 used 17 agents for 2.75 h and about 10% of the weekly usage budget; 75% remains.
## Facts the design must face
- **Card data:** what a card holds is shown in `shared/enrichment.ts` (PageEnrichment / MintStatsSnapshot) and `shared/testnet.ts` (BlockHeader).
- **Article:** pageId, title, extract, image, category, revisionId.
- **Mint snapshot:** pageBytes, languageCount, 6 months of pageviews with trendPercent and dailyAverage, and the attention, depth and reach scores.
- **Night 1 also used:** the Wikidata id, P31 "instance of", and live pageviews, all fetched off-chain.
- Real distributions are in `docs/game/CARD_DATA.md`: compressed scores, a skewed category split, and a reach of 0 for 18% of cards.
- **SUPPLY:**
- One card is minted per block, with a consensus target of one block per 15 minutes: at most about 96 new cards a day, network-wide.
- **Mainnet today has 12 cards in total, all owned by one wallet**, all mined on 2026-11-01.
- A "deck of your own mined cards" in the Magic sense (40–60 cards) is impossible for anyone for a long time.
- **This is the biggest viability question; see Open problem 1.**
- **Cards are unique NFTs:** each card is one specific mint, and the same article can be minted more than once (`pageId` repeats).
- **Night 1 code to reuse:**
- the deterministic rules engine and its rules-as-data style (`shared/game/`)
- the bots and the balance simulator (`shared/bots/`, `scripts/sim/`)
- hosted lobbies and modes (`server/game/`)
- Dex accounts (`server/account/`)
- the Android shell (`android/`)
## Proposed design
### A. Card identity from the article (MTG-style types)
The card type comes from Wikidata P31, with a fallback to Wikipedia categories:
| Article is a… | Card type | MTG analogue |
|---|---|---|
| person, character, animal species | **Figure** | creature |
| place, region, celestial body, structure | **Location** | land (resource) and/or permanent |
| event, battle, election, disaster | **Event** | instant/sorcery |
| creative work, organisation, company, team, product | **Institution** | artifact |
| concept, theory, mathematical object, ideology, field | **Doctrine** | enchantment |
**Factions (colours):** the 6 P31-based factions proposed in CARD_DATA.md, plus a neutral fallback.
**Stats from data:**
- **Power and toughness** come from percentile attention, depth and reach. For example, attention drives power, and depth drives toughness and staying power.
- **Cost** follows the curve: high-stat cards cost more.
**Rules text:**
- Generated deterministically from a fixed table of templates keyed on type, faction, category keywords, trend, language count, dates (birth/death, founding, event date), coordinates, and so on.
- It is written in MTG's terse register.
- **Flavour text:** the first sentence of the article's extract.
### B. Story mechanics
- **Connected:** two cards whose articles link to each other, or share a Wikidata property such as country, field or era, gain a bonus together. Barack Obama with the White House; Tetrated dodecahedron with Polyhedron.
- **Citations:** a resource or counter flavoured as sources.
- **Edit wars and vandalism:** removal and interaction effects.
- **Deadpan tone:** the game is completely straight, like an encyclopedia or an MTG judge. The comedy comes from the matchups, never from jokes in the text.
- **Match log:** written as a dry encyclopedic account.
- **After each match:** a Wikipedia-style article, *"Battle of the Tetrated Dodecahedron (2026)"*. It has:
- an infobox: date, belligerents, commanders (the players), strength (the cards), result
- a short deterministic narrative built from the match log
- a "References" list citing every card's real article
- These recaps are shareable.
### C. Game structure
- **Duel:** two players, a life total, turns with attack and block, and permanents on a battlefield.
- **Resources:** from Locations and/or a fixed per-turn income, designed to avoid MTG's "land screw" (no resource cards, no game).
- **Deck size and composition:** depends on Open problem 1.
### D. PvP first
- **Matchmaking:** a queue, invite-by-link and a ranked ladder (Elo or Glicko).
- **Identity:** the eom.dev account, with linked wallets as the card source.
- **Hosting:** the hosting node runs the match, so there's no client trust.
- **AI opponents:** still available for practice and onboarding.
### E. Modes (kept)
- **Classic:** constructed from owned cards.
- **Draft:** players draft from a shared pool, so they don't need large collections.
- **Trending:** stats boosted by live pageviews.
- **Peer-hosted house rules:** remain data-only.
### F. Wikimedia politeness by default
- **One client:** a single throttled Wikimedia client used by every server-side caller (`server/wiki.ts`, `server/enrichment.ts`, P31 lookups, link lookups).
- **Throttling:**
- a conservative rate limit by default (for example 1 request/s and 1 concurrent request per node, configurable)
- `maxlag`
- honour `Retry-After` with backoff
- batch up to 50 titles per request
- an on-disk cache with ETags and conditional requests
- a daily refresh for live stats
- **User-Agent:** a default UA that identifies the node and an operator contact, as Wikimedia's policy asks.
- **Volume:** a design budget for requests per match and per mint.
## Open problems for the review team
1. **Supply versus "real cards only".** What makes a real-cards game playable when a player owns 0–12 cards and the network mints at most about 96 a day? Options to evaluate (add others):
- (a) A small deck size, such as 7–10 cards, with recursion and reuse.
- (b) Your owned cards are your "commanders" or champions, and a shared pool of common public-domain article cards fills the rest. This conflicts with Eric's requirement, so it would have to be argued.
- (c) Draft as the main mode, where the pool is drawn from the whole chain's minted cards and ownership gives cosmetic credit or a guaranteed pick.
- (d) A collection-as-deck where every owned card counts, scaled by size.
- (e) Card copies or "editions" (no consensus change possible, so off-chain only?).
Recommend one, and say what Eric must decide.
2. Is MTG-style attack/block too complex to build, balance and make readable in one night? What is the smallest rules core that still feels like Magic?
3. Is P31 typing reliable enough? Check against the real sample in `docs/game/card-sample.json` and `docs/game/starter-cards.json`. Plan for unclassified cards, which were 14% of Night 1's sample.
4. Can "Connected" link lookups be done within the Wikimedia budget? Where does the data come from, and when is it fetched and cached?
5. Can the generated rules text be both deterministic and good? Does it need an LLM? LocalAI exists on the cluster, but determinism and the consensus boundary matter.
6. What scope is realistic for 4.5 hours with about 10 agents, and what gets cut first?
+67
View File
@@ -0,0 +1,67 @@
# 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.
+72
View File
@@ -0,0 +1,72 @@
# Polite Wikimedia client (Night 2, issue #62)
Every server-side Wikimedia request goes through one process-wide `WikimediaClient`
(`server/wikimedia/client.ts`). The design comes from engineer review §4 and data review §5.
## What it does
| Behaviour | Default |
|---|---|
| Rate per upstream host (`en.wikipedia.org`, `wikimedia.org`, `www.wikidata.org`) | token bucket, 1 req/s, burst 3 |
| Concurrency | 1 request in flight per host |
| Priority lanes | `mint` → `interactive` → `background`; the queue holds 64 waiters, and background work is shed first |
| Longest queue wait | mint 10 s, interactive 5 s, background 120 s |
| `maxlag` | `maxlag=5` on every Action API request; a maxlag reply waits for `Retry-After` and retries up to 2 times |
| 429 / 503 | honour `Retry-After` (seconds or HTTP date), else back off 2ⁿ s with jitter, capped at 10 min, by pausing the whole host |
| Circuit breaker | 3 consecutive 429s stop that host for 10 min. Requests are refused at once without touching Wikimedia |
| Daily cap | 20,000 requests a day per egress IP. Background work stops at 80 %, interactive at 100 %; mint has a 10 % reserve |
| Disk cache | `$WIKIDECK_DATA_DIR/wikimedia-cache.sqlite`: ETag / Last-Modified, `If-None-Match`, stale-while-revalidate on the background lane, stale copy served on refusal |
| User-Agent | `WikiDeck/<version> (+https://gitea.eom.dev/WikiDeck/wikideck; <operator contact>) node/<version>` |
The rate is deliberately 1 req/s for **every** host, including the `wikimedia.org` REST (pageviews) host.
The engineer review suggested 5 req/s there; we are stricter on purpose after the Night 1 rate limiting, because the
budget is per egress IP. Raise it only with a reason and a per-host setting.
Cache lifetimes: article metadata 24 h, monthly pageviews 7 days (the URL names six closed
months, which do not change). Random articles and all mint reads are never cached.
## Operator settings
| Variable | Meaning |
|---|---|
| `WIKIDECK_OPERATOR_CONTACT` | **Set this.** An email address or URL, put in the User-Agent. Without it (and without `PUBLIC_ORIGIN`), the node logs a warning at start-up. Wikimedia policy requires a contact, and contact-less clients are the first to be blocked. |
| `PUBLIC_ORIGIN` | Used as the contact when `WIKIDECK_OPERATOR_CONTACT` is unset. |
| `WIKIDECK_USER_AGENT` | Overrides the whole User-Agent string (sanitized; kept from Night 1). |
| `WIKIDECK_WIKIMEDIA_RPS` | Requests per second per host for the **whole egress IP** (default 1). |
| `WIKIDECK_WIKIMEDIA_BURST` | Token-bucket burst (default 3). |
| `WIKIDECK_WIKIMEDIA_CONCURRENCY` | In-flight requests per host (default 1). |
| `WIKIDECK_WIKIMEDIA_DAILY_CAP` | Requests per UTC day for the whole egress IP (default 20000). |
| `WIKIDECK_WIKIMEDIA_NODES_PER_IP` | How many nodes share this egress IP. The rate and the daily cap are divided by it. **The testnet runs several nodes behind one IP: set it to the node count** (e.g. 3 for `deploy/night/compose.lan.yaml`). |
The testnet's `WIKIDECK_USER_AGENT` already names the project URL, which satisfies the policy.
Counters (`lane.*`, `http.429`, `breaker.open`, `cache.hit`, `refused.*`, …), per-host pause state and the
mint pool's state are in the private operations listener's `/status`, under `wikimedia`.
## Mint path: transport only
- `random()` (W1) and `getFresh()` (W2 and W3) keep their request parameters byte-identical. The only
addition is `maxlag=5`, which changes only error behaviour. `tests/wikimedia-mint.test.ts` pins the exact URLs.
- Mint reads use the `mint` lane and **never** read or write the disk cache, and never join a display read.
- **Fixed:** a 429, 5xx, timeout, network error or non-JSON reply on the pageviews call used to mint a card with
`attention: null` forever (`enrichment.ts`). Now `getFresh()` rejects, the template returns 503 and the miner
retries. `unavailable` is minted only for a genuine 404 (no data) or missing months.
- No block, transfer, trade or validation code changed. Validation never calls Wikimedia.
## Mining prefetch pool (`server/wikimedia/pool.ts`)
Each template used to cost 3+ requests, all in a burst at each new tip, so load scaled with the number of miners.
Now every template on the same tip gets the same fresh article+snapshot pair (miners race for one block anyway),
and a new tip takes the next prefetched pair. Load is about one pair, or 3 requests, per block, whatever the number
of miners.
- Pairs come from the mint-path reads above, and the snapshot is stamped when the pair is fetched, so `capturedAt` is true.
- Pairs older than 5 minutes are dropped, never served.
- The pool (2 pairs) refills only after use, so an idle node makes no requests.
## Card faces
`/api/wikipedia/:id` → `get()`: memory LRU, then the disk cache (fresh, or stale with a background
revalidation), and only then the interactive lane. A grid of cards therefore no longer means a burst
of 2 upstream requests per card per render. `TrendCache` can use `getBackground()` to stay off the
interactive lane.
+44
View File
@@ -0,0 +1,44 @@
"""How often random card pairs share cheap relations. Usage: python3 -I connected.py <card-sample.json>"""
import json, sys, re, itertools, collections, importlib.util, os
cards = json.load(open(sys.argv[1]))['cards']
spec = importlib.util.spec_from_file_location('ty', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'types.py'))
ty = importlib.util.module_from_spec(spec); spec.loader.exec_module(ty)
GENERIC = re.compile(r'stubs|living people|\d+ (births|deaths)$|articles|wikidata|pages', re.I)
COUNTRIES = ['United States','American','England','English','British','France','French','Germany','German','Japan','Japanese','China','Chinese',
'India','Indian','Brazil','Poland','Polish','Italy','Italian','Spain','Spanish','Austria','Canada','Canadian','Australia','Australian','Russia','Russian',
'Mexico','Mexican','Iran','Pakistan','Bangladesh','Sweden','Swedish','Norway','Estonia','Ukraine','Croatia','Philippines','Cuba','Israel','Portugal','Scotland','Wales','Ireland','Kazakhstan','Malaysia','Argentin','Belgi','Iceland','Bermuda','Thailand','Singapore','Sri Lanka','Slovenia','Moldova','Cyprus','Macedonia','Mauritania','Congo','Gibraltar','Hong Kong','New Zealand','Korea','Indonesia','Aceh']
NORM = {'American':'United States','English':'England','British':'United Kingdom','England':'United Kingdom','Scotland':'United Kingdom','Wales':'United Kingdom',
'French':'France','German':'Germany','Japanese':'Japan','Chinese':'China','Indian':'India','Polish':'Poland','Italian':'Italy','Spanish':'Spain',
'Canadian':'Canada','Australian':'Australia','Russian':'Russia','Mexican':'Mexico','Swedish':'Sweden'}
Y = re.compile(r'\b(1[0-9]{3}|20[0-2][0-9])')
def feats(c):
txt = (c['description'] or '') + ' | ' + ' | '.join(c['categories'])
ctry = {NORM.get(k, k) for k in COUNTRIES if k in txt}
cents = {int(y) // 100 for y in Y.findall(c['title'] + ' ' + txt)}
cats = {x for x in c['categories'] if not GENERIC.search(x)}
p31 = {i['id'] for i in c['instanceOf']}
return dict(ctry=ctry, cent=cents, cats=cats, allcats=set(c['categories']), p31=p31, type=ty.classify(c)[0])
F = [feats(c) for c in cards]; pairs = list(itertools.combinations(range(len(cards)), 2)); N = len(pairs)
def rate(f):
k = sum(1 for i, j in pairs if f(F[i], F[j])); return f'{k}/{N} ({100*k/N:.2f}%)'
print('pairs', N)
print('share any category (incl. generic)', rate(lambda a, b: a['allcats'] & b['allcats']))
print('share specific category', rate(lambda a, b: a['cats'] & b['cats']))
print('share P31 class', rate(lambda a, b: a['p31'] & b['p31']))
print('share P31 excl human/taxon', rate(lambda a, b: a['p31'] & b['p31'] - {'Q5', 'Q16521'}))
print('share country (text proxy for P17/P27)', rate(lambda a, b: a['ctry'] & b['ctry']))
print('share century (text proxy for dates)', rate(lambda a, b: a['cent'] & b['cent']))
print('share type', rate(lambda a, b: a['type'] == b['type']))
print('country OR century OR specific cat', rate(lambda a, b: (a['ctry'] & b['ctry']) or (a['cent'] & b['cent']) or (a['cats'] & b['cats'])))
print('cards with >=1 country', sum(1 for f in F if f['ctry']), 'with >=1 century', sum(1 for f in F if f['cent']))
# deck-level: chance that a random 10-card hand-pair (10 vs 10, own deck) has >=1 connected pair within a deck
import random; random.seed(1)
def deck_hits(pred, size=10, trials=2000):
h = 0
for _ in range(trials):
s = random.sample(range(len(F)), size)
if any(pred(F[i], F[j]) for i, j in itertools.combinations(s, 2)): h += 1
return f'{100*h/trials:.0f}%'
pc = lambda a, b: (a['ctry'] & b['ctry'])
print('10-card deck has >=1 same-country pair', deck_hits(pc), '| specific category', deck_hits(lambda a, b: a['cats'] & b['cats']),
'| country-or-century', deck_hits(lambda a, b: (a['ctry'] & b['ctry']) or (a['cent'] & b['cent'])))
+23
View File
@@ -0,0 +1,23 @@
"""Field availability for rules-text generation in card-sample.json. Usage: python3 -I fields.py <card-sample.json>"""
import json, sys, re, statistics, collections
cards = json.load(open(sys.argv[1]))['cards']; n = len(cards)
Y = re.compile(r'\b(1[0-9]{3}|20[0-2][0-9])\b')
def share(f): k = sum(1 for c in cards if f(c)); return f'{k}/{n} ({100*k/n:.0f}%)'
print('description non-empty', share(lambda c: bool(c['description'])))
print('wikidataId', share(lambda c: bool(c['wikidataId'])))
print('P31 present', share(lambda c: bool(c['instanceOf'])))
print('>=1 non-hidden category', share(lambda c: len(c['categories']) > 0))
print('categories truncated (cllimit 50)', share(lambda c: c['categoriesTruncated']))
print('median categories', statistics.median(len(c['categories']) for c in cards))
print('year in title', share(lambda c: Y.search(c['title'])))
print('year in description', share(lambda c: Y.search(c['description'] or '')))
print('year in categories', share(lambda c: any(Y.search(x) for x in c['categories'])))
print('year anywhere (title/desc/cats)', share(lambda c: Y.search(c['title'] + ' ' + (c['description'] or '') + ' ' + ' '.join(c['categories']))))
print('births/deaths category', share(lambda c: any(re.search(r'\d+ (births|deaths)', x) for x in c['categories'])))
print('establishments/completed category', share(lambda c: any(re.search(r'establishments|completed in|disestablish|opened in', x) for x in c['categories'])))
print('living people', share(lambda c: 'Living people' in c['categories']))
print('stub category', share(lambda c: any('stubs' in x for x in c['categories'])))
print('country/nationality word in desc or cats', share(lambda c: re.search(r'American|British|English|French|German|Japan|China|Chinese|India|Brazil|Poland|Polish|Italy|Italian|Spain|Spanish|Austria|Canada|Australia|Russia|United States', (c['description'] or '') + ' '.join(c['categories']))))
print('legacy category on-chain', collections.Counter(c['legacyCategory'] for c in cards))
print('pageviews available', share(lambda c: c['pageviews']['status'] == 'available'))
print('languagesTruncated', share(lambda c: c['languagesTruncated']))
+59
View File
@@ -0,0 +1,59 @@
"""Proposed percentile -> cost/power/toughness derivation, evaluated on card-sample.json.
Usage: python3 -I stats.py <card-sample.json>"""
import json, sys, collections, statistics, itertools
d = json.load(open(sys.argv[1])); cards = d['cards']; P = d['percentiles']
def pct(s, v): # DESIGN 1.1 counting: cut points strictly below + half of equal
if v is None: return None
cut = P[s]; return int(sum(c < v for c in cut) + sum(c == v for c in cut) / 2)
TH = [26, 39, 51, 63, 78] # v1.1 costThresholds (fame -> cost 1..6)
BUDGET = [None, 3, 4, 6, 8, 10, 12] # P+T per cost, MTG vanilla curve (2/1, 2/2, 3/3, 4/4, 5/5, 6/6)
def derive(c):
a, dp, r = (pct(k, c['stats'][k]) for k in ('attention', 'depth', 'reach'))
vals = [x for x in (a, dp, r) if x is not None]
fame = int(sum(vals) / len(vals) + 0.5)
cost = 1 + sum(t <= fame for t in TH)
b = BUDGET[cost]
kw = 'Multilingual' if r >= 75 else ('Local' if c['stats']['reach'] == 0 else None)
if kw == 'Multilingual': b -= 1 # evasion-like keyword is paid for out of the body
if kw == 'Local': b += 0 # Local = gains +1/+1 next to a same-country Location (conditional, no tax)
share = (a if a is not None else 50) / max(1, (a if a is not None else 50) + dp) # attention vs depth
pw = min(b - 1, max(1, round(b * share))); t = b - pw
return dict(title=c['title'], a=a, d=dp, r=r, fame=fame, cost=cost, P=pw, T=t, kw=kw,
trend=c['pageviews']['trendPercent'], daily=c['pageviews']['dailyAverage'])
rows = [derive(c) for c in cards]; n = len(rows)
def naive(c): # straw man: power = attention tier, toughness = depth tier, cost from their sum
ti = c['tiers']; pw = (ti['attention'] or 1 + 1) // 2 + 0; t = (ti['depth'] + 1) // 2
return dict(cost=max(1, min(6, round((pw + t) / 2))), P=pw, T=t)
nv = [naive(c) for c in cards]
def dominated_pairs(rs, use_kw=False):
k = 0
for x, y in itertools.permutations(rs, 2):
if x['cost'] <= y['cost'] and x['P'] >= y['P'] and x['T'] >= y['T'] and \
(x['cost'] < y['cost'] or x['P'] > y['P'] or x['T'] > y['T']) and (not use_kw or x.get('kw') == y.get('kw')):
k += 1
return k
print('cost distribution', sorted(collections.Counter(r['cost'] for r in rows).items()))
print('power distribution', sorted(collections.Counter(r['P'] for r in rows).items()))
print('toughness distribution', sorted(collections.Counter(r['T'] for r in rows).items()))
print('keywords', collections.Counter(r['kw'] for r in rows))
print('P/T by cost:')
for cst in range(1, 7):
g = [r for r in rows if r['cost'] == cst]
if g: print(' ', cst, len(g), collections.Counter(f"{r['P']}/{r['T']}" for r in g).most_common(6))
pairs = n * (n - 1)
print('strict-dominance pairs proposed', dominated_pairs(rows), 'of', pairs, '; same-keyword only', dominated_pairs(rows, True))
print('strict-dominance pairs naive ', dominated_pairs(nv), 'of', pairs)
# efficiency by fame quintile
q = sorted(rows, key=lambda r: r['fame'])
print('fame quintile: mean cost, mean (P+T)/cost proposed | naive (P+T)/cost')
idx = sorted(range(n), key=lambda i: rows[i]['fame'])
for k in range(5):
sl = idx[k * n // 5:(k + 1) * n // 5]
print(f" Q{k+1} fame {rows[sl[0]]['fame']}-{rows[sl[-1]]['fame']}: cost {statistics.mean(rows[i]['cost'] for i in sl):.2f} "
f"eff {statistics.mean((rows[i]['P']+rows[i]['T'])/rows[i]['cost'] for i in sl):.2f} | naive eff "
f"{statistics.mean((nv[i]['P']+nv[i]['T'])/nv[i]['cost'] for i in sl):.2f}")
top = sorted(rows, key=lambda r: -r['fame'])[:6] + sorted(rows, key=lambda r: r['fame'])[:3]
print('examples (top fame, bottom fame):')
for r in top: print(f" {r['title'][:34]:34s} a{r['a']} d{r['d']} r{r['r']} fame{r['fame']} cost{r['cost']} {r['P']}/{r['T']} {r['kw'] or ''}")
tr = [r for r in rows if r['trend'] is not None and r['trend'] >= 25 and (r['daily'] or 0) >= 20]
print('trending (+25% and daily>=20):', len(tr), f'{100*len(tr)/n:.1f}%')
+79
View File
@@ -0,0 +1,79 @@
"""Classify card-sample.json into Figure/Location/Event/Institution/Doctrine.
Order: P31 label rules (first rule that matches ANY P31 label wins, rule order = priority),
then category keywords, then description keywords, then deterministic fallback.
Usage: python3 -I types.py <card-sample.json> [--list]"""
import json, re, sys, collections
RULES_P31 = [ # (type, regex on a P31 label). Order matters: specific before generic.
('Doctrine', r'aspect of|aspect in|disease|clinical sign|list article|chemical entity'),
('Event', r'election|protest|battle|war\b|storm|nor.easter|cyclone|tornado|earthquake|disaster|event|match|final\b|'
r'season|championship|tournament|\brace\b|grand prix|scandal|annexation|treaty|incident|festival|referendum|'
r'conference|ceremony|time period|delegation'),
('Institution', r'artificial satellite|space station|space telescope|spacecraft|space probe'),
('Location', r'planet|natural satellite|\bstar\b|galaxy|nebula|planetary system|astronomical object|rainforest|reef|'
r'civili[sz]ation|empire|historical country|archaeological site|'
r'human settlement|settlement|village|town|city|commune|municipal|parish|county|district|region|province|'
r'township|hamlet|townland|census area|local government|community of|island|river|lake|mountain|plateau|'
r'waterfall|valley|bay|peak|geographical feature|historic district|park|state park|square|road|highway|'
r'building|castle|mosque|church|temple|cathedral|house|home|museum|station|bridge|monument|historic site|'
r'military base|battery|refinery|shopping|stadium|arch|tower|fort|palace|columbari|council'),
('Figure', r'^human$|fictional character|stock character|person|deity|orisha|loa\b|taxon|species|genus|breed|'
r'^family$|organism'),
('Institution', r'company|business|organi[sz]ation|association|society|party|agency|studio|band|musical group|team|club|'
r'university|college|school|institute|diocese|ecclesiastical|manufacturer|newspaper|magazine|film|album|'
r'song|single|musical work|composition|television|series|book|novel|video game|painting|award|position|'
r'aircraft|ship|steamship|vehicle|automobile|tram|railway line|route|typeface|software|product|brand'),
('Doctrine', r'concept|theory|theorem|mathematical|programming language|language|gene|protein|chemical|compound|'
r'disease|clinical sign|ideology|religion|discipline|field|cuisine|food|dish|drink|aspect|list article|'
r'particle|process|genre|form\b|game\b|branch of|class of|type of|tabular'),
]
RULES_CAT = [ # fallback on non-hidden category titles (lowercase)
('Figure', r'\bbirth|\bdeaths\b|living people|people from|\bspecies\b|described in \d|\bgenera\b|deities|characters'),
('Event', r'\belections\b|protests|\bbattles\b|disasters|\braces\b|\bseasons\b|\bevents\b|scandals|annexations|competitions'),
('Location', r'villages|communes|parishes|local government|populated places|geography|rivers|islands|buildings and structures|bridges|'
r'stations|parks|districts|townships|cities and towns|historic places'),
('Institution', r'companies|organi[sz]ations|\bfilms\b|albums|songs|novels|newspapers|television series|musical groups|'
r'aircraft|ships|typefaces|software|awards|teams|clubs'),
('Doctrine', r'theory|structures$|algebra|terminology|cuisine|drinks|desserts|ecology|languages|diseases|conditions|'
r'concepts|ranks|etymology|maps|atlases'),
]
RULES_DESC = [
('Figure', r'\b(painter|politician|actor|writer|player|born|species|genus)\b'),
('Event', r'\b(race|election|battle|match|protest|storm|war|competition)\b'),
('Location', r'\b(village|town|city|river|island|building|church|columbarium|station|park)\b'),
('Institution', r'\b(company|band|film|album|organi[sz]ation|team|aircraft|ship|newspaper)\b'),
('Doctrine', r'\b(concept|theory|structure|dessert|drink|dish|technique|class of)\b'),
]
TYPES = ['Figure', 'Location', 'Event', 'Institution', 'Doctrine']
def classify(card):
labels = [i['label'].lower() for i in card.get('instanceOf') or []]
for t, rx in RULES_P31:
for l in labels:
if re.search(rx, l): return t, 'p31', l
cats = [c.lower() for c in card.get('categories') or [] if 'stubs' not in c.lower()]
for t, rx in RULES_CAT:
for c in cats:
if re.search(rx, c): return t, 'category', c
desc = (card.get('description') or '').lower()
for t, rx in RULES_DESC:
if re.search(rx, desc): return t, 'description', desc
# deterministic last resort: Doctrine (the residual "idea" class); never hash-random.
return 'Doctrine', 'fallback', ''
if __name__ == '__main__':
d = json.load(open(sys.argv[1])); cards = d['cards']
res = [(c, *classify(c)) for c in cards]
n = len(res)
by_t = collections.Counter(r[1] for r in res); by_src = collections.Counter(r[2] for r in res)
print('n', n)
for t in TYPES: print(f'{t:12s} {by_t[t]:4d} {100*by_t[t]/n:5.1f}%')
for s in ['p31', 'category', 'description', 'fallback']: print(f'src {s:12s} {by_src[s]:4d} {100*by_src[s]/n:5.1f}%')
print('labels w/o p31 match but has p31:', sum(1 for c,t,s,w in res if s!='p31' and c['instanceOf']))
print('cross-tab old faction x new type')
ct = collections.Counter((c['faction'], t) for c,t,s,w in res)
for f in sorted({c['faction'] for c in cards}):
print(f' {f:14s}', {t: ct[(f,t)] for t in TYPES if ct[(f,t)]})
if '--list' in sys.argv:
for c,t,s,w in res:
if [i['label'] for i in c['instanceOf']] == ['human']: continue
print(f"{t[:5]} {s[:4]} | {c['title'][:42]:42s} | {w[:40]}")
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+171
View File
@@ -0,0 +1,171 @@
# Night 2 plan: critic / player-advocate review
Reviewer: critic. Sources: night2/PLAN.md, wd/docs/game/{DESIGN,CARD_DATA}.md, card-sample.json, wd/docs/night/{HANDBOOK,BOUNDARIES}.md, Night 1 report (`~/Desktop/night/night-lead/REPORT.md`; it is not in wd/docs/night). Ranked by severity, most severe first.
## Facts the plan doesn't state, but which decide everything
- **Mined cards are random articles.** `server/wiki.ts` uses `generator=random`. Nobody chooses Barack Obama. The real pool looks like card-sample.json: 34% stubs, villages, beetles, French communes, local elections. "Tetrated dodecahedron vs Obama" will be rare. The everyday matchup is *Dichromorpha viridis vs 1954 Gold Coast general election*. That's still funny in a deadpan way, but the design and its examples must be built for it, not for celebrity cards.
- **Supply is about zero, not 96 a day.** 12 cards in 16 days, all in one wallet (Eric's), all from day 1. Mining has effectively stopped.
- **Mobile can't mine.** `App.tsx` hides the mining panel when `isNativeApp()`, so an Android player can never get a real card.
- **14% of sampled cards are living people** (33/236 in "Living people"). Events include ongoing protests with deaths (*2024–2026 Cuban protests*, *2025 Tehreek-e-Labbaik Pakistan protests*), a *sex scandal*, an *annexation*, and *Organization of the Luftwaffe (1933–1945)*. The safety rules (§6) are needed tonight, not someday.
---
## S1 (blocker). "Real cards" + PvP is impossible today. This is Eric's decision, not the agents'.
Under a literal reading of point 1, exactly one person on Earth can play, and PvP has no opponent. Each option, measured against the request:
- **(a) Small decks of 7–10:** literal and honest. But only Eric qualifies, and with exactly 12 cards there's no deckbuilding, which is half of what makes MTG feel like MTG.
- **(b) Owned "commanders" plus a public filler pool:** this *is* the loaner system Eric just said was only for the demo, renamed. If agents choose it without asking, it's a quiet betrayal of the request.
- **(c) Draft from the chain's cards:** the cards are real mined cards, but the pool is the same 12 cards every match. It's degenerate until supply grows. On testnet, about 50 cards, it's fine.
- **(e) Off-chain editions:** prints cards with no proof of work and no consensus. It undermines what "mined" means. Reject it.
- **(d) Collection-as-deck:** this is (a) with scaling. Fine as the mechanism, but it doesn't solve the 0–3 card player.
**Fix:** before 21:30, put these questions to Eric. Per standing preference, agents don't start building until Eric gives an explicit go.
1. "Does Classic and ranked PvP require 100% owned mined cards? (Recommend: yes.)"
2. "Can a player with fewer than N owned cards play casual or practice matches with clearly labelled **proxies**? They're never ranked, never shown as owned, and appear greyed out with the stamp 'Proxy'. (Recommend: yes, for practice, AI and invite-link casual only.)"
3. "Is Draft from the whole chain's minted cards 'real cards'? Ownership would earn the first pick and a credit line in the recap. (Recommend: yes.)"
4. "Can your 12 cards be used as public bot and ghost decks? (They're your wallet.)"
5. "Should we fix the supply side, so mobile users can get real cards, given that mobile can't mine? Options: a desktop-mining CTA, gifting by transfer (an on-chain action by Eric, not by agents), or an unlock condition such as 'mine 1 card to enter ranked'."
**Default if Eric doesn't answer:** take the most literal reading. Ranked and Classic use owned cards only. Practice and AI use proxies, which look different. Draft uses chain-minted cards only. No editions. Record the decision in DESIGN.md §0 in Eric's own words.
**Design implication either way:** the format must be fun with a small deck. Recommend **one format with no deck minimum**: a 10-card deck at most, and if you own fewer, you play what you own plus visible proxies, casual only. The engine must handle running out of cards gracefully. Draw from a reshuffled graveyard (DESIGN-style "recursion") instead of losing to an empty library.
## S2 (blocker). PvP has no population. A ranked ladder tonight is wasted work, and unsafe.
Elo with one eligible player is theatre. Night 1's REPORT (known issues 2–3) also says hosted PvP trusts the host: the host picks the seed, there's no commit–reveal, and the UI log is built from full state and leaks hand contents. A ladder on top of that is cheatable.
**Fix, in order:**
1. **Invite-by-link casual PvP** first, made prominent on the Play screen. Eric can test it with a second account on testnet.
2. **Async "ghost" matches.** You play a bot piloting a real wallet's real deck (with that owner's opt-in), and the result is posted to the owner. This is the PvP that a population of five can actually have.
3. The **queue backfills with a bot after 30 s**, *labelled as a bot*. Never pass a bot off as a human.
4. Defer the ranked ladder until commit–reveal and `viewFor`-only logs land. Cut it tonight.
## S3 (high). An MTG clone built in one night will be worse than Edit War
Edit War had a real hook: each lane is judged by one Wikipedia stat. The plan replaces it with generic power/toughness/cost. MTG is fun because of hand-designed cards, the stack and instant-speed interaction, and deckbuilding across thousands of cards. Tonight has none of that: procedurally generated text, 12 cards, and no stack.
**Fix: name the smallest core that still feels like Magic**, and only that:
- Two players, 20 life, and a resource that grows by 1 a turn automatically. Locations add +1 when played (no land screw).
- Board of 5 per side. Figures attack. The defender makes one block per attacker, chosen by tapping a blocker and then an attacker. No first strike, trample or multi-block in v1.
- Events are **sorcery-speed only**. No stack, no priority passes, no opponent-turn interaction. Every response window doubles PvP round-trips and the time needed for UI work.
- One keyword per card at most, from a list of about 8 (Night 1 used 6, with property tests).
- **Keep a Wikipedia hook that MTG doesn't have**, or this is "MTG with worse cards". Candidate: home stat as the creature's "evasion" (an attention attacker can only be blocked by a card with attention ≥ its own), or the trend arrow as haste. One hook, kept and tested.
- **Keep Edit War playable as a mode.** The code exists; deleting it removes a working fallback.
## S4 (high). 360 px readability
An MTG board (two battlefields, hand, life, resources, rules text, combat arrows) doesn't fit 360 px if the cards carry generated paragraphs.
**Fix:**
- The card face on the battlefield shows: title (2-line clamp), type icon, cost, P/T, one keyword chip. The rules text and flavour live **only** in the tap-to-zoom sheet.
- Rules text has a hard limit of 90 characters, enforced by a test over the whole sample.
- Combat uses a "declare attackers → defender blocks → preview outcome → confirm" sheet, not drawn arrows.
- The QA gate is a 360×640 screenshot of a full board (5 + 5) on Android, attached to the UI PR.
## S5 (high). Night 1 process lessons the plan doesn't apply
What went wrong (REPORT plus handbook):
- The design froze at 23:01, but the balance numbers were measured before the #38 change, so the shipped seat-advantage figure is stale.
- 3 OOMs (tower-plus, and r350 twice).
- imac's Gitea MCP was down all night, so the council had to relay through night-lead.
- Squash merges of stacked PRs caused add/add conflicts.
- Wikimedia 429s came from our own sampler.
- On Node 20, 12 tests failed falsely.
**Fixes:**
- **Freeze rules on a schedule, and gate them on evidence.** Design frozen by 22:30 (one hour, not 45 minutes: this is a bigger redesign). Engine API by 22:45. The balance re-run happens on the final head, after the last engine PR, and its numbers go in the report with the SHA they were measured on.
- **Fewer, wider agents.** 7–8, not 10:
- designer and critic as one council pair
- an engine agent
- a card-derivation and text-generator agent (it owns the safety rules)
- a UI agent
- a PvP/host agent
- a wiki-client agent
- a lead and a review agent
Night 1's 17 agents produced conflict and relay overhead.
- **Pre-flight at 21:30:**
- run `get_me` on Gitea MCP on every machine
- `node:24-alpine` is the only test image
- all heavy work runs under `flock` on inspiron
- no stacked PRs: rebase-and-merge, or wait for the parent to merge
- **No network in tests.** Every test and sim reads card-sample.json and starter-cards.json, plus a new red-team fixture (§6). The **only** process allowed to call Wikimedia tonight is the new throttled client's own smoke test, at 1 request/s.
- **Use testnet for real-cards testing.** It has about 50 mined cards across wallets the team controls. Seed 3–4 test wallets with 1, 3, 8 and 20 cards by transfer *on testnet*. Never simulate mainnet supply by copying Eric's wallet.
- **Mainnet is read-only, and only if needed at all.** Read the 12 cards' public data so Eric's own deck can go into a fixture. Nothing is written.
## S6 (high). Ethics and safety: content rules for the deadpan generator
The joke only works if the game is respectful about the subject and absurd only in the juxtaposition. These rules are **requirements** with tests, owned by the card-text agent:
1. **No free-form generated prose about real people or events.** Templates only. No LLM, including LocalAI. That also keeps the output deterministic. The only article-derived prose is the extract's first sentence, quoted verbatim and attributed.
2. **Figures are never harmed, killed or humiliated in text.** Log verbs for a Figure leaving play come from an editorial whitelist: "was reverted", "left the battlefield", "was archived", "was withdrawn from the record". Banned for any card: killed, died, destroyed (for Figures), executed, assassinated, murdered, humiliated, crushed, slaughtered, raped, lynched. "Destroy target Institution" is fine.
3. **Mechanics never derive from sensitive attributes.** Category-keyword templates for Figures come from an **allowlist** of neutral occupation and field words (politicians, mathematicians, footballers, painters, alumni). Never derive a mechanic from: crime, conviction, scandal, illness, disability, cause of death, ethnicity, religion, sexuality, gender, nationality as a trait, victimhood.
- Country is allowed **only** as a neutral "Connected" link (shared P27/P17). It must never carry a modifier such as "French: −1".
- Birth and death years may appear in the type line ("Figure — 1949–2019"). Nothing triggers on death.
4. **Solemn subjects get a `solemn` flag.** It's set by P31 class (war, battle with casualties, massacre, genocide, terrorist attack, mass shooting, disaster, epidemic/pandemic, aviation or maritime accident, protest with deaths, war crime, the Holocaust) or by category words (massacres, genocides, terrorist incidents, disasters in, deaths in, murders, sexual abuse, victims, suicides).
- Solemn cards are playable. They get one fixed neutral effect ("Commemoration: gain 1 Citation; draw a card"), no damage or removal text, a plain log line ("entered the record"), and they are **never** used to name a battle or shown in a recap headline.
- Events in general never "deal damage to" a Figure. Removal comes from Doctrines and Institutions ("Revert", "Edit war").
5. **Glorification guard.** No "leader", "inspire" or "rally" keywords keyed on heads of state, military leaders or dictators. Every Figure's keyword comes from stats, type and faction only. A *Adolf Hitler* card must be a plain statted Figure with no buff-allies text. Test it.
6. **Living people (BLP):** the flavour text is the extract sentence only, and the recap uses only the card title. Any `Living people` card mentioned in a recap is linked to its article and nothing is asserted about the person. Card actions in text are attributed to "the *Barack Obama* card" or the commander, not to the person.
7. **Mint-time vandalism.** The extract is frozen at mint and may be a vandalised revision. Render flavour from the cached **current** extract when possible. Give node operators a data-only `hiddenFlavour: [pageId]` list and a report link on the card zoom sheet.
8. **Recap pages must not impersonate Wikipedia.**
- No Wikipedia wordmark or puzzle-globe logo, and no "From Wikipedia, the free encyclopedia".
- The header reads "WikiDeck match record", with a hatnote: *"This article is about a WikiDeck match. For the polyhedron, see Tetrated dodecahedron."* That's funny, honest, and keeps us clear of the trademark.
- CC BY-SA attribution for extracts and images, in References.
9. **Player privacy.** Shareable recaps are opt-in per match. Commanders show as the account display name or "Anonymous", never a wallet address unless the player chooses.
10. **Red-team fixture plus a sign-off gate.** `tests/fixtures/sensitive-cards.json` holds hand-written PageEnrichment for: Barack Obama, Donald Trump, Adolf Hitler, Jesus, Muhammad, Yemọja, September 11 attacks, The Holocaust, Sandy Hook Elementary School shooting, 2004 Indian Ocean earthquake and tsunami, COVID-19 pandemic, a living child actor, Pullman porter affair, *2024–2026 Cuban protests*, Cho Yang-ho, and Tetrated dodecahedron.
- A test snapshots their full rules text, log lines and a recap, then asserts the banned-verb list and the solemn rules.
- The snapshot file goes into the morning report **for Eric to read before anything is shared publicly**.
## S7 (medium). Tone: how deadpan fails, with examples
- **Failure modes:**
- *Wacky:* puns, exclamation marks, emoji, winks.
- *Cringe:* the generator "noticing" the joke ("In a surprising twist…").
- *Dull:* logs that read like a stack trace.
- *Mean:* adjectives about the losing side.
- **Rule:** the text never comments on how odd the matchup is. The comedy is entirely in the nouns.
- **Card rules text.**
- DO: "*Tetrated dodecahedron* — Doctrine — Ideas. Figures you control with Depth 7 or more get +1/+1."
- DO: "*Barack Obama* — Figure — People, 1961– · 3/4 · Connected (+1/+1 while you control a Connected card)."
- DON'T: "Yes He Can! Obama gets +2 power because he's the president!"
- DON'T: "This shape is so complex it hurts your opponent's brain."
- **Match log.**
- DO: "Turn 6. *Cho Yang-ho* (4/5) attacked. *Dichromorpha viridis* (1/2) blocked and was reverted. Commander Eric cited *Tetrated dodecahedron*: *Cho Yang-ho* +1/+1 until end of turn."
- DON'T: "Cho Yang-ho SQUASHED the grasshopper lol." Also don't use "killed", or use any adjective (brutal, humiliating, heroic).
- **Recap.**
- DO: "The **Battle of the Tetrated Dodecahedron** was a WikiDeck engagement fought on 17 November 2026 between the forces of Eric and Bot (Normal). It lasted nine turns and ended in a decisive victory for Eric.[1] Contemporary accounts note the deployment of *Barack Obama* in the fourth turn.[2]"
- The infobox field is "Cards withdrawn", **not** "Casualties". Battles are named after the decisive non-Figure, non-solemn card; fall back to "Match of 17 November 2026".
- DON'T: "Obama was humiliated by a shape," or "the bloodiest battle in WikiDeck history."
- **Dull guard:** vary sentences by deterministic seed across 3–4 synonymous templates per event, and use citation numbers [n] that link to the card's real article. That small Wikipedia texture is most of the charm.
## S8 (medium). "Connected" will almost never fire on random articles
Two random articles almost never link to each other. Fetching `prop=links` per card is costly, at hundreds of links a page, and it doesn't fit the 1 request/s budget.
**Fix:**
- Connect cards on cheap shared Wikidata claims fetched once per card at first sight and cached for good: country (P17/P27), century (from P569/P571/P585), and same P31 superclass or faction. Leave out the article link graph tonight.
- Measure the fire rate on card-sample.json (random pairs) and on Eric's 12. Target 15–30% of pairs. If it's lower, the mechanic is invisible.
## S9 (medium). Wikimedia politeness (point 7): good plan, three gaps
1. The plan never says **who decides the production UA**. REPORT next step 8 leaves it to Eric. Ship the default as `WikiDeck/<version> (node: <PUBLIC_ORIGIN>; operator contact required)`, refuse to start the enrichment client without a contact configured, and leave production config to Eric.
2. Rate limits must be **per egress IP**, but all of Eric's nodes share one IP. Use one shared limiter per host IP: a single node acts as the Wikimedia proxy for the cluster, or the budget is split statically.
3. Set a request budget per match: **zero Wikimedia calls during a match.** All P31, claims and trend data are fetched at deck validation or lobby time from the cache. Trending's live stats come from the daily refresh.
## S10 (medium). Modes under the new engine (point 5)
Draft and Trending must be re-specified, not just "kept":
- Draft with a 12-card pool must deal from **all chain-minted cards**, or Eric must decide (S1-3).
- Trending uses the daily cache (S9).
- The house-rules JSON schema changes with the engine. Version it (`rulesetVersion: 2`) so Night 1 mode files on testnet nodes are rejected cleanly instead of misread.
## S11 (low). Story (point 3) depends on the recap
The plan's "story" is Connected plus the recap. Given S8, the recap and log carry the whole of point 3, so prioritise them over the ladder. The recap is cheap (a deterministic template over the match log) and is the most "Eric" deliverable.
## Scope: what gets built, and what gets cut first
**Build, in this order:**
1. The throttled Wikimedia client and cache. Nothing else calls Wikipedia.
2. Card derivation (type, faction, P/T, cost, keyword) with safety rules and the red-team test.
3. The smallest MTG core engine plus bots.
4. A 360 px match UI.
5. Invite-link PvP and ghost or bot matches.
6. The match log and battle recap.
7. Draft and Trending ported.
**Cut first:** the ranked ladder and Elo, the Wikipedia link graph, instant-speed Events, the Citations resource as a second currency (fold it into one keyword), and the "editions" idea.
## Decisions for Eric (to ask before kickoff, all in one message)
1. Real-cards strictness (S1 questions 1–3).
2. Use of his 12 cards as public bot and ghost decks.
3. A mobile path to owning cards.
4. Keep Edit War as a mode? (Recommend: yes.)
5. Sign-off on the safety rules in S6, especially solemn Events and living persons.
6. Production User-Agent and contact.
7. Are shareable recaps public by default? (Recommend: opt-in.)
+272
View File
@@ -0,0 +1,272 @@
# Night 2 plan review: data analyst
Inputs: `docs/game/card-sample.json` (236 random illustrated cards), `starter-cards.json`, `shared/enrichment.ts`, `shared/testnet.ts`, `server/{wiki,enrichment,wikimedia-user-agent}.ts`, `server/testnet/{http,miner}.ts`.
Scripts (all `python3 -I`, offline, no API calls): `night2/analysis/types.py`, `stats.py`, `fields.py`, `connected.py`.
**Caveat:** the type rules were tuned on this same sample, so the in-sample accuracy is optimistic. Anything marked *(memory)* comes from my knowledge of the Wikimedia APIs, not from a live check, because we are rate-limited.
## 1. Typing (P31, then categories, then description, then a residual)
The classifier in `analysis/types.py` checks the rules in **priority order**. The first rule that matches *any* P31 label wins. If nothing matches, it tries non-stub category titles, then the description. If all three fail, the card becomes **Doctrine**, which is the residual "idea" class and is deterministic, never hash-random.
| Type | n | share | Mostly |
|---|---|---|---|
| Figure | 86 | 36.4% | human 64, taxon 16, breed, deity, stock character, family |
| Location | 78 | 33.1% | villages, communes, rivers, buildings, parks, roads |
| Institution | 32 | 13.6% | companies, bands, films, parties, aircraft, ships, awards |
| Event | 21 | 8.9% | elections, protests, storms, matches, team seasons |
| Doctrine | 19 | 8.1% | genes, diseases, maths, cuisine, lists, etymology |
| Decided by | n | share |
|---|---|---|
| P31 | 222 | 94.1% |
| category fallback | 12 | 5.1% |
| description fallback | 2 | 0.8% |
| residual (Doctrine) | 0 | 0% |
- **Unclassified rate:** 0% in-sample, down from 14% ("Other") under Night 1's faction rules. 13 cards have no P31, and one card's P31 matched no rule.
- **Accuracy:** I judge about 8 of 236 (about 3–4%) to be debatable or wrong.
- **Expected out of sample:** about 5–10% would reach the category or residual steps on regex alone. That is why the P279 step below matters.
**Hard or misclassified examples:**
| # | Card | P31 | Result | Problem |
|---|---|---|---|---|
| 1 | Buky, Lunugala, Žižki, Laukhella | human settlement | Location | **Existing bug:** Night 1's `\bhuman\b` faction rule puts these 4 villages in *People*. Use `^human$`. |
| 2 | Lewis and Elizabeth Bolton House | single-family detached home | Location | Night 1 calls it *Works* because the label contains "single". Substring rules bite. |
| 3 | Corruption in Kazakhstan | aspect in a geographic region | Doctrine | "region" pulls it to Location unless an "aspect of/in" rule runs first. |
| 4 | 2023 Seville municipal election | municipal election | Event | "municipal" pulls it to Location unless Event outranks Location. Rule order is load-bearing. |
| 5 | Agda (programming language) | functional PL; free software | Institution | Several P31 labels disagree (Doctrine vs product). Tie-breaking is by type priority, not by label order. |
| 6 | Diocese of Mindelo | Diocese of the Catholic Church | Location | "church" matches. It is really an organisation (Institution). |
| 7 | Region Östergötland | county council of Sweden | Location | A governing body, so Institution. "county" matches first. |
| 8 | Christianity in the 5th century | events in a specific year or time period | Event | A history overview. Doctrine fits better. |
| 9 | NRHP listings in Yates County | Wikimedia list article | Doctrine | A list is not a thing. Consider a neutral "Index" type or rerolling at mint (consensus says no). |
| 10 | Dojikko; Tracheal collapse | stock character; type of animal disease | Figure; Doctrine | A trope as a Figure is fun but debatable. The disease was a Figure until "animal" was removed from the Figure rule. |
| 11 | Figueiredo (Guimarães) | former freguesia of Portugal | Location (via category) | Local admin-unit names defeat English regexes. Only the categories rescued it. |
| 12 | *(memory)* Rosetta Stone (stele), Apollo 11 (crewed spaceflight), ISS (space station) | | residual, residual, Institution | Famous starter cards fall through, or hit "station" and become a Location, unless explicit rules come first. |
**Proposed rules** (as implemented in `analysis/types.py`):
1. **Doctrine overrides first:** `aspect of|in`, `disease`, `clinical sign`, `list article`, `chemical entity`.
2. **Event:** `election`, `protest`, `battle`, `war`, `storm`, `match`, `final`, `season`, `race`, `grand prix`, `scandal`, `annexation`, `time period`, `delegation`.
3. **Institution overrides:** artificial satellites, space stations and space probes.
4. **Location:** settlement and administrative-unit words, geography, celestial bodies, `civilization`, `empire`, `historical country`, built structures.
5. **Figure:** `^human$`, `taxon`, `species`, `genus`, `breed`, `deity`, `character`, `^family$`.
6. **Institution:** organisations, companies, teams, creative works, vehicles, positions, awards, typefaces.
7. **Doctrine:** concepts, theories, genes, languages, cuisine, genre, form, process, `type of`, `class of`.
**Production recommendation** (the regex rules above are the fallback):
- Resolve each P31 class through **P279 (subclass of), up to 4 hops**, against a curated table of about 200 anchor classes. For example: Q5 → Figure, Q16521 → Figure, Q486972 (human settlement) → Location, Q1656682 (event) → Event, Q43229 (organisation) → Institution, Q17537576 (creative work) → Institution, Q151885 (concept) → Doctrine.
- **Class cache:** the sample has only **141 distinct P31 classes in 236 cards**. Class lookups saturate quickly, cost under 0.1 requests per card amortised, and are cached forever.
- **Fallback chain:** P279 anchors → label regex → category regex → description regex → **Doctrine**.
- **Freeze the result per card:** store it in the card profile (§3) so that a later Wikidata edit cannot retype a card someone owns.
**Deck consequence:** Event and Doctrine are scarce.
| Type | P(none in 10 random cards) | P(none in 7) |
|---|---|---|
| Event | 39% | 52% |
| Doctrine | 43% | 55% |
| Institution | 23% | 36% |
| Location | 1.8% | 6% |
| Figure | 1.1% | 4% |
- **Instants and enchantments:** a deck built from random mints often has none. The core loop must not need them.
- **Resources:** this argues for a fixed per-turn income (as plan C says). With Locations as the only resource, about 6% of 7-card decks would have no resource at all.
## 2. Stats: percentiles → cost, power, toughness (`analysis/stats.py`)
**Facts that drive the design:**
- **No independent signal in the raw fields.** pageBytes, languageCount and monthly views are monotonic in depth, reach and attention, so their percentiles are identical. They add nothing beyond the three scores.
- **attention and depth correlate** (ρ 0.61), and **reach is independent** of both.
- **trendPercent is live, small and noisy.** Only 2.1% of cards pass the Night 1 gate (+25% and ≥20 views a day).
- **A new independent-ish signal** is available from the on-chain `months[]`: the volatility (coefficient of variation) of the 6 monthly views, median 0.22. Its ρ is −0.52 with attention, −0.30 with depth and −0.19 with reach. It could drive a "Volatile" keyword.
**Proposal:**
1. `pct_s` for attention, depth and reach, using the §1.1 counting against the sample's 99 cut points (unchanged from Night 1).
2. `fame` = the mean of the three percentiles. Cost = 1–6, using the v1.1 `costThresholds` [26, 39, 51, 63, 78] (unchanged).
3. **The body budget depends on cost only:** P+T = [3, 4, 6, 8, 10, 12] for costs 1–6, which is MTG's vanilla curve (2/1, 2/2, 3/3, 4/4, 5/5, 6/6).
4. **The shape comes from the stats:** power = round(budget × pct_a / (pct_a + pct_d)), clamped to [1, budget−1], and toughness is the remainder. Attention reads as "loud", depth as "sturdy".
5. **Reach gives a keyword, paid for from the body.**
- **pct_r ≥ 75 → Multilingual** (evasion-like), costing −1 from the budget.
- **reach = 0 → Local** (a conditional bonus with a same-country Location, no tax).
- Local covers the 18% of cards with reach 0.
6. **Non-Figures use the same budget as effect size:**
- **Event:** deals ⌈budget/2⌉.
- **Location:** P=0 with T=budget, or a per-turn bonus.
- **Doctrine:** ±1 effects, scaled by cost.
- **Institution:** a utility ability.
7. **Trend:** ±1 power, in Trending mode only, using live data frozen at match start.
**Resulting distribution (236 cards, every card rated as if it had a body):**
| cost | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| cards | 30 (13%) | 48 (20%) | 51 (22%) | 48 (20%) | 35 (15%) | 24 (10%) |
| most common P/T | 2/1, 1/2 | 1/3, 3/1, 2/2 | 3/3, 4/2, 2/4, 5/1 | 3/5, 4/4, 5/3 | 5/5, 4/5, 5/4 | 6/5, 6/6, 5/6 |
| Measure | Value |
|---|---|
| power, 1..7 | 38 / 43 / 53 / 33 / 42 / 26 / 1 |
| toughness, 1..7 | 43 / 43 / 50 / 30 / 53 / 16 / 1 |
| keywords | none 139, Multilingual 55, Local 42 |
**"Famous isn't strictly better" check:**
- **Strict dominance** means another card with cost ≤, power ≥ and toughness ≥, and strictly better in at least one.
- **Proposal:** 0 of 55,460 ordered pairs among cards with the same keyword. All 945 raw pairs are cases where a keyword costs one point of body, which is intended.
- **Straw man:** with P and T taken directly from the attention and depth tiers and cost derived from their sum, **3,058 pairs**.
- **Efficiency, (P+T)/cost by fame quintile:** Q1 2.64 (the cheap 2/1s), then Q2–Q5 at 1.90, 1.96, 1.95 and 1.89.
- **Famous cards are bigger and pricier, never more efficient.** Pallas's cat (fame 98) is a cost-6 6/5 Multilingual. Dr. John L. Butler House (fame 8) is a cost-1 1/2 Local.
- **Remaining risk:** in a small-deck game with fixed income, a 6-drop can still dominate the late game. Balance that in the simulator (Night 1's `scripts/sim/`), not in derivation.
## 3. Rules-text inputs (`analysis/fields.py`)
| Field | Where | Reliability (sample) | Use for abilities | Extra cost |
|---|---|---|---|---|
| title, extract (≤900 chars), image, legacy category, pageId, revisionId | **on-chain** (`Article`) | 100%. Extract ≥40 chars by filter. | Flavour text is the first sentence of the extract. Years and "(born …)" can be parsed from the extract. | 0 |
| pageBytes, languageCount, 6 months of views, dailyAverage, trendPercent, attention/depth/reach | **on-chain** (`MintStatsSnapshot`) | 100% (attention null under 1%) | Cost and body, Multilingual/Local, Volatile, Rising/Fading | 0 |
| description (short) | live: WP `prop=description` | 90% | Keywords such as "Species of", "Village in", "film by" | in the batched meta query |
| non-hidden categories | live: WP `prop=categories` | 100%, median 5 | Year in 55% of cards; births/deaths 25%; establishments 10%; stub 34%; country words 52% | same query |
| wikidataId | live: `pageprops` | 100% | Key for all Wikidata data | same query |
| P31 (instance of) | live: Wikidata | 94% | **Type** | 1 per 50 cards |
| Dates: P569/P570 birth and death, P571 inception, P585/P580 point in time and start | live: Wikidata | *(memory)* Common for humans, organisations and events; rare for taxa and concepts | Era keywords ("Ancient", "19th-c."), "Contemporary" links | same `wbgetentities` |
| Coordinates: P625, or WP `prop=coordinates` | live | *(memory)* Nearly all Locations, few others | "Adjacent" (distance), hemisphere, lat/long flavour | in the batched meta query |
| Country: P17 / P27 | live | *(memory)* Most places, people and organisations | "Compatriot" connection | same `wbgetentities` |
| Outlinks: `prop=links` | live | 100% | Connected (§4) | 1–6 per card, continuation |
**Request cost per card, first sight, cached forever:**
- **Batched, amortised:** about 1.5 requests per card.
- 1/50 for the WP meta query (description, categories, pageprops, coordinates)
- 1/50 for `wbgetentities&props=claims`
- under 0.1 for class/P279 lookups
- about 1.2 for outlinks
- **Unbatched (a single card at a time):** about 4 requests.
- **Payload warning *(memory)*:** `props=claims` for famous items can be **hundreds of KB to over 1 MB** (Q76, Barack Obama). It cannot filter by property.
- **Option 1:** a WDQS SPARQL `VALUES` query for the ~12 needed properties, covering up to about 100 items per query.
- **Option 2:** accept the size and only ever fetch each item once.
**Request cost per match**, two decks of 10 cards:
- **Warm caches:** **0–1**. That is the links matrix (§4) if per-card outlinks aren't cached.
- **Trending mode:** add up to **20 per-article pageview requests** for today's figures. These can't be batched, so refresh them in a daily background job, never at match start.
- **Cold worst case:** about 23 requests, which is 23 s at 1 request per second. So prefetch when a card is minted or received, or when a deck is saved, never at queue time.
**Frozen vs live:**
- **On-chain (frozen by consensus):** only `article` and `statsSnapshot`.
- **Everything else is mutable.** That covers type, dates, country, categories and links.
- **Card profile:** freeze it once into an off-chain record, `{tokenId, pageId, mintRevisionId, fetchedRevisionId, wikidataRev, type, faction, dates, country, coords, outlinks hash}`. Cache it forever, and log it in the match record so replays and recaps are deterministic.
- **Why not the mint revision:** fetching categories or links *as of* the mint revision needs `action=parse&oldid=`, which is costly because of the parser-cache miss *(memory)*. Freeze at first sight instead, and record which revision was used.
- **Agreement between hosts:** different hosts could freeze different profiles. To fix that, a node publishes its signed profile file per tokenId, and hosts adopt the first one seen.
## 4. Connected: cheap relationship detection (`analysis/connected.py`)
**Measured on random pairs** (27,730 pairs):
| Relation | Pairs | In a 10-card deck (≥1 pair) |
|---|---|---|
| any shared category (including generic ones such as "Living people" or "1948 births") | 1.96% | |
| shared **specific** category | **0.04%** | 2% |
| same P31 class | 7.9% (mostly human/taxon) | |
| same P31, excluding human and taxon | 0.22% | |
| same country (text proxy for P17/P27) | 7.4% | 91% |
| same century (text proxy for dates) | 16.6% | |
| country OR century OR specific category | 21.5% | 99% |
**Direct article links between two random cards will almost never fire.**
- Shared specific categories are already 0.04%, and links are rarer still between random stubs.
- Obama ↔ White House only works because both are famous starter-style titles.
- **Proposed tiers:**
- **Linked (rare, strong):** a direct link in either direction.
- **Compatriot:** same P17 or P27.
- **Contemporary:** same century, from P569, P571 or P585.
- **Kin:** same P31, excluding human and taxon.
**Methods compared:**
| Method | Cost | Notes |
|---|---|---|
| Pairwise links matrix: `action=query&titles=A1…An&prop=links&pltitles=A1…An&pllimit=max` | **1 request per match** for up to 50 titles; at most 400 edges for 20 cards, under the 500 limit | Gives both directions for every pair. Uses current revisions. Misses links that go through redirects, unless you add `redirects` and also check the redirect titles. |
| Per-card outlinks (`prop=links`, ns0), cached | 1–6 requests per card, once | Intersection is local and free, so it scales to the whole chain. Network-wide this is at most 96 × about 2 ≈ 200 requests a day. **Recommended.** |
| `prop=linkshere` (backlinks) | Famous pages: thousands to millions, many continuations | **Avoid.** Outlinks from both sides already cover A↔B. |
| Shared Wikidata values (P17, P27, P131, P106, P101, P361, dates) | Included in the card profile fetch | Most useful in practice. Gives readable reasons ("both Polish"). |
| Categories | Included in the meta fetch | Too sparse except for generic categories, which are meaningless. Use only for era and country when Wikidata lacks them. |
**Caching:**
- **On first use:** compute each card's outlinks and profile once, keyed by `(pageId, fetchedRevisionId)`, and pin them to the `tokenId` forever.
- **During a match:** the host computes the edge list at match start from cached profiles, which needs no requests, and writes it into the match log.
- **Re-fetching:** never re-fetch for an owned card. An optional "re-sync" can be a deliberate, logged action.
## 5. Wikimedia politeness *(memory: not checked live tonight)*
**Rules:**
- **User-Agent policy:**
- The policy asks for a descriptive UA with contact details: `Tool/version (https://site; contact@…) lib/ver`.
- Generic or library-default UAs may be throttled or blocked. Browsers must use `Api-User-Agent`.
- **Finding:** our defaults have **no contact at all**. That covers `Wikideck/0.1 (experimental Wikipedia article cards)`, the enrichment UA, and the sampler UA `WikiDeckCardDataSampler/0.1`. Contact is opt-in only, through `WIKIDECK_USER_AGENT`. This is likely part of why the shared IP got 429.
- **Action API etiquette:**
- Make requests **serially**, not in parallel. There is no fixed read limit, but use "reasonable" volume.
- Send `maxlag=5` on non-interactive requests, and on a `maxlag` error wait for `Retry-After`.
- Batch: `titles`/`pageids` take 50 per request (500 with the bot flag), and `pltitles` 50 likewise.
- Use continuation, `Accept-Encoding: gzip`, and `formatversion=2`.
- **REST API (`/api/rest_v1`):** the historical guidance was ≤200 requests per second per client. Since 2025 Wikimedia has tightened limits on unauthenticated automated traffic and enforces them per IP/UA. Treat any published number as a ceiling, not a target.
- **API Portal or token traffic:** I recall anonymous traffic at about 500 requests an hour and a personal token at about 5,000 an hour. **Unverified.**
- **Pageviews (AQS):**
- The documented limit was about 100 requests per second per client.
- It is **per article and has no batching**.
- Daily data lands once a day, a few hours after 00:00 UTC, so refreshing more than once a day is waste.
- **Wikidata:**
- `wbgetentities` takes up to 50 ids per request; use `props=` to slim the response.
- WDQS allows about 60 s of query time per minute and 5 concurrent queries per client, and blocks after repeated errors.
- **Always:** honour `429`/`503` with `Retry-After`, use exponential backoff, and cache.
**Concrete node defaults:**
| Setting | Default |
|---|---|
| Client | one shared `WikimediaClient` per **process, and budget per egress IP** (several nodes or agents behind one IP must share it) |
| Rate | token bucket: **1 request/s sustained, burst 3**, **1 in-flight per host** (en.wikipedia.org, wikimedia.org, wikidata.org) |
| Daily cap | 20,000 requests a day per node (configurable). Past it, serve from cache or 503. |
| maxlag | `maxlag=5` on every Action API call from background jobs |
| 429/503 | honour `Retry-After`, else 5 s × 2ⁿ up to 15 min. **Circuit breaker:** after 3 consecutive 429s, stop all Wikimedia calls for 10 min. |
| Batching | 50 pageids/titles, 50 Wikidata ids, links matrix per match |
| UA | `WikiDeck-node/<ver> (+https://<node host>; <operator contact>)`. **Start-up warns loudly**, or refuses in prod, unless a contact is set. |
| Cache | on disk. Profiles and outlinks are immutable (keyed by tokenId and revision). Pageviews keyed by (title, day). ETag / `If-None-Match` on REST. |
| Background | one daily job after about 06:00 UTC refreshes live views for cards in active decks only |
**Mining load: a real issue the plan doesn't list.**
- **What a template costs:** `POST /api/mining/template` calls `wikipediaArticles.random()`, plus `getFresh()` enrichment, on **every template**. That is 3 or more Wikimedia requests (`server/testnet/http.ts:122`).
- **How often:** each miner asks for a new template whenever the tip changes (`server/testnet/miner.ts:89`).
- **Load:** M miners make **about 3M requests per block, all in a burst at each new tip**, or 288·M a day. With 100 miners that is 28,800 a day, which breaks the cap above.
- **Fix:** prefetch a small pool of article+snapshot pairs in the background at 1 request/s, and serve each template from the pool.
- `grnlimit=10` yields about 4.4 usable articles per request.
- This changes no consensus rules.
- Wikimedia load then stays at about 2–3 requests per block, whatever the number of miners.
## 6. Supply
- **Production:** at most 96 blocks a day means at most 96 cards a day: 672 a week, about 2,900 a month, 35k a year.
- **Mainnet reality:** 12 cards, all mined on 2026-11-01. That is **0.75 a day averaged over 16 days**; mining has effectively stopped.
- **Model:** with M equal-hashrate miners, each expects 96/M cards a day, so the time to N cards = **N·M/96 days**. This assumes continuous full block production.
| Active miners M | N=7 | N=10 | N=20 | N=40 | N=60 |
|---|---|---|---|---|---|
| 1 | 1.8 h | 2.5 h | 5 h | 10 h | 15 h |
| 10 | 0.7 d | 1.0 d | 2.1 d | 4.2 d | 6.3 d |
| 50 | 3.6 d | 5.2 d | 10 d | 21 d | 31 d |
| 100 | 7.3 d | 10 d | 21 d | 42 d | 63 d |
| 500 | 36 d | 52 d | 104 d | 208 d | 313 d |
**Caveats:**
- **Mining is a Poisson lottery.** At M=100, 10 cards take a mean of 10.4 days, but about 15 days at the 90th percentile.
- **Hashrate is skewed.** The *median* miner gets well under 96/M; a phone-class CPU gets about 0. Non-miners only get cards through trades.
**Implications for deck size:**
- **Rule of thumb:** a deck size D is reachable in T days only if D ≤ 96·T/M.
- For a 1-week ramp with 100 miners, D ≤ 6.7.
- **40–60-card constructed decks** need M ≤ about 12, or months of play.
- **Recommendation: a 7–10-card constructed deck**, plan option (a).
- Every card is unique anyway, so this is effectively Highlander, with recursion and reuse.
- **Collection-as-deck**, option (d), covers players with fewer than 7 cards.
- **Draft, option (c), is supply-friendly**, but only once the chain holds enough cards.
- An 8-player draft of 3×15 needs 360 cards (about 4 days of full production); a 2-player draft needs about 60.
- **Today's 12 cards cannot feed even one draft.**
- **The cold start is the blocker, not the steady state.** Eric must decide one of two things for launch week:
- accept a loaner or shared pool (plan option (b), which conflicts with requirement 1), or
- accept that PvP only works after someone mines continuously for a day or two.
+278
View File
@@ -0,0 +1,278 @@
# Night 2 review: game designer
**Verdict: approve the direction with changes.** Do the MTG-style duel, the article-derived types, the Connected bonus and the battle recap. The plan has one gap: it has no answer to supply, and Open problem 1 decides whether any of the rest gets played. My answer is a **15-card deck made of your owned article cards plus Basics**. Basics are non-article "process" cards, the equivalent of MTG basic lands. **Draft** from the chain's whole register is the front door for players who own few cards. Rules core: **no stack, no land cards, fixed income, attack/block with single blocks, 16 Notability.** Everything below is data in the existing rules-as-data style.
---
## 1. Supply (Open problem 1)
**The facts:** mainnet holds 12 cards, all in one wallet. At most about 96 a day can be mined, and the real rate is far lower. For months nearly every player will own 0–3 cards. No version of "real cards only" fills a 40-card deck. The question is how the rules bend.
### Recommendation: "Collection + Basics" (options a and d, with the MTG basic-land argument)
- **Deck:** exactly **15 cards**.
- **Article slots:** any number of your owned mints, up to 15. Each mint can appear once, since it is unique. Different mints of the same `pageId` can appear up to 2 times.
- **Basics** fill the rest, at most 3 copies of each.
- Owned and loaner copies no longer mix (v1 §2 is retired).
- **Basics are not articles.** They are a fixed set of 8 Wikipedia process cards that nobody owns and anyone can use in any number. Listed in §2.4.
- **The argument for Eric:** in Magic, about 40% of every deck is basic lands that nobody collects, and the deck is still "your deck". Here, **every article in your deck is one you mined**. The letter of the requirement holds for articles. It bends only in that the deck isn't made *only* of articles.
- **Signature card:** before the match you name one owned article as your Signature. It **starts in your opening hand**, in addition to the 5 cards you draw.
- So a player with 1 card plays that card in every game.
- The recap's infobox lists it under "Commanders".
- **Small deck, high visibility:** a typical game lasts about 8 turns each, so you see 5 + 8 = 13 of your 15 cards. Your owned cards nearly always show up.
- **Running out of cards doesn't lose the game.** When your library is empty, shuffle your Deleted pile (the graveyard) into it. This is option (a)'s "recursion and reuse".
- **Power parity:** an article and a Basic of the same cost are worth about the same, with articles roughly 10% ahead from keywords and Connected (sim target: an all-Basics deck wins 42–48% against a 12-article deck).
- Owning cards buys **variety, story and a modest edge**. It doesn't decide games. Ranked Glicko absorbs the rest.
### What a new player does
| Owns | Practice / AI | Casual PvP | Ranked | Draft |
|---|---|---|---|---|
| 0 cards | Tutorial: the Basics deck plus 3 Archive cards, the existing loaners in a grey "Not owned" frame | Basics-only deck allowed | no (one article needed) | **yes: main path** |
| 1–5 | any | Collection + Basics; the Signature guarantees their card | yes | yes, plus the owner perk |
| 6–15 | any | mostly articles | yes | yes |
Casual matchmaking groups players by article count (0–2 / 3–7 / 8+). Ranked has one ladder.
### Fallbacks, in order
- **Fallback A (if all-Basics games test as dull):** the "Archive ramp".
- Up to `max(0, 8 − owned)` Archive loaner articles may fill slots, and they shrink as you own more.
- Archive cards are grey-framed and listed in the recap as "(Archive, not owned)".
- This is option (b) with a sunset clause. **Eric must accept it explicitly.**
- **Fallback B (strictest "real mints" reading):** "Register as shared library".
- Both players draw from one shared library: every mint on the chain, whoever owns it, plus Basics.
- Your owned cards sit in a Command zone. You can cast them at any time, and they return there with +1 cost tax.
- Every article in play is then a real mint, but your *deck* is no longer yours. It also needs ≥ 30 mints before games stop repeating.
### What Eric must decide
1. Are Basics acceptable as a deck's "lands"? I recommend yes.
2. Archive loaners below 8 owned cards: allowed, or Basics only? I recommend Basics only at launch, with Fallback A behind a ruleset flag.
3. Can owning cards give a small edge in ranked? I recommend yes, capped by the parity target above.
---
## 2. Rules core (Open problem 2)
**Is MTG combat too complex for one night?** Not if the rules are cut to the bone: no stack, single blocks and one main phase. It is the only part that gives "feels like Magic", so keep it. The lane engine, `Topic` and `Portal` are retired. `rng.ts`, `ruleset.ts`, `modes.ts`, `validateDeck`, `replay`, `viewFor` and serialisation carry over.
### 2.1 Setup and turn
- **Notability:** each player starts at **16** Notability (the life total). Reaching 0 loses.
- The log reads: "*X* was nominated for deletion. The result was **delete**."
- **Opening hand:** draw 5, plus your Signature. One free mulligan: shuffle, draw 5, put 1 on the bottom.
- **First player:** skips the first draw. The second player gets **Second Opinion**, a 0-cost token: "Gain 1 Citation this turn".
- **Turn:** (1) **Refresh:** Citation maximum +1 (to at most 7, plus Territory), Citations refill, permanents untap. (2) **Draw** 1. (3) **Main:** play cards in any order. (4) **Combat.** (5) **End:** damage clears, "until end of turn" effects end, hand limit 7. No second main phase.
- **Resources:** fixed income, the Hearthstone model. **No land cards, so no land screw.**
- Locations add ramp (+1 maximum each, at most +2 from Territory in total). Max Citations is 9.
- **Summoning sickness:** a Figure can't attack the turn it enters ("Pending review"). Trending removes this.
### 2.2 Combat
- **Attack:** the active player taps any untapped Figures to attack. They attack the opponent only, not permanents.
- **Block:** the defender assigns at most one blocker to each attacker. Each blocker blocks one attacker. Locations with Garrison may block.
- **Damage:** simultaneous. Blocked pairs trade damage, and an unblocked attacker deals its power to Notability.
- No trample and no first strike in v1. That is about 150 lines of engine, and it is easy for bots.
### 2.3 Interaction without a stack
- **There is no priority, and nothing happens at instant speed.** That is the right call for online PvP on phones, because priority passes cost latency and clock time. Events are sorcery-speed.
- **v2, cut tonight:** *Pending changes*, Events set face-down that trigger on a condition (like Hearthstone's Secrets). They add interaction on the opponent's turn without priority passes.
### 2.4 Basics (the 8 process cards, max 3 copies each)
| Basic | Type | Cost | Text |
|---|---|---|---|
| Anonymous Editor | Figure | 1 | 1/2 |
| Established Editor | Figure | 3 | 3/3 |
| Administrator | Figure | 5 | 4/5. When this enters, destroy target Figure with power 2 or less. |
| Citation | Event | 1 | Put a +1/+1 counter on target Figure. |
| Revert | Event | 2 | Return target Figure or Doctrine with cost 3 or less to its owner's hand. |
| Talk Page | Event | 2 | Draw 2 cards, then discard 1. |
| Speedy Deletion | Event | 4 | Destroy target Figure. |
| Sandbox | Location | 1 | Territory. Garrison 0/1. |
### 2.5 Length
- **Clock:** 60 s per turn plus a 5-minute bank per player.
- **Turn cap:** at the end of turn 12 (each player's), the player with more Notability wins. A tie goes to the higher total power on the battlefield, then to the second player.
- **Sim target:** median 7–9 turns each, 6–12 minutes, decided before the turn cap in ≥ 85% of games.
- **Tunable:** Notability (14–20) and the maximum Citations are ruleset keys.
---
## 3. Derivation: article to card (Open problems 3 and 5)
All of it is deterministic: no LLM, fixed tables, and a versioned `deriveVersion`.
**Inputs:**
- the snapshot (as v1)
- `description`, `categories` and `pageBytes`, already in `PageEnrichment`
- the Wikidata entity's **claims**, fetched in the same `wbgetentities` call (≤ 50 ids per request) that Night 1 already used for P31, so no extra requests
The host caches the claims per `(wikidataId, lastrevid)` and freezes them into the `CardInput` at deck validation.
### 3.1 Type: the first rule that matches wins
1. **Exact Q-id table:**
- Q5 human, Q95074 fictional character, Q16521 taxon, Q23038290 fossil taxon, Q8436 family, deities → **Figure**
- Q486972 human settlement → **Location**
2. **P31 label regex,** reusing `factionRules`, grouped by type:
- People and Nature taxa → Figure
- Places and Structures → Location
- Events and Sport matches/seasons/finals → Event
- Works, Organisations, Sport teams and companies → Institution
- Ideas & Tech → Doctrine
3. **P279 "subclass of" labels,** with the same regexes. Concepts such as *Monoid* have no P31 and only P279. This is why 13 sample cards have no P31.
4. **Description regex,** present on 90% of the sample:
- `^Species of|genus of` → Figure
- `(actor|politician|player|singer|writer)\b` → Figure
- `^(Commune|Village|Town|Municipality|River) in` → Location
- `election|storm|battle` → Event
5. **Categories:** `\d+ births|deaths|Living people` → Figure, `Communes of|Villages in|Populated places` → Location, `establishments` → Institution, `elections|disasters|battles` → Event.
6. **Otherwise Doctrine (Neutral).** An abstract thing is the safest default.
**Bug to fix:** the People regex `\bhuman\b` matches "human settlement". As a result *Buky*, *Lunugala*, *Žižki* and *Laukhella* are People in the sample today (4 of 68). Run the exact Q-id step first. Then score the sample's 236 cards in CI and hand-check the 34 "Other" cards. Target ≥ 95% plausible.
### 3.2 Portal (the faction or colour), orthogonal to type
Five **Portals**, each with an MTG colour analogue, plus **Neutral**:
- **Arts** (red)
- **Earth** (green)
- **History** (black)
- **Science** (blue)
- **Society** (white)
**How a card gets one:**
- **Score:** count keyword hits in description + categories + P31/P106 labels, using fixed regex lists in data. For example:
- History: `\d+(st|nd|rd|th)-century|deaths|sultan|empire|castle|medieval`
- Science: `mathemat|algebra|programming|gene|chemi|disease|scientist`
- **Ties** go to the type default: Figure → Society, Location → Earth, Event → History, Institution → Arts, Doctrine → Science.
- **Zero hits:** the card is Neutral.
**Deck rule: none.** You can't ask for colour discipline from a 3-card collection. Portals matter only through effects, for example "Figures from your Portal get +1/+0".
### 3.3 Cost and stats
- **Percentiles, `fame` and cost 1–6:** exactly as v1 §1.1–1.2, using the existing `costThresholds`.
- **Figure:**
- budget `B = 2·cost + 1` (3/5/7/9/11/13)
- `s = clamp(pct_att/(pct_att+pct_depth), 0.3, 0.7)`
- `power = max(1, round(B·s))`, `toughness = B − power`
- each keyword costs 1 point from the larger stat (minimum 1)
- at most 2 keywords
- fame sets cost, never efficiency: v1's anti-inflation principle is kept
- **Location:**
- cost `ceil(cost/2)` (1–3)
- Territory
- Garrison 0/T, where `T = 1 + floor(pct_depth/25)`
- can't attack
- **Event, Institution and Doctrine:** magnitude `k = ceil(cost/2)` (1–3) inside the templates in §3.5.
### 3.4 Keywords, in priority order, max 2
Rates are measured on the 236-card sample.
| Keyword | Trigger | Rules text | Sample rate |
|---|---|---|---|
| **Protected** | category `Living people` | Can't be targeted by Events an opponent controls. | 14% |
| **Featured** (flying) | pct_attention ≥ 85 | Can be blocked only by Featured or Translated Figures. | ~15% |
| **Translated** (reach) | languageCount ≥ 20 | Can block Featured Figures. | 12% |
| **Legacy** | P570 present or a `\d+ deaths` category | When this is destroyed, draw a card. | 12% |
| **Stub** | category contains "stubs" or pageBytes < 3000 | At the start of your turn, put a +1/+1 counter on this (at most 2). | 34% |
| **Well-sourced** | pct_depth ≥ 85 | Prevent the first 1 damage dealt to this each turn. | ~15% |
| **Trending** (haste) | Trending mode only: live ▲ | Can attack the turn it enters. | mode |
### 3.5 Templates by type
Text is set in MTG's terse register. Subtype regexes run over the P31/P279 labels and the description.
- **Event:**
- conflict (`battle|war|siege|annexation|protest|riot`): "Deal k+1 damage to target Figure or Location."
- disaster (`storm|nor.easter|cyclone|earthquake|flood|tornado`): "Deal k−1 (min 1) damage to each Figure and each Location."
- election (`election|referendum|straw poll`): "Create k 1/1 Society Figure tokens named Elected Member."
- sport (`match|final|season|tournament`): "Target Figure you control gets +k/+0 until end of turn, then fights target Figure you don't control."
- period (`events in a specific year|ceremony|festival`): "Draw k cards."
- default: "Target Figure gets +k/+k until end of turn."
- **Institution** (a permanent, like an artifact):
- organisation/company/party/military: "At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member." (for cost ≥ 4; below that, "When this enters, …")
- creative work: "Figures you control that are Connected to this get +1/+1. When this enters, draw a card."
- team/club: "Figures you control with power 2 or less get +1/+0."
- vehicles and ships (v2: Crew): "Figures you control have Featured while attacking."
- **Doctrine** (an Aura, the mechanic in Eric's Tetrated dodecahedron → Cho Yang-ho anecdote):
- **Adopt:** "Attach to target Figure. Adopted Figure gets +k/+k." If the Figure leaves, the Doctrine goes to Deleted.
- Riders by subtype:
- mathematics: "and has Well-sourced"
- language/software: "Whenever it deals combat damage to a player, draw a card"
- ideology/religion: "Other Figures you control from the same Portal get +1/+0"
- **Pathology** (`disease|clinical sign|gene|chemical`) is inverted: "Attach to target Figure. It gets −k/−k."
- **Flavour text:** the first sentence of the extract, or `description` if the extract is missing (the sample has none).
### 3.6 Example cards from `card-sample.json`
Tiers and stats are taken from the file. The final numbers come from the real percentile function.
| Card | Derivation | Generated card |
|---|---|---|
| **Tom Ewell** (person) | Q5 → Figure. "actor" → **Arts**. Tiers 10/9/10 → fame ≈ 92 → cost 6. B = 13, s ≈ .53 → 7/6. Featured (att), Translated (30 langs), Legacy (1994 deaths) apply; capped at 2 by priority: Featured, Legacy. | **Tom Ewell**, 6, Figure — Arts. **6/5**. *Featured. Legacy.* "American actor (1909–1994)." *(description; extract not in sample)* |
| **Salahuddin of Aceh** (person) | Q5 → Figure. "16th-century", "Sultans" → **History**. 7/6/7 → fame ≈ 62 → cost 4. B = 9 → 5/4. Legacy (1548 deaths) → 4/4. | **Salahuddin of Aceh**, 4, Figure — History. **4/4**. *Legacy.* "Sultan of Aceh (1530–1537/9)." |
| **Monoid** (maths/concept) | No P31 → P279 "algebraic structure" → Doctrine. "Algebraic structures", "Category theory" → **Science**. 10/10/10 → cost 6, k = 3. Maths rider. | **Monoid**, 6, Doctrine — Science. *Adopt.* Adopted Figure gets +3/+3 and has Well-sourced. "Algebraic structure with an associative operation and an identity element." |
| **Agda (programming language)** | P31 programming language → Doctrine. **Science**. 10/9/9 → cost 6. Language rider. | **Agda**, 6, Doctrine — Science. Adopted Figure gets +3/+3. Whenever it deals combat damage to a player, draw a card. |
| **Dichromorpha viridis** | Q16521 taxon → Figure. "Species of grasshopper" → **Earth**. 7/1/6 → fame ≈ 45 → cost 3. B = 7, s clamped to .7 → 5/2. Stub (1,347 B) → 4/2. | **Dichromorpha viridis**, 3, Figure — Earth. **4/2**. *Stub.* "Species of grasshopper." |
| **April 2021 nor'easter** | P31 nor'easter → Event, disaster. "2021 in Maine" … → **Earth**. 6/10/2 → cost 4, k = 2. | **April 2021 nor'easter**, 4, Event — Earth. Deal 1 damage to each Figure and each Location. *(k−1 = 1: the sim decides whether disasters need k instead)* |
| **1954 Gold Coast general election** | legislative election → Event, election. **Society**. 7/4/5 → cost 4, k = 2. | 4, Event — Society. Create two 1/1 Society Figure tokens named Elected Member. |
| **Pathrail Mosque** | mosque → Location. "15th-century mosques" → **History** (2 hits) vs Society (1). Derived cost 4 → Location cost 2. pct_depth ≈ 55 → Garrison 0/3. | **Pathrail Mosque**, 2, Location — History. Territory. Garrison 0/3. |
| **Tatsunoko Production** | animation studio → Institution, organisation. **Arts**. 10/10/9 → cost 6. | **Tatsunoko Production**, 6, Institution — Arts. At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member. *(the sim may want 2/2 at cost 6)* |
| **Charmont-en-Beauce** | commune of France → Location. **Earth**. 2/2/10 → cost 1. Stub ignored (Locations take no keywords). | **Charmont-en-Beauce**, 1, Location — Earth. Territory. Garrison 0/2. |
**Readability:** a Figure shows cost, P/T, Portal, the type line and up to 2 keyword words. The full text is behind a tap. This is still one phone-sized face.
---
## 4. Story mechanics (Open problem 4, design side)
### 4.1 Connected
- **Data:** the frozen claims (§3). Each card gets `qid` and `connectKeys` at derivation. The engine intersects keys without any I/O.
- Keys come from P17/P27/P131/P495 (place), P106/P101/P921/P136 (field), P361 (part of), P171 (parent taxon) and `C<century>` (from P569/P570/P571/P580/P585).
- Century counts only between cards of **different** types, because it is too common otherwise.
- Wikipedia link tables are not used in v1, which gives zero extra requests.
- **Direct connection:** one card's claims cite the other card's `qid`, for example Barack Obama with the White House (residence).
- **Bonuses:**
- A Figure gets **+1/+1** while you control another card Connected to it; **+2/+2** if the connection is Direct.
- A Doctrine adopted by a Figure Connected to it gives its bonus twice.
- A Connected creative-work Institution buffs, as in §3.5.
- **The card shows why:** "Connected — Pathrail Mosque (country: Bangladesh)".
- **Rivalry (log only, v1):** an opposing pair that is Connected is noted in the log and the recap ("The two had previously been associated through …").
- **Tuning:** sim on random 15-card decks from the sample. Target 0.5–2 Connected pairs per deck. Drop the noisiest keys (P17 = United States, or France) if the rate is above that.
### 4.2 Match log
Past tense, third person, no adjectives about real people, numbered references. Card names are *italic* links, and the first mention is "the card *X*". Examples:
> Turn 3. *Tom Ewell* (American actor, 1909–1994) was deployed by eric.[1]
> Turn 4. *Monoid* was adopted by *Salahuddin of Aceh*, which became a 7/7.[2][3]
> Turn 5. The *April 2021 nor'easter* dealt 1 damage to each Figure. *Dichromorpha viridis* was destroyed.[4][5]
There is one template per engine event type (about 25 strings). It is generated from the deterministic event list, so `replay` regenerates it exactly.
### 4.3 Battle recap ("Battle of X (2026)")
- **Title:**
- "Battle of {Location}": the winner's highest-cost Location at the end, else any Location in play.
- With no Location: "{Signature of the winner} campaign".
- The prefix is "Skirmish at" under 6 turns and "Siege of" over 10.
- **Infobox:** date, Location, result ("Decisive victory" if the margin is ≥ 10, "Pyrrhic victory" if the winner has ≤ 3 Notability, "Victory by decision" at the turn cap), belligerents (players), commanders (Signatures), strength (cards deployed), casualties (cards destroyed).
- **Sections:** Background (Portals, Signatures); Course of the battle (the 3–5 largest swings); Aftermath (final Notability, rating change); See also (Connected pairs); References (every card's real article with `revisionId`, plus the mint id).
- **Branding:** Wikipedia-*style* typography, but **no Wikipedia or Wikimedia logo or name in the masthead.** Footer: "This page records a WikiDeck match. Card names refer to Wikipedia articles; the events described are game events."
---
## 5. Modes in the new structure
- **Classic:** Collection + Basics, 15 cards, Signature. Ranked (Glicko-2) and casual queue, plus invite-by-link.
- **Draft (front door):**
- **Pool:** the host's **Register**, every mint on its chain whoever owns it. That means real mined cards for players with none.
- **Picks:** an open pool of 20 cards, made of min(Register, 16) random mints plus Basics. The two players snake-pick 10 each, at 20 s per pick, and the deck is their 10 picks + 5 Basics of their choice.
- **Owner perk:** if you own a mint in the pool, you may take it as your first pick, once, and the recap credits it "from the collection of X".
- **Small Register:** mainnet's 12 mints still work, padded with Basics. If the Register has fewer than 16 mints, the ruleset may allow Archive padding (Fallback A).
- **Trending:** any deck policy. Live trend frozen at match start, through the throttled client and its daily cache:
- **▲** (trend ≥ +25% and daily ≥ 20): Trending (haste) and +1/+0
- **▼** (≤ −50%, daily ≥ 20): −1/−0
- the 20/day floor keeps noise out (CARD_DATA finding 6)
- **House rules:** unchanged, data-only. New keys: `startingNotability`, `deckSize`, `maxCitations`, `turnCap`, `basicsAllowed`, `archiveRamp`, `connectedBonus`.
## 6. Scope for tonight (designer's cut order)
**Must:** the duel engine (§2); derivation (§3.1–3.5) with the classifier test on the sample; the 8 Basics; Connected with frozen claims; the match log; the recap page; Classic + Draft through PvP lobbies; a greedy combat bot.
**Cut first:** Rivalry text, Trending's ▼, Pathology inversion, Institution subtypes beyond the default. **Defer:** Pending changes, vehicles/Crew, the Archive ramp (flag only).
## 7. Risks
1. **The engine rewrite is the night's critical path.** The lane engine, bots and golden tests don't transfer. Mitigation: freeze the §2 rules at 21:45, then one engine owner and one bot/sim owner from the first hour.
2. **Famous cards all cost 6** (Tom Ewell, Monoid, Agda, Tatsunoko). Collections of notable articles are top-heavy. Mitigation: the Signature in hand plus fixed income make 6-drops castable by turn 6. Watch the sim's curve.
3. **Basics games are generic.** For 0–2 card owners, Classic has little story. That is exactly why Draft is the front door, and why Fallback A exists.
4. **The classifier is wrong ~5–10% of the time** (the human-settlement bug, P279-only concepts). Show the type line with a "derived from: P31 = …" tooltip so mistakes read as data, not bugs. Correct it by `deriveVersion` bumps, never by hand.
5. **Claims are live data, not the mint snapshot.** Card text can drift between nodes. Freeze the claims per card at first sight with `claimsRevision`, and log it. The host's copy is authoritative for its matches.
6. **Real people in shareable recaps:** this is a living-persons and tone risk. Use mechanical verbs only ("was destroyed", "attacked"), use "the card X", and add no commentary.
7. **Collector advantage in ranked:** enforce the parity target in the sim before ranked opens.
8. **Connected density** may be near zero in random collections (good for surprise) or everywhere through country keys (noise). Tune the keys from the sim. Don't guess.
+246
View File
@@ -0,0 +1,246 @@
# Night 2 plan review: lead engineer (feasibility and scope)
Reviewed against `wd` @ 4f7a8a7 (upstream main with Night 1). Paths are repo-relative. `docs/night/REPORT.md` does **not exist** in this checkout, so Night 1 lessons come from HANDBOOK/BOUNDARIES and the coordinator's notes.
**Verdict:** the plan is feasible in 4.5 h **if** the duel engine is a *new sibling package* with no stack and sorcery-speed only, PvP stays on the self host, and the Wikimedia client is handled as transport-only for the mint path. Three facts change the plan:
1. **Owned cards cannot reach PvP today.** The host never accepts a player deck (see §2).
2. **Card data is not trustworthy.** Article and stats are claims made by the miner: consensus only checks internal consistency.
3. **The browser drives most Wikimedia traffic.** Every card face triggers a server enrichment fetch.
---
## 1. Engine: reuse, rewrite, smallest change
**Reusable as is:**
- `shared/game/rng.ts` (mulberry32, `Rng.fromSeed`, exported via `index.ts:3`)
- the clone-on-apply pattern
- the `(ruleset, decks, seed, actions)` replay contract: `replay` at `engine.ts:433`, `applyAction` at `engine.ts:291`
- zod `parseRuleset` (`ruleset.ts:83`)
- `percentile`/`fame`/`costFor` in `derive.ts:52-79`
- the generated sample percentiles (`card-data.ts`, `scripts/game-card-data.mjs`)
The host is **engine-agnostic** through `EnginePort` (`server/game/engine-port.ts:9-43`), so a second engine plugs in with a new binding file instead of host surgery. Bots are also engine-agnostic (`shared/bots/types.ts` `EngineAdapter`, with `toAct`, `assume` and `evaluate`), and a sequential duel fits that adapter *better* than Edit War does: `game-adapter.ts:243` fakes `toAct` from `committed`.
**Must be rewritten:**
- **Everything lane- or Topic-shaped:**
- `MatchState.lanes` / `LaneState` (`types.ts:136-170`)
- the simultaneous queue/commit/reveal turn (`engine.ts:291-363`)
- Topic scoring (`finish`, `engine.ts:366`)
- Portals and keywords (`keywords.ts`, 241 lines, hooks assume lanes and `onReveal`)
- **`GameCard`** (`types.ts:24-43`): a duel card needs `type`, `toughness`, rules-text ids and flavour, and `validateDeck` (`engine.ts:27`) hard-codes cost 0–6, power 0–30, Faction and lane fields.
- **UI boards** (`src/game/MatchBoard.tsx`, `adapter.ts`).
- **`parseModeRuleset`** host checks (`engine-binding.ts:31-43`), which are Edit War-specific: `turns × turnSeconds ≤ 240`, `topicCount`.
**Recommendation: build `shared/duel/` as a sibling package and leave `shared/game/` untouched.**
- Edit War stays playable: its 6 test files keep passing and its modes keep working.
- Two engine agents don't conflict with anyone.
- Duel exposes the same API names (`createMatch`, `legalActions`, `applyAction`, `viewFor`, `replay`, `validateDeck`, `isOver`, `result`), so `EnginePort` and `EngineAdapter` bindings are thin files.
**Smallest core that still feels like Magic (one night):**
- **Turn:** start (untap, income, draw) → main → combat → end. No second main phase, no stack, no instants and no priority passing. Events are sorcery-speed only.
- **Triggers** resolve immediately in a fixed order: active player first, then reveal `seq`, as Edit War's `onReveal` already does.
- **Resources:** fixed income ramp, `incomeByTurn` as data (Edit War's `energyByTurn` idea, `types.ts:70`), with no carry. A Location is a permanent that gives +1 income. No land cards means no land screw.
- **Figures** have power, toughness and summoning sickness; damage clears at end of turn. **Institutions and Doctrines** are permanents with `ongoing` statics (port the pure `ongoing` hook contract, `keywords.ts:16`). Life is 20 by default (data).
- **Actions must be atomic** so that `legalActions` stays small. That matters because the host checks each action by deep-equal against the full list (`host.ts:187-189`), and the bots enumerate it:
- `play {cardId, target?}`
- `toggleAttacker {id}`, then `confirmAttack`
- `block {blocker, attacker}`, then `confirmBlocks`
- `endPhase`, `concede`, `timeout`
Never enumerate whole block assignments, which explode combinatorially.
- **Empty library** behaviour is data: `libraryEmpty: 'lose' | 'reshuffle' | 'fatigue'`. This keeps option (a), small decks with recursion, open with no code change.
- **`legalActions` is `[]` for the seat without priority.** The host sweep already treats "has legal actions" as "is the one waiting" (`host.ts:264`), so timeouts work without host changes.
**Determinism, rules-as-data, `viewFor` and information hiding all carry over.**
- Hidden information is simpler than in Edit War: there is no simultaneous hidden queue, only the hand and library order.
- **New requirement: `logFor(state, seat)`.** Edit War's `viewFor` returns no log at all (`engine.ts:395-419`). The plan's "dry encyclopedic match log" and the recap both need a per-seat log that masks the opponent's `draw` card ids.
- **Card typing (P31) and "Connected" are not on-chain**, so they must be *frozen into the deck at match start*, exactly as the trend arrow is today (`host.ts:318-334`). Match records already store the derived decks (`host.ts:361-363`), so replay stays exact even if Wikidata changes later.
- **Other host limits:** the host's 2000-action cap (`host.ts:344`) is fine for about 15 turns of atomic actions. `MatchRecord` needs an `engine` field.
- **Multi-engine host** (about 15 lines):
- `ModeHost` holds one `engine` (`host.ts:53`); change to `HostedMode {mode, rules, engine}` and `Lobby.engine`.
- Add an optional `engine: 'editwar' | 'duel'` to `ModeSchema` (`modes.ts:88`, default `editwar`).
- Caveat: the schema is `.strict()`, so un-upgraded peers will count duel modes as `rejected` in discovery. That is acceptable on the testnet.
## 2. "The cards a player owns": the trace and the gaps
**Today's path:**
1. The client computes ownership itself. `src/App.tsx:130` filters `snapshot.blocks` (from `GET /api/state`, `http.ts:68` → `legacySnapshot(limits.legacyBlocks)`) by the **browser-local wallet** address.
2. `PlaySection` gets `owned` (`App.tsx:203`) and merges `cardFromBlock` into the deck-builder pool (`PlaySection.tsx:42`). `cardFromBlock` derives in the browser, marks the card `unchecked` with its cost capped, and computes rarity from `powHash` client-side (`cards.ts:39-46`).
3. Owned cards are used **only in browser-local bot matches** (`MatchScreen`).
**Gaps:**
- **G1. No player decks in PvP.** `ModeHost.join` deals `engine.starterDeck` to both seats for every non-draft policy (`host.ts:144`). The `constructed` policy (`modes.ts:64`, which is also the default, `modes.ts:99`) is **unimplemented**: no create/join route takes a deck (`router.ts:123-131`). Ownership is therefore never verified server-side, because it is never used.
- **G2. Accounts are not wired to the game.**
- Linked wallets live in `accounts.sqlite` (`server/account/store.ts:126-130`), but nothing in `server/game/` reads them.
- `gameRouter` receives only `{dataDir, enrichment}` (`http.ts:154`), with no ledger and no account store.
- The `AccountStore` is created privately inside `createAccountRouter` (`router.ts:19`), so it must be injectable to be shared.
- The `auth` middleware is local to that router (`router.ts:25-33`); export it, or call `verifyIdToken` directly.
- **G3. Host identity is not the account.** The player id is `sha256(localStorage secret HMAC hostOrigin)` (`online.ts:161`, `host.ts:380`), so a ladder keyed on it can be farmed trivially by sybils. Also, `Authorization: Bearer` is already taken by seat tokens with a 16–64 character regex (`router.ts:98-101`). Pass the Dex ID token in the **body** at create/join instead.
- **G4. Collection truncation.** `/api/state` returns at most 128 blocks (`server/resources.ts:20`), so older owned cards silently disappear from Play. Use `ledger.deck(address)`, paged by 24 (`ledger.ts:293`), or a new authed `GET /api/game/collection`.
- **G5. Chain card data is a miner claim.**
- The ledger accepts any peer-valid block. `template()` (`ledger.ts:255`) is advisory, and nothing binds a block to a node-issued template.
- `articleSchema` (`consensus.ts:43-56`) does not cross-check `pageId` against `title`.
- `statsSnapshotSchema` (`consensus.ts:59-93`) only checks internal consistency (`deriveStats` of the declared bytes, languages and views).
- So a custom miner can mint "Barack Obama" with any stats. DESIGN §1.10 plausibility exists only as types: `verifyStats` and `check: 'verified'` are never read (no hits outside `types.ts`, `ruleset.ts`, `engine.ts:22` and `derive.ts`).
- **G6. Per-node account stores.** Peer hosts have their own `accounts.sqlite`, so a wallet linked on node A is unknown on node B. Sending a Dex ID token to a peer also lets that peer replay it on other nodes until it expires, since every node shares the `wikideck` audience.
**Recommended (MVP, self host only):**
- Create and join take `{idToken, deck: tokenId[]}`. The host:
1. verifies the token (`verifyIdToken`);
2. loads `wallets(sub)` from the account store;
3. for each token, checks `ledger.nft(token)` (`canonical-index.ts:163`): owner ∈ wallets and `confirmations ≥ rules.minConfirmations` (1 casual, 3 rated);
4. builds `CardInput` **from the block**, never from client card JSON, then derives and freezes.
- Put this in a new `server/game/ownership.ts` exposing a pure `resolveDeck(deps, sub, tokenIds)`. `host.ts` calls it from `startMatch`.
- Plausibility (G5), stretch:
- Check `pageId → title` and `revisionId → size` with **one batched request per 50 cards** (`prop=revisions&revids=…&rvprop=size|ids`). Revisions are immutable, so the result can be cached forever and verifies `pageBytes` exactly.
- Past monthly pageviews are also immutable, so they can be checked exactly at one request per card.
- On a mismatch, the card is marked `unverified` and its cost is capped.
- Peers (stretch): replace the ID token with a wallet-signed deck claim `["wikideck:deck-claim:v1", NETWORK, hostOrigin, nonce, tokenIds]`. The client builds the message itself, like `shared/account-link.ts`. This needs no account on the peer and cannot be replayed on another host.
## 3. PvP: what exists, what's needed, transport
**What exists:**
- **`server/game/host.ts`:** in-memory lobbies, snake draft, the turn timer and AFK handling via `timeoutAction` (`host.ts:263-270`), legal-action enforcement, live-lobby persistence across restarts (`index.ts:205-226`), JSONL match records with replayable audit (`store.ts`) and a W/L leaderboard (`store.ts:64-68`).
- **`router.ts`:** rate-limited (`router.ts:90-94`).
- **UI:** `OnlinePlay.tsx` is a lobby list (polled every 4 s), create/join, draft and a match board. It is reachable only from inside the Play section.
**What's needed:**
| Feature | Minimal design | Files | Size |
|---|---|---|---|
| Invite link | `createLobby({private:true})` is excluded from `openLobbies` (`host.ts:108-112`); the UI route `/play/join/<lobbyId>` works because the SPA catch-all serves `index.html` (`http.ts:157`), and `join` already takes an id | host, router, OnlinePlay | S |
| Quick match | `POST /modes/:id/quick` joins the oldest open lobby within the rating window, else creates one; no separate queue structure | host, router | S |
| Rated ladder | Elo (K=24, start 1200) per mode, keyed by account id, recomputed by replaying `matches.jsonl` in order at startup (deterministic, no new store); rated only when both seats are account-verified and `rated:true` in mode limits; Glicko-2 is not worth the night | store.ts, host.ts | M |
| Account seat identity | `idToken` in the create/join body → player id `sha256('acct:'+iss+sub)`; guests keep the secret but are unrated | host.ts, online.ts | S |
| Duel binding | `server/game/duel-binding.ts` plus multi-engine `HostedMode` | new file, host.ts | S |
**Transport is polling:** the client polls every 1 s (`OnlinePlay.tsx:11, 45-50`), with no WebSocket or SSE anywhere. It is adequate for a sequential duel: about 0.5 s average hand-off latency.
Three caveats:
1. **Cost.** Each poll runs `viewFor` and `legalActions` and returns the full view. Add a monotonic `version` to the lobby and `GET …?v=N` → `204` when unchanged. Poll every 500 ms while waiting on the opponent and every 3 s otherwise.
2. **Do not long-poll under `/api`.** `RpcBudget` caps the whole node at 32 active `/api` requests (`resources.ts:17`, applied at `http.ts:54`), so 16 matches holding long-polls would starve the node. Real push would need SSE mounted *outside* `/api` (a `server/testnet/http.ts` shared-hook change): a stretch only.
3. **Rate limits.** Two humans behind one NAT, or QA agents on one machine, see 1 req/s × 2 against `plays` 240/min and the global 300/min per IP (`http.ts:56`). That is OK, but QA should not run more than 2 matches per IP.
## 4. Wikimedia politeness
**Every call site** (grep over `server`, `src`, `scripts`, `shared` and `android`; the browser never calls Wikimedia APIs directly, because CSP `connect-src 'self'` at `http.ts:50` forbids it):
| # | Where | Upstream | Trigger | Limits today |
|---|---|---|---|---|
| W1 | `server/wiki.ts:73-78` `random()` | en Action API, `generator=random` ×10 | **mint template** `http.ts:122` | ≤4 concurrent, 3 attempts, 3.5 s timeout, no 429/Retry-After, no maxlag |
| W2 | `server/enrichment.ts:134-138` `load()` metadata | en Action API, `pageids=1` | `getFresh` at **mint** `http.ts:123`; `get` from `/api/wikipedia/:id` `http.ts:93-98`; TrendCache | ≤4 active, 8 pending, then **reject**; in-memory LRU of 128 entries, 6 h TTL; errors cached 30 s |
| W3 | `server/enrichment.ts:148` pageviews | `wikimedia.org` REST, monthly | same as W2 | same |
| W4 | `server/game/trends.ts:37-56` via `index.ts:174-186` | W2+W3 | background, one page per 20 s | about 8.6k requests/day steady if the queue stays warm |
| W5 | **browser:** `src/Card.tsx:24` → `src/useEnrichment.ts:10` → `/api/wikipedia/:id` | W2+W3 | **every card face rendered** (collection, explorer, hero) | per-tab cache 5 min; server limit is 60/min **per client IP** only, with no node-wide upstream budget |
| W6 | `scripts/night/card_sample.py:13-38` | en API, Wikidata `wbgetentities`, REST daily views | offline research | 1 req/s, honours Retry-After, disk cache (its docstring says "~4 req/s"; the code does 1) |
| W7 | browser `<img>` from `upload.wikimedia.org` (`Card.tsx:28`, CSP `http.ts:49`) | CDN | each render | hotlinking; acceptable, but the plan should cache thumbnails or use `pithumbsize` |
**Likely cause of the Night 1 429:** W5 fan-out (each grid page means N cards × 2 upstream requests, with a 128-entry LRU thrashing across users) plus W4, multiplied by several testnet nodes sharing one egress IP. Each node also uses the default UA, `Wikideck/0.1 (experimental …)` (`wikimedia-user-agent.ts:4-5`), which has **no contact**. That breaks the Wikimedia UA policy and is the kind of client that gets blocked first.
**Design: `server/wikimedia/client.ts`, one process-wide `WikimediaClient`.**
- **Rate:** a token bucket per upstream host. Defaults (env-configurable):
- `en.wikipedia.org`: **1 req/s, burst 2**
- `www.wikidata.org`: 1 req/s
- `wikimedia.org` REST: 5 req/s
- **Concurrency:** **1 in flight per host** by default (`WIKIDECK_WIKIMEDIA_CONCURRENCY`). The Action API etiquette is serial requests.
- **Co-located nodes:** document `WIKIDECK_WIKIMEDIA_RPS=0.3` for nodes behind a shared IP (testnet compose).
- **Priority lanes**, with a bounded queue (64):
- `mint`: always first; the timeout starts at dispatch; the queue wait is capped at 15 s, and the miner tolerates it (30 s timeout, `miner.ts:57`)
- `interactive`: on overflow, serve stale cache or 503
- `background`: trends, P31, links, plausibility; dropped when the queue is full
- **maxlag:** add `maxlag=5` to every Action API request (en and Wikidata). Detect `error.code==='maxlag'` (HTTP 200 with a JSON error), wait for `Retry-After` (default 5 s) and retry at most 3 times. REST has no maxlag.
- **429 and 503:** parse `Retry-After` (seconds or HTTP-date), then **pause the whole host bucket** (circuit-open) for max(Retry-After, exponential backoff 2^n s with jitter, cap 10 min). Log once per pause and expose a counter in `/healthz`-adjacent ops output.
- **Batching:**
- `pageids=`/`titles=`/`revids=` up to 50 for cheap props: `info`, `pageprops` (`wikibase_item`), `description`, `revisions|size`.
- P31 via `wbgetentities&ids=Q1|…(50)&props=claims` is heavy (Obama's claims alone are megabytes). Use `wbgetclaims&property=P31` per entity (small, cached for 30 days), or one WDQS `VALUES` query per ≤50 QIDs.
- **"Connected"** costs one request per deck pair: `prop=links&titles=<≤50 deck titles>&pltitles=<same>&pllimit=max` returns exactly the intra-set links. Cache it by the sorted pageId set.
- **Never batch** `langlinks` or `categories`: their limits are shared across the batch, which forces continuation and changes `languagesTruncated` semantics.
- **Persistent cache:** `node:sqlite` (already used by accounts; Node 24) at `$WIKIDECK_DATA_DIR/wikimedia-cache.sqlite`. Key = canonical URL with sorted params and without `maxlag`. Store the body, ETag and Last-Modified; send `If-None-Match` (REST returns ETags; the Action API mostly doesn't); serve stale-while-revalidate for `interactive`. TTLs:
| Data | TTL |
|---|---|
| metadata | 24 h |
| monthly pageviews | until month rollover (already the rule, `enrichment.ts:70`); closed months are immutable |
| P31 | 30 d |
| links | 7 d |
| revision size | forever |
| random | never |
Raise the 128-entry cap (`enrichment.ts:51`) once the cache is on disk.
- **UA:** `WikiDeck/<pkg version> (+https://gitea.eom.dev/WikiDeck/wikideck; <WIKIDECK_OPERATOR_CONTACT or PUBLIC_ORIGIN>) node/<ver>`.
- Keep `WIKIDECK_USER_AGENT` as an override, still sanitized as at `wikimedia-user-agent.ts:8-12`.
- Warn at startup if there is no operator contact.
- Update `tests/testnet-user-agent.test.ts`, which pins today's fallback strings.
- **Volume budget:**
- mint: 3 requests (≤5 with random retries)
- match: **0 synchronous** (cache-only at match start; unknown data means "no bonus" or a fallback type, as `trends.ts` already does)
- per new card first seen: ≤1 batched metadata/plausibility share + 1 P31
- per deck save: 1 links request
- card-face render: 0 when cached
**Consensus boundary (checked carefully):**
- **Validation never touches Wikimedia.** `consensus.ts:43-93` is pure, and the only callers of `wikipediaArticles` and `wikipediaEnrichment` are `http.ts:96, 122-123, 154`. Throttling, caching and retry therefore **cannot affect block validation or fork choice**.
- **The mint template's *content* becomes immutable chain data.** The client must be *transport-only* on the mint path:
1. Keep W1/W2/W3 request params byte-identical: `grnlimit`, `exchars=900`, `pithumbsize`, `cllimit=20` (no hidden filter, which feeds `category()` at `wiki.ts:17`), `clshow=!hidden`, `cllimit=50`, `lllimit=500`. They determine `article.category`, `languageCount` and `languagesTruncated`, and the percentile calibration. `tests/enrichment.test.ts:42-52` already pins part of this; add a golden URL test for W1. Adding `maxlag` is safe because it changes only error behaviour.
2. `getFresh` must bypass the persistent cache. `snapshotStats` stamps `capturedAt = new Date()` (`shared/enrichment.ts:41`), so cached data would be misdated.
3. **Existing bug that throttling would amplify.** A 429/5xx on the pageviews call is swallowed into `status:'unavailable'` (`enrichment.ts:145-164`). On the mint path that **permanently mints a card with `attention: null`**. With the new client, mint must fail the template (503, the miner retries) on 429/5xx/timeout, and record "unavailable" only on a genuine 404 or no-data. Both outcomes are valid blocks, so this is template policy, not a consensus change; it needs one owner and a test.
## 5. Scope: 4.5 h, about 10 agents, one integration branch
**Rules learned from Night 1:**
- **No stacked PRs.** Squash-merge makes every child PR conflict. Branch only from `night/2026-11-17` after the dependency has merged.
- **Contracts first:** `shared/duel/types.ts` and `docs/game/DUEL_API.md` merge by 22:15.
- **Node 24 everywhere** (`node:sqlite`; the Dockerfile uses `node:24-alpine`). Check `node -v` before `npm ci`.
- **No new npm dependencies.** The lead alone owns lockfile regeneration.
- **Test files:** top-level `tests/<team>-*.test.ts` only (`scripts/run-tests.mjs:7`).
**Workstreams** (9 workers plus the lead; ✱ = touches a shared file, one line or a small edit):
| WS | Owner paths | Delivers | Depends on |
|---|---|---|---|
| A duel-core | `shared/duel/{types,engine,ruleset,index}.ts`, `tests/duel-core*.test.ts`, `docs/game/DUEL_API.md` | turn and combat engine, `viewFor`/`logFor`, `replay`; **types PR by 22:15**, alpha by 23:15 | — |
| B duel-cards | `shared/duel/{derive,classify,effects,text}.ts`, `tests/duel-cards*.test.ts` | P31 → type table (from `card-sample.json` `instanceOf`, 236 cards), category fallback, P/T and cost curve, ≤8 effect templates, deterministic MTG-register rules text, flavour from `article.extract` | A types |
| C sim-balance | `shared/bots/duel-adapter.ts`, `scripts/sim/*duel*`, `docs/game/DUEL_BALANCE.md` | greedy and MC bots on duel; win rate by type and faction; ruleset number tuning (data-only PRs) | A alpha (23:15) |
| D wikimedia | `server/wikimedia/*`, `server/wiki.ts`, `server/enrichment.ts`, `server/wikimedia-user-agent.ts`, `tests/wikimedia-*.test.ts` | §4 client, mint-path fix, sqlite cache, UA; `trends.ts` unchanged (it goes through enrichment) | — (starts 21:30) |
| E identity | `server/game/identity.ts`, `scripts/night2/prebake-identity.ts` | background P31, links and plausibility via D's `background` lane; persistent per-token identity; pre-bakes testnet and mainnet cards | D interface (stub until merged), B input type |
| F ownership | `server/game/ownership.ts`, `server/game/collection.ts`, ✱`server/account/router.ts` (inject store, export auth), ✱`http.ts` (pass `{ledger, accounts}` into `gameRouter`) | `resolveDeck`, `GET /api/game/collection`, chain-pool draft source (option c) | — |
| G host-pvp | `server/game/{host,router,store,index,duel-binding}.ts`, `shared/game/modes.ts` (`engine` field), `deploy/night2/modes/*.json` | multi-engine host, constructed decks via F, account seats, private lobbies, invite, quick match, Elo, `?v=` polling | F function signature (agree by 22:00), A types |
| H ui-duel | `src/game/duel/*` (board, card face with type line, P/T, text, flavour; adapter; local bot practice) | playable vs bot in the browser | A types → A alpha |
| I ui-pvp+story | `src/game/OnlinePlay.tsx`, `online.ts`, `PlaySection.tsx`, `Leaderboards.tsx`, `src/game/recap/*`, `shared/duel/recap.ts` | collection deck picker, invite and quick-match UI, ladder, "Battle of X (2026)" recap rendered client-side by `replay` of `GET /matches/:id` (`router.ts:137`) | G API (stub), A log format |
| Lead | integration branch, `docs/night/*`, QA, REPORT | merges, lockfile, end-to-end on testnet with 2 Dex accounts | — |
Overlap is limited to the ✱ lines. `host.ts` is G's alone: F ships pure functions that G calls.
**Timeline (EST):**
| Time | Milestone |
|---|---|
| 21:30 | A, D and F start |
| 22:15 | types contract merged; B, G, H and I build against it |
| 23:15 | engine alpha; C starts sims; H plays vs bot |
| 00:00 | D merged; E live; G binds duel; I wired to G |
| 00:45 | balance v1 (data-only tuning) |
| 01:15 | **freeze** |
| 01:15–01:45 | QA PvP plus recap |
| 01:50 | REPORT |
| 02:00 | stop |
**Cut first, in order:**
1. WDQS/shared-property "Connected": keep article-link Connected only, or none.
2. Plausibility verification (G5): trust chain stats and document the gap.
3. Quick match: invite link and open lobbies suffice.
4. Elo ladder: keep W/L keyed by account.
5. Peer-hosted duel and wallet-signed deck claims.
6. Recap infobox polish: keep the plain encyclopedic log.
**Never cut:**
- the Wikimedia client (requirement 7: low risk, independent, and protects every later night)
- server-side ownership verification
- the duel core
- self-hosted PvP with owned or draft decks
- bot practice
**Biggest risks:**
1. Duel engine plus balance in about 2 h of real build time. Mitigation: no stack, atomic actions, effects as ≤8 templates.
2. UI combat readability. H must start on mock views at 22:15, not wait for the alpha.
3. Supply: 12 mainnet cards make a constructed duel unplayable without option (c) or (a). Make deck size and `libraryEmpty` ruleset data so Eric's decision is a mode file, not code.
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
# Cross-compile the pinned native RandomX engine (native/, RandomX v1.2.1) for the Android app.
# Output: android/app/src/main/jniLibs/<abi>/libwikideck_randomx.so, an executable named like a
# library so Android extracts it to nativeLibraryDir, where an app may exec it (docs/night2/MOBILE_MINING.md).
#
# Needs ANDROID_HOME with an NDK (ndk;<version>) and CMake 3.24+ (cmake;<version>, or cmake on PATH).
# ABIS="x86_64 arm64-v8a" JOBS=2 sh scripts/build-randomx-android.sh
set -eu
cd "$(dirname "$0")/.."
: "${ANDROID_HOME:?set ANDROID_HOME}"
ABIS="${ABIS:-arm64-v8a x86_64}"
JOBS="${JOBS:-2}"
API="${ANDROID_API:-24}"
NDK="${ANDROID_NDK_HOME:-$(ls -d "$ANDROID_HOME"/ndk/* 2>/dev/null | sort -V | tail -n1)}"
[ -f "$NDK/build/cmake/android.toolchain.cmake" ] || { echo "No NDK under $ANDROID_HOME/ndk" >&2; exit 1; }
CMAKE_DIR="$(ls -d "$ANDROID_HOME"/cmake/* 2>/dev/null | sort -V | tail -n1 || true)"
[ -n "$CMAKE_DIR" ] && PATH="$CMAKE_DIR/bin:$PATH"
command -v cmake >/dev/null || { echo "cmake not found" >&2; exit 1; }
GEN=""
command -v ninja >/dev/null && GEN="-G Ninja"
for abi in $ABIS; do
build="native/build-android-$abi"
# shellcheck disable=SC2086
cmake -S native -B "$build" $GEN \
-DCMAKE_TOOLCHAIN_FILE="$NDK/build/cmake/android.toolchain.cmake" \
-DANDROID_ABI="$abi" -DANDROID_PLATFORM="android-$API" \
-DCMAKE_BUILD_TYPE=Release -DWIKIDECK_RANDOMX_TESTS=OFF
cmake --build "$build" --config Release --target wikideck-randomx --parallel "$JOBS"
out="android/app/src/main/jniLibs/$abi"
mkdir -p "$out"
cp "$build/wikideck-randomx" "$out/libwikideck_randomx.so"
"$NDK"/toolchains/llvm/prebuilt/*/bin/llvm-strip "$out/libwikideck_randomx.so"
ls -l "$out/libwikideck_randomx.so"
done
+32
View File
@@ -0,0 +1,32 @@
/**
* Writes docs/game/duel-card-sample.json (card-sample.json → DuelCard[]) and prints the
* type / Portal / cost / keyword distributions. Offline. Usage:
* node --experimental-strip-types scripts/duel-card-sample.ts [--check]
* --check exits non-zero if the committed fixture is out of date.
*/
import { readFileSync, writeFileSync } from 'node:fs';
import { deriveSample, type SampleCard } from '../shared/duel/sample.ts';
import { DERIVE_VERSION } from '../shared/duel/derive.ts';
const root = new URL('../', import.meta.url);
const sample = JSON.parse(readFileSync(new URL('docs/game/card-sample.json', root), 'utf8')) as { cards: SampleCard[] };
const cards = deriveSample(sample.cards);
const out = JSON.stringify({ source: 'docs/game/card-sample.json', deriveVersion: DERIVE_VERSION, count: cards.length, cards }, null, 1) + '\n';
const path = new URL('docs/game/duel-card-sample.json', root);
const tally = (f: (c: typeof cards[number]) => string | number) => {
const m = new Map<string | number, number>();
for (const c of cards) m.set(f(c), (m.get(f(c)) ?? 0) + 1);
return [...m].sort((a, b) => String(a[0]).localeCompare(String(b[0]), 'en', { numeric: true }))
.map(([k, v]) => `${k} ${v} (${(100 * v / cards.length).toFixed(1)}%)`).join(', ');
};
console.log('type:', tally(c => c.type));
console.log('typedBy:', tally(c => c.typedBy));
console.log('portal:', tally(c => c.portal));
console.log('cost:', tally(c => c.cost));
console.log('subtype:', tally(c => `${c.type}/${c.subtype ?? '-'}`));
console.log('keywords:', tally(c => c.keywords.join('+') || 'none'));
if (process.argv.includes('--check')) {
if (readFileSync(path, 'utf8') !== out) { console.error('duel-card-sample.json is stale'); process.exit(1); }
} else writeFileSync(path, out);
+56
View File
@@ -0,0 +1,56 @@
// 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(); }
+68
View File
@@ -0,0 +1,68 @@
// DuelSim binding for duel-core's shared/duel engine, with the 236 sample cards derived by duel-cards.
import { readFileSync, existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import type { DuelCard, DuelEngineApi, DuelRuleset } from '../../shared/duel/index.ts';
import { connectedTierOf, duelMetrics, makeDuelAdapter } from '../../shared/bots/duel-adapter.ts';
import type { DuelSim } from './duel-sim-types.ts';
import type { PoolCard } from './duel-decks.ts';
export interface DuelPoolCard extends PoolCard { title: string; card: DuelCard }
const FIXTURE = fileURLToPath(new URL('../../docs/game/duel-card-sample.json', import.meta.url));
/** The duel engine's functions, whether engine.ts exports them one by one or as an object. */
async function loadApi(): Promise<DuelEngineApi> {
const mod = '../../shared/duel/engine.ts';
const m = await import(mod) as Record<string, any>;
const obj = Object.values(m).find(v => v && typeof v === 'object' && typeof v.createDuel === 'function' && typeof v.statsOf === 'function');
return (obj ?? m) as DuelEngineApi;
}
async function loadCards(sampleFile: string): Promise<DuelCard[]> {
try {
const mod = '../../shared/duel/sample.ts';
const { deriveSample } = await import(mod) as { deriveSample: (c: unknown[], r?: unknown) => DuelCard[] };
const raw = JSON.parse(readFileSync(sampleFile, 'utf8')).cards;
// SIM_DERIVE: JSON patch over duel-cards' DERIVE_RULES (data-only derivation tuning).
if (!process.env.SIM_DERIVE) return deriveSample(raw);
const d = await import('../../shared/duel/derive.ts' as string) as { DERIVE_RULES: Record<string, unknown> };
return deriveSample(raw, { ...d.DERIVE_RULES, ...JSON.parse(process.env.SIM_DERIVE) });
} catch (e) {
if (process.env.SIM_DERIVE || !existsSync(FIXTURE)) throw e;
return JSON.parse(readFileSync(FIXTURE, 'utf8')).cards as DuelCard[];
}
}
export async function makeDuelSim(sampleFile: string, overrides: Record<string, unknown> = {}): Promise<DuelSim<any, any, DuelPoolCard>> {
const api = await loadApi();
const rs = await import('../../shared/duel/ruleset.ts') as { mergeDuelRuleset: (o: unknown) => DuelRuleset };
const rules = rs.mergeDuelRuleset(overrides);
let cards = await loadCards(sampleFile);
// SIM_LOCATION_DRAW=n: experiment for duel-design's T2 rider ("When this enters, draw n cards") on every Location.
const locDraw = Number(process.env.SIM_LOCATION_DRAW ?? 0);
if (locDraw > 0) cards = cards.map(c => (c.type === 'Location' ? { ...c, effects: [...c.effects, { trigger: 'onEnter', op: 'draw', amount: locDraw, target: 'controller' } as DuelCard['effects'][number]] } : c));
const pool: DuelPoolCard[] = cards.map(c => ({
id: c.cardId, title: c.title, type: c.type, portal: c.portal, cost: c.cost, keywords: [...c.keywords],
fame: (c as any).basis?.fame, card: c,
}));
const engine = makeDuelAdapter(api, { rules, pool: cards });
// SIM_SECOND_EXTRA=n: experiment for a proposed ruleset key. The second seat starts with n extra cards
// (moved from its library top before mulligans). Sim-only; the engine has no such key yet.
const extra = Number(process.env.SIM_SECOND_EXTRA ?? 0);
if (extra > 0) {
const create = engine.createMatch;
engine.createMatch = (r, d, seed) => {
const s = create(r, d, seed);
const second = (1 - s.firstSeat) as 0 | 1;
const p = s.players[second];
p.hand.push(...p.library.splice(0, extra));
return s;
};
}
return {
name: 'duel', engine, lens: engine.lens, pool,
deckPayload: cs => cs.map(c => c.card),
metrics: duelMetrics,
connected: (a, b) => connectedTierOf(a.card, b.card, rules.connectedTiers),
};
}
+49
View File
@@ -0,0 +1,49 @@
// 40-card sim decks drawn from a card pool (the 236 real sample cards). Every card is unique (one NFT each),
// so decks sample without replacement. Archetypes skew the type or cost mix. Pure, seeded.
import { mulberry32 } from '../../shared/bots/index.ts';
export interface PoolCard { id: string; type: string; portal: string; cost: number; keywords: string[]; fame?: number }
export interface SimDeck<C extends PoolCard = PoolCard> { id: string; tags: string[]; cards: C[] }
export const ARCHETYPES = ['random', 'figure-heavy', 'doctrine-heavy', 'event-heavy', 'location-heavy', 'institution-heavy', 'low-curve', 'high-curve'] as const;
export type Archetype = typeof ARCHETYPES[number];
function weight(c: PoolCard, arch: Archetype): number {
switch (arch) {
case 'figure-heavy': return c.type === 'Figure' ? 8 : 1;
case 'doctrine-heavy': return c.type === 'Doctrine' ? 8 : 1;
case 'event-heavy': return c.type === 'Event' ? 12 : 1;
case 'location-heavy': return c.type === 'Location' ? 8 : 1;
case 'institution-heavy': return c.type === 'Institution' ? 10 : 1;
case 'low-curve': return c.cost <= 2 ? 8 : c.cost === 3 ? 3 : 0.3;
case 'high-curve': return c.cost >= 5 ? 8 : c.cost === 4 ? 3 : 0.5;
default: return 1;
}
}
/** Weighted sampling without replacement (Efraimidis–Spirakis keys). */
export function buildDeck<C extends PoolCard>(pool: C[], arch: Archetype, seed: number, size = 40): SimDeck<C> {
const rng = mulberry32(seed);
const keyed = pool.map(c => ({ c, k: Math.pow(rng(), 1 / Math.max(1e-6, weight(c, arch))) }));
keyed.sort((a, b) => b.k - a.k);
const cards = keyed.slice(0, Math.min(size, pool.length)).map(x => x.c);
return { id: `${arch}#${seed}`, tags: deckTags(cards, arch), cards };
}
export function deckTags(cards: PoolCard[], arch: string): string[] {
const count = (f: (c: PoolCard) => string) => { const m: Record<string, number> = {}; for (const c of cards) m[f(c)] = (m[f(c)] ?? 0) + 1; return m; };
const top = (m: Record<string, number>) => Object.entries(m).sort((a, b) => b[1] - a[1])[0]?.[0] ?? '?';
const avg = cards.reduce((t, c) => t + c.cost, 0) / (cards.length || 1);
const curve = avg < 2.6 ? 'low' : avg < 3.4 ? 'mid' : 'high';
return [`arch:${arch}`, `portal:${top(count(c => c.portal))}`, `curve:${curve}`, `mainType:${top(count(c => c.type))}`];
}
/** n decks: half random, the rest cycling through the skewed archetypes. */
export function deckSet<C extends PoolCard>(pool: C[], n: number, seed: number, size = 40): SimDeck<C>[] {
const out: SimDeck<C>[] = [];
for (let i = 0; i < n; i++) {
const arch: Archetype = i % 2 === 0 ? 'random' : ARCHETYPES[1 + ((i >> 1) % (ARCHETYPES.length - 1))];
out.push(buildDeck(pool, arch, (seed * 7919 + i * 104729) >>> 0, size));
}
return out;
}
+138
View File
@@ -0,0 +1,138 @@
// Duel balance simulation.
// npx tsx scripts/sim/duel-run.ts --engine duel --matches 2000 --workers 4 --out sim-out/duel [--rules '{"startingLife":18}']
// Writes <out>/<label>.jsonl, <out>/<label>.stats.json and <out>/<label>.md. Workers are capped at 4 (r350 memory).
import { fork } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { createWriteStream, mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { mulberry32 } from '../../shared/bots/index.ts';
import { makeDuelBot } from '../../shared/bots/duel-bots.ts';
import type { BotFn, DeckSpec, Seat } from '../../shared/bots/types.ts';
import { deckSet, type SimDeck } from './duel-decks.ts';
import type { DuelSim } from './duel-sim-types.ts';
import { aggregateDuel, duelMarkdown, type DuelRecord } from './duel-stats.ts';
export const MAX_WORKERS = 4;
export const MAX_ACTIONS = 3000;
const SAMPLE = fileURLToPath(new URL('../../docs/game/card-sample.json', import.meta.url));
export async function loadDuelSim(name: string, rules: Record<string, unknown> = {}): Promise<DuelSim<any, any>> {
if (name === 'standin') return (await import('./duel-standin-adapter.ts')).makeStandinSim(SAMPLE, rules as any);
if (name === 'duel') { const mod = './duel-core-sim.ts'; return (await import(mod)).makeDuelSim(SAMPLE, rules); }
throw new Error(`unknown duel engine ${name}`);
}
export function playDuel<S, A>(sim: DuelSim<S, A>, decks: [SimDeck, SimDeck], botNames: [string, string], seed: number, bots?: [BotFn<unknown, A>, BotFn<unknown, A>]): DuelRecord {
const t0 = performance.now();
const { engine } = sim;
const b = bots ?? [makeDuelBot(botNames[0], engine, sim.lens), makeDuelBot(botNames[1], engine, sim.lens)];
const rng = [mulberry32(seed ^ 0x9e3779b9), mulberry32(seed ^ 0x85ebca6b)];
const specs: [DeckSpec, DeckSpec] = [0, 1].map(i => ({ id: decks[i].id, tags: decks[i].tags, payload: sim.deckPayload(decks[i].cards) })) as [DeckSpec, DeckSpec];
let s = engine.createMatch('duel', specs, seed);
const first = (engine.firstSeat ? engine.firstSeat(s) : engine.toAct(s)) as Seat;
const played: [string[], string[]] = [[], []];
let actions = 0;
while (!engine.isOver(s) && actions < MAX_ACTIONS) {
const seat = engine.toAct(s);
const a = b[seat](engine.observe ? engine.observe(s, seat) : s, seat, rng[seat]);
for (const c of engine.cardsOf(s, a)) played[seat].push(c);
s = engine.applyAction(s, a);
actions++;
}
const truncated = !engine.isOver(s);
const res = truncated ? { winner: null, reason: 'action-cap' } : engine.result(s);
const turns = engine.turn(s);
return {
seed, bots: botNames, decks: [decks[0].id, decks[1].id], tags: [decks[0].tags, decks[1].tags],
first, winner: res.winner, reason: res.reason ?? 'none', turns, turnsEach: Math.ceil(turns / 2), actions, truncated,
// Clock model: 10 s of overhead per turn plus 4 s per atomic action (taps, plays, blocks).
minutes: (turns * 10 + actions * 4) / 60,
played, metrics: sim.metrics ? sim.metrics(s) : {}, ms: performance.now() - t0,
};
}
/** Bot pairings and their share of the schedule. Symmetric pairs carry the balance stats. */
export const DUEL_MIXES: Record<string, [string, string, number][]> = {
default: [['heuristic', 'heuristic', 0.7], ['mc-lite', 'mc-lite', 0.06], ['heuristic', 'mc-lite', 0.08], ['random', 'heuristic', 0.06], ['greedy', 'heuristic', 0.05], ['random', 'random', 0.05]],
fast: [['heuristic', 'heuristic', 0.9], ['random', 'heuristic', 0.05], ['greedy', 'heuristic', 0.05]],
mirror: [['mc-lite', 'mc-lite', 1]],
skill: [['heuristic', 'mc', 0.4], ['random', 'heuristic', 0.2], ['greedy', 'heuristic', 0.2], ['heuristic', 'mc-lite', 0.2]],
};
interface Job { i: number; seed: number; decks: [number, number]; bots: [string, string] }
export function schedule(n: number, nDecks: number, baseSeed: number, mix: [string, string, number][]): Job[] {
const rng = mulberry32(baseSeed);
const total = mix.reduce((t, m) => t + m[2], 0);
return Array.from({ length: n }, (_, i) => {
let r = rng() * total, k = 0;
while (r > mix[k][2] && k < mix.length - 1) { r -= mix[k][2]; k++; }
const flip = rng() < 0.5;
let d0 = Math.floor(rng() * nDecks), d1 = Math.floor(rng() * nDecks);
if (d1 === d0) d1 = (d1 + 1) % nDecks;
return { i, seed: (baseSeed * 1000003 + i * 7919) >>> 0, decks: [d0, d1], bots: flip ? [mix[k][1], mix[k][0]] : [mix[k][0], mix[k][1]] };
});
}
function arg(name: string, def?: string): string | undefined { const i = process.argv.indexOf(`--${name}`); return i >= 0 ? process.argv[i + 1] : def; }
interface Ctx { engineName: string; rules: Record<string, unknown>; nDecks: number; deckSeed: number }
async function setup(ctx: Ctx) {
const sim = await loadDuelSim(ctx.engineName, ctx.rules);
const decks = deckSet(sim.pool, ctx.nDecks, ctx.deckSeed, Number(ctx.rules.deckSize ?? 40));
return { sim, decks };
}
function runJobs(sim: DuelSim<any, any>, decks: SimDeck[], jobs: Job[], on: (r: DuelRecord | { error: string }) => void) {
for (const j of jobs) {
try { on(playDuel(sim, [decks[j.decks[0]], decks[j.decks[1]]], j.bots, j.seed)); }
catch (e) { on({ error: String((e as Error)?.stack ?? e).slice(0, 800) }); }
}
}
async function main() {
const ctx: Ctx = { engineName: arg('engine', 'standin')!, rules: JSON.parse(arg('rules', '{}')!), nDecks: Number(arg('decks', '120')), deckSeed: Number(arg('deck-seed', '7')) };
const n = Number(arg('matches', '1000'));
const workers = Math.max(1, Math.min(MAX_WORKERS, Number(arg('workers', '4'))));
const seed = Number(arg('seed', '1'));
const out = arg('out', 'sim-out/duel')!;
const label = arg('label', ctx.engineName)!;
mkdirSync(out, { recursive: true });
const { sim, decks } = await setup(ctx);
const jobs = schedule(n, decks.length, seed, DUEL_MIXES[arg('mix', 'default')!]);
const records: DuelRecord[] = [], errors: string[] = [];
const file = createWriteStream(join(out, `${label}.jsonl`));
const t0 = Date.now();
const handle = (r: any) => {
if (r.error) { errors.push(r.error); return; }
records.push(r); file.write(JSON.stringify(r) + '\n');
if ((records.length + errors.length) % 250 === 0) process.stderr.write(`[${label}] ${records.length + errors.length}/${n} ${((Date.now() - t0) / 1000).toFixed(0)}s\n`);
};
if (workers === 1) runJobs(sim, decks, jobs, handle);
else {
const chunks: Job[][] = Array.from({ length: workers }, () => []);
jobs.forEach((j, i) => chunks[i % workers].push(j));
await Promise.all(chunks.map(chunk => new Promise<void>((resolve, reject) => {
const w = fork(fileURLToPath(import.meta.url), ['--child'], { execArgv: ['--import', 'tsx', '--max-old-space-size=384'], serialization: 'advanced' });
w.on('message', (m: any) => (m === 'done' ? w.kill() : handle(m)));
w.on('error', reject);
w.on('exit', () => resolve());
w.send({ ctx, jobs: chunk });
})));
}
file.end();
const stats = aggregateDuel(records, sim, decks, errors.length, { engine: ctx.engineName, rules: ctx.rules, label, sha: arg('sha') });
writeFileSync(join(out, `${label}.stats.json`), JSON.stringify(stats, null, 1));
if (errors.length) writeFileSync(join(out, `${label}.errors.txt`), errors.slice(0, 30).join('\n----\n'));
const md = duelMarkdown(stats);
writeFileSync(join(out, `${label}.md`), md);
process.stderr.write(`[${label}] done: ${records.length} matches, ${errors.length} errors, ${((Date.now() - t0) / 1000).toFixed(1)}s\n`);
process.stdout.write(md);
}
const isEntry = !!process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];
if (isEntry && process.argv.includes('--child')) {
process.once('message', async (msg: any) => {
const { sim, decks } = await setup(msg.ctx);
runJobs(sim, decks, msg.jobs, r => process.send!(r));
process.send!('done');
});
} else if (isEntry) main().catch(e => { console.error(e); process.exit(1); });
+18
View File
@@ -0,0 +1,18 @@
// What the duel simulation needs from an engine binding (stand-in or shared/duel).
import type { EngineAdapter } from '../../shared/bots/types.ts';
import type { DuelLens } from '../../shared/bots/duel-bots.ts';
import type { PoolCard } from './duel-decks.ts';
export interface DuelSim<S, A, C extends PoolCard = any> {
name: string;
engine: EngineAdapter<S, A>;
lens: DuelLens<S, A>;
/** The card pool decks are drawn from (the 236 sample cards, derived). */
pool: C[];
/** DeckSpec.payload for a list of pool cards. */
deckPayload(cards: C[]): unknown;
/** Extra per-match numbers from the final state (connected fires, plays, ...). */
metrics?(final: S): Record<string, number>;
/** Static Connected test for a pair of pool cards (for the pairwise fire rate). */
connected?(a: C, b: C): boolean | string | null;
}
+76
View File
@@ -0,0 +1,76 @@
// EngineAdapter + DuelLens over the sim stand-in duel engine (scripts/sim/duel-standin.ts).
import type { DeckSpec, EngineAdapter, Seat } from '../../shared/bots/types.ts';
import { duelEvaluate, type DuelLens, type LensAction } from '../../shared/bots/duel-bots.ts';
import { existsSync } from 'node:fs';
import { applyAction, createDuel, fromDuelCards, isCreature, legalActions, pow, tough, viewFor, deriveSample, STANDIN_RULES, type SAction, type SCard, type SRules, type SState } from './duel-standin.ts';
import { mulberry32 } from '../../shared/bots/index.ts';
import type { DuelSim } from './duel-sim-types.ts';
export const standinLens: DuelLens<SState, SAction> = {
phase: s => s.phase,
life: (s, p) => s.players[p].life,
handSize: (s, p) => (s as any).view && (s as any).view.seat !== p ? (s as any).view.oppHand : s.players[p].hand.length,
creatures: (s, p) => s.players[p].board.filter(isCreature).map(b => ({
uid: String(b.uid), power: pow(b), toughness: Math.max(0, tough(b) - b.damage), tapped: b.tapped,
canAttack: b.card.type === 'Figure' && !b.tapped && !b.sick, canBlock: !b.tapped,
value: pow(b) + tough(b) * 0.8 + (b.card.type === 'Figure' ? 0.5 : 0),
})),
attackers: s => s.attackers.map(String),
blocks: s => s.blocks.map(([b, a]) => [String(b), String(a)]),
decode: (s, a): LensAction => {
switch (a.type) {
case 'play': { const c = s.players[a.seat].hand.find(h => h.id === a.card); return { kind: 'play', cost: c?.cost ?? 0, cardType: c?.type ?? '?' }; }
case 'toggleAttacker': return { kind: 'attack', uid: String(a.uid), on: !s.attackers.includes(a.uid) };
case 'confirmAttack': return { kind: 'confirmAttack' };
case 'block': return { kind: 'block', blocker: String(a.blocker), attacker: String(a.attacker) };
case 'confirmBlocks': return { kind: 'confirmBlocks' };
case 'endPhase': return { kind: 'endMain' };
}
},
};
export function makeStandinSim(poolFile: string, rules: Partial<SRules> = {}): DuelSim<SState, SAction, SCard> {
const fixture = poolFile.replace(/card-sample\.json$/, 'duel-card-sample.json');
const pool = process.env.SIM_STANDIN_POOL !== 'own' && existsSync(fixture) ? fromDuelCards(fixture) : deriveSample(poolFile);
const R = { ...STANDIN_RULES, ...rules };
const engine: EngineAdapter<SState, SAction> = {
name: 'duel-standin',
rulesets: () => ['standin'],
decks: () => [],
createMatch: (_r, decks, seed) => createDuel([decks[0].payload as SCard[], decks[1].payload as SCard[]], seed, R),
toAct: s => (s.phase === 'block' ? (1 - s.active) : s.active) as Seat,
legalActions: (s, seat) => legalActions(s, seat),
applyAction: (s, a) => applyAction(s, a),
isOver: s => s.over,
result: s => ({ winner: s.winner, reason: s.reason }),
turn: s => s.turn,
evaluate: (s, seat) => duelEvaluate(standinLens, s, seat),
cardsOf: (s, a) => (a.type === 'play' ? [a.card] : []),
actionKind: a => a.type,
firstSeat: s => s.first,
observe: (s, seat) => viewFor(s, seat),
assume: (obs, seat, rng) => {
// Refill hidden zones from the unseen part of the pool (a determinization).
const v = structuredClone(obs) as SState & { view: { oppHand: number; oppLib: number; myLib: number } };
const seen = new Set<string>();
for (const p of v.players) for (const z of [p.hand, p.grave, p.board.map(b => b.card)]) for (const c of z) seen.add(c.id);
const unseen = pool.filter(c => !seen.has(c.id));
const r = mulberry32(Math.floor(rng() * 2 ** 31));
for (let i = unseen.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [unseen[i], unseen[j]] = [unseen[j], unseen[i]]; }
let k = 0;
const take = (n: number) => { const out: SCard[] = []; for (let i = 0; i < n; i++) out.push(unseen[k++ % Math.max(1, unseen.length)]); return out; };
const o = 1 - seat;
v.players[o].hand = take(v.view.oppHand);
v.players[o].library = take(v.view.oppLib);
v.players[seat].library = take(v.view.myLib);
delete (v as any).view;
return v;
},
};
return {
name: 'standin', engine, lens: standinLens, pool,
deckPayload: cards => cards,
metrics: s => ({ connectedFires: s.stats.connectedFires, plays: s.stats.plays, lifeLeft: s.winner === null ? 0 : s.players[s.winner].life }),
connected: (a, b) => a.connect.some((k: string) => b.connect.includes(k)),
};
}
+229
View File
@@ -0,0 +1,229 @@
// Stand-in duel engine for sim-balance, used only until (and as a test double alongside) duel-core's
// shared/duel engine. Implements the BRIEF "Game rules core" in miniature: 40-card decks, 20 Notability,
// Citations +1/turn to 10, no stack, sorcery-speed Events, single blocks, simultaneous damage,
// summoning sickness, empty-library loss. Card derivation is a rough copy of duel-cards' plan
// (fame percentile -> cost 1..6, P+T budget per cost). Pure and deterministic.
import { readFileSync } from 'node:fs';
import { mulberry32 } from '../../shared/bots/index.ts';
export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
export interface SCard {
id: string; pageId: number; title: string; type: CardType; portal: string;
cost: number; power: number; toughness: number; keywords: string[];
fame: number; connect: string[];
}
export interface SPerm { card: SCard; uid: number; damage: number; tapped: boolean; sick: boolean; buff: [number, number]; attachedTo?: number }
export interface SPlayer { life: number; library: SCard[]; hand: SCard[]; grave: SCard[]; board: SPerm[]; citations: number; maxCitations: number; ramp: number }
export type Phase = 'main' | 'attack' | 'block';
export interface SState {
rules: SRules; seed: number; rngState: number; turn: number; active: 0 | 1; phase: Phase;
players: [SPlayer, SPlayer]; attackers: number[]; blocks: [number, number][]; uid: number;
winner: 0 | 1 | null; over: boolean; reason?: string; first: 0 | 1;
stats: { connectedFires: number; plays: number };
}
export interface SRules { deckSize: number; startingLife: number; maxCitations: number; handSize: number; openingHand: number; turnCap?: number; connectedBonus: number }
export const STANDIN_RULES: SRules = { deckSize: 40, startingLife: 20, maxCitations: 10, handSize: 7, openingHand: 7, connectedBonus: 1 };
export type SAction =
| { type: 'play'; seat: 0 | 1; card: string; target?: number | 'face' }
| { type: 'toggleAttacker'; seat: 0 | 1; uid: number }
| { type: 'confirmAttack'; seat: 0 | 1 }
| { type: 'block'; seat: 0 | 1; blocker: number; attacker: number }
| { type: 'confirmBlocks'; seat: 0 | 1 }
| { type: 'endPhase'; seat: 0 | 1 };
// ---------- card derivation (sample JSON -> SCard) ----------
const COST_T = [26, 39, 51, 63, 78];
const BUDGET = [3, 4, 6, 8, 10, 12];
function classify(c: any): CardType {
const p31 = (c.instanceOf ?? []).map((x: any) => String(x.label ?? ''));
const ids = (c.instanceOf ?? []).map((x: any) => x.id);
if (ids.some((i: string) => ['Q5', 'Q16521', 'Q95074'].includes(i))) return 'Figure';
if (p31.some((l: string) => /settlement|commune|village|town|city|municipality|river|island|castle|building|township|mountain|lake/i.test(l))) return 'Location';
if (p31.some((l: string) => /election|storm|protest|battle|season|events|war|nor'easter|tournament|final/i.test(l))) return 'Event';
if (p31.some((l: string) => /group|company|film|album|band|team|organi[sz]ation|club|school|novel|song|series/i.test(l))) return 'Institution';
const cats = (c.categories ?? []).join('|');
if (/\d+ births|\d+ deaths|Living people/.test(cats)) return 'Figure';
if (/Communes of|Villages in|Populated places/.test(cats)) return 'Location';
return 'Doctrine';
}
function pctTable(cards: any[], key: string): number[] { return cards.map(c => c.stats?.[key]).filter((v: any) => typeof v === 'number').sort((a: number, b: number) => a - b); }
function pct(v: number | null | undefined, t: number[]): number | null { if (typeof v !== 'number') return null; let b = 0; for (const x of t) if (x < v) b++; return Math.round(100 * b / t.length); }
const COUNTRY = /\b(American|United States|English|British|France|French|German|Japan|Japanese|Chin(a|ese)|India|Brazil|Pol(and|ish)|Ital(y|ian)|Spa(in|nish)|Austria|Canad|Australia|Russia|Mexic|Iran|Pakistan|Swed|Norw|Estonia|Ukrain|Croatia|Philippin|Indonesia|Korea)/g;
export function deriveSample(file: string): SCard[] {
const raw = JSON.parse(readFileSync(file, 'utf8')).cards as any[];
const tA = pctTable(raw, 'attention'), tD = pctTable(raw, 'depth'), tR = pctTable(raw, 'reach');
return raw.map(c => {
const ps = [pct(c.stats?.attention, tA), pct(c.stats?.depth, tD), pct(c.stats?.reach, tR)].filter((x): x is number => x !== null);
const fame = ps.length ? Math.round(ps.reduce((a, b) => a + b, 0) / ps.length) : 0;
const cost = 1 + COST_T.filter(t => t <= fame).length;
const budget = BUDGET[cost - 1];
const a = pct(c.stats?.attention, tA) ?? 50, d = pct(c.stats?.depth, tD) ?? 50;
const share = Math.min(0.7, Math.max(0.3, a / Math.max(1, a + d)));
const power = Math.max(1, Math.round(budget * share)), toughness = Math.max(1, budget - power);
const txt = `${c.description ?? ''} ${(c.categories ?? []).join(' ')}`;
const countries = [...new Set([...txt.matchAll(COUNTRY)].map(m => m[1].slice(0, 5)))].map(x => `c:${x}`);
const cents = [...new Set([...`${c.title} ${txt}`.matchAll(/\b(1[0-9]{3}|20[0-2][0-9])\b/g)].map(m => `t:${Math.floor(Number(m[1]) / 100)}`))];
const type = classify(c);
if (type === 'Location') return { id: `p${c.pageId}`, pageId: c.pageId, title: c.title, type, portal: c.faction ?? 'Other', cost: Math.ceil(cost / 2), power: 0, toughness: Math.max(1, Math.ceil(toughness / 2)), keywords: [], fame, connect: [...countries, ...cents] };
const kw: string[] = [];
if (c.languageCount >= 20) kw.push('Multilingual');
if (c.pageBytes < 3000) kw.push('Stub');
return { id: `p${c.pageId}`, pageId: c.pageId, title: c.title, type, portal: c.faction ?? 'Other', cost, power, toughness, keywords: kw.slice(0, 2), fame, connect: [...countries, ...cents] };
});
}
// ---------- engine ----------
const clone = <T>(x: T): T => structuredClone(x);
function rng(s: SState) { const r = mulberry32(s.rngState); return () => { const v = r(); s.rngState = (s.rngState + 0x6d2b79f5) >>> 0; return v; }; }
function shuffle<T>(xs: T[], r: () => number) { for (let i = xs.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [xs[i], xs[j]] = [xs[j], xs[i]]; } }
const opp = (p: 0 | 1): 0 | 1 => (p === 0 ? 1 : 0);
export const pow = (p: SPerm) => p.card.power + p.buff[0];
export const tough = (p: SPerm) => p.card.toughness + p.buff[1];
export const isCreature = (p: SPerm) => p.card.type === 'Figure' || (p.card.type === 'Location' && p.attachedTo === undefined);
export function createDuel(decks: [SCard[], SCard[]], seed: number, rules: SRules = STANDIN_RULES): SState {
const s: SState = { rules, seed, rngState: seed >>> 0, turn: 1, active: 0, phase: 'main', players: [null, null] as any, attackers: [], blocks: [], uid: 1, winner: null, over: false, first: 0, stats: { connectedFires: 0, plays: 0 } };
const r = rng(s);
s.first = r() < 0.5 ? 0 : 1; s.active = s.first;
for (const p of [0, 1] as const) {
const lib = decks[p].slice(0, rules.deckSize).map(c => ({ ...c }));
shuffle(lib, r);
s.players[p] = { life: rules.startingLife, library: lib, hand: lib.splice(0, rules.openingHand), grave: [], board: [], citations: 0, maxCitations: 0, ramp: 0 };
}
refresh(s, false);
return s;
}
function lose(s: SState, p: 0 | 1, reason: string) { if (!s.over) { s.over = true; s.winner = opp(p); s.reason = reason; } }
function draw(s: SState, p: 0 | 1) { const pl = s.players[p]; const c = pl.library.shift(); if (!c) return lose(s, p, 'library-empty'); pl.hand.push(c); }
function refresh(s: SState, doDraw: boolean) {
const pl = s.players[s.active];
pl.maxCitations = Math.min(s.rules.maxCitations, pl.maxCitations + 1);
pl.citations = pl.maxCitations + pl.ramp;
for (const b of pl.board) { b.tapped = false; b.sick = false; }
if (doDraw) draw(s, s.active);
s.phase = 'main'; s.attackers = []; s.blocks = [];
}
function endTurn(s: SState) {
for (const pl of s.players) for (const b of pl.board) b.damage = 0;
const pl = s.players[s.active];
while (pl.hand.length > s.rules.handSize) pl.grave.push(pl.hand.pop()!);
if (s.rules.turnCap && s.turn >= s.rules.turnCap * 2) {
const [a, b] = s.players; s.over = true; s.reason = 'turn-cap';
s.winner = a.life === b.life ? null : a.life > b.life ? 0 : 1; return;
}
s.turn++; s.active = opp(s.active); refresh(s, true);
}
function connectedWith(card: SCard, board: SPerm[]): boolean { return board.some(b => b.card.connect.some(k => card.connect.includes(k))); }
export function legalActions(s: SState, seat: 0 | 1): SAction[] {
if (s.over) return [];
const pl = s.players[seat], foe = s.players[opp(seat)];
if (s.phase === 'block') {
if (seat !== opp(s.active)) return [];
const out: SAction[] = [{ type: 'confirmBlocks', seat }];
const used = new Set(s.blocks.map(b => b[0])), blocked = new Set(s.blocks.map(b => b[1]));
for (const bl of pl.board) if (isCreature(bl) && !bl.tapped && !used.has(bl.uid) && (bl.card.type === 'Figure' || tough(bl) > 0))
for (const a of s.attackers) if (!blocked.has(a)) out.push({ type: 'block', seat, blocker: bl.uid, attacker: a });
return out;
}
if (seat !== s.active) return [];
if (s.phase === 'attack') {
const out: SAction[] = [{ type: 'confirmAttack', seat }];
for (const b of pl.board) if (b.card.type === 'Figure' && !b.tapped && !b.sick) out.push({ type: 'toggleAttacker', seat, uid: b.uid });
return out;
}
const out: SAction[] = [{ type: 'endPhase', seat }];
const seen = new Set<string>();
for (const c of pl.hand) {
if (c.cost > pl.citations || seen.has(c.id)) continue; seen.add(c.id);
if (c.type === 'Event') {
out.push({ type: 'play', seat, card: c.id, target: 'face' });
for (const b of foe.board) if (b.card.type === 'Figure' && !b.card.keywords.includes('Protected')) out.push({ type: 'play', seat, card: c.id, target: b.uid });
} else if (c.type === 'Doctrine') {
for (const b of pl.board) if (b.card.type === 'Figure') out.push({ type: 'play', seat, card: c.id, target: b.uid });
} else out.push({ type: 'play', seat, card: c.id });
}
return out;
}
function kill(s: SState) {
for (const p of [0, 1] as const) {
const pl = s.players[p];
const dead = pl.board.filter(b => isCreature(b) && b.damage >= tough(b) && tough(b) > 0);
if (!dead.length) continue;
const ids = new Set(dead.map(d => d.uid));
for (const d of dead) pl.grave.push(d.card);
pl.board = pl.board.filter(b => !ids.has(b.uid) && !(b.attachedTo !== undefined && ids.has(b.attachedTo)));
}
}
export function applyAction(s0: SState, a: SAction): SState {
const s = clone(s0);
const pl = s.players[a.seat], foe = s.players[opp(a.seat)];
switch (a.type) {
case 'play': {
const i = pl.hand.findIndex(c => c.id === a.card); const c = pl.hand[i];
pl.hand.splice(i, 1); pl.citations -= c.cost; s.stats.plays++;
const conn = connectedWith(c, pl.board); if (conn) s.stats.connectedFires++;
const bonus = conn ? s.rules.connectedBonus : 0;
if (c.type === 'Event') {
const dmg = c.cost + 1 + bonus;
if (a.target === 'face') foe.life -= Math.ceil(dmg / 2);
else { const t = foe.board.find(b => b.uid === a.target); if (t) t.damage += dmg; kill(s); }
pl.grave.push(c);
} else if (c.type === 'Doctrine') {
const t = pl.board.find(b => b.uid === a.target)!;
t.buff = [t.buff[0] + Math.ceil(c.power / 2) + bonus, t.buff[1] + Math.ceil(c.toughness / 2) + bonus];
pl.board.push({ card: c, uid: s.uid++, damage: 0, tapped: false, sick: false, buff: [0, 0], attachedTo: t.uid });
} else if (c.type === 'Institution') {
pl.board.push({ card: c, uid: s.uid++, damage: 0, tapped: false, sick: false, buff: [0, 0], attachedTo: -1 });
draw(s, a.seat); if (c.cost >= 4) draw(s, a.seat);
} else if (c.type === 'Location') {
if (pl.ramp < 2) pl.ramp++;
pl.board.push({ card: { ...c, power: 0 }, uid: s.uid++, damage: 0, tapped: false, sick: false, buff: [0, bonus] });
} else pl.board.push({ card: c, uid: s.uid++, damage: 0, tapped: false, sick: true, buff: [bonus, bonus] });
if (foe.life <= 0) lose(s, opp(a.seat), 'notability');
return s;
}
case 'endPhase': s.phase = 'attack'; return s;
case 'toggleAttacker': { const k = s.attackers.indexOf(a.uid); if (k >= 0) s.attackers.splice(k, 1); else s.attackers.push(a.uid); return s; }
case 'confirmAttack':
if (!s.attackers.length) { endTurn(s); return s; }
for (const u of s.attackers) pl.board.find(b => b.uid === u)!.tapped = true;
s.phase = 'block'; return s;
case 'block': s.blocks.push([a.blocker, a.attacker]); return s;
case 'confirmBlocks': {
const att = s.players[s.active], def = s.players[a.seat];
for (const u of s.attackers) {
const A = att.board.find(b => b.uid === u); if (!A) continue;
const bl = s.blocks.find(b => b[1] === u);
const B = bl && def.board.find(b => b.uid === bl[0]);
if (B) { B.damage += pow(A); A.damage += pow(B); } else def.life -= pow(A);
}
kill(s);
if (def.life <= 0) { lose(s, a.seat, 'notability'); return s; }
endTurn(s); return s;
}
}
}
/** Seat-local copy: opponent hand and both libraries' contents are hidden (replaced by counts). */
export function viewFor(s: SState, seat: 0 | 1) {
const v = clone(s) as any;
const o = v.players[opp(seat)];
v.view = { seat, oppHand: o.hand.length, oppLib: o.library.length, myLib: v.players[seat].library.length };
o.hand = []; o.library = []; v.players[seat].library = [];
return v as SState & { view: { seat: 0 | 1; oppHand: number; oppLib: number; myLib: number } };
}
/** duel-cards' derived DuelCards (docs/game/duel-card-sample.json) mapped onto the stand-in's card shape. */
export function fromDuelCards(file: string): SCard[] {
const cards = JSON.parse(readFileSync(file, 'utf8')).cards as any[];
return cards.map(c => ({
id: c.cardId, pageId: c.pageId, title: c.title, type: c.type, portal: c.portal, cost: c.cost,
power: c.type === 'Location' ? 0 : (c.power ?? c.basis?.magnitude ?? 1), toughness: c.type === 'Location' ? Math.max(1, c.toughness ?? 1) : (c.toughness ?? c.basis?.magnitude ?? 1),
keywords: c.keywords ?? [], fame: c.basis?.fame ?? 0,
connect: [...(c.connect?.countries ?? []).map((x: string) => `c:${x}`), ...(c.connect?.centuries ?? []).map((x: number) => `t:${x}`)],
}));
}
+156
View File
@@ -0,0 +1,156 @@
// Aggregate duel match records into the DUEL_BALANCE.md metrics.
import type { Seat } from '../../shared/bots/types.ts';
import { rate, type Rate } from './stats.ts';
import type { SimDeck, PoolCard } from './duel-decks.ts';
import type { DuelSim } from './duel-sim-types.ts';
export interface DuelRecord {
seed: number; bots: [string, string]; decks: [string, string]; tags: [string[], string[]];
first: Seat; winner: Seat | null; reason: string; turns: number; turnsEach: number; actions: number; truncated: boolean;
minutes: number; played: [string[], string[]]; metrics: Record<string, number>; ms: number;
}
const quant = (xs: number[], q: number) => { if (!xs.length) return NaN; const s = [...xs].sort((a, b) => a - b); return s[Math.min(s.length - 1, Math.floor(q * s.length))]; };
const mean = (xs: number[]) => xs.reduce((a, b) => a + b, 0) / (xs.length || 1);
function pearson(xs: number[], ys: number[]) {
const mx = mean(xs), my = mean(ys); let sxy = 0, sxx = 0, syy = 0;
for (let i = 0; i < xs.length; i++) { const dx = xs[i] - mx, dy = ys[i] - my; sxy += dx * dy; sxx += dx * dx; syy += dy * dy; }
return sxx && syy ? sxy / Math.sqrt(sxx * syy) : NaN;
}
export interface DuelStats {
meta: Record<string, unknown>;
matches: number; errors: number; draws: number; truncated: number; reasons: Record<string, number>;
firstPlayer: Rate; firstPlayerAll: Rate;
turnsEach: { p10: number; p50: number; p90: number; mean: number };
minutes: { p10: number; p50: number; p90: number };
stalls: { actionCap: number; turnCap: number; over20Each: number; rate: number };
skill: Record<string, Rate>;
byTag: Record<string, Rate>;
byType: Record<string, Rate & { plays: number }>;
byPortal: Record<string, Rate & { plays: number }>;
byKeyword: Record<string, Rate & { plays: number }>;
byCost: Record<string, Rate & { plays: number }>;
fame: { rCardWr: number; rWithinCost: Record<string, number>; topDecile: Rate; bottomDecile: Rate; cards: number };
connected: { pairRate: number; pairs: number; firesPerPlay: number; firesPerGame: number };
cards: { id: string; title?: string; type: string; cost: number; fame?: number; games: number; wr: Rate }[];
}
const sym = (m: DuelRecord) => m.bots[0] === m.bots[1];
export function aggregateDuel(records: DuelRecord[], sim: DuelSim<any, any>, decks: SimDeck[], errors: number, meta: Record<string, unknown>): DuelStats {
const byId = new Map<string, PoolCard & { title?: string }>(sim.pool.map((c: any) => [c.id, c]));
const decisive = records.filter(m => m.winner !== null);
const symDec = decisive.filter(sym);
const reasons: Record<string, number> = {};
for (const m of records) reasons[m.reason] = (reasons[m.reason] ?? 0) + 1;
const skill: Record<string, Rate> = {};
const pairs: Record<string, [number, number]> = {};
for (const m of decisive) {
if (sym(m)) continue;
const key = [...m.bots].sort().join('>');
const [a] = key.split('>');
const aSeat = m.bots[0] === a ? 0 : 1;
const p = pairs[key] ?? (pairs[key] = [0, 0]); p[0]++; if (m.winner === aSeat) p[1]++;
}
for (const [k, [n, w]] of Object.entries(pairs)) {
// Report as "stronger>weaker" with the stronger side's rate.
const [a, b] = k.split('>'); const r = rate(w, n);
if (r.rate >= 0.5) skill[`${a}>${b}`] = r; else skill[`${b}>${a}`] = rate(n - w, n);
}
// Tags: exclude games where both decks share the tag.
const tagAcc: Record<string, [number, number]> = {};
for (const m of symDec) for (const s of [0, 1] as Seat[]) for (const t of m.tags[s]) {
if (m.tags[1 - s].includes(t)) continue;
const a = tagAcc[t] ?? (tagAcc[t] = [0, 0]); a[0]++; if (m.winner === s) a[1]++;
}
const byTag = Object.fromEntries(Object.entries(tagAcc).sort().map(([k, [n, w]]) => [k, rate(w, n)]));
// Card-level: a card "appears" in a game if its seat played it. WR of the seat that played it.
const cardAcc = new Map<string, [number, number]>();
for (const m of symDec) for (const s of [0, 1] as Seat[]) for (const id of new Set(m.played[s])) {
if (new Set(m.played[1 - s]).has(id)) continue;
const a = cardAcc.get(id) ?? [0, 0]; a[0]++; if (m.winner === s) a[1]++; cardAcc.set(id, a);
}
const group = (f: (c: PoolCard) => string[]) => {
const acc: Record<string, [number, number]> = {};
for (const [id, [n, w]] of cardAcc) { const c = byId.get(id); if (!c) continue; for (const k of f(c)) { const a = acc[k] ?? (acc[k] = [0, 0]); a[0] += n; a[1] += w; } }
return Object.fromEntries(Object.entries(acc).sort().map(([k, [n, w]]) => [k, { ...rate(w, n), plays: n }]));
};
const cards = [...cardAcc].map(([id, [n, w]]) => { const c = byId.get(id) as any; return { id, title: c?.title, type: c?.type ?? '?', cost: c?.cost ?? 0, fame: c?.fame, games: n, wr: rate(w, n) }; })
.sort((a, b) => b.games - a.games);
const solid = cards.filter(c => c.games >= 20 && typeof c.fame === 'number');
const rWithinCost: Record<string, number> = {};
for (const cost of [1, 2, 3, 4, 5, 6]) { const xs = solid.filter(c => c.cost === cost); if (xs.length >= 5) rWithinCost[cost] = pearson(xs.map(c => c.fame!), xs.map(c => c.wr.rate)); }
const byFame = [...solid].sort((a, b) => a.fame! - b.fame!);
const dec = Math.max(1, Math.floor(byFame.length / 10));
const pool = (xs: typeof solid) => rate(xs.reduce((t, c) => t + c.wr.wins, 0), xs.reduce((t, c) => t + c.games, 0));
// Connected: static pair rate over the pool, and in-game fires.
let pairsN = 0, hits = 0;
if (sim.connected) for (let i = 0; i < sim.pool.length; i++) for (let j = i + 1; j < sim.pool.length; j++) { pairsN++; if (sim.connected(sim.pool[i], sim.pool[j])) hits++; }
const fires = records.map(m => m.metrics.connectedFires ?? 0), plays = records.map(m => m.metrics.plays ?? 0);
const turns = records.filter(m => !m.truncated).map(m => m.turnsEach);
const fp = (xs: DuelRecord[]) => rate(xs.filter(m => m.winner === m.first).length, xs.length);
const actionCap = records.filter(m => m.truncated).length, turnCap = reasons['turn-cap'] ?? 0, over20 = records.filter(m => m.turnsEach > 20).length;
return {
meta: { ...meta, decks: decks.length, when: new Date().toISOString() },
matches: records.length, errors, draws: records.length - decisive.length, truncated: actionCap, reasons,
firstPlayer: fp(symDec), firstPlayerAll: fp(decisive),
turnsEach: { p10: quant(turns, 0.1), p50: quant(turns, 0.5), p90: quant(turns, 0.9), mean: mean(turns) },
minutes: { p10: quant(records.map(m => m.minutes), 0.1), p50: quant(records.map(m => m.minutes), 0.5), p90: quant(records.map(m => m.minutes), 0.9) },
stalls: { actionCap, turnCap, over20Each: over20, rate: (actionCap + turnCap + over20) / (records.length || 1) },
skill, byTag,
byType: group(c => [c.type]), byPortal: group(c => [c.portal]), byKeyword: group(c => (c.keywords.length ? c.keywords : ['(none)'])), byCost: group(c => [String(c.cost)]),
fame: { rCardWr: pearson(solid.map(c => c.fame!), solid.map(c => c.wr.rate)), rWithinCost, topDecile: pool(byFame.slice(-dec)), bottomDecile: pool(byFame.slice(0, dec)), cards: solid.length },
connected: { pairRate: pairsN ? hits / pairsN : NaN, pairs: pairsN, firesPerPlay: mean(plays) ? mean(fires) / mean(plays) : NaN, firesPerGame: mean(fires) },
cards,
};
}
const pc = (r: Rate) => (Number.isNaN(r.rate) ? '—' : `${(100 * r.rate).toFixed(1)}% [${(100 * r.lo).toFixed(0)}–${(100 * r.hi).toFixed(0)}] n=${r.n}`);
const table = (title: string, m: Record<string, Rate & { plays?: number }>) =>
`| ${title} | Win rate (95% CI) |\n|---|---|\n` + Object.entries(m).map(([k, r]) => `| ${k} | ${pc(r)} |`).join('\n') + '\n';
export function duelMarkdown(s: DuelStats): string {
const f = (x: number, d = 1) => (Number.isNaN(x) ? '—' : x.toFixed(d));
const top = s.cards.filter(c => c.games >= 20).sort((a, b) => b.wr.rate - a.wr.rate);
const line = (c: DuelStats['cards'][number]) => `| ${c.title ?? c.id} | ${c.type} | ${c.cost} | ${f(c.fame ?? NaN, 0)} | ${pc(c.wr)} |`;
return `### Run \`${s.meta.label}\` (engine \`${s.meta.engine}\`${s.meta.sha ? `, SHA \`${s.meta.sha}\`` : ''})
Rules overrides: \`${JSON.stringify(s.meta.rules)}\`. ${s.matches} matches, ${s.meta.decks} decks, ${s.errors} errors, ${s.draws} draws.
| Metric | Value | Target |
|---|---|---|
| First-player win rate (symmetric bots) | ${pc(s.firstPlayer)} | 48–52% |
| First-player win rate (all decisive) | ${pc(s.firstPlayerAll)} | |
| Turns each p10 / median / p90 | ${f(s.turnsEach.p10, 0)} / **${f(s.turnsEach.p50, 0)}** / ${f(s.turnsEach.p90, 0)} | median 8–12 |
| Est. minutes p10 / median / p90 | ${f(s.minutes.p10)} / **${f(s.minutes.p50)}** / ${f(s.minutes.p90)} | 8–15 |
| Stalls (action cap + turn cap + >20 turns each) | ${s.stalls.actionCap} + ${s.stalls.turnCap} + ${s.stalls.over20Each} (${f(100 * s.stalls.rate)}%) | ~0 |
| Connected: static pair rate over the pool | ${f(100 * s.connected.pairRate)}% of ${s.connected.pairs} pairs | 15–30% |
| Connected: fires per play / per game | ${f(100 * s.connected.firesPerPlay)}% / ${f(s.connected.firesPerGame, 2)} | |
| Fame vs card win rate (Pearson r, cards with ≥20 games) | ${f(s.fame.rCardWr, 2)} (n=${s.fame.cards}) | ≈0 (not strictly better) |
| Top vs bottom fame decile | ${pc(s.fame.topDecile)} vs ${pc(s.fame.bottomDecile)} | close |
End reasons: ${Object.entries(s.reasons).map(([k, v]) => `${k} ${v}`).join(', ')}.
Skill (stronger bot's win rate): ${Object.entries(s.skill).map(([k, r]) => `${k} ${pc(r)}`).join('; ') || '—'}.
Fame vs win rate within each cost: ${Object.entries(s.fame.rWithinCost).map(([k, r]) => `cost ${k}: r=${f(r, 2)}`).join(', ') || '—'}.
${table('Card type (seat that played it)', s.byType)}
${table('Portal', s.byPortal)}
${table('Keyword', s.byKeyword)}
${table('Cost', s.byCost)}
${table('Deck tag (vs decks without it)', s.byTag)}
Top cards by win rate when played (≥20 games):
| Card | Type | Cost | Fame | WR |
|---|---|---|---|---|
${top.slice(0, 8).map(line).join('\n')}
Bottom cards:
| Card | Type | Cost | Fame | WR |
|---|---|---|---|---|
${top.slice(-8).reverse().map(line).join('\n')}
`;
}
+17 -2
View File
@@ -12,12 +12,28 @@ export type AccountDeps = { config?: OidcConfig; keys?: DexKeys; store?: Account
type Authed = Request & { account?: Account };
const hex64 = z.string().regex(/^[a-f0-9]{64}$/);
/**
* Verifies a Dex ID token and records the account. Shared with the game routes
* (server/game/collection.ts, the PvP host) so every route uses the same store and keys.
* Throws TokenError (status 401) for a bad token; other errors mean Dex is unreachable.
*/
export function accountVerifier(config: OidcConfig, keys: Pick<DexKeys, 'key'>, store: Pick<AccountStore, 'upsert'>,
now: () => number = Date.now): (idToken: string) => Promise<Account> {
return async idToken => {
const claims = await verifyIdToken(idToken, keys, config, { now: now() });
const account: Account = { sub: claims.sub, issuer: claims.iss, name: displayName(claims), username: claims.preferred_username ?? '' };
store.upsert(account);
return account;
};
}
export function createAccountRouter(deps: AccountDeps = {}): Router {
const config = deps.config ?? oidcConfig();
const now = deps.now ?? Date.now;
const keys = deps.keys ?? new DexKeys(config, deps.fetcher, now);
const store = deps.store ?? new AccountStore(resolve(deps.dataDir ?? 'data', 'accounts.sqlite'), now);
const router = Router();
const verify = accountVerifier(config, keys, store, now);
const toAccount = (claims: Awaited<ReturnType<typeof verifyIdToken>>): Account =>
({ sub: claims.sub, issuer: claims.iss, name: displayName(claims), username: claims.preferred_username ?? '' });
@@ -26,8 +42,7 @@ export function createAccountRouter(deps: AccountDeps = {}): Router {
try {
const m = /^Bearer ([A-Za-z0-9_.-]+)$/.exec(req.get('authorization') ?? '');
if (!m) throw new TokenError('Log in with your eom.dev account');
req.account = toAccount(await verifyIdToken(m[1], keys, config, { now: now() }));
store.upsert(req.account);
req.account = await verify(m[1]);
next();
} catch (e) { next(e); }
};
+72 -27
View File
@@ -1,5 +1,5 @@
import { z } from 'zod';
import { ENRICHMENT_USER_AGENT, wikimediaUserAgent } from './wikimedia-user-agent.ts';
import { WikimediaClient, WikimediaUnavailable, wikimediaClient, type CachePolicy, type Lane } from './wikimedia/client.ts';
import { deriveStats, type PageEnrichment } from '../shared/enrichment.ts';
const MAX_BYTES = 1024 * 1024;
@@ -25,7 +25,23 @@ const viewsSchema = z.object({ items: z.array(z.object({
})).max(6) });
type CacheEntry = { expires: number; value: PageEnrichment } | { expires: number; error: Error };
type Options = { fetch?: typeof globalThis.fetch; now?: () => Date; ttlMs?: number; maxEntries?: number };
type Options = { fetch?: typeof globalThis.fetch; client?: WikimediaClient; now?: () => Date; ttlMs?: number; maxEntries?: number };
type Mode = 'mint' | 'display' | 'background';
/** Disk-cache lifetimes (engineer review §4). Mint reads never use the cache. */
const METADATA_CACHE: CachePolicy = { ttlMs: 24 * 3600_000, staleWhileRevalidate: true, maxBytes: MAX_BYTES };
// The URL names its six completed months, which are immutable; a week bounds late corrections.
const PAGEVIEWS_CACHE: CachePolicy = { ttlMs: 7 * 24 * 3600_000, staleWhileRevalidate: true, maxBytes: MAX_BYTES };
const NOT_FOUND = Symbol('not found');
/** The upstream did not answer properly (throttled, 5xx, timeout, network, non-JSON). Not "no data". */
export class UpstreamFailure extends Error {
constructor(message: string) { super(message); this.name = 'UpstreamFailure'; }
}
function transportFailure(error: unknown): boolean {
return error instanceof WikimediaUnavailable || error instanceof UpstreamFailure ||
(error instanceof DOMException && (error.name === 'TimeoutError' || error.name === 'AbortError'));
}
function monthWindow(now: Date): string[] {
return Array.from({ length: 6 }, (_, index) =>
@@ -34,16 +50,17 @@ function monthWindow(now: Date): string[] {
/** Fixed-source read-only enrichment; no consensus, persistence, URL or header inputs. */
export class WikipediaEnrichment {
private readonly fetcher: typeof globalThis.fetch;
private readonly client: WikimediaClient;
private readonly now: () => Date;
private readonly ttlMs: number;
private readonly maxEntries: number;
private readonly cache = new Map<number, CacheEntry>();
private readonly pending = new Map<number, Promise<PageEnrichment>>();
private readonly pending = new Map<string, Promise<PageEnrichment>>();
private active = 0;
private mintActive = 0;
constructor(options: Options = {}) {
this.fetcher = options.fetch ?? globalThis.fetch;
this.client = options.client ?? (options.fetch ? WikimediaClient.unthrottled(options.fetch) : wikimediaClient);
this.now = options.now ?? (() => new Date());
this.ttlMs = options.ttlMs ?? 6 * 60 * 60 * 1000;
this.maxEntries = options.maxEntries ?? 128;
@@ -53,16 +70,27 @@ export class WikipediaEnrichment {
}
}
/** Card faces (`/api/wikipedia/:id`): memory, then the disk cache, then the interactive lane. */
async get(pageId: number): Promise<PageEnrichment> {
return this.loadCached(pageId, false);
return this.loadCached(pageId, 'display');
}
/** Bypass cached values when the result is being pinned into a newly minted block. */
/** Like get(), on the background lane: for trends and other work nobody is waiting on. */
async getBackground(pageId: number): Promise<PageEnrichment> {
return this.loadCached(pageId, 'background');
}
/**
* Mint data: bypasses every cache and uses the mint lane. If pageviews fail in transport
* (429, 5xx, timeout, throttled), this rejects so the template fails and the miner retries;
* `unavailable` is recorded only for a genuine 404 or missing data.
*/
async getFresh(pageId: number): Promise<PageEnrichment> {
return this.loadCached(pageId, true);
return this.loadCached(pageId, 'mint');
}
private async loadCached(pageId: number, fresh: boolean): Promise<PageEnrichment> {
private async loadCached(pageId: number, mode: Mode): Promise<PageEnrichment> {
const fresh = mode === 'mint';
if (!Number.isSafeInteger(pageId) || pageId <= 0) throw new RangeError('Invalid Wikipedia page ID');
const now = this.now();
const cached = this.cache.get(pageId);
@@ -73,23 +101,29 @@ export class WikipediaEnrichment {
if ('error' in cached) throw cached.error;
return structuredClone(cached.value);
}
this.cache.delete(pageId);
const existing = this.pending.get(pageId);
if (!fresh) this.cache.delete(pageId);
// Mint jobs never join a display job: that one may be served from the disk cache.
const pendingKey = `${fresh ? 'mint' : 'cached'}:${pageId}`;
const existing = this.pending.get(pendingKey);
if (existing) return structuredClone(await existing);
// Reject immediately: no unbounded waiting queue. Four active jobs also keep
// the pending-map ceiling of eight conservative (one upstream request/job).
if (this.pending.size >= 8 || this.active >= 4) throw new Error('Wikipedia enrichment busy');
this.active++;
const job = this.load(pageId, now).then(value => {
// Mint jobs have their own small allowance so card faces can never starve a template.
if (fresh ? this.mintActive >= 2 : this.pending.size - this.mintActive >= 8 || this.active >= 4) {
throw new Error('Wikipedia enrichment busy');
}
if (fresh) this.mintActive++; else this.active++;
const job = this.load(pageId, now, mode).then(value => {
const ttl = value.pageviews.status === 'available' ? this.ttlMs : Math.min(this.ttlMs, 5 * 60 * 1000);
this.remember(pageId, { value, expires: this.now().getTime() + ttl });
return value;
}, () => {
const error = new Error('Wikipedia page enrichment unavailable');
this.remember(pageId, { error, expires: this.now().getTime() + 30_000 });
// A failed mint read says nothing new about display data; keep any cached value.
if (!fresh) this.remember(pageId, { error, expires: this.now().getTime() + 30_000 });
throw error;
}).finally(() => { this.active--; this.pending.delete(pageId); });
this.pending.set(pageId, job);
}).finally(() => { if (fresh) this.mintActive--; else this.active--; this.pending.delete(pendingKey); });
this.pending.set(pendingKey, job);
return structuredClone(await job);
}
@@ -99,16 +133,19 @@ export class WikipediaEnrichment {
while (this.cache.size > this.maxEntries) this.cache.delete(this.cache.keys().next().value!);
}
private async json(url: URL): Promise<unknown> {
const signal = AbortSignal.timeout(6000);
const response = await this.fetcher(url, { signal, redirect: 'error',
headers: { Accept: 'application/json', 'User-Agent': wikimediaUserAgent(ENRICHMENT_USER_AGENT) } });
private async json(url: URL, lane: Lane, cache: CachePolicy | undefined, allowNotFound = false): Promise<unknown> {
const { response, signal } = await this.client.request(url, { lane, timeoutMs: 6000, cache });
if (allowNotFound && response.status === 404) { await response.body?.cancel(); return NOT_FOUND; }
if (!response.ok || response.redirected) {
await response.body?.cancel();
throw new UpstreamFailure(`Upstream HTTP ${response.status}`);
}
const length = response.headers.get('content-length');
if (!response.ok || response.redirected ||
if (
!/^application\/json(?:\s*;|\s*$)/i.test(response.headers.get('content-type') ?? '') ||
(length !== null && (!/^\d+$/.test(length) || Number(length) > MAX_BYTES)) || !response.body) {
await response.body?.cancel();
throw new Error('Invalid upstream response');
throw new UpstreamFailure('Invalid upstream response');
}
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
@@ -130,12 +167,14 @@ export class WikipediaEnrichment {
}
}
private async load(pageId: number, now: Date): Promise<PageEnrichment> {
private async load(pageId: number, now: Date, mode: Mode): Promise<PageEnrichment> {
const lane: Lane = mode === 'mint' ? 'mint' : mode === 'display' ? 'interactive' : 'background';
const fresh = mode === 'mint';
const url = new URL('https://en.wikipedia.org/w/api.php');
url.search = new URLSearchParams({ action: 'query', format: 'json', formatversion: '2',
pageids: String(pageId), prop: 'info|categories|pageprops|description|langlinks',
clshow: '!hidden', cllimit: '50', lllimit: '500', ppprop: 'wikibase_item' }).toString();
const metadata = metadataSchema.parse(await this.json(url));
const metadata = metadataSchema.parse(await this.json(url, lane, fresh ? undefined : METADATA_CACHE));
const page = metadata.query.pages[0];
if (page.pageid !== pageId) throw new Error('Wikipedia page ID mismatch');
const months = monthWindow(now);
@@ -146,7 +185,9 @@ export class WikipediaEnrichment {
const title = encodeURIComponent(page.title.replace(/ /g, '_'));
const stamp = (month: string) => `${month.replace('-', '')}0100`;
const endpoint = new URL(`https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/user/${title}/monthly/${stamp(months[0])}/${stamp(latestMonth)}`);
const result = viewsSchema.parse(await this.json(endpoint));
const raw = await this.json(endpoint, lane, fresh ? undefined : PAGEVIEWS_CACHE, true);
if (raw === NOT_FOUND) throw new Error('No pageview data');
const result = viewsSchema.parse(raw);
const byMonth = new Map<string, number>();
for (const item of result.items) {
const month = `${item.timestamp.slice(0, 4)}-${item.timestamp.slice(4, 6)}`;
@@ -161,7 +202,11 @@ export class WikipediaEnrichment {
const days = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 0)).getUTCDate();
pageviews = { status: 'available', months: ordered, latestMonth, total,
dailyAverage: latest / days, trendPercent: prior > 0 ? (latest - prior) / prior * 100 : null };
} catch { /* Metadata remains useful; unknown views must not become fake zeroes. */ }
} catch (error) {
// Mint: a throttled or failed upstream must not pin `attention: null` into a block forever.
if (fresh && transportFailure(error)) throw error;
/* Metadata remains useful; unknown views must not become fake zeroes. */
}
return { pageId, title: page.title, description: page.description ?? null,
wikidataId: page.pageprops?.wikibase_item ?? null, revisionId: page.lastrevid, pageBytes: page.length,
languageCount: page.langlinks?.length ?? 0, languagesTruncated: metadata.continue?.llcontinue !== undefined,
+76
View File
@@ -0,0 +1,76 @@
/**
* GET /api/game/collection Authorization: Bearer <Dex ID token> [?minConfirmations=N]
*
* Every card the account's linked wallets own (no 128-block cap) and whether that is enough to
* build a deck. Eligibility counts the copy limit: 40 copies of one article is 4 playable cards.
*/
import { Router, type Request, type Response } from 'express';
import { DeckError, collectionAt, ownershipRules, playableCount, verifyAccount,
type ChainCard, type OwnershipDeps, type OwnershipRules } from './ownership.ts';
export type CollectionResponse = {
tip: string;
wallets: string[];
deckSize: number;
/** Max copies per pageId. `maxCopiesPerPage` is the same value under the ruleset's name. */
copyLimit: number;
maxCopiesPerPage: number;
minConfirmations: number;
/** Confirmed cards across all linked wallets. */
owned: number;
/** Σ min(copies, copyLimit) per pageId: the most cards a legal deck can draw from. */
playable: number;
/** max(0, deckSize - playable). */
needed: number;
/** playable >= deckSize. */
eligible: boolean;
/** `duel` is present when the server has a frozen profile for the card (see collectionRouter's `duelCard`). */
cards: (ChainCard & { duel?: unknown })[];
};
export function collectionResponse(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, sub: string,
rules?: Partial<OwnershipRules>): CollectionResponse {
const r = ownershipRules(rules);
const { tip, wallets, cards } = collectionAt(deps, { sub }, { minConfirmations: r.minConfirmations });
const playable = playableCount(cards, r.maxCopiesPerPage);
return { tip, wallets, deckSize: r.deckSize, copyLimit: r.maxCopiesPerPage, maxCopiesPerPage: r.maxCopiesPerPage,
minConfirmations: r.minConfirmations, owned: cards.length, playable, needed: Math.max(0, r.deckSize - playable),
eligible: playable >= r.deckSize, cards };
}
export type CollectionRouterDeps = OwnershipDeps & {
rules?: Partial<OwnershipRules>;
/**
* Optional: the same chain card → duel card function the PvP host uses, so the browser shows and
* plays exactly what PvP would. Return undefined while a card's profile is pending; it must not fetch.
*/
duelCard?: (card: ChainCard) => unknown;
};
export function collectionRouter(deps: CollectionRouterDeps): Router {
const router = Router();
router.get('/', async (req: Request, res: Response) => {
res.setHeader('Cache-Control', 'no-store');
const q = req.query.minConfirmations;
if (q !== undefined && (typeof q !== 'string' || !/^[1-9]\d{0,3}$/.test(q))) { res.status(400).json({ error: 'Invalid minConfirmations' }); return; }
const m = /^Bearer ([A-Za-z0-9_.-]{1,8192})$/.exec(req.get('authorization') ?? '');
try {
const account = await verifyAccount(deps, m?.[1]);
const body = collectionResponse(deps, account.sub, { ...deps.rules, ...(q ? { minConfirmations: Number(q) } : {}) });
if (deps.duelCard) {
const toDuel = deps.duelCard;
body.cards = body.cards.map(c => {
let duel: unknown;
try { duel = toDuel(c); } catch { duel = undefined; }
return duel === undefined ? c : { ...c, duel };
});
}
res.json(body);
} catch (e) {
const err = e as Error & { status?: number };
const status = e instanceof DeckError ? err.status! : err.status === 503 ? 503 : 500;
res.status(status).json({ error: status === 500 ? 'Collection unavailable' : err.message });
}
});
return router;
}
+5 -3
View File
@@ -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)));
+86
View File
@@ -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<IdentityStore, 'get'>;
};
type AnyPort = EnginePort<any, any, any, any>;
/**
* 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<Record<string, string>> = {
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<AnyPort | null> {
const mod = await import('../../shared/duel/index.ts') as Record<string, unknown>;
const port = mod.duelEnginePort as AnyPort | undefined;
return port && typeof port.createMatch === 'function' ? duelBinding(port, sources) : null;
}
+30
View File
@@ -32,6 +32,8 @@ export interface EnginePort<Rules = unknown, Card = unknown, State = unknown, Ac
timeoutAction?(seat: Seat): Action;
/** Optional per-turn time limit from the ruleset, in seconds. */
turnSeconds?(rules: Rules): number;
/** Optional per-seat time bank (seconds), spent once a turn runs past `turnSeconds`. */
bankSeconds?(rules: Rules): number;
/** Optional current turn number, so the host can time turns rather than actions. */
turnOf?(state: State): number;
/** Optional: freeze live data onto a card at match start (e.g. a trend arrow). */
@@ -40,4 +42,32 @@ export interface EnginePort<Rules = unknown, Card = unknown, State = unknown, Ac
result(state: State): MatchOutcome;
/** What one seat may see (hides the opponent's hand and staged plays). */
viewFor(state: State, seat: Seat): unknown;
/**
* Build a match card from an owned NFT the ownership layer resolved from its block on the
* chain. Required for constructed and collection-draft modes. Must be deterministic: the
* same block gives the same card (derive once, freeze).
*/
fromChain?(rules: Rules, card: ChainCard): Card;
/** Copies of one Wikipedia page allowed in a deck (MTG-style 4); default 4. */
copyLimit?(rules: Rules): number;
/** Optional per-seat match log (past tense, no hidden information), stored with the record. */
logFor?(state: State, seat: Seat): unknown;
}
/** One owned NFT as built by server/game/ownership.ts from its block (never from client JSON). */
export type ChainCard = { tokenId: string; owner: string; confirmations: number; pageId: number; title: string; [k: string]: unknown };
/** An eom.dev (Dex) account, verified from an ID token. */
export type SeatAccount = { sub: string; issuer: string; name: string; username?: string };
/**
* What the host needs from server/game/ownership.ts (#57). Errors carry an HTTP `status`
* (400/401/403) and a player-facing message; the host passes both through.
*/
export interface OwnershipPort {
verifyAccount(idToken: unknown): Promise<SeatAccount>;
resolveDeck(account: SeatAccount, tokenIds: unknown,
opts: { deckSize: number; maxCopiesPerPage: number; minConfirmations: number }): Promise<ChainCard[]>;
/** Every card the account owns across its linked wallets. */
collection(account: SeatAccount): Promise<ChainCard[]>;
}
+291 -73
View File
@@ -2,38 +2,66 @@
* Hosts lobbies and matches for this node's modes, with the deterministic engine.
* All state is off-chain and in memory; finished matches go to the MatchStore.
*
* Trust model: the host is authoritative for its own matches. Players are identified by a
* client-held secret (only its SHA-256 is stored or shown) and act through per-seat bearer
* tokens. Every action must equal one of the engine's legalActions for that seat.
* Trust model: the host is authoritative for its own matches. A seat is either an eom.dev
* account (Dex ID token in the create/join body, verified server-side; player id
* `sha256('acct:' + iss + '\n' + sub)`) or, in guest-friendly Edit War modes, a client-held
* secret (only its SHA-256 is stored). Seats act through per-seat bearer tokens. Every
* action must equal one of the engine's legalActions for that seat.
*
* Engines: each mode names its engine (`editwar` or `duel`); the host runs every engine it
* was given. Constructed decks are NFT token ids the player owns, resolved from the chain by
* the ownership port (server/game/ownership.ts) and turned into cards by the engine.
*/
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import { modeKey, resolveRuleset, trendBonus, clampPower, MODE_SCHEMA_VERSION,
type HostIdentity, type ModeDocument, type ModeList, type ModeStats, type LiveCardData } from '../../shared/game/modes.ts';
import type { EnginePort, Seat } from './engine-port.ts';
import { modeKey, resolveRuleset, trendBonus, clampPower, requiresAccount, MODE_SCHEMA_VERSION,
type EngineId, type HostIdentity, type ModeDocument, type ModeList, type ModeStats, type LiveCardData } from '../../shared/game/modes.ts';
import type { ChainCard, EnginePort, OwnershipPort, Seat, SeatAccount } from './engine-port.ts';
import { MatchStore, type MatchRecord } from './store.ts';
export class GameError extends Error {
readonly status: number;
constructor(status: number, message: string) { super(message); this.status = status; }
}
/** The lobby's creator no longer has a valid deck; the lobby was expired. */
class StaleLobby extends GameError { constructor(message: string) { super(409, message); } }
type Player = { id: string; name: string; tokenHash: Buffer; seen: number };
type AnyEngine = EnginePort<any, any, any, any>;
type Player = { id: string; name: string; tokenHash: Buffer; seen: number;
/** Set for account seats: who to resolve the deck for. Never the ID token itself. */
account?: SeatAccount;
/** Constructed modes: the token ids this seat submitted (re-resolved at match start). */
deckIds?: string[] };
type Phase = 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired';
type Lobby = {
id: string; mode: ModeDocument; rules: unknown; seed: string; createdAt: number;
/** Bumped on every observable change, so unchanged polls (`?v=`) can return 204. */
version: number;
/** Private lobbies are hidden from lists and quick match; joined through the invite code. */
private?: boolean; invite?: string;
/** Rated (Elo) iff the mode is rated and both seats are accounts; decided at join. */
rated?: boolean;
/** Constructed modes: token ids per seat, for the record's references. */
tokens?: [string[], string[]];
players: Player[]; phase: Phase;
draft?: { pool: unknown[]; taken: (Seat | null)[]; order: Seat[]; turn: number; deadline: number };
decks?: [unknown[], unknown[]];
state?: unknown; actions: { seat: Seat; action: unknown }[]; startedAt?: number; lastMove: number; turnStartedAt?: number; turn?: number;
/** Per-seat time bank in ms (engines with `bankSeconds`): spent after the turn timer runs out. */
bank?: [number, number];
outcome?: { winner: Seat | null; reason: string }; matchId?: string;
};
type HostedMode = { mode: ModeDocument; rules: unknown };
type HostedMode = { mode: ModeDocument; rules: unknown; engine: AnyEngine };
export type HostOptions = {
identity: HostIdentity;
modes: ModeDocument[];
engine: EnginePort<any, any, any, any>;
/** Engines by id. Every mode's `engine` must be present here. */
engines?: Partial<Record<EngineId, AnyEngine>>;
/** Shorthand for `engines: { editwar: engine }` (Night 1 callers and tests). */
engine?: AnyEngine;
/** Account verification and server-side ownership (#57). Without it, account seats are unavailable. */
ownership?: OwnershipPort;
store: MatchStore;
/** Optional live Wikipedia trend lookup for `trending` modes. Failures mean "no bonus". */
liveData?: (pageId: number) => Promise<LiveCardData | null>;
@@ -42,16 +70,19 @@ export type HostOptions = {
maxLobbies?: number;
};
export type SeatTicket = { lobbyId: string; seat: Seat; token: string };
export type SeatTicket = { lobbyId: string; seat: Seat; token: string; invite?: string; playerId: string };
/** Body of create / join / quick match. `idToken` is a Dex ID token; `deck` is NFT token ids. */
export type SeatRequest = { name?: unknown; secret?: unknown; idToken?: unknown; deck?: unknown; private?: unknown };
const NAME = /^[\p{L}\p{N} _.\-]{1,24}$/u;
const SECRET = /^[A-Za-z0-9_-]{22,128}$/;
const LOBBY_ID = /^[a-f0-9]{24}$/;
const INVITE = /^[A-Za-z0-9_-]{12}$/;
export class ModeHost {
readonly identity: HostIdentity;
private readonly engine: EnginePort<any, any, any, any>;
private readonly store: MatchStore;
private readonly ownership?: OwnershipPort;
private readonly hosted = new Map<string, HostedMode>();
private readonly lobbies = new Map<string, Lobby>();
private readonly liveData?: HostOptions['liveData'];
@@ -60,24 +91,31 @@ export class ModeHost {
constructor(options: HostOptions) {
this.identity = options.identity;
this.engine = options.engine;
this.store = options.store;
this.ownership = options.ownership;
const engines: Partial<Record<EngineId, AnyEngine>> = { ...(options.engine ? { editwar: options.engine } : {}), ...options.engines };
this.liveData = options.liveData;
this.now = options.now ?? Date.now;
this.maxLobbies = options.maxLobbies ?? 512;
for (const mode of options.modes) {
if (this.hosted.has(mode.id)) throw new Error(`Duplicate mode id ${mode.id}`);
const engine = engines[mode.engine];
if (!engine) throw new Error(`Mode ${mode.id}: engine "${mode.engine}" is not available on this host`);
// Validate rules once at startup with the engine's own parser: a bad mode fails loudly.
const rules = resolveRuleset(this.engine.defaultRuleset, mode.rules, v => this.engine.parseRuleset(v));
if (mode.decks.kind === 'draft' && mode.decks.poolSize < 2 * this.engine.deckSize(rules)) {
const rules = resolveRuleset(engine.defaultRuleset, mode.rules, v => engine.parseRuleset(v));
const loaners = mode.decks.kind === 'starter' || (mode.decks.kind === 'draft' && mode.decks.source === 'preview');
// BRIEF decision 1: duel decks are only cards the players own. No starter, loaner or preview cards.
if (mode.engine === 'duel' && loaners) throw new Error(`Mode ${mode.id}: duel modes use owned cards only (constructed, or a collections draft)`);
if (mode.decks.kind === 'draft' && mode.decks.poolSize < 2 * engine.deckSize(rules)) {
throw new Error(`Mode ${mode.id}: draft poolSize must be at least 2 × deck size`);
}
if (mode.decks.kind !== 'draft') {
if (!loaners && !engine.fromChain) throw new Error(`Mode ${mode.id}: engine "${mode.engine}" cannot build cards from owned NFTs`);
if (mode.decks.kind === 'starter') {
// Host-dealt starter decks must be legal under the mode's rules, or the mode is unplayable.
try { this.engine.validateDeck(rules, this.engine.starterDeck(rules, 'startup-check')); }
try { engine.validateDeck(rules, engine.starterDeck(rules, 'startup-check')); }
catch (e) { throw new Error(`Mode ${mode.id}: starter decks are illegal under its rules (${(e as Error).message.slice(0, 120)}); use a draft deck policy`); }
}
this.hosted.set(mode.id, { mode, rules });
this.hosted.set(mode.id, { mode, rules, engine });
}
}
@@ -107,61 +145,146 @@ export class ModeHost {
openLobbies(modeId: string) {
this.mode(modeId);
return [...this.lobbies.values()].filter(l => l.mode.id === modeId && l.phase === 'waiting')
.slice(0, 50).map(l => ({ lobbyId: l.id, host: l.players[0]!.name, createdAt: l.createdAt }));
return [...this.lobbies.values()].filter(l => l.mode.id === modeId && l.phase === 'waiting' && !l.private)
.slice(0, 50).map(l => ({ lobbyId: l.id, host: l.players[0]!.name, createdAt: l.createdAt,
hostId: l.players[0]!.id, account: !!l.players[0]!.account }));
}
createLobby(modeId: string, player: { name: unknown; secret: unknown }): SeatTicket {
/** Look up a private (or public) waiting lobby by its invite code: what an invite link shows. */
invite(code: string) {
this.sweep();
const l = typeof code === 'string' && INVITE.test(code) ? [...this.lobbies.values()].find(x => x.invite === code) : undefined;
if (!l) throw new GameError(404, 'Invite not found or expired.');
return { lobbyId: l.id, phase: l.phase, open: l.phase === 'waiting', host: this.identity,
mode: { id: l.mode.id, version: l.mode.version, name: l.mode.name, engine: l.mode.engine },
createdBy: l.players[0]!.name, createdAt: l.createdAt, accountRequired: requiresAccount(l.mode) };
}
async createLobby(modeId: string, request: SeatRequest): Promise<SeatTicket> {
const h = this.mode(modeId);
this.sweep();
this.checkCapacity(h);
const p = await this.seat(h, request);
if (h.mode.decks.kind === 'constructed') await this.resolveDeck(h, p.player, request.deck);
return this.openLobby(h, p, request.private === true);
}
async join(lobbyId: string, request: SeatRequest): Promise<SeatTicket> {
const l = this.lobby(lobbyId);
this.sweep();
if (l.phase !== 'waiting') throw new GameError(409, 'This lobby is no longer open.');
const h = this.mode(l.mode.id);
const p = await this.seat(h, request);
const cards = h.mode.decks.kind === 'constructed' ? await this.resolveDeck(h, p.player, request.deck) : undefined;
return this.seatInLobby(l, p, cards);
}
/**
* Quick match: join the oldest open public lobby of this mode that someone else opened,
* else open a new public lobby and wait. No rating window (the ladder is small).
*/
async quickMatch(modeId: string, request: SeatRequest): Promise<SeatTicket & { matched: boolean }> {
const h = this.mode(modeId);
this.sweep();
const p = await this.seat(h, request);
const cards = h.mode.decks.kind === 'constructed' ? await this.resolveDeck(h, p.player, request.deck) : undefined;
const candidates = [...this.lobbies.values()].filter(l => l.mode.id === modeId && l.phase === 'waiting' && !l.private &&
l.players[0]!.id !== p.player.id).sort((a, b) => a.createdAt - b.createdAt);
for (const l of candidates) {
if (l.phase !== 'waiting') continue;
// A stale lobby (its host's cards moved) is expired and skipped: not the quick-matcher's fault.
try { return { ...await this.seatInLobby(l, p, cards), matched: true }; }
catch (e) { if (e instanceof StaleLobby) continue; throw e; }
}
this.checkCapacity(h);
return { ...this.openLobby(h, p, false), matched: false };
}
/** The lobby's current state version (see `view`). */
version(lobbyId: string): number { return this.lobby(lobbyId).version; }
private checkCapacity(h: HostedMode) {
const active = [...this.lobbies.values()].filter(l => l.phase !== 'finished' && l.phase !== 'expired');
if (active.length >= this.maxLobbies) throw new GameError(503, 'This host is full; try again later.');
if (active.filter(l => l.mode.id === modeId).length >= h.mode.limits.maxConcurrentMatches) {
if (active.filter(l => l.mode.id === h.mode.id).length >= h.mode.limits.maxConcurrentMatches) {
throw new GameError(503, 'This mode is at its match limit on this host; try again later.');
}
const p = this.player(player);
}
private openLobby(h: HostedMode, p: { player: Player; token: string }, isPrivate: boolean): SeatTicket {
const active = [...this.lobbies.values()].filter(l => l.phase !== 'finished' && l.phase !== 'expired');
if (active.filter(l => l.players.some(x => x.id === p.player.id)).length >= 3) {
throw new GameError(429, 'Too many open lobbies or matches for this player.');
}
const id = randomBytes(12).toString('hex');
const invite = randomBytes(9).toString('base64url');
const now = this.now();
this.lobbies.set(id, { id, mode: h.mode, rules: h.rules, seed: randomBytes(16).toString('hex'), createdAt: now,
players: [p.player], phase: 'waiting', actions: [], lastMove: now });
return { lobbyId: id, seat: 0, token: p.token };
version: 1, private: isPrivate, invite, players: [p.player], phase: 'waiting', actions: [], lastMove: now });
return { lobbyId: id, seat: 0, token: p.token, invite, playerId: p.player.id };
}
async join(lobbyId: string, player: { name: unknown; secret: unknown }): Promise<SeatTicket> {
const l = this.lobby(lobbyId);
this.sweep();
/** Seat a prepared player in a waiting lobby and start the draft or match. Synchronous until claimed. */
private async seatInLobby(l: Lobby, p: { player: Player; token: string }, joinerCards?: ChainCard[]): Promise<SeatTicket> {
// Re-check after the caller's awaits: another join may have claimed the lobby meanwhile.
if (l.phase !== 'waiting') throw new GameError(409, 'This lobby is no longer open.');
const p = this.player(player);
if (l.players[0]!.id === p.player.id) throw new GameError(409, 'You cannot play against yourself.');
l.players.push(p.player);
l.lastMove = this.now();
const h = this.mode(l.mode.id);
// Claim the lobby before any await, so a concurrent join can't also pass the 'waiting' check.
l.phase = 'starting';
if (l.mode.decks.kind === 'draft') this.startDraft(l);
else await this.startMatch(l, [this.engine.starterDeck(l.rules, `${l.seed}:0`), this.engine.starterDeck(l.rules, `${l.seed}:1`)]);
return { lobbyId: l.id, seat: 1, token: p.token };
l.lastMove = this.now();
const policy = h.mode.decks;
// The creator's cards may have moved since they opened the lobby: resolve them again now,
// at match start, before the joiner is seated (a stale lobby never lists the joiner).
const creatorCards = policy.kind === 'constructed'
? await this.resolveDeck(h, l.players[0]!, l.players[0]!.deckIds).catch(e => {
this.expire(l); throw new StaleLobby(`The lobby host's deck is no longer valid: ${(e as Error).message}`.slice(0, 200)); })
: undefined;
l.players.push(p.player);
l.rated = h.mode.limits.rated && l.players.every(x => x.account);
this.bump(l);
if (policy.kind === 'draft' && policy.source === 'collections') {
const pools = await Promise.all(l.players.map(x => this.ownershipCall(() => this.ownership!.collection(x.account!))))
.catch(e => { this.expire(l); throw e; });
const size = h.engine.deckSize(l.rules);
pools.forEach((c, seat) => { if (c.length < size) { this.expire(l);
throw new GameError(409, `${seat === 0 ? 'The lobby host' : 'You'} own${seat === 0 ? 's' : ''} ${c.length} / ${size} cards: both players must be eligible to draft.`); } });
const cards = seededShuffle([...pools[0]!, ...pools[1]!], `${l.seed}:pool`).slice(0, policy.poolSize)
.map(c => h.engine.fromChain!(l.rules, c));
this.startDraft(l, cards);
} else if (policy.kind === 'draft') this.startDraft(l, h.engine.previewPool(l.rules, `${l.seed}:pool`, policy.poolSize));
else if (policy.kind === 'constructed') {
const decks = [creatorCards!, joinerCards!];
l.tokens = [decks[0]!.map(c => c.tokenId), decks[1]!.map(c => c.tokenId)];
await this.startMatch(l, [decks[0]!.map(c => h.engine.fromChain!(l.rules, c)), decks[1]!.map(c => h.engine.fromChain!(l.rules, c))]);
} else await this.startMatch(l, [h.engine.starterDeck(l.rules, `${l.seed}:0`), h.engine.starterDeck(l.rules, `${l.seed}:1`)]);
return { lobbyId: l.id, seat: 1, token: p.token, invite: l.invite, playerId: p.player.id };
}
/** Public status, plus the seat's private view when a valid token is given. */
view(lobbyId: string, token?: string) {
/**
* Public status, plus the seat's private view when a valid token is given.
* With `since` equal to the lobby's current version, returns null (the router sends 204).
*/
view(lobbyId: string, token?: string, since?: number) {
const l = this.lobby(lobbyId);
this.sweep();
if (since !== undefined && since === l.version) return null;
const engine = this.mode(l.mode.id).engine;
const seat = token ? this.seatFor(l, token) : null;
const base = { lobbyId: l.id, phase: l.phase, host: this.identity,
mode: { id: l.mode.id, version: l.mode.version, name: l.mode.name },
players: l.players.map(p => ({ id: p.id, name: p.name })), seat, matchId: l.matchId ?? null,
const base = { lobbyId: l.id, version: l.version, phase: l.phase, host: this.identity,
mode: { id: l.mode.id, version: l.mode.version, name: l.mode.name, engine: l.mode.engine },
players: l.players.map(p => ({ id: p.id, name: p.name, account: !!p.account })), seat, matchId: l.matchId ?? null,
rated: l.rated ?? false, private: l.private ?? false, invite: seat === 0 ? l.invite ?? null : undefined,
outcome: l.outcome ?? null };
if (l.phase === 'drafting' && l.draft) {
if (l.phase === 'drafting' && l.draft && seat !== null) {
const d = l.draft;
return { ...base, draft: { pool: d.pool.map((c, i) => ({ index: i, card: this.engine.cardSummary(c), takenBy: d.taken[i] })),
return { ...base, draft: { pool: d.pool.map((c, i) => ({ index: i, card: engine.cardSummary(c), takenBy: d.taken[i] })),
toPick: d.order[d.turn] ?? null, deadline: d.deadline } };
}
if ((l.phase === 'playing' || l.phase === 'finished') && l.state !== undefined && seat !== null) {
return { ...base, state: this.engine.viewFor(l.state, seat),
legalActions: l.phase === 'playing' ? this.engine.legalActions(l.state, seat) : [] };
return { ...base, clock: l.phase === 'playing' ? { turnStartedAt: l.turnStartedAt ?? null, turnMs: this.turnMs(l), bankMs: l.bank ?? null } : null,
state: engine.viewFor(l.state, seat),
legalActions: l.phase === 'playing' ? engine.legalActions(l.state, seat) : [] };
}
return base;
}
@@ -184,7 +307,7 @@ export class ModeHost {
this.sweep();
if (l.phase !== 'playing' || l.state === undefined) throw new GameError(409, 'No match in progress.');
// The host never trusts a client action: it must be one of the engine's legal actions.
const legal = this.engine.legalActions(l.state, seat);
const legal = this.mode(l.mode.id).engine.legalActions(l.state, seat);
const chosen = legal.find(a => isDeepStrictEqual(a, action));
if (chosen === undefined) throw new GameError(400, 'Illegal action.');
this.apply(l, seat, chosen);
@@ -195,10 +318,11 @@ export class ModeHost {
resign(lobbyId: string, token: string) {
const l = this.lobby(lobbyId);
const seat = this.requireSeat(l, token);
if (l.phase === 'waiting') { l.phase = 'expired'; return this.view(lobbyId, token); }
if (l.phase === 'waiting') { this.expire(l); return this.view(lobbyId, token); }
if (l.phase !== 'playing' && l.phase !== 'drafting') throw new GameError(409, 'Nothing to resign.');
if (l.phase === 'playing' && l.state !== undefined && this.engine.concedeAction) {
this.apply(l, seat, this.engine.concedeAction(seat), 'resign');
const engine = this.mode(l.mode.id).engine;
if (l.phase === 'playing' && l.state !== undefined && engine.concedeAction) {
this.apply(l, seat, engine.concedeAction(seat), 'resign');
if ((l.phase as Phase) === 'finished') return this.view(lobbyId, token);
}
this.finish(l, seat === 0 ? 1 : 0, 'resign');
@@ -239,7 +363,11 @@ export class ModeHost {
if (typeof raw.id !== 'string' || !LOBBY_ID.test(raw.id) || this.lobbies.has(raw.id)) continue;
if (!['waiting', 'drafting', 'playing'].includes(raw.phase) || !Array.isArray(raw.players) || raw.players.length < 1 || raw.players.length > 2) continue;
const lobby: Lobby = { ...raw, mode: h.mode, rules: h.rules,
players: raw.players.map((p: any) => ({ id: String(p.id), name: String(p.name), seen: now, tokenHash: Buffer.from(String(p.tokenHash), 'hex') })),
players: raw.players.map((p: any) => ({ id: String(p.id), name: String(p.name), seen: now, tokenHash: Buffer.from(String(p.tokenHash), 'hex'),
...(p.account && typeof p.account.sub === 'string' && typeof p.account.issuer === 'string'
? { account: { sub: p.account.sub, issuer: p.account.issuer, name: String(p.account.name ?? p.name) } } : {}),
...(Array.isArray(p.deckIds) ? { deckIds: p.deckIds.map(String).slice(0, 64) } : {}) })),
version: Number.isSafeInteger(raw.version) ? raw.version : 1,
lastMove: now, createdAt: raw.phase === 'waiting' ? now : raw.createdAt, turnStartedAt: now };
if (lobby.players.some(p => p.tokenHash.length !== 32)) continue;
if (lobby.draft && lobby.mode.decks.kind === 'draft') lobby.draft.deadline = now + lobby.mode.decks.pickSeconds * 1000;
@@ -255,16 +383,20 @@ export class ModeHost {
sweep(): void {
const now = this.now();
for (const l of this.lobbies.values()) {
if (l.phase === 'waiting' && now - l.createdAt > l.mode.limits.lobbyMinutes * 60_000) l.phase = 'expired';
const engine = this.hosted.get(l.mode.id)!.engine;
if (l.phase === 'waiting' && now - l.createdAt > l.mode.limits.lobbyMinutes * 60_000) this.expire(l);
else if (l.phase === 'drafting' && l.draft && now > l.draft.deadline) {
// Auto-pick the first free card for whoever is stalling; synchronous, no live data.
const idx = l.draft.taken.indexOf(null);
if (idx >= 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 => this.engine.legalActions(l.state, s).length > 0);
if (this.engine.timeoutAction) {
const waiting = ([0, 1] as Seat[]).filter(s => engine.legalActions(l.state, s).length > 0);
// 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, this.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');
@@ -273,17 +405,17 @@ export class ModeHost {
}
}
private startDraft(l: Lobby) {
private startDraft(l: Lobby, pool: unknown[]) {
if (l.mode.decks.kind !== 'draft') return;
const size = this.engine.deckSize(l.rules);
const pool = this.engine.previewPool(l.rules, `${l.seed}:pool`, l.mode.decks.poolSize);
if (pool.length < 2 * size) throw new GameError(500, 'Engine returned a short draft pool.');
const size = this.mode(l.mode.id).engine.deckSize(l.rules);
if (pool.length < 2 * size) { this.expire(l); throw new GameError(409, `The draft pool has only ${pool.length} cards; it needs ${2 * size}.`); }
// Snake order 0,1,1,0,0,1,... with a seed-chosen first picker.
const first: Seat = parseInt(l.seed.slice(0, 2), 16) % 2 === 0 ? 0 : 1;
const order: Seat[] = [];
for (let i = 0; i < 2 * size; i++) order.push(((Math.floor((i + 1) / 2) % 2 === 0 ? first : 1 - first)) as Seat);
l.draft = { pool, taken: pool.map(() => null), order, turn: 0, deadline: this.now() + l.mode.decks.pickSeconds * 1000 };
l.phase = 'drafting';
this.bump(l);
}
private async takePick(l: Lobby, seat: Seat, index: number) {
@@ -291,6 +423,7 @@ export class ModeHost {
d.taken[index] = seat;
d.turn++;
l.lastMove = this.now();
this.bump(l);
if (l.mode.decks.kind === 'draft') d.deadline = this.now() + l.mode.decks.pickSeconds * 1000;
if (d.turn >= d.order.length) {
const decks: [unknown[], unknown[]] = [[], []];
@@ -300,34 +433,39 @@ export class ModeHost {
}
private async startMatch(l: Lobby, decks: [unknown[], unknown[]]) {
const engine = this.mode(l.mode.id).engine;
const mapped = await Promise.all(decks.map(d => this.mapDeck(l.mode, d))) as [unknown[], unknown[]];
for (const d of mapped) {
try { this.engine.validateDeck(l.rules, d); }
catch (e) { l.phase = 'expired'; throw new GameError(400, `Deck rejected by the engine: ${(e as Error).message}`.slice(0, 200)); }
try { engine.validateDeck(l.rules, d); }
catch (e) { this.expire(l); throw new GameError(400, `Deck rejected by the engine: ${(e as Error).message}`.slice(0, 200)); }
}
l.decks = mapped;
l.state = this.engine.createMatch(l.rules, mapped, l.seed);
l.state = engine.createMatch(l.rules, mapped, l.seed);
l.phase = 'playing';
l.startedAt = l.lastMove = l.turnStartedAt = this.now();
l.turn = this.engine.turnOf?.(l.state);
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;
if (this.engine.isOver(l.state)) { const r = this.engine.result(l.state); this.finish(l, r.winner, r.reason ?? 'complete'); }
this.bump(l);
if (engine.isOver(l.state)) { const r = engine.result(l.state); this.finish(l, r.winner, r.reason ?? 'complete'); }
}
/** Apply the mode's card-mapping preset. Bonus data is looked up once, before the match. */
private async mapDeck(mode: ModeDocument, deck: unknown[]): Promise<unknown[]> {
const mapping = mode.cards;
if (mapping.preset === 'standard' || !this.liveData) return deck;
const { engine, rules } = this.hosted.get(mode.id)!;
return Promise.all(deck.map(async card => {
const pageId = this.engine.cardPageId(card);
const pageId = engine.cardPageId(card);
if (pageId === null) return card;
const live = await this.liveData!(pageId).catch(() => null);
if (!live) return card;
// `live` and `trending`: freeze the live trend arrow onto the card (engine rules decide its effect).
let mapped = this.engine.applyLive ? this.engine.applyLive(this.hosted.get(mode.id)!.rules, card, live) : card;
let mapped = engine.applyLive ? engine.applyLive(rules, card, live) : card;
if (mapping.preset === 'trending') {
const bonus = trendBonus(mapping, live.trendPercent);
if (bonus !== 0) mapped = this.engine.withPower(mapped, clampPower(this.engine.cardPower(mapped) + bonus));
if (bonus !== 0) mapped = engine.withPower(mapped, clampPower(engine.cardPower(mapped) + bonus));
}
return mapped;
}));
@@ -335,18 +473,27 @@ export class ModeHost {
/** Apply an action already known to be legal (or host-issued), log it, and settle the match if over. */
private apply(l: Lobby, seat: Seat, action: unknown, reason?: string) {
l.state = this.engine.applyAction(l.state, seat, action);
const engine = this.mode(l.mode.id).engine;
l.state = engine.applyAction(l.state, seat, action);
l.actions.push({ seat, action });
l.lastMove = this.now();
const turn = this.engine.turnOf?.(l.state);
if (turn !== l.turn) { l.turn = turn; l.turnStartedAt = l.lastMove; }
if (this.engine.isOver(l.state)) { const r = this.engine.result(l.state); this.finish(l, r.winner, reason ?? r.reason ?? 'complete'); }
this.bump(l);
const turn = engine.turnOf?.(l.state);
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');
}
/** Turn timer: the engine's own per-turn limit plus a little network grace, else the mode's limit. */
private turnMs(l: Lobby): number {
const engineSeconds = this.engine.turnSeconds?.(l.rules);
const engineSeconds = this.mode(l.mode.id).engine.turnSeconds?.(l.rules);
return engineSeconds !== undefined ? (engineSeconds + 5) * 1000 : l.mode.limits.turnSeconds * 1000;
}
@@ -355,12 +502,63 @@ export class ModeHost {
l.phase = 'finished';
l.outcome = { winner, reason };
l.lastMove = this.now();
this.bump(l);
if (!l.decks || l.players.length !== 2) return; // Resigned during draft: no match record.
const matchId = randomBytes(16).toString('hex');
l.matchId = matchId;
this.store.add({ matchId, modeId: l.mode.id, modeVersion: l.mode.version, seed: l.seed, rules: l.rules,
players: l.players.map(p => ({ id: p.id, name: p.name })), winner, reason: reason.slice(0, 40),
startedAt: l.startedAt ?? l.createdAt, endedAt: l.lastMove, decks: l.decks, actions: l.actions });
this.store.add({ matchId, modeId: l.mode.id, modeVersion: l.mode.version, engine: l.mode.engine, rated: l.rated ?? false,
seed: l.seed, rules: l.rules,
players: l.players.map(p => ({ id: p.id, name: p.name, account: !!p.account })), winner, reason: reason.slice(0, 40),
startedAt: l.startedAt ?? l.createdAt, endedAt: l.lastMove, decks: l.decks, actions: l.actions,
...(l.tokens ? { tokens: l.tokens } : {}) });
}
private bump(l: Lobby) { l.version = (l.version ?? 0) + 1; }
private expire(l: Lobby) {
if (l.phase === 'finished' || l.phase === 'expired') return;
l.phase = 'expired'; l.lastMove = this.now(); this.bump(l);
}
/** Verify the seat: an eom.dev account (ID token) or, where the mode allows guests, a secret. */
private async seat(h: HostedMode, input: SeatRequest): Promise<{ player: Player; token: string }> {
const token = randomBytes(24).toString('base64url');
if (input.idToken !== undefined && input.idToken !== null && input.idToken !== '') {
if (!this.ownership) throw new GameError(503, 'eom.dev accounts are not available on this host.');
const account = await this.ownershipCall(() => this.ownership!.verifyAccount(input.idToken));
const id = createHash('sha256').update(`acct:${account.issuer}\n${account.sub}`).digest('hex');
const name = displayName(account.name || account.username || '') ?? 'Player';
return { player: { id, name, tokenHash: hashToken(token), seen: this.now(),
account: { sub: account.sub, issuer: account.issuer, name } }, token };
}
if (requiresAccount(h.mode)) throw new GameError(401, 'This mode plays with cards you own: log in with your eom.dev account.');
return this.player(input, token);
}
/** Resolve a seat's submitted token ids to owned, confirmed chain cards (#57). */
private async resolveDeck(h: HostedMode, p: Player, tokenIds: unknown): Promise<ChainCard[]> {
if (h.mode.decks.kind !== 'constructed') return [];
if (!this.ownership || !p.account) throw new GameError(401, 'Log in with your eom.dev account to play your own cards.');
const deckSize = h.engine.deckSize(h.rules);
if (!Array.isArray(tokenIds) || tokenIds.length !== deckSize || !tokenIds.every(t => typeof t === 'string' && t.length <= 128)) {
throw new GameError(400, `A deck is exactly ${deckSize} card token ids you own.`);
}
const cards = await this.ownershipCall(() => this.ownership!.resolveDeck(p.account!, tokenIds,
{ deckSize, maxCopiesPerPage: h.engine.copyLimit?.(h.rules) ?? 4, minConfirmations: h.mode.decks.kind === 'constructed' ? h.mode.decks.minConfirmations : 1 }));
// Belt and braces: the ownership layer must hand back exactly the submitted tokens.
if (cards.length !== deckSize || cards.some((c, i) => c.tokenId !== tokenIds[i])) throw new GameError(500, 'Ownership check returned a different deck.');
p.deckIds = [...tokenIds as string[]];
return cards;
}
/** Pass player-facing ownership errors (status 4xx) through; anything else is a 503. */
private async ownershipCall<T>(fn: () => Promise<T>): Promise<T> {
try { return await fn(); }
catch (e) {
if (e instanceof GameError) throw e;
const status = (e as { status?: unknown })?.status;
if (typeof status === 'number' && status >= 400 && status < 500) throw new GameError(status, String((e as Error).message).slice(0, 200));
throw new GameError(503, 'Could not check accounts or ownership right now; try again.');
}
}
private mode(modeId: string): HostedMode {
@@ -373,12 +571,11 @@ export class ModeHost {
if (!l) throw new GameError(404, 'Lobby not found.');
return l;
}
private player(input: { name: unknown; secret: unknown }): { player: Player; token: string } {
private player(input: SeatRequest, token: string): { player: Player; token: string } {
const name = typeof input.name === 'string' ? input.name.trim() : '';
if (!NAME.test(name)) throw new GameError(400, 'Name must be 1-24 letters, digits, spaces, _ . or -');
if (typeof input.secret !== 'string' || !SECRET.test(input.secret)) throw new GameError(400, 'Invalid player secret.');
const id = createHash('sha256').update(`wikideck-player:${input.secret}`).digest('hex');
const token = randomBytes(24).toString('base64url');
return { player: { id, name, tokenHash: hashToken(token), seen: this.now() }, token };
}
private seatFor(l: Lobby, token: string): Seat | null {
@@ -394,3 +591,24 @@ export class ModeHost {
}
function hashToken(token: string): Buffer { return createHash('sha256').update(token).digest(); }
/** An account display name reduced to the lobby name alphabet; null if nothing is left. */
function displayName(raw: string): string | null {
const cleaned = raw.normalize('NFC').replace(/[^\p{L}\p{N} _.\-]/gu, '').replace(/\s+/g, ' ').trim().slice(0, 24).trim();
return NAME.test(cleaned) ? cleaned : null;
}
/** Deterministic Fisher-Yates from a seed (SHA-256 counter stream): replayable draft pools. */
export function seededShuffle<T>(items: T[], seed: string): T[] {
const out = [...items];
let counter = 0, buf = Buffer.alloc(0), off = 0;
const next32 = () => {
if (off + 4 > buf.length) { buf = createHash('sha256').update(`${seed}:${counter++}`).digest(); off = 0; }
const v = buf.readUInt32BE(off); off += 4; return v;
};
for (let i = out.length - 1; i > 0; i--) {
const j = next32() % (i + 1);
[out[i], out[j]] = [out[j]!, out[i]!];
}
return out;
}
+113
View File
@@ -0,0 +1,113 @@
// 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
@@ -0,0 +1,204 @@
// 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];
}));
},
};
}
+47 -6
View File
@@ -4,22 +4,47 @@
*/
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';
import { createGameRouter } from './router.ts';
import { MatchStore } from './store.ts';
import type { EnginePort } from './engine-port.ts';
import type { EnginePort, OwnershipPort } from './engine-port.ts';
import type { EngineId } from '../../shared/game/modes.ts';
import { TrendCache } from './trends.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 } }> };
export async function gameRouter(options: { dataDir: string | null; enrichment?: Enrichment;
engine?: EnginePort<any, any, any, any>; env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean }): Promise<express.Router> {
/** The Edit War engine (default: the real binding). */
engine?: EnginePort<any, any, any, any>;
/** Extra engines by id, e.g. `{ duel }` (tests inject stubs). */
engines?: Partial<Record<EngineId, EnginePort<any, any, any, any>>>;
/** Account verification + server-side ownership, adapted from server/game/ownership.ts (#57). */
ownershipPort?: OwnershipPort;
/** Server-side ownership deps (#57): http.ts passes `{ledger, accounts, verifyIdToken}`; adapted to the port here. */
ownership?: OwnershipDeps;
env?: NodeJS.ProcessEnv; warmTrends?: boolean; handleSignals?: boolean }): Promise<express.Router> {
const env = options.env ?? process.env;
const engine = options.engine ?? (await import('./engine-binding.ts')).engineBinding;
const modes = loadModes(env);
const engines: Partial<Record<EngineId, EnginePort<any, any, any, any>>> = { 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')) {
@@ -36,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, engine,
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;
+23 -8
View File
@@ -1,12 +1,27 @@
{
"schema": "wikideck.mode/1",
"id": "classic",
"schema": "wikideck.mode/2",
"version": 1,
"name": "Classic",
"description": "The base WikiDeck rules with starter decks. Cards use their at-mint snapshot stats.",
"tags": ["base", "starter"],
"engine": "duel",
"rules": {},
"cards": { "preset": "standard" },
"decks": { "kind": "starter" },
"limits": { "maxConcurrentMatches": 32, "turnSeconds": 90, "lobbyMinutes": 15 }
"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": "constructed",
"minConfirmations": 3
},
"limits": {
"maxConcurrentMatches": 32,
"turnSeconds": 90,
"lobbyMinutes": 15,
"rated": true,
"accountsOnly": true
}
}
+13 -12
View File
@@ -1,28 +1,29 @@
{
"schema": "wikideck.mode/1",
"id": "draft",
"schema": "wikideck.mode/2",
"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"
],
"rules": {
"deckSize": 10,
"openingHand": 4
},
"cards": {
"preset": "standard"
},
"decks": {
"kind": "draft",
"poolSize": 30,
"pickSeconds": 30
"source": "collections",
"poolSize": 100,
"pickSeconds": 20
},
"limits": {
"maxConcurrentMatches": 16,
"turnSeconds": 90,
"lobbyMinutes": 15
"lobbyMinutes": 15,
"rated": false,
"accountsOnly": true
}
}
+30
View File
@@ -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
}
}
+30
View File
@@ -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
}
}
+24
View File
@@ -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
}
}
+12 -14
View File
@@ -1,29 +1,27 @@
{
"schema": "wikideck.mode/1",
"id": "trending",
"schema": "wikideck.mode/2",
"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"
],
"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
}
}
+211
View File
@@ -0,0 +1,211 @@
/**
* Server-side ownership for constructed play (Night 2, #57). Signature agreed with host-pvp (#56).
*
* The host never trusts card data from a client. A deck arrives as token ids only; each one
* must be on the canonical chain, owned by one of the account's linked wallets, and confirmed
* enough. The card is then rebuilt from its own block (article + mint stats snapshot).
*
* Off-chain only: nothing here moves, burns or locks a card, and nothing touches consensus.
* No Wikipedia calls; the only I/O is the injected ID-token verifier (Dex JWKS, cached).
*/
import type { Account } from '../account/store.ts';
import type { Article } from '../../shared/protocol.ts';
import type { MintStatsSnapshot } from '../../shared/enrichment.ts';
import type { TestnetBlock } from '../../shared/testnet.ts';
export type OwnershipRules = {
/** Exact deck size for constructed play. Production is 40; a testnet mode file may lower it. */
deckSize: number;
/** MTG-style copy limit: cards minted from the same Wikipedia pageId. */
maxCopiesPerPage: number;
/** Minimum confirmations of each card's mint block (1 casual, 3 rated). */
minConfirmations: number;
};
export const DEFAULT_OWNERSHIP_RULES: Readonly<OwnershipRules> = Object.freeze({ deckSize: 40, maxCopiesPerPage: 4, minConfirmations: 1 });
export const RATED_MIN_CONFIRMATIONS = 3;
/** Upper bound on any deck request we will even look at (a deck is 40; this only guards the loop). */
export const MAX_DECK_TOKENS = 200;
/** Guard against an unbounded collection. Far above anything the chain can mint for one player soon. */
export const MAX_COLLECTION = 20_000;
/** server/testnet/ledger.ts MAX_DECK_PAGE. */
const PAGE = 24;
/** A tip change mid-scan restarts the scan; give up after this many rather than loop forever. */
const MAX_RESTARTS = 4;
// Structural: server/testnet/ledger.ts `Ledger` and server/account/store.ts `AccountStore`
// satisfy these, and tests pass in-memory fixtures.
export type OwnershipLedger = {
nft(tokenId: string): { block: TestnetBlock; owner: string; sequence: number; confirmations: number } | undefined;
deck(address: string, offset: number, limit: number): {
tip: string; total: number; next: number | null;
nfts: { block: TestnetBlock; sequence: number; confirmations: number }[];
};
summary(): { tip: string; height: number };
};
export type OwnershipAccounts = { wallets(sub: string): { address: string }[]; upsert?(a: Account): void };
export type OwnershipDeps = {
ledger: OwnershipLedger;
accounts: OwnershipAccounts;
/** server/account/router.ts accountVerifier(); throws an error with status 401 for a bad token. */
verifyIdToken(idToken: string): Promise<Account>;
};
/** One owned NFT as built from its canonical block (never from client JSON). */
export type ChainCard = {
tokenId: string;
/** Current owner (after transfers), one of the account's linked wallets. */
owner: string;
confirmations: number;
pageId: number;
title: string;
revisionId: number;
url: string;
extract: string;
imageUrl?: string;
height: number;
blockHash: string;
createdAt: number;
powHash: string;
article: Article;
statsSnapshot: MintStatsSnapshot;
};
export type DeckErrorCode = 'auth' | 'size' | 'duplicate-token' | 'unknown-token' | 'not-owned' | 'unconfirmed' | 'copy-limit';
const STATUS: Record<DeckErrorCode, 400 | 401 | 403> = {
auth: 401, size: 400, 'duplicate-token': 400, 'unknown-token': 400, 'not-owned': 403, unconfirmed: 400, 'copy-limit': 400,
};
export class DeckError extends Error {
readonly code: DeckErrorCode;
/** Every offending token of this class, so the UI can highlight them. */
readonly tokenIds: string[];
readonly status: 400 | 401 | 403;
readonly pageId?: number;
constructor(code: DeckErrorCode, message: string, tokenIds: string[] = [], pageId?: number) {
super(message);
this.name = 'DeckError';
this.code = code; this.tokenIds = tokenIds; this.status = STATUS[code];
if (pageId !== undefined) this.pageId = pageId;
}
}
/** Thrown when Dex or the ledger cannot answer right now (not the player's fault). */
export class OwnershipUnavailable extends Error { readonly status = 503; }
const TOKEN = /^[a-f0-9]{64}$/;
const isInt = (n: unknown, min: number, max: number): n is number => Number.isSafeInteger(n) && (n as number) >= min && (n as number) <= max;
/** Merges partial rules over the defaults and rejects nonsense (mode files are data, so validate). */
export function ownershipRules(rules: Partial<OwnershipRules> = {}): OwnershipRules {
const defined = Object.fromEntries(Object.entries(rules).filter(([, v]) => v !== undefined)) as Partial<OwnershipRules>;
const r = { ...DEFAULT_OWNERSHIP_RULES, ...defined };
if (!isInt(r.deckSize, 1, MAX_DECK_TOKENS)) throw new RangeError(`deckSize must be 1..${MAX_DECK_TOKENS}`);
if (!isInt(r.maxCopiesPerPage, 1, MAX_DECK_TOKENS)) throw new RangeError(`maxCopiesPerPage must be 1..${MAX_DECK_TOKENS}`);
if (!isInt(r.minConfirmations, 1, 1_000_000)) throw new RangeError('minConfirmations must be >= 1');
return r;
}
/** Builds the card from the canonical block. `owner` is the current owner from the index, not the miner. */
export function cardFromChain(nft: { block: TestnetBlock; confirmations: number }, owner: string): ChainCard {
const b = structuredClone(nft.block);
const card: ChainCard = { tokenId: b.tokenId, owner, confirmations: nft.confirmations,
pageId: b.article.pageId, title: b.article.title, revisionId: b.article.revisionId, url: b.article.url, extract: b.article.extract,
height: b.height, blockHash: b.hash, createdAt: b.createdAt, powHash: b.powHash, article: b.article, statsSnapshot: b.statsSnapshot };
if (b.article.image) card.imageUrl = b.article.image;
return card;
}
/** Verifies a Dex ID token from a request body. Throws DeckError('auth') or OwnershipUnavailable. */
export async function verifyAccount(deps: Pick<OwnershipDeps, 'verifyIdToken'>, idToken: unknown): Promise<Account> {
if (typeof idToken !== 'string' || !idToken || idToken.length > 8192) throw new DeckError('auth', 'Log in with your eom.dev account to play with your cards');
try { return await deps.verifyIdToken(idToken); }
catch (e) {
if ((e as { status?: number }).status === 401) throw new DeckError('auth', (e as Error).message || 'Log in again with your eom.dev account');
throw new OwnershipUnavailable('eom.dev login is temporarily unavailable');
}
}
/**
* Verifies a constructed deck for an already-verified account. Resolves to the cards in the
* order given, or throws the first class of DeckError found (listing every offending token).
*/
export async function resolveDeck(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, account: Pick<Account, 'sub'>, tokenIds: unknown,
opts?: Partial<OwnershipRules>): Promise<ChainCard[]> {
const r = ownershipRules(opts);
if (!Array.isArray(tokenIds) || tokenIds.length > MAX_DECK_TOKENS) throw new DeckError('size', `A deck is exactly ${r.deckSize} cards`);
const invalid = tokenIds.filter(t => typeof t !== 'string' || !TOKEN.test(t)).map(t => String(t).slice(0, 80)).slice(0, 10);
if (invalid.length) throw new DeckError('unknown-token', 'Invalid card identifier', invalid);
const ids = tokenIds as string[];
if (ids.length !== r.deckSize) throw new DeckError('size', `A deck is exactly ${r.deckSize} cards (got ${ids.length})`);
const seen = new Set<string>(), dupes = new Set<string>();
for (const id of ids) (seen.has(id) ? dupes : seen).add(id);
if (dupes.size) throw new DeckError('duplicate-token', 'The same card appears more than once', [...dupes]);
const wallets = new Set(deps.accounts.wallets(account.sub).map(w => w.address));
if (!wallets.size) throw new DeckError('not-owned', 'Link a wallet to your eom.dev account to play with your cards', ids);
const cards: ChainCard[] = [], missing: string[] = [], foreign: string[] = [], young: string[] = [];
for (const id of ids) {
const nft = deps.ledger.nft(id);
if (!nft || nft.block.tokenId !== id) { missing.push(id); continue; }
if (!wallets.has(nft.owner)) { foreign.push(id); continue; }
if (nft.confirmations < r.minConfirmations) { young.push(id); continue; }
cards.push(cardFromChain(nft, nft.owner));
}
if (missing.length) throw new DeckError('unknown-token', 'Card not found on the canonical chain', missing);
if (foreign.length) throw new DeckError('not-owned', 'Card is not owned by a wallet linked to this account', foreign);
if (young.length) throw new DeckError('unconfirmed', `Card needs ${r.minConfirmations} confirmation${r.minConfirmations === 1 ? '' : 's'}`, young);
const byPage = new Map<number, string[]>();
for (const c of cards) byPage.set(c.pageId, [...(byPage.get(c.pageId) ?? []), c.tokenId]);
for (const [pageId, tokens] of byPage)
if (tokens.length > r.maxCopiesPerPage) throw new DeckError('copy-limit', `At most ${r.maxCopiesPerPage} copies of the same article`, tokens, pageId);
return cards;
}
/**
* Every card the account owns across its linked wallets, read at one canonical tip (restarting
* if the tip moves), with no snapshot cap. Only cards with `minConfirmations` (default 1).
*/
export async function collection(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, account: Pick<Account, 'sub'>,
opts: { minConfirmations?: number } = {}): Promise<ChainCard[]> {
return collectionAt(deps, account, opts).cards;
}
/** collection() plus the tip and wallets it was read at. Synchronous. */
export function collectionAt(deps: Pick<OwnershipDeps, 'ledger' | 'accounts'>, account: Pick<Account, 'sub'>,
opts: { minConfirmations?: number } = {}): { tip: string; wallets: string[]; cards: ChainCard[] } {
const minConfirmations = ownershipRules({ minConfirmations: opts.minConfirmations }).minConfirmations;
const wallets = [...new Set(deps.accounts.wallets(account.sub).map(w => w.address))];
for (let attempt = 0; attempt <= MAX_RESTARTS; attempt++) {
const tip = deps.ledger.summary().tip;
const cards = scan(deps.ledger, wallets, tip, minConfirmations);
if (cards) return { tip, wallets, cards };
}
throw new OwnershipUnavailable('The chain is moving too fast to read a consistent collection; try again');
}
/** Returns null if the tip moved during the scan. */
function scan(ledger: OwnershipLedger, wallets: string[], tip: string, minConfirmations: number): ChainCard[] | null {
const cards: ChainCard[] = [];
for (const address of wallets) {
let offset: number | null = 0;
while (offset !== null) {
const page = ledger.deck(address, offset, PAGE);
if (page.tip !== tip) return null;
for (const nft of page.nfts) {
if (nft.confirmations >= minConfirmations) cards.push(cardFromChain(nft, address));
if (cards.length > MAX_COLLECTION) throw new OwnershipUnavailable('Collection too large to list');
}
// Defensive: a page that makes no progress would loop forever.
offset = page.next !== null && page.next > offset ? page.next : null;
}
}
return cards;
}
/** How many of these cards a legal deck could use under the copy limit: Σ min(copies, limit) per pageId. */
export function playableCount(cards: Pick<ChainCard, 'pageId'>[], maxCopiesPerPage: number): number {
const perPage = new Map<number, number>();
for (const c of cards) perPage.set(c.pageId, (perPage.get(c.pageId) ?? 0) + 1);
let n = 0; for (const count of perPage.values()) n += Math.min(count, maxCopiesPerPage);
return n;
}
+27 -6
View File
@@ -40,17 +40,38 @@ export function createGameRouter(host: ModeHost, discovery: ModeDiscovery): expr
return { hosts: rows };
}));
r.get('/modes/:modeId/leaderboard', reads, wrap(req => host.leaderboard(String(req.params.modeId))));
// Same body; entries carry `rating` (Elo, null if unrated) plus W/L.
r.get('/modes/:modeId/ladder', reads, wrap(req => host.leaderboard(String(req.params.modeId))));
r.get('/modes/:modeId/lobbies', reads, wrap(req => ({ lobbies: host.openLobbies(String(req.params.modeId)) })));
r.post('/modes/:modeId/lobbies', writes, wrap((req, res) => {
// Seat bodies: `{name, secret}` for guests (Edit War only), or `{idToken}` for an eom.dev account
// (the Dex ID token travels in the body: Authorization carries seat tokens). Constructed
// modes add `deck: tokenId[]`; `private: true` hides the lobby (join it by invite code).
const seat = (req: Request) => {
const b = body(req);
// Also accept the Dex ID token as `Authorization: Bearer <jwt>` on seat-creating routes: a
// JWT (three dot-separated parts) can never match the seat-token format above.
const m = /^Bearer ([A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)$/.exec(req.get('authorization') ?? '');
return { name: b.name, secret: b.secret, idToken: b.idToken ?? m?.[1], deck: b.deck, private: b.private };
};
r.post('/modes/:modeId/lobbies', writes, wrap(async (req, res) => {
const ticket = await host.createLobby(String(req.params.modeId), seat(req));
res.status(201);
return host.createLobby(String(req.params.modeId), { name: b.name, secret: b.secret });
return ticket;
}));
r.post('/lobbies/:lobbyId/join', writes, wrap(req => {
const b = body(req);
return host.join(String(req.params.lobbyId), { name: b.name, secret: b.secret });
// Quick match: join the oldest open public lobby, else open one (`matched: false`) and poll it.
r.post('/modes/:modeId/quick', writes, wrap(req => host.quickMatch(String(req.params.modeId), seat(req))));
r.post('/lobbies/:lobbyId/join', writes, wrap(req => host.join(String(req.params.lobbyId), seat(req))));
// Invite links (/play/invite/<code> in the SPA) resolve here, then join by lobby id or code.
r.get('/invites/:code', reads, wrap(req => host.invite(String(req.params.code))));
r.post('/invites/:code/join', writes, wrap(req => host.join(host.invite(String(req.params.code)).lobbyId, seat(req))));
// Polling: `?v=<version>` from the last response returns 204 while nothing changed.
r.get('/lobbies/:lobbyId', plays, wrap((req, res) => {
const raw = typeof req.query.v === 'string' ? req.query.v : undefined;
const since = raw !== undefined && /^\d{1,15}$/.test(raw) ? Number(raw) : undefined;
const out = host.view(String(req.params.lobbyId), bearer(req) || undefined, since);
if (out === null) { res.status(204).end(); return; }
return out;
}));
r.get('/lobbies/:lobbyId', plays, wrap(req => host.view(String(req.params.lobbyId), bearer(req) || undefined)));
r.post('/lobbies/:lobbyId/pick', plays, wrap(req => host.pick(String(req.params.lobbyId), bearer(req), body(req).index)));
r.post('/lobbies/:lobbyId/actions', plays, wrap(req => host.act(String(req.params.lobbyId), bearer(req), body(req).action)));
r.post('/lobbies/:lobbyId/resign', writes, wrap(req => host.resign(String(req.params.lobbyId), bearer(req))));
+36 -6
View File
@@ -10,21 +10,42 @@ export const MatchRecordSchema = z.object({
matchId: z.string().regex(/^[a-f0-9]{32}$/),
modeId: z.string().max(40),
modeVersion: z.number().int(),
/** Engine the match ran on (absent in Night 1 records: `editwar`). */
engine: z.enum(['editwar', 'duel']).optional(),
/** Counted for Elo: the mode was rated and both seats were eom.dev accounts. */
rated: z.boolean().optional(),
/** Host-chosen seed. Together with decks and actions it lets anyone replay the match. */
seed: z.string().max(128),
/** The resolved ruleset the match ran under (mode overrides already applied). */
rules: z.unknown(),
players: z.array(z.object({ id: z.string().regex(/^[a-f0-9]{64}$/), name: z.string().max(24) }).strict()).length(2),
players: z.array(z.object({ id: z.string().regex(/^[a-f0-9]{64}$/), name: z.string().max(24),
account: z.boolean().optional() }).strict()).length(2),
winner: z.union([z.literal(0), z.literal(1), z.null()]),
reason: z.string().max(40),
startedAt: z.number().int(),
endedAt: z.number().int(),
decks: z.array(z.array(z.unknown()).max(64)).length(2),
actions: z.array(z.object({ seat: z.union([z.literal(0), z.literal(1)]), action: z.unknown() }).strict()).max(2000),
/** Constructed modes: the NFT token ids each seat played, in deck order (recap references). */
tokens: z.array(z.array(z.string().max(128)).max(64)).length(2).optional(),
}).strict();
export type MatchRecord = z.infer<typeof MatchRecordSchema>;
export type LeaderboardEntry = { playerId: string; name: string; wins: number; losses: number; draws: number; played: number };
export type LeaderboardEntry = { playerId: string; name: string; wins: number; losses: number; draws: number; played: number;
/** Elo (start 1200, K 24) from rated matches; null if the player has none in this mode. */
rating: number | null; ratedPlayed: number };
/** Elo constants (engineer review §3). Ratings are recomputed by replaying records in order. */
export const ELO_START = 1200;
export const ELO_K = 24;
/** New ratings for [seat0, seat1] after one game; winner null is a draw. */
export function eloUpdate(r0: number, r1: number, winner: 0 | 1 | null): [number, number] {
const e0 = 1 / (1 + 10 ** ((r1 - r0) / 400));
const s0 = winner === null ? 0.5 : winner === 0 ? 1 : 0;
const d = ELO_K * (s0 - e0);
return [r0 + d, r1 - d];
}
type ModeAgg = { matches: number; players: Map<string, LeaderboardEntry> };
const KEEP_RECENT = 500;
@@ -63,8 +84,10 @@ export class MatchStore {
leaderboard(modeId: string, limit = 20): LeaderboardEntry[] {
const players = [...(this.modes.get(modeId)?.players.values() ?? [])];
return players.sort((a, b) => b.wins - a.wins || a.losses - b.losses || b.played - a.played ||
a.playerId.localeCompare(b.playerId)).slice(0, limit).map(p => ({ ...p }));
// Rated players first, by Elo; then everyone else by W/L (the cut-order fallback).
return players.sort((a, b) => (b.rating ?? -Infinity) - (a.rating ?? -Infinity) || b.wins - a.wins || a.losses - b.losses ||
b.played - a.played || a.playerId.localeCompare(b.playerId)).slice(0, limit)
.map(p => ({ ...p, rating: p.rating === null ? null : Math.round(p.rating) }));
}
private index(r: MatchRecord): void {
@@ -72,13 +95,20 @@ export class MatchStore {
const agg = this.modes.get(r.modeId) ?? { matches: 0, players: new Map() };
this.modes.set(r.modeId, agg);
agg.matches++;
r.players.forEach((p, seat) => {
const entries = r.players.map((p, seat) => {
this.allPlayers.add(p.id);
const e = agg.players.get(p.id) ?? { playerId: p.id, name: p.name, wins: 0, losses: 0, draws: 0, played: 0 };
const e = agg.players.get(p.id) ?? { playerId: p.id, name: p.name, wins: 0, losses: 0, draws: 0, played: 0, rating: null, ratedPlayed: 0 };
e.name = p.name; e.played++;
if (r.winner === null) e.draws++; else if (r.winner === seat) e.wins++; else e.losses++;
agg.players.set(p.id, e);
return e;
});
// Elo only for rated matches between two account seats that actually played (no aborted 0-action games).
if (r.rated && r.players.every(p => p.account) && r.actions.length > 0 && r.reason !== 'abandoned') {
const [a, b] = entries as [LeaderboardEntry, LeaderboardEntry];
[a.rating, b.rating] = eloUpdate(a.rating ?? ELO_START, b.rating ?? ELO_START, r.winner);
a.ratedPlayed++; b.ratedPlayed++;
}
this.recent.set(r.matchId, r);
if (this.recent.size > KEEP_RECENT) this.recent.delete(this.recent.keys().next().value!);
}
+15 -9
View File
@@ -11,13 +11,14 @@ import { RandomX } from './randomx.ts';
import { Ledger } from './ledger.ts';
import { PeerNetwork } from './peers.ts';
import { wikipediaEnrichment } from '../enrichment.ts';
import { snapshotStats } from '../../shared/enrichment.ts';
import { wikipediaArticles } from '../wiki.ts';
import { configureWikimedia, mintPool, wikimediaStatus } from '../wikimedia/index.ts';
import { IS_MAINNET, PROFILE } from '../../shared/network.ts';
import { assertLaunchAllowed, launchManifest } from '../launch.ts';
import { resourceConfig, RpcBudget, RpcError } from '../resources.ts';
import { trustedProxies, operationsPort, startOperations } from '../operations.ts';
import { createAccountRouter } from '../account/router.ts';
import { accountVerifier, createAccountRouter } from '../account/router.ts';
import { AccountStore } from '../account/store.ts';
import { DexKeys, oidcConfig } from '../account/oidc.ts';
const root = fileURLToPath(new URL('../../', import.meta.url));
assertLaunchAllowed();
@@ -28,6 +29,7 @@ const apiBudget = new RpcBudget(limits);
const peerBudget = new RpcBudget({ ...limits, requestsPerSecond: 40, writesPerSecond: 10, active: 16 });
const dataDir = process.env.WIKIDECK_DATA_DIR ?? resolve(root,'data');
await mkdir(dataDir,{recursive:true});
configureWikimedia({dataDir});
// Never permit two processes to rewrite the same ledger. A stale lock requires operator review.
const lockPath = resolve(dataDir,`${PROFILE}-node.lock`);
const lock = await open(lockPath,'wx',0o600).catch(()=>{throw new Error('Data directory locked. Stop its other node; remove stale testnet-node.lock only after verifying no node is running.');});
@@ -119,9 +121,9 @@ const templateLimit=rateLimit({windowMs:60000,limit:20,standardHeaders:'draft-8'
app.post('/api/mining/template', templateLimit, async (req,res)=>{
const body=z.object({owner:z.string().regex(/^[a-f0-9]{64}$/),publicKey:z.string().max(256)}).strict().parse(req.body);
try {
const article=await wikipediaArticles.random();
const metrics=await wikipediaEnrichment.getFresh(article.pageId);
res.json(ledger.template(body.owner,body.publicKey,article,snapshotStats(metrics)));
// One fresh article+snapshot per tip, shared by every miner (server/wikimedia/pool.ts).
const {article,statsSnapshot}=await mintPool.take(ledger.summary().tip);
res.json(ledger.template(body.owner,body.publicKey,article,statsSnapshot));
} catch {
res.status(503).json({error:'Could not prepare a Wikipedia article and current statistics. Retry shortly.'});
}
@@ -150,8 +152,12 @@ app.post('/p2p/transaction',workLimit,async(req,res)=>{
const id=await ledger.submitTransaction(transaction);
res.status(202).json({id,status:'pending'});
});
app.use('/api/account',createAccountRouter({dataDir}));
app.use('/api/game',await (await import('../game/index.ts')).gameRouter({dataDir,enrichment:wikipediaEnrichment}));
// One account store and one Dex key cache, shared by the account and game routes (#57).
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}));
// 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')));
app.get('/{*path}',(_req,res)=>res.sendFile(resolve(root,'dist/index.html')));
@@ -170,7 +176,7 @@ const server=app.listen(port,host,()=>{
const operations=startOperations(opsPort,()=>({network:NETWORK,
ledger:ledger.diagnostics(),native:engine.diagnostics(),
peers:{configured:peers.status().length,connected:peers.status().filter(p=>p.connected).length},
rpc:{api:apiBudget.status(),p2p:peerBudget.status()}}),resolve(dataDir,PROFILE));
rpc:{api:apiBudget.status(),p2p:peerBudget.status()},wikimedia:wikimediaStatus()}),resolve(dataDir,PROFILE));
server.maxConnections=256;
server.headersTimeout=10000;
server.requestTimeout=15000;
+22 -10
View File
@@ -1,6 +1,6 @@
import { z } from 'zod';
import type { Article } from '../shared/protocol.ts';
import { ARTICLE_USER_AGENT, wikimediaUserAgent } from './wikimedia-user-agent.ts';
import { WikimediaClient, WikimediaUnavailable, wikimediaClient } from './wikimedia/client.ts';
const pageSchema = z.object({
pageid: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), ns: z.literal(0),
@@ -58,11 +58,23 @@ function pictureUrl(value: string | undefined): string | undefined {
} catch { return undefined; }
}
/** The exact W1 request. Its parameters decide minted article content: keep them byte-identical. */
export function randomArticlesUrl(): URL {
const url = new URL('https://en.wikipedia.org/w/api.php');
url.search = new URLSearchParams({ action: 'query', format: 'json', formatversion: '2',
generator: 'random', grnnamespace: '0', grnlimit: '10', prop: 'extracts|pageimages|info|categories',
exintro: '1', explaintext: '1', exchars: '900', piprop: 'thumbnail', pithumbsize: '800', cllimit: '20' }).toString();
return url;
}
export class WikipediaArticleSource {
private readonly fetcher: typeof globalThis.fetch;
private readonly client: WikimediaClient;
private active = 0;
constructor(fetcher: typeof globalThis.fetch = globalThis.fetch) { this.fetcher = fetcher; }
/** A bare fetch (tests) gets an unthrottled pass-through client; production uses the shared client. */
constructor(source: typeof globalThis.fetch | WikimediaClient = wikimediaClient) {
this.client = source instanceof WikimediaClient ? source : WikimediaClient.unthrottled(source);
}
async random(): Promise<Article> {
if (this.active >= 4) throw new Error('Wikipedia article service is busy');
@@ -70,12 +82,8 @@ export class WikipediaArticleSource {
try {
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
try {
const url = new URL('https://en.wikipedia.org/w/api.php');
url.search = new URLSearchParams({ action: 'query', format: 'json', formatversion: '2',
generator: 'random', grnnamespace: '0', grnlimit: '10', prop: 'extracts|pageimages|info|categories',
exintro: '1', explaintext: '1', exchars: '900', piprop: 'thumbnail', pithumbsize: '800', cllimit: '20' }).toString();
const response = await this.fetcher(url, { signal: AbortSignal.timeout(3500), redirect: 'error',
headers: { 'User-Agent': wikimediaUserAgent(ARTICLE_USER_AGENT), Accept: 'application/json' } });
// Mint lane, never cached: random articles become immutable chain data.
const { response } = await this.client.request(randomArticlesUrl(), { lane: 'mint', timeoutMs: 3500 });
const data = responseSchema.parse(await readJson(response));
for (const rawPage of data.query.pages) {
const parsedPage = pageSchema.safeParse(rawPage);
@@ -88,7 +96,11 @@ export class WikipediaArticleSource {
url: `https://en.wikipedia.org/?curid=${page.pageid}`, revisionId: page.lastrevid,
source: 'live', category: category(page.title, page.categories?.map(c => c.title) ?? []) };
}
} catch { /* Try another random API response, but keep the number of attempts bounded. */ }
} catch (error) {
// Throttled, paused or failing upstream: stop now rather than hammer it with retries.
if (error instanceof WikimediaUnavailable) throw error;
/* Otherwise try another random API response, but keep the number of attempts bounded. */
}
}
throw new Error('Wikipedia did not return an article with a picture after three attempts');
} finally {
+41 -6
View File
@@ -1,13 +1,48 @@
// User-Agent for Wikimedia API requests. Wikimedia asks automated clients to identify
// themselves with contact information; operators can opt in with WIKIDECK_USER_AGENT.
// Unset (or blank), each caller keeps its historical default string unchanged.
export const ARTICLE_USER_AGENT = 'Wikideck/0.1 (experimental Wikipedia article cards)';
export const ENRICHMENT_USER_AGENT = 'Wikideck/0.1 (Wikipedia off-chain page enrichment)';
// User-Agent for Wikimedia API requests. Wikimedia's User-Agent policy asks automated clients for a
// descriptive agent with contact details: `Tool/version (+https://site; contact) lib/version`.
// Operators set WIKIDECK_OPERATOR_CONTACT (an email address or URL); PUBLIC_ORIGIN is the fallback.
// WIKIDECK_USER_AGENT still overrides the whole string.
import { readFileSync } from 'node:fs';
export const PROJECT_URL = 'https://gitea.eom.dev/WikiDeck/wikideck';
const MAX_LENGTH = 256;
const SAFE = /^[\x20-\x7e]+$/;
function packageVersion(): string {
try {
const raw = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version?: unknown };
return typeof raw.version === 'string' && /^[\w.+-]{1,32}$/.test(raw.version) ? raw.version : '0';
} catch { return '0'; }
}
const VERSION = packageVersion();
/** The operator contact, or undefined when none (or only an unsafe value) is configured. */
export function operatorContact(env: Record<string, string | undefined> = process.env): string | undefined {
for (const value of [env.WIKIDECK_OPERATOR_CONTACT, env.PUBLIC_ORIGIN]) {
const trimmed = value?.trim();
if (trimmed && trimmed.length <= 128 && SAFE.test(trimmed) && !/[();]/.test(trimmed)) return trimmed;
}
return undefined;
}
/** `WikiDeck/<version> (+<project URL>; <contact>) node/<version>`. */
export function defaultUserAgent(env: Record<string, string | undefined> = process.env): string {
const contact = operatorContact(env);
return `WikiDeck/${VERSION} (+${PROJECT_URL}${contact ? `; ${contact}` : ''}) node/${process.versions.node}`;
}
export function wikimediaUserAgent(fallback: string, env: Record<string, string | undefined> = process.env): string {
const configured = env.WIKIDECK_USER_AGENT?.trim();
// Reject header-injection/control characters and oversized values; fall back to the default.
if (!configured || configured.length > MAX_LENGTH || !/^[\x20-\x7e]+$/.test(configured)) return fallback;
if (!configured || configured.length > MAX_LENGTH || !SAFE.test(configured)) return fallback;
return configured;
}
/** Start-up check: Wikimedia throttles or blocks clients without contact details first. */
export function warnIfNoContact(env: Record<string, string | undefined> = process.env,
warn: (message: string) => void = console.warn): boolean {
if (wikimediaUserAgent('', env) || operatorContact(env)) return false;
warn('[wikimedia] WARNING: no operator contact in the Wikimedia User-Agent. Set WIKIDECK_OPERATOR_CONTACT '
+ '(an email address or URL) or PUBLIC_ORIGIN; Wikimedia policy requires it and may block this node.');
return true;
}
+74
View File
@@ -0,0 +1,74 @@
/**
* On-disk HTTP cache for off-chain Wikimedia reads (`$WIKIDECK_DATA_DIR/wikimedia-cache.sqlite`).
* It stores the raw body with its ETag / Last-Modified so stale entries can be revalidated with
* conditional requests. Mint-path requests never use it (see client.ts).
*/
import { DatabaseSync } from 'node:sqlite';
export type StoredEntry = {
status: number; body: Buffer; contentType: string; etag: string | null; lastModified: string | null;
expiresAt: number; storedAt: number;
};
export type CacheEntry = StoredEntry & { toResponse(): Response };
/** Canonical key: origin + path + sorted query, without `maxlag` (it changes only error behaviour). */
export function cacheKey(url: URL): string {
const params = [...url.searchParams].filter(([name]) => name !== 'maxlag')
.sort(([a, x], [b, y]) => a < b ? -1 : a > b ? 1 : x < y ? -1 : x > y ? 1 : 0);
return `${url.origin}${url.pathname}?${new URLSearchParams(params).toString()}`;
}
function withResponse(entry: StoredEntry): CacheEntry {
return { ...entry, toResponse: () => new Response(new Uint8Array(entry.body), { status: entry.status,
headers: { 'Content-Type': entry.contentType, 'Content-Length': String(entry.body.byteLength),
...(entry.etag ? { ETag: entry.etag } : {}) } }) };
}
type Row = { status: number; body: Uint8Array; content_type: string; etag: string | null;
last_modified: string | null; expires_at: number; stored_at: number };
export class WikimediaCache {
private readonly db: DatabaseSync;
private readonly maxRows: number;
private writes = 0;
/** `path` may be ':memory:' (tests). */
constructor(path: string, options: { maxRows?: number } = {}) {
this.maxRows = options.maxRows ?? 100_000;
this.db = new DatabaseSync(path);
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;
CREATE TABLE IF NOT EXISTS http_cache (key TEXT PRIMARY KEY, status INTEGER NOT NULL, body BLOB NOT NULL,
content_type TEXT NOT NULL, etag TEXT, last_modified TEXT, expires_at INTEGER NOT NULL, stored_at INTEGER NOT NULL);
CREATE INDEX IF NOT EXISTS http_cache_stored ON http_cache(stored_at);`);
}
get(key: string): CacheEntry | undefined {
const row = this.db.prepare('SELECT * FROM http_cache WHERE key = ?').get(key) as Row | undefined;
if (!row) return undefined;
return withResponse({ status: row.status, body: Buffer.from(row.body), contentType: row.content_type,
etag: row.etag, lastModified: row.last_modified, expiresAt: row.expires_at, storedAt: row.stored_at });
}
put(key: string, entry: StoredEntry): CacheEntry {
this.db.prepare(`INSERT OR REPLACE INTO http_cache (key, status, body, content_type, etag, last_modified, expires_at, stored_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(key, entry.status, entry.body, entry.contentType, entry.etag,
entry.lastModified, entry.expiresAt, entry.storedAt);
if (++this.writes % 500 === 0) this.prune();
return withResponse(entry);
}
touch(key: string, expiresAt: number): void {
this.db.prepare('UPDATE http_cache SET expires_at = ? WHERE key = ?').run(expiresAt, key);
}
delete(key: string): void { this.db.prepare('DELETE FROM http_cache WHERE key = ?').run(key); }
size(): number { return (this.db.prepare('SELECT COUNT(*) AS n FROM http_cache').get() as { n: number }).n; }
prune(): void {
this.db.prepare(`DELETE FROM http_cache WHERE key IN (SELECT key FROM http_cache ORDER BY stored_at DESC LIMIT -1 OFFSET ?)`)
.run(this.maxRows);
}
close(): void { this.db.close(); }
}
+441
View File
@@ -0,0 +1,441 @@
/**
* One process-wide, polite Wikimedia HTTP client (engineer review §4, data review §5).
*
* Every server-side Wikimedia request goes through `WikimediaClient.request()`:
* - a token bucket per upstream host (default 1 req/s, burst 3) and 1 request in flight per host;
* - priority lanes: `mint` before `interactive` before `background`, with a bounded queue;
* - `maxlag=5` on Action API requests (it changes only error behaviour, never content);
* - `Retry-After` honoured on 429/503/maxlag by pausing the whole host, with exponential backoff;
* - a circuit breaker: 3 consecutive 429s stop all requests to that host for 10 minutes;
* - a daily request cap, and a budget shared by the nodes behind one egress IP;
* - an optional on-disk cache (see cache.ts) with ETag / If-None-Match and stale-while-revalidate.
*
* The client is transport only. It never rewrites request parameters other than adding `maxlag`,
* and requests made with `cache: undefined` (all mint-path requests) never read or write the cache.
* Nothing here is reachable from block validation, so it cannot affect consensus.
*/
import { WikimediaCache, cacheKey } from './cache.ts';
import { wikimediaUserAgent, defaultUserAgent } from '../wikimedia-user-agent.ts';
export type Lane = 'mint' | 'interactive' | 'background';
const LANES: Lane[] = ['mint', 'interactive', 'background'];
export type Clock = {
now(): number;
setTimeout(fn: () => void, ms: number): unknown;
clearTimeout(handle: unknown): void;
};
const realClock: Clock = {
now: () => Date.now(),
setTimeout: (fn, ms) => { const t = setTimeout(fn, ms); t.unref?.(); return t; },
clearTimeout: handle => clearTimeout(handle as ReturnType<typeof setTimeout>),
};
export type ClientConfig = {
/** Sustained requests per second per upstream host, for this whole egress IP. */
requestsPerSecond: number;
burst: number;
concurrencyPerHost: number;
/** Requests per UTC day for this whole egress IP. */
dailyCap: number;
/** Nodes sharing one egress IP; the rate and daily cap are divided between them. */
nodesPerIp: number;
queueLimit: number;
/** Longest wait in the queue before a request fails, per lane. */
maxWaitMs: Record<Lane, number>;
breakerThreshold: number;
breakerMs: number;
maxBackoffMs: number;
maxlag: number;
/** Retries of a single request after a maxlag reply (HTTP 200/503 with MediaWiki-API-Error: maxlag). */
maxlagRetries: number;
};
export const DEFAULT_CONFIG: ClientConfig = {
requestsPerSecond: 1, burst: 3, concurrencyPerHost: 1, dailyCap: 20_000, nodesPerIp: 1, queueLimit: 64,
maxWaitMs: { mint: 10_000, interactive: 5_000, background: 120_000 },
breakerThreshold: 3, breakerMs: 10 * 60_000, maxBackoffMs: 10 * 60_000, maxlag: 5, maxlagRetries: 2,
};
/** Unthrottled settings for tests and tools that inject their own fetch. */
export const UNTHROTTLED: Partial<ClientConfig> = {
requestsPerSecond: 1e9, burst: 1e9, concurrencyPerHost: 1e9, dailyCap: Number.MAX_SAFE_INTEGER, queueLimit: 1e9,
breakerThreshold: Number.MAX_SAFE_INTEGER, maxlagRetries: 0, maxBackoffMs: 0,
};
function positive(value: string | undefined, fallback: number, integer = false): number {
if (value === undefined || value.trim() === '') return fallback;
const n = Number(value);
if (!Number.isFinite(n) || n <= 0 || (integer && !Number.isSafeInteger(n))) {
console.warn(`[wikimedia] ignoring invalid setting ${JSON.stringify(value)}; using ${fallback}`);
return fallback;
}
return n;
}
/** Operator settings. Documented in docs/night2/WIKIMEDIA.md. */
export function configFromEnv(env: Record<string, string | undefined> = process.env): ClientConfig {
return { ...DEFAULT_CONFIG,
requestsPerSecond: positive(env.WIKIDECK_WIKIMEDIA_RPS, DEFAULT_CONFIG.requestsPerSecond),
burst: positive(env.WIKIDECK_WIKIMEDIA_BURST, DEFAULT_CONFIG.burst),
concurrencyPerHost: positive(env.WIKIDECK_WIKIMEDIA_CONCURRENCY, DEFAULT_CONFIG.concurrencyPerHost, true),
dailyCap: positive(env.WIKIDECK_WIKIMEDIA_DAILY_CAP, DEFAULT_CONFIG.dailyCap, true),
nodesPerIp: positive(env.WIKIDECK_WIKIMEDIA_NODES_PER_IP, DEFAULT_CONFIG.nodesPerIp, true),
};
}
/** Thrown for every refusal or transport failure: queue full, cap reached, circuit open, timeout, network. */
export class WikimediaUnavailable extends Error {
readonly reason: string;
readonly status?: number;
constructor(reason: string, status?: number) {
super(`Wikimedia unavailable: ${reason}`);
this.name = 'WikimediaUnavailable';
this.reason = reason; this.status = status;
}
}
export type CachePolicy = {
ttlMs: number;
/** Serve a stale entry at once and revalidate it on the background lane. */
staleWhileRevalidate?: boolean;
/** Largest body stored, in bytes. */
maxBytes?: number;
};
export type RequestOptions = {
lane: Lane;
/** Starts when the request is dispatched, not while it waits in the queue. */
timeoutMs: number;
headers?: Record<string, string>;
/** Omit for mint data: the request then bypasses the cache completely. */
cache?: CachePolicy;
};
export type ClientResponse = { response: Response; signal: AbortSignal; fromCache: boolean };
type Waiter = {
lane: Lane; host: string; enqueuedAt: number;
run: () => void; fail: (error: Error) => void; timer?: unknown;
};
type HostState = {
tokens: number; refilledAt: number; inFlight: number;
pausedUntil: number; breakerUntil: number; consecutive429: number; backoffExponent: number;
};
export type ClientStatus = {
day: string; requestsToday: number; dailyCap: number; requestsPerSecond: number; queued: number;
counters: Record<string, number>;
hosts: Record<string, { inFlight: number; pausedForMs: number; circuitOpen: boolean; consecutive429: number }>;
};
function parseRetryAfter(value: string | null, now: number): number | undefined {
if (!value) return undefined;
if (/^\d+$/.test(value.trim())) return Number(value.trim()) * 1000;
const at = Date.parse(value);
return Number.isNaN(at) ? undefined : Math.max(0, at - now);
}
function isActionApi(url: URL): boolean {
return url.pathname === '/w/api.php' && /(^|\.)(wikipedia|wikidata|wikimedia)\.org$/.test(url.hostname);
}
export class WikimediaClient {
readonly config: ClientConfig;
private readonly fetcher: typeof globalThis.fetch;
private readonly clock: Clock;
private readonly userAgent: () => string;
private cache: WikimediaCache | undefined;
private readonly hosts = new Map<string, HostState>();
private readonly queues = new Map<Lane, Waiter[]>(LANES.map(lane => [lane, []]));
private readonly revalidating = new Set<string>();
private pumpTimer: unknown;
private pumpAt = Infinity;
private day = '';
private requestsToday = 0;
readonly counters: Record<string, number> = {};
constructor(options: { fetch?: typeof globalThis.fetch; config?: Partial<ClientConfig>; clock?: Clock;
cache?: WikimediaCache; userAgent?: () => string } = {}) {
this.fetcher = options.fetch ?? ((...args) => globalThis.fetch(...args));
this.config = { ...DEFAULT_CONFIG, ...options.config,
maxWaitMs: { ...DEFAULT_CONFIG.maxWaitMs, ...options.config?.maxWaitMs } };
this.clock = options.clock ?? realClock;
this.userAgent = options.userAgent ?? (() => wikimediaUserAgent(defaultUserAgent()));
this.cache = options.cache;
}
/** A pass-through client for injected fetchers (tests): no rate limit, no breaker, no cache. */
static unthrottled(fetcher: typeof globalThis.fetch): WikimediaClient {
return new WikimediaClient({ fetch: fetcher, config: UNTHROTTLED });
}
attachCache(cache: WikimediaCache | undefined): void { this.cache = cache; }
private count(name: string): void { this.counters[name] = (this.counters[name] ?? 0) + 1; }
private get rate(): number { return this.config.requestsPerSecond / this.config.nodesPerIp; }
private get cap(): number { return Math.max(1, Math.floor(this.config.dailyCap / this.config.nodesPerIp)); }
private host(name: string): HostState {
let state = this.hosts.get(name);
if (!state) {
state = { tokens: this.config.burst, refilledAt: this.clock.now(), inFlight: 0,
pausedUntil: 0, breakerUntil: 0, consecutive429: 0, backoffExponent: 0 };
this.hosts.set(name, state);
}
return state;
}
private refill(state: HostState, now: number): void {
state.tokens = Math.min(this.config.burst, state.tokens + (now - state.refilledAt) / 1000 * this.rate);
state.refilledAt = now;
}
/** Daily budget by lane: background stops at 80 %, interactive at 100 %, mint has a 10 % reserve. */
private overCap(lane: Lane): boolean {
const today = new Date(this.clock.now()).toISOString().slice(0, 10);
if (today !== this.day) { this.day = today; this.requestsToday = 0; }
const limit = lane === 'background' ? this.cap * 0.8 : lane === 'interactive' ? this.cap : this.cap * 1.1;
return this.requestsToday >= limit;
}
status(): ClientStatus {
const now = this.clock.now();
return { day: this.day, requestsToday: this.requestsToday, dailyCap: this.cap, requestsPerSecond: this.rate,
queued: LANES.reduce((n, lane) => n + this.queues.get(lane)!.length, 0), counters: { ...this.counters },
hosts: Object.fromEntries([...this.hosts].map(([name, s]) => [name,
{ inFlight: s.inFlight, pausedForMs: Math.max(0, s.pausedUntil - now), circuitOpen: s.breakerUntil > now,
consecutive429: s.consecutive429 }])) };
}
async request(input: URL, options: RequestOptions): Promise<ClientResponse> {
const url = new URL(input);
if (url.protocol !== 'https:') throw new RangeError('Wikimedia requests must use HTTPS');
if (isActionApi(url) && !url.searchParams.has('maxlag')) url.searchParams.append('maxlag', String(this.config.maxlag));
const key = options.cache && this.cache ? cacheKey(url) : undefined;
const entry = key ? this.cache?.get(key) : undefined;
const now = this.clock.now();
if (entry && entry.expiresAt > now) {
this.count('cache.hit');
return { response: entry.toResponse(), signal: new AbortController().signal, fromCache: true };
}
if (entry && options.cache?.staleWhileRevalidate) {
this.count('cache.stale');
this.revalidate(url, key!, options);
return { response: entry.toResponse(), signal: new AbortController().signal, fromCache: true };
}
try {
return await this.network(url, options, key);
} catch (error) {
// Prefer a stale copy over an error for anything that is allowed to use the cache.
if (entry && error instanceof WikimediaUnavailable) {
this.count('cache.staleOnError');
return { response: entry.toResponse(), signal: new AbortController().signal, fromCache: true };
}
throw error;
}
}
private revalidate(url: URL, key: string, options: RequestOptions): void {
if (this.revalidating.has(key)) return;
this.revalidating.add(key);
void this.network(url, { ...options, lane: 'background' }, key)
.then(({ response }) => response.body?.cancel(), () => this.count('cache.revalidateFailed'))
.finally(() => this.revalidating.delete(key));
}
private async network(url: URL, options: RequestOptions, key: string | undefined): Promise<ClientResponse> {
for (let attempt = 0; ; attempt++) {
const result = await this.dispatch(url, options, key);
if (result !== 'maxlag') return result;
if (attempt >= this.config.maxlagRetries) throw new WikimediaUnavailable('maxlag');
}
}
/** Wait for a slot, send one request, and classify the reply. */
private async dispatch(url: URL, options: RequestOptions, key: string | undefined): Promise<ClientResponse | 'maxlag'> {
const hostName = url.hostname;
const wait = this.acquire(hostName, options.lane);
if (wait) await wait; // No await on the fast path: an idle host dispatches synchronously.
const state = this.host(hostName);
const headers = new Headers({ Accept: 'application/json', 'Accept-Encoding': 'gzip', ...options.headers,
'User-Agent': this.userAgent() });
const entry = key ? this.cache?.get(key) : undefined;
if (entry?.etag) headers.set('If-None-Match', entry.etag);
if (entry?.lastModified) headers.set('If-Modified-Since', entry.lastModified);
const signal = AbortSignal.timeout(options.timeoutMs);
this.requestsToday++;
this.count(`lane.${options.lane}`);
let response: Response;
try {
response = await this.fetcher(url, { signal, redirect: 'error', headers });
} catch (error) {
this.release(state);
this.count('error.network');
throw new WikimediaUnavailable(signal.aborted ? 'timeout' : `network: ${(error as Error).message}`);
}
const now = this.clock.now();
const retryAfter = parseRetryAfter(response.headers.get('retry-after'), now);
const apiError = response.headers.get('mediawiki-api-error');
if (apiError === 'maxlag') {
await response.body?.cancel();
this.count('maxlag');
this.pause(state, Math.min(this.config.maxBackoffMs, retryAfter ?? 5000), false);
this.release(state);
return 'maxlag';
}
if (response.status === 429 || response.status === 503) {
await response.body?.cancel();
this.count(`http.${response.status}`);
if (response.status === 429) state.consecutive429++;
const backoff = Math.min(this.config.maxBackoffMs, 2 ** state.backoffExponent * 1000 * (1 + Math.random() * 0.25));
state.backoffExponent = Math.min(state.backoffExponent + 1, 20);
if (state.consecutive429 >= this.config.breakerThreshold) {
this.pause(state, this.config.breakerMs, true);
this.count('breaker.open');
} else {
this.pause(state, Math.min(this.config.maxBackoffMs, Math.max(retryAfter ?? 0, backoff)), false);
}
this.release(state);
throw new WikimediaUnavailable(`HTTP ${response.status}`, response.status);
}
state.consecutive429 = 0;
state.backoffExponent = 0;
this.release(state);
if (response.status === 304 && entry && key) {
this.count('cache.revalidated');
this.cache?.touch(key, now + options.cache!.ttlMs);
return { response: entry.toResponse(), signal, fromCache: true };
}
if (key && this.cache && response.status === 200 && !response.redirected && options.cache &&
/^application\/json(?:\s*;|\s*$)/i.test(response.headers.get('content-type') ?? '')) {
// Store the raw body; callers re-validate it exactly as they would a network reply.
const body = await this.readLimited(response, options.cache.maxBytes ?? 1024 * 1024, signal);
const stored = this.cache.put(key, { status: response.status, body,
contentType: response.headers.get('content-type') ?? '', etag: response.headers.get('etag'),
lastModified: response.headers.get('last-modified'), expiresAt: now + options.cache.ttlMs, storedAt: now });
return { response: stored.toResponse(), signal, fromCache: false };
}
if (response.status >= 500) this.count(`http.${response.status}`);
return { response, signal, fromCache: false };
}
private async readLimited(response: Response, maxBytes: number, signal: AbortSignal): Promise<Buffer> {
const length = response.headers.get('content-length');
if (length !== null && (!/^\d+$/.test(length) || Number(length) > maxBytes) || !response.body) {
await response.body?.cancel();
throw new WikimediaUnavailable('oversized or empty response');
}
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let size = 0;
try {
for (;;) {
if (signal.aborted) throw new WikimediaUnavailable('timeout');
const { done, value } = await reader.read();
if (done) break;
size += value.byteLength;
if (size > maxBytes) throw new WikimediaUnavailable('oversized response');
chunks.push(value);
}
return Buffer.concat(chunks);
} catch (error) {
throw error instanceof WikimediaUnavailable ? error : new WikimediaUnavailable('read failed');
} finally {
await reader.cancel().catch(() => {});
reader.releaseLock();
}
}
private pause(state: HostState, ms: number, breaker: boolean): void {
const until = this.clock.now() + ms;
if (until > state.pausedUntil) {
if (state.pausedUntil <= this.clock.now()) {
console.warn(`[wikimedia] ${breaker ? 'circuit open' : 'pausing'} for ${Math.ceil(ms / 1000)} s`);
}
state.pausedUntil = until;
}
if (breaker) { state.consecutive429 = 0; state.breakerUntil = until; }
}
private release(state: HostState): void {
state.inFlight--;
this.pump();
}
/** Undefined when a slot was taken at once; otherwise a promise for the slot. Throws on refusal. */
private acquire(hostName: string, lane: Lane): Promise<void> | undefined {
const state = this.host(hostName);
const now = this.clock.now();
if (this.overCap(lane)) { this.count('refused.cap'); throw new WikimediaUnavailable('daily cap reached'); }
// A paused host refuses at once when the pause outlasts this lane's patience.
if (state.pausedUntil - now > this.config.maxWaitMs[lane]) {
this.count('refused.paused');
throw new WikimediaUnavailable(state.breakerUntil > now ? 'circuit open' : 'host paused');
}
this.refill(state, now);
if (state.pausedUntil <= now && state.inFlight < this.config.concurrencyPerHost && state.tokens >= 1 &&
!LANES.some(l => this.queues.get(l)!.some(w => w.host === hostName))) {
state.tokens -= 1;
state.inFlight++;
return undefined;
}
const queued = LANES.reduce((n, l) => n + this.queues.get(l)!.length, 0);
if (queued >= this.config.queueLimit) {
// Background work is shed first; a mint request evicts the newest background waiter.
const background = this.queues.get('background')!;
if (lane === 'background' || background.length === 0) {
this.count('refused.queue');
throw new WikimediaUnavailable('queue full');
}
const evicted = background.pop()!;
this.clock.clearTimeout(evicted.timer);
evicted.fail(new WikimediaUnavailable('queue full'));
}
return new Promise<void>((resolve, reject) => {
const waiter: Waiter = { lane, host: hostName, enqueuedAt: now,
run: () => { this.clock.clearTimeout(waiter.timer); resolve(); },
fail: error => reject(error) };
waiter.timer = this.clock.setTimeout(() => {
const queue = this.queues.get(lane)!;
const index = queue.indexOf(waiter);
if (index >= 0) { queue.splice(index, 1); this.count('refused.wait'); reject(new WikimediaUnavailable('queue wait')); }
}, this.config.maxWaitMs[lane]);
this.queues.get(lane)!.push(waiter);
this.pump();
});
}
/** Start every waiter that may run now, highest lane first; otherwise arm a timer for the next slot. */
private pump(): void {
const now = this.clock.now();
let next = Infinity;
for (const lane of LANES) {
const queue = this.queues.get(lane)!;
for (let i = 0; i < queue.length;) {
const waiter = queue[i];
// A host is served strictly by priority: lower lanes wait while a higher lane waits for the same host.
if (LANES.slice(0, LANES.indexOf(lane)).some(l => this.queues.get(l)!.some(w => w.host === waiter.host))) { i++; continue; }
const state = this.host(waiter.host);
this.refill(state, now);
if (state.pausedUntil > now) { next = Math.min(next, state.pausedUntil); i++; continue; }
if (state.inFlight >= this.config.concurrencyPerHost) { i++; continue; }
if (state.tokens < 1) { next = Math.min(next, now + (1 - state.tokens) / this.rate * 1000); i++; continue; }
state.tokens -= 1;
state.inFlight++;
queue.splice(i, 1);
waiter.run();
}
}
if (next < Infinity && next < this.pumpAt) {
if (this.pumpTimer !== undefined) this.clock.clearTimeout(this.pumpTimer);
this.pumpAt = next;
this.pumpTimer = this.clock.setTimeout(() => { this.pumpTimer = undefined; this.pumpAt = Infinity; this.pump(); },
Math.max(1, Math.ceil(next - now)));
}
}
}
/** The process-wide client. `configureWikimedia()` (server start-up) attaches the disk cache. */
export const wikimediaClient = new WikimediaClient({ config: configFromEnv() });
+36
View File
@@ -0,0 +1,36 @@
/**
* Node start-up wiring for the polite Wikimedia client: the disk cache, the User-Agent warning,
* the mining prefetch pool and an ops status snapshot. See docs/night2/WIKIMEDIA.md.
*/
import { resolve } from 'node:path';
import { WikimediaCache } from './cache.ts';
import { wikimediaClient } from './client.ts';
import { MintTemplatePool } from './pool.ts';
import { warnIfNoContact } from '../wikimedia-user-agent.ts';
import { wikipediaArticles } from '../wiki.ts';
import { wikipediaEnrichment } from '../enrichment.ts';
export { wikimediaClient } from './client.ts';
/** Serves every mining template; shared by all miners of this node. */
export const mintPool = new MintTemplatePool({ articles: wikipediaArticles, enrichment: wikipediaEnrichment });
let cache: WikimediaCache | undefined;
/** Call once at start-up. Without it the client still works, with in-memory caching only. */
export function configureWikimedia(options: { dataDir: string }): void {
warnIfNoContact();
if (cache) return;
try {
cache = new WikimediaCache(resolve(options.dataDir, 'wikimedia-cache.sqlite'));
wikimediaClient.attachCache(cache);
} catch (error) {
console.warn(`[wikimedia] disk cache disabled: ${(error as Error).message}`);
}
}
export function closeWikimedia(): void { wikimediaClient.attachCache(undefined); cache?.close(); cache = undefined; }
export function wikimediaStatus() {
return { client: wikimediaClient.status(), cacheEntries: cache?.size() ?? null, mintPool: mintPool.status() };
}
+88
View File
@@ -0,0 +1,88 @@
/**
* Mining-template prefetch pool (data review §5, "Mining load").
*
* Without it every miner costs 3+ Wikimedia requests per template, all in a burst at each new tip.
* The pool keeps a few fresh article + stats snapshots ready, and serves the SAME pair to every
* template built on the same tip (miners race for one block anyway). Wikimedia load is then about
* one pair (3 requests) per block, whatever the number of miners.
*
* Mint data stays transport-only: each pair comes from the mint-path reads (`random()` and
* `getFresh()`, byte-identical parameters, never the disk cache), and the snapshot is stamped when it
* is fetched, so `capturedAt` stays true. Pairs older than `maxAgeMs` are discarded, never served.
* The pool refills only after it is used, so an idle node makes no requests.
*/
import type { Article } from '../../shared/protocol.ts';
import { snapshotStats, type MintStatsSnapshot, type PageEnrichment } from '../../shared/enrichment.ts';
export type MintPair = { article: Article; statsSnapshot: MintStatsSnapshot };
type Entry = MintPair & { fetchedAt: number };
type Sources = {
articles: { random(): Promise<Article> };
enrichment: { getFresh(pageId: number): Promise<PageEnrichment> };
};
export class MintTemplatePool {
private readonly sources: Sources;
private readonly size: number;
private readonly maxAgeMs: number;
private readonly now: () => number;
private readonly ready: Entry[] = [];
private assigned: { tip: string; entry: Entry } | undefined;
private filling: Promise<void> | undefined;
private direct: Promise<Entry> | undefined;
readonly counters = { served: 0, shared: 0, fetched: 0, expired: 0, failed: 0 };
constructor(sources: Sources, options: { size?: number; maxAgeMs?: number; now?: () => number } = {}) {
this.sources = sources;
this.size = options.size ?? 2;
this.maxAgeMs = options.maxAgeMs ?? 5 * 60_000;
this.now = options.now ?? Date.now;
if (!Number.isSafeInteger(this.size) || this.size < 0 || this.size > 16 ||
!Number.isFinite(this.maxAgeMs) || this.maxAgeMs <= 0) throw new RangeError('Invalid mint pool options');
}
private fresh(entry: Entry): boolean { return this.now() - entry.fetchedAt < this.maxAgeMs; }
private async fetchOne(): Promise<Entry> {
const article = await this.sources.articles.random();
const metrics = await this.sources.enrichment.getFresh(article.pageId);
this.counters.fetched++;
return { article, statsSnapshot: snapshotStats(metrics), fetchedAt: this.now() };
}
/** The article and snapshot for a template on `tip`. Rejects when Wikimedia is unavailable. */
async take(tip: string): Promise<MintPair> {
let entry: Entry | undefined;
if (this.assigned && this.assigned.tip === tip && this.fresh(this.assigned.entry)) {
entry = this.assigned.entry;
this.counters.shared++;
} else {
while (this.ready.length && !this.fresh(this.ready[0])) { this.ready.shift(); this.counters.expired++; }
entry = this.ready.shift();
if (!entry) {
// Cold: fetch directly, and let concurrent templates share that one fetch.
this.direct ??= this.fetchOne().finally(() => { this.direct = undefined; });
try { entry = await this.direct; }
catch (error) { this.counters.failed++; throw error; }
if (this.assigned && this.assigned.tip === tip && this.fresh(this.assigned.entry)) entry = this.assigned.entry;
}
this.assigned = { tip, entry };
}
this.counters.served++;
this.refill();
return structuredClone({ article: entry.article, statsSnapshot: entry.statsSnapshot });
}
/** Top the pool up one pair at a time, in the background. Exposed for tests. */
refill(): Promise<void> {
this.filling ??= (async () => {
while (this.ready.filter(e => this.fresh(e)).length < this.size) {
try { this.ready.push(await this.fetchOne()); }
catch { this.counters.failed++; break; } // The next take() tries again; no retry loop.
}
})().finally(() => { this.filling = undefined; });
return this.filling;
}
status() { return { ready: this.ready.length, size: this.size, maxAgeMs: this.maxAgeMs, ...this.counters }; }
}
+176
View File
@@ -0,0 +1,176 @@
// EngineAdapter + DuelLens over duel-core's shared/duel engine (DuelEngineApi, docs/game/DUEL_API.md),
// for the duel bots (shared/bots/duel-bots.ts) and the balance sim (scripts/sim/duel-run.ts). Pure, no I/O:
// the engine module and the card pool are passed in.
import type {
CardInstance, ConnectedTier, DuelAction, DuelCard, DuelEngineApi, DuelRuleset, DuelState, Permanent, PlayerView, Seat,
} from '../duel/index.ts';
import type { EngineAdapter, Rng } from './types.ts';
import { duelEvaluate, type DuelLens, type LensAction, type LensCreature } from './duel-bots.ts';
/** What a duel bot sees: its seat's view, its own decklist (players know their deck) and its legal actions. */
export interface DuelObservation { view: PlayerView; deck: DuelCard[]; legal: DuelAction[] }
const KW_VALUE: Record<string, number> = { Featured: 1, Protected: 0.4, 'Well-sourced': 0.5, Legacy: 0.5, Stub: 0.5, Multilingual: 0.4, Translated: 0.2, Local: 0.2, Trending: 0.3 };
/** Connected test between two cards (DUEL_API "Connected"), for the pairwise pool rate. */
export function connectedTierOf(a: DuelCard, b: DuelCard, tiers: readonly ConnectedTier[]): ConnectedTier | null {
if (a.cardId === b.cardId || !a.connect || !b.connect) return null;
const meets = <T>(x: readonly T[], y: readonly T[]) => x.some(v => y.includes(v));
for (const t of tiers) {
if (t === 'Linked' && ((b.pageId !== null && a.connect.links.includes(b.pageId)) || (a.pageId !== null && b.connect.links.includes(a.pageId)))) return t;
if (t === 'Compatriot' && meets(a.connect.countries, b.connect.countries)) return t;
if (t === 'Contemporary' && a.type !== b.type && meets(a.connect.centuries, b.connect.centuries)) return t;
if (t === 'Kin' && meets(a.connect.p31.filter(q => q !== 'Q5' && q !== 'Q16521'), b.connect.p31)) return t;
}
return null;
}
export function makeDuelLens(api: DuelEngineApi): DuelLens<DuelState, DuelAction> {
const stats = (s: DuelState, p: Permanent) => { try { return api.statsOf(s, p.uid); } catch { return { power: p.card.power ?? 0, toughness: p.card.toughness ?? 0 }; } };
const blocker = (p: Permanent) => p.card.type === 'Figure' || (p.card.type === 'Location' && (p.card.toughness ?? 0) > 0);
return {
phase: s => (s.phase === 'over' ? 'other' : s.phase),
life: (s, seat) => s.players[seat].life,
handSize: (s, seat) => s.players[seat].hand.length,
creatures: (s, seat): LensCreature[] => s.battlefield.filter(p => p.controller === seat && blocker(p)).map(p => {
const { power, toughness } = stats(s, p);
const left = Math.max(0, toughness - p.damage);
const kw = (p.card.keywords ?? []).reduce((t, k) => t + (KW_VALUE[k] ?? 0), 0);
const fig = p.card.type === 'Figure';
return { uid: p.uid, power, toughness: left, tapped: p.tapped, canAttack: fig && !p.tapped && !p.sick, canBlock: !p.tapped, value: fig ? power + left * 0.8 + 0.5 + kw : left * 0.5 };
}),
attackers: s => s.combat.attackers,
blocks: s => Object.entries(s.combat.blocks) as [string, string][],
decode: (s, a): LensAction => {
switch (a.type) {
case 'play': {
const c = s.players[s.active].hand.find(h => h.uid === a.uid)?.card;
return { kind: 'play', cost: c?.cost ?? 0, cardType: c?.type ?? '?' };
}
case 'toggleAttacker': return { kind: 'attack', uid: a.uid, on: true };
case 'confirmAttack': return { kind: 'confirmAttack' };
case 'block': return { kind: 'block', blocker: a.blocker, attacker: a.attacker };
case 'confirmBlocks': return { kind: 'confirmBlocks' };
case 'endPhase': return { kind: 'endMain' };
case 'keep': return { kind: 'keep' };
case 'mulligan': return { kind: 'mulligan' };
default: return { kind: 'other' };
}
},
};
}
function shuffled<T>(xs: T[], rng: Rng): T[] {
const a = [...xs];
for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; }
return a;
}
/**
* Rebuild a full DuelState from a seat's observation (a determinization). Hidden zones are sampled:
* our library from our decklist minus every card we can see, the opponent's hand and library from `pool`
* minus everything visible. Permanent modifiers are recovered exactly from the view's current
* power/toughness (whatever statsOf doesn't recompute goes into permPower/permToughness).
*/
export function stateFromObservation(api: DuelEngineApi, obs: DuelObservation, seat: Seat, rng: Rng, pool: readonly DuelCard[]): DuelState {
const v = obs.view, o = (1 - seat) as Seat;
const seen = new Set<string>();
const mark = (c: DuelCard) => seen.add(c.cardId);
v.you.hand.forEach(h => mark(h.card));
v.you.graveyard.forEach(g => mark(g.card));
v.opponent.graveyard.forEach(g => mark(g.card));
v.battlefield.forEach(p => mark(p.card));
const ownLeft = shuffled(obs.deck.filter(c => !seen.has(c.cardId) && !v.battlefield.some(p => p.card.cardId === c.cardId && p.owner === seat)), rng);
const oppPool = shuffled(pool.filter(c => !seen.has(c.cardId) && !obs.deck.some(d => d.cardId === c.cardId)), rng);
let k = 0;
const hidden = (owner: Seat, card: DuelCard): CardInstance => ({ uid: `${owner}:h${k++}`, owner, card });
const take = (n: number) => Array.from({ length: n }, (_, i) => hidden(o, oppPool[i % Math.max(1, oppPool.length)] ?? obs.deck[0]));
const oppHand = take(v.opponent.handSize);
const oppLib = Array.from({ length: v.opponent.librarySize }, (_, i) => hidden(o, oppPool[(v.opponent.handSize + i) % Math.max(1, oppPool.length)] ?? obs.deck[0]));
const myLib = Array.from({ length: v.you.librarySize }, (_, i) => hidden(seat, ownLeft[i % Math.max(1, ownLeft.length)] ?? obs.deck[0]));
const side = (sv: PlayerView['opponent'], hand: CardInstance[], library: CardInstance[]) => {
const territory = Math.min(v.rules.territoryCap, v.battlefield.filter(p => p.controller === sv.seat && p.card.type === 'Location').reduce((t, p) => t + (p.card.territory ?? 0), 0));
return {
life: sv.life, citations: sv.citations, baseCitations: Math.max(0, sv.maxCitations - territory), library, hand, graveyard: sv.graveyard,
mulligansTaken: sv.mulligansTaken, ready: sv.ready, locationsThisTurn: 0, bankSeconds: sv.bankSeconds, timeouts: 0, fatigue: 0,
};
};
const players = [] as unknown as DuelState['players'];
players[seat] = side(v.you, v.you.hand, myLib);
players[o] = side(v.opponent, oppHand, oppLib);
// Locations played this turn aren't in the view: if we hold an affordable Location that isn't legal to play, assume one was played.
if (v.active === seat && v.phase === 'main') {
const legalUids = new Set(obs.legal.flatMap(a => (a.type === 'play' ? [a.uid] : [])));
players[seat].locationsThisTurn = v.you.hand.some(h => h.card.type === 'Location' && h.card.cost <= v.you.citations && !legalUids.has(h.uid)) ? 1 : 0;
}
const battlefield: Permanent[] = v.battlefield.map((p, i) => ({
uid: p.uid, owner: p.owner, controller: p.controller, card: p.card, tapped: p.tapped, sick: p.sick, damage: p.damage, counters: p.counters,
permPower: 0, permToughness: 0, tempPower: 0, tempToughness: 0, tempKeywords: [], permKeywords: [], attachedTo: p.attachedTo,
shielded: false, entered: i, connectedLogged: true,
}));
const s: DuelState = {
engine: 'duel', rules: v.rules, seed: 'assumed', rng: Math.floor(rng() * 2 ** 32) >>> 0, turn: v.turn, active: v.active,
firstSeat: v.active, phase: v.phase, players, battlefield, combat: structuredClone(v.combat), log: [], result: v.result,
version: v.version, nextToken: 100000 + v.version, nextEntry: battlefield.length,
};
for (const p of battlefield) {
const want = v.battlefield.find(x => x.uid === p.uid)!;
try {
const got = api.statsOf(s, p.uid);
p.permPower = want.power - got.power;
p.permToughness = want.toughness - got.toughness;
} catch { /* keep zero */ }
const extra = want.keywords.filter(kw => !(p.card.keywords ?? []).includes(kw));
if (extra.length) p.permKeywords = extra;
}
return s;
}
export interface DuelAdapterOptions { rules: DuelRuleset; pool: readonly DuelCard[] }
export function makeDuelAdapter(api: DuelEngineApi, opts: DuelAdapterOptions): EngineAdapter<DuelState, DuelAction> & { lens: DuelLens<DuelState, DuelAction> } {
const lens = makeDuelLens(api);
const decks = new WeakMap<DuelState, [DuelCard[], DuelCard[]]>();
const deckOf = new Map<string, [DuelCard[], DuelCard[]]>();
const adapter: EngineAdapter<DuelState, DuelAction> & { lens: typeof lens } = {
name: 'duel',
lens,
rulesets: () => [opts.rules.version],
decks: () => [],
createMatch: (_r, specs, seed) => {
const d: [DuelCard[], DuelCard[]] = [specs[0].payload as DuelCard[], specs[1].payload as DuelCard[]];
const s = api.createDuel(opts.rules, d, String(seed));
decks.set(s, d); deckOf.set(s.seed, d);
return s;
},
toAct: s => api.toAct(s) ?? s.active,
legalActions: (s, seat) => api.legalActions(s, seat),
applyAction: (s, a) => api.applyAction(s, api.toAct(s) ?? s.active, a),
isOver: s => api.isOver(s),
result: s => { const r = api.result(s); return { winner: r?.winner ?? null, reason: r?.reason }; },
turn: s => s.turn,
evaluate: (s, seat) => duelEvaluate(lens, s, seat),
cardsOf: (s, a) => (a.type === 'play' ? [s.players[api.toAct(s) ?? s.active].hand.find(h => h.uid === a.uid)?.card.cardId ?? a.uid] : []),
actionKind: a => a.type,
firstSeat: s => s.firstSeat,
observe: (s, seat): DuelObservation => ({ view: api.viewFor(s, seat), deck: (deckOf.get(s.seed) ?? decks.get(s) ?? [[], []])[seat], legal: api.legalActions(s, seat) }),
assume: (obs, seat, rng) => stateFromObservation(api, obs as DuelObservation, seat, rng, opts.pool),
};
return adapter;
}
/** Per-match numbers from the omniscient log, for DUEL_BALANCE.md. */
export function duelMetrics(s: DuelState): Record<string, number> {
const m: Record<string, number> = { connectedFires: 0, plays: 0, rivalries: 0, destroyed: 0, mulligans: 0, tokens: 0, discards: 0 };
for (const e of s.log) {
if (e.kind === 'connected') m.connectedFires++;
else if (e.kind === 'deploy' || e.kind === 'cast' || e.kind === 'adopt') m.plays++;
else if (e.kind === 'rivalry') m.rivalries++;
else if (e.kind === 'destroyed') m.destroyed++;
else if (e.kind === 'mulligan') m.mulligans++;
else if (e.kind === 'tokenCreated') m.tokens++;
else if (e.kind === 'discard') m.discards++;
}
m.lifeLeft = s.result?.winner != null ? s.players[s.result.winner].life : 0;
return m;
}
+233
View File
@@ -0,0 +1,233 @@
// Duel bots: engine-agnostic heuristics for a Magic-style duel (attack/block/sorcery-speed plays).
// Bots see the duel through a DuelLens (a few accessors over state and action), so the same bots run
// on duel-core's shared/duel engine and on the sim stand-in. Pure: no I/O.
import type { EngineAdapter, Rng, Seat, BotFn } from './types.ts';
import { lookaheadBot } from './index.ts';
/**
* Observations may carry the acting seat's legal actions (`legal`): the UI shows them anyway, and choosing
* from them guarantees a bot never returns an action that is legal only in its determinized guess.
*/
function legalOf<S, A>(engine: EngineAdapter<S, A>, obs: unknown, s: S, seat: Seat): A[] {
const l = (obs as { legal?: A[] } | null)?.legal;
return Array.isArray(l) ? l : engine.legalActions(s, seat);
}
const seeState = <S, A>(engine: EngineAdapter<S, A>, obs: unknown, seat: Seat, rng: Rng): S => (engine.assume ? engine.assume(obs, seat, rng) : (obs as S));
/** Uniformly random legal action. */
export function duelRandomBot<S, A>(engine: EngineAdapter<S, A>): BotFn<unknown, A> {
return (obs, seat, rng) => { const l = (obs as { legal?: A[] })?.legal; const legal = Array.isArray(l) ? l : engine.legalActions(seeState(engine, obs, seat, rng), seat); return legal[Math.floor(rng() * legal.length)]; };
}
/** One-ply greedy on the evaluation over every legal action (weak at combat: toggles have no immediate value). */
export function duelGreedyBot<S, A>(engine: EngineAdapter<S, A>): BotFn<unknown, A> {
return (obs, seat, rng) => {
const s = seeState(engine, obs, seat, rng);
const legal = legalOf(engine, obs, s, seat);
let best = legal[0], bestV = -Infinity;
for (const a of legal) { const v = safeEval(engine, s, a, seat) + rng() * 1e-6; if (v > bestV) { bestV = v; best = a; } }
return best;
};
}
/** Evaluate `a` from `s`; an action the determinized state rejects scores -5 (it stays a candidate). */
function safeEval<S, A>(engine: EngineAdapter<S, A>, s: S, a: A, seat: Seat): number {
try { const n = engine.applyAction(s, a); return engine.isOver(n) ? (engine.result(n).winner === seat ? 10 : engine.result(n).winner === null ? 0 : -10) : engine.evaluate(n, seat); }
catch { return -5; }
}
export interface LensCreature { uid: string; power: number; toughness: number; tapped: boolean; canAttack: boolean; canBlock: boolean; value: number }
export type LensAction =
| { kind: 'play'; cost: number; cardType: string }
| { kind: 'attack'; uid: string; on: boolean }
| { kind: 'confirmAttack' }
| { kind: 'block'; blocker: string; attacker: string }
| { kind: 'confirmBlocks' }
| { kind: 'endMain' }
| { kind: 'mulligan' | 'keep' | 'other' };
export interface DuelLens<S, A> {
phase(s: S): 'main' | 'attack' | 'block' | 'mulligan' | 'other';
life(s: S, seat: Seat): number;
creatures(s: S, seat: Seat): LensCreature[];
handSize(s: S, seat: Seat): number;
/** Attackers currently declared by the active player (uids). */
attackers(s: S): string[];
/** Blocks declared so far [blocker, attacker]. */
blocks(s: S): [string, string][];
decode(s: S, a: A): LensAction;
}
/** Material evaluation in [-1, 1]: life, board (power+toughness) and cards in hand. */
export function duelEvaluate<S, A>(lens: DuelLens<S, A>, s: S, seat: Seat): number {
const o = (seat === 0 ? 1 : 0) as Seat;
const board = (p: Seat) => lens.creatures(s, p).reduce((t, c) => t + c.value, 0);
const myLife = lens.life(s, seat), oLife = lens.life(s, o);
const lifeTerm = (Math.min(myLife, 20) - Math.min(oLife, 20)) / 20 + (oLife <= 0 ? 1 : 0) - (myLife <= 0 ? 1 : 0);
const boardTerm = Math.tanh((board(seat) - board(o)) / 12);
const handTerm = Math.tanh((lens.handSize(s, seat) - lens.handSize(s, o)) / 6);
return Math.max(-1, Math.min(1, 0.4 * lifeTerm + 0.45 * boardTerm + 0.15 * handTerm));
}
const pick = <T>(xs: T[], rng: Rng): T => xs[Math.floor(rng() * xs.length)];
/** Choose attackers: attack with a creature unless the foe has an untapped blocker that kills it and survives; all-in when lethal-ish. */
function wantAttack<S, A>(lens: DuelLens<S, A>, s: S, seat: Seat, c: LensCreature): boolean {
const o = (seat === 0 ? 1 : 0) as Seat;
const blockers = lens.creatures(s, o).filter(b => b.canBlock);
const mine = lens.creatures(s, seat).filter(x => x.canAttack);
// Lethal check: assume the foe blocks our biggest attackers; the rest must cover its life.
const unblocked = mine.map(x => x.power).sort((a, b) => b - a).slice(blockers.length).reduce((t, p) => t + p, 0);
if (unblocked >= lens.life(s, o)) return true;
if (c.power <= 0) return false;
const badBlock = blockers.some(b => b.power >= c.toughness && b.toughness > c.power);
if (badBlock) return false;
const trade = blockers.some(b => b.power >= c.toughness);
// Trading is fine if we are ahead on board or the foe is low.
if (trade) return lens.life(s, o) <= 8 || mine.length > blockers.length;
return true;
}
/** Choose a block for an attacker: kill-and-survive > chump only when lethal > even trade if attacker is worth more. */
function chooseBlock<S, A>(lens: DuelLens<S, A>, s: S, seat: Seat, legal: { a: A; d: LensAction & { kind: 'block' } }[]): A | null {
if (!legal.length) return null;
const o = (seat === 0 ? 1 : 0) as Seat;
const att = new Map(lens.creatures(s, o).map(c => [c.uid, c]));
const mine = new Map(lens.creatures(s, seat).map(c => [c.uid, c]));
const blocked = new Set(lens.blocks(s).map(b => b[1]));
const incoming = lens.attackers(s).filter(u => !blocked.has(u)).reduce((t, u) => t + (att.get(u)?.power ?? 0), 0);
const lethal = incoming >= lens.life(s, seat);
let best: A | null = null, bestScore = 0;
for (const { a, d } of legal) {
const A = att.get(d.attacker), B = mine.get(d.blocker);
if (!A || !B) continue;
const kills = B.power >= A.toughness, dies = A.power >= B.toughness;
let score = 0;
if (kills && !dies) score = 10 + A.value;
else if (kills && dies) score = A.value > B.value ? 5 + A.value - B.value : lethal ? 3 : 0;
else if (!dies) score = 2 + A.power * 0.5; // safe absorb
else score = lethal ? 1 + A.power - B.value * 0.1 : 0;
if (score > bestScore) { bestScore = score; best = a; }
}
return best;
}
/**
* Heuristic duel bot: main phase is one-ply greedy over plays (material eval), attacks and blocks follow
* simple Magic heuristics. Strong enough to be the balance baseline; deterministic given rng.
*/
export function heuristicBot<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A>): BotFn<unknown, A> {
return (obs, seat, rng) => {
const s = seeState(engine, obs, seat, rng);
const legal = legalOf(engine, obs, s, seat);
if (legal.length === 1) return legal[0];
return heuristicChoice(engine, lens, s, seat, legal, rng);
};
}
export function heuristicChoice<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A>, s: S, seat: Seat, legal: A[], rng: Rng): A {
const dec = legal.map(a => ({ a, d: lens.decode(s, a) }));
const find = (k: LensAction['kind']) => dec.find(x => x.d.kind === k)?.a;
switch (lens.phase(s)) {
case 'mulligan': return find('keep') ?? legal[0];
case 'main': {
const plays = dec.filter(x => x.d.kind === 'play');
const base = engine.evaluate(s, seat);
let best: A | undefined, bestV = -Infinity;
for (const { a, d } of plays) {
const v = safeEval(engine, s, a, seat) + 0.004 * (d as any).cost + rng() * 1e-6;
if (v > bestV) { bestV = v; best = a; }
}
if (best !== undefined && bestV > base - 0.02) return best;
return find('endMain') ?? find('other') ?? legal[0];
}
case 'attack': {
const declared = new Set(lens.attackers(s));
for (const { a, d } of dec) {
if (d.kind !== 'attack') continue;
const c = lens.creatures(s, seat).find(x => x.uid === d.uid);
if (!c) continue;
const want = wantAttack(lens, s, seat, c);
if (want !== declared.has(d.uid) && d.on === want) return a;
}
return find('confirmAttack') ?? legal[0];
}
case 'block': {
const b = chooseBlock(lens, s, seat, dec.filter((x): x is { a: A; d: LensAction & { kind: 'block' } } => x.d.kind === 'block'));
return b ?? find('confirmBlocks') ?? legal[0];
}
default: return pick(legal, rng);
}
}
export interface DuelMCOptions { rollouts?: number; k?: number; horizon?: number }
/**
* Shallow Monte Carlo over the heuristic: in the main and block phases, shortlist up to k candidate actions,
* run `rollouts` heuristic playouts (fresh determinization each) for `horizon` actions and pick the best mean.
* Attack declarations use the heuristic directly (toggles have no immediate value to rank).
*/
export function duelMCBot<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A>, opts: DuelMCOptions = {}): BotFn<unknown, A> {
const rollouts = opts.rollouts ?? 6, k = opts.k ?? 4, horizon = opts.horizon ?? 120;
return (obs, seat, rng) => {
const s = seeState(engine, obs, seat, rng);
const legal = legalOf(engine, obs, s, seat);
if (legal.length === 1) return legal[0];
const ph = lens.phase(s);
if (ph !== 'main' && ph !== 'attack') return heuristicChoice(engine, lens, s, seat, legal, rng);
const h = heuristicChoice(engine, lens, s, seat, legal, rng);
let cands: A[];
if (ph === 'attack') {
// Candidates: heuristic choice, confirm now, or all-in (toggle every not-yet-declared attacker).
const dec = legal.map(a => ({ a, d: lens.decode(s, a) }));
cands = [h, ...dec.filter(x => x.d.kind === 'confirmAttack' || (x.d.kind === 'attack' && x.d.on)).map(x => x.a)];
} else {
cands = [h, ...legal.map(a => ({ a, v: safeEval(engine, s, a, seat) })).sort((x, y) => y.v - x.v).map(x => x.a)];
}
const uniq: A[] = [];
for (const c of cands) if (!uniq.some(u => JSON.stringify(u) === JSON.stringify(c))) uniq.push(c);
const short = uniq.slice(0, k);
if (short.length === 1) return short[0];
let best = short[0], bestScore = -Infinity;
for (const c of short) {
let total = 0;
for (let r = 0; r < rollouts; r++) {
let st: S, steps = 0;
try { st = engine.applyAction(seeState(engine, obs, seat, rng), c); } catch { total -= 1; continue; }
while (!engine.isOver(st) && steps < horizon) {
const who = engine.toAct(st);
const lg = engine.legalActions(st, who);
if (!lg.length) break;
st = engine.applyAction(st, lg.length === 1 ? lg[0] : heuristicChoice(engine, lens, st, who, lg, rng));
steps++;
}
if (engine.isOver(st)) { const w = engine.result(st).winner; total += w === null ? 0 : w === seat ? 1 : -1; }
else total += engine.evaluate(st, seat);
}
const score = total / rollouts + (c === h ? 0.02 : 0);
if (score > bestScore) { bestScore = score; best = c; }
}
return best;
};
}
/** Heuristic with blunders: with probability `rate` a uniformly random legal action instead (UI "Easy"). */
export function blunderBot<S, A>(engine: EngineAdapter<S, A>, lens: DuelLens<S, A>, rate = 0.3): BotFn<unknown, A> {
const h = heuristicBot(engine, lens), r = duelRandomBot(engine);
return (obs, seat, rng) => (rng() < rate ? r(obs, seat, rng) : h(obs, seat, rng));
}
export const DUEL_BOT_NAMES = ['random', 'greedy', 'easy', 'heuristic', 'mc', 'mc-lite'] as const;
export function makeDuelBot<S, A>(name: string, engine: EngineAdapter<S, A>, lens: DuelLens<S, A>): BotFn<unknown, A> {
switch (name) {
case 'random': return duelRandomBot(engine);
case 'greedy': return duelGreedyBot(engine);
case 'heuristic': return heuristicBot(engine, lens);
case 'easy': return blunderBot(engine, lens);
case 'mc': return duelMCBot(engine, lens);
case 'mc-lite': return duelMCBot(engine, lens, { rollouts: 3, k: 3, horizon: 60 });
case 'lookahead': return lookaheadBot(engine);
default: throw new Error(`unknown duel bot ${name}`);
}
}
+184
View File
@@ -0,0 +1,184 @@
/**
* Card type classification (BRIEF "Card types", data review §1, designer review §3.1).
* Pure and deterministic: everything comes from the frozen CardProfile, nothing is fetched here.
* Order: exact Q-id anchors on P31, then P279 anchors, then P31 label regex (rule order is the
* priority), then P279 label regex, then non-stub categories, then the description, then Doctrine.
* Owner: duel-cards.
*/
import type { CardType } from './types.ts';
export type { CardType } from './types.ts';
export { CARD_TYPES } from './types.ts';
export interface WikidataClass { id: string; label: string }
/**
* The off-chain card profile, frozen the first time a host sees the card (data §3) and logged
* with the match so replays and recaps stay deterministic. Only what derivation reads.
*/
export interface CardProfile {
wikidataId: string | null;
/** Wikipedia short description. */
description: string | null;
/** Non-hidden category titles without the "Category:" prefix. */
categories: readonly string[];
/** P31 (instance of). */
instanceOf: readonly WikidataClass[];
/** P279 (subclass of) of the item itself, or the P31 classes' superclasses up to 4 hops, nearest first. */
subclassOf?: readonly WikidataClass[];
/** P17 / P27 country Q-ids (or labels when only text is known). */
countries?: readonly string[];
/** Years from P569/P570/P571/P580/P585 (negative = BCE). */
years?: readonly number[];
/** P570 (date of death) present. */
died?: boolean;
/** ns0 outlinks as pageIds (data §4), for the Linked tier of Connected. */
links?: readonly number[];
/** Item Q-ids cited by the frozen claims (P17, P27, P131, P361, P106, …), for the Linked tier. */
cites?: readonly string[];
/** The live revision the profile was fetched from (data §3). */
fetchedRevisionId?: number;
}
export type ClassifySource = 'qid' | 'p279-qid' | 'p31' | 'p279' | 'category' | 'description'
| 'extract' | 'title' | 'chain-category' | 'fallback';
export interface Classification { type: CardType; source: ClassifySource; matched: string }
/** Exact anchors (designer §3.1 step 1, data §1 production table). Checked against P31, then P279. */
export const QID_ANCHORS: Readonly<Record<string, CardType>> = {
Q5: 'Figure', Q95074: 'Figure', Q16521: 'Figure', Q23038290: 'Figure', Q8436: 'Figure', Q178885: 'Figure',
Q486972: 'Location', Q515: 'Location', Q532: 'Location', Q3957: 'Location', Q4022: 'Location', Q23397: 'Location',
Q8502: 'Location', Q23442: 'Location', Q41176: 'Location',
Q1656682: 'Event', Q40231: 'Event', Q178561: 'Event', Q198: 'Event', Q8065: 'Event',
Q43229: 'Institution', Q4830453: 'Institution', Q783794: 'Institution', Q7278: 'Institution', Q215380: 'Institution',
Q17537576: 'Institution', Q11424: 'Institution', Q482994: 'Institution', Q7366: 'Institution', Q571: 'Institution',
Q12136: 'Doctrine', Q151885: 'Doctrine', Q7187: 'Doctrine', Q9143: 'Doctrine', Q315: 'Doctrine',
};
type Rules = readonly (readonly [CardType, RegExp])[];
/** P31/P279 label rules (data §1 types.py, with `^human$` and the governing-body fix). Order is load-bearing. */
export const LABEL_RULES: Rules = [
['Doctrine', /aspect of|aspect in|disease|clinical sign|list article|chemical entity/],
['Event', new RegExp('election|protest|battle|war\\b|storm|nor.easter|cyclone|tornado|earthquake|disaster|event|match|final\\b|'
+ 'season|championship|tournament|\\brace\\b|grand prix|scandal|annexation|treaty|incident|festival|referendum|'
+ 'conference|ceremony|time period|delegation|spaceflight|siege|riot|massacre|flood|pandemic|epidemic|straw poll')],
['Institution', /artificial satellite|space station|space telescope|spacecraft|space probe|diocese|ecclesiastical|council\b|governing body|stele/],
['Location', new RegExp('planet|natural satellite|\\bstar\\b|galaxy|nebula|planetary system|astronomical object|rainforest|reef|'
+ 'civili[sz]ation|empire|historical country|archaeological site|'
+ 'human settlement|settlement|village|town|city|commune|municipal|parish|county|district|region|province|'
+ 'township|hamlet|townland|census area|local government|community of|island|river|lake|mountain|plateau|'
+ 'waterfall|valley|bay|peak|geographical feature|historic district|park|state park|square|road|highway|'
+ 'building|castle|mosque|church|temple|cathedral|house|home|museum|station|bridge|monument|historic site|'
+ 'military base|battery|refinery|shopping|stadium|arch|tower|fort|palace|columbari|freguesia|country\\b|sovereign state')],
['Figure', /^human$|fictional character|stock character|person|deity|orisha|loa\b|taxon|species|genus|breed|^family$|organism/],
['Institution', new RegExp('company|business|organi[sz]ation|association|society|party|agency|studio|band|musical group|team|club|'
+ 'university|college|school|institute|manufacturer|newspaper|magazine|film|album|'
+ 'song|single|musical work|composition|television|series|book|novel|video game|painting|award|position|'
+ 'aircraft|ship|steamship|vehicle|automobile|tram|railway line|route|typeface|software|product|brand|artifact|artefact')],
['Doctrine', new RegExp('concept|theory|theorem|mathematical|programming language|language|gene|protein|chemical|compound|'
+ 'ideology|religion|discipline|field|cuisine|food|dish|drink|aspect|'
+ 'particle|process|genre|form\\b|game\\b|branch of|class of|type of|tabular|structure')],
];
/** Category fallback (stub categories are skipped). */
export const CATEGORY_RULES: Rules = [
['Figure', /\bbirth|\bdeaths\b|living people|people from|\bspecies\b|described in \d|\bgenera\b|deities|characters/],
['Event', /\belections\b|protests|\bbattles\b|disasters|\braces\b|\bseasons\b|\bevents\b|scandals|annexations|competitions/],
['Location', new RegExp('villages|communes|parishes|local government|populated places|geography|rivers|islands|buildings and structures|bridges|'
+ 'stations|parks|districts|townships|cities and towns|historic places|freguesias')],
['Institution', new RegExp('companies|organi[sz]ations|\\bfilms\\b|albums|songs|novels|newspapers|television series|musical groups|'
+ 'aircraft|ships|typefaces|software|awards|teams|clubs|establishments')],
['Doctrine', new RegExp('theory|structures$|algebra|terminology|cuisine|drinks|desserts|ecology|languages|diseases|conditions|'
+ 'concepts|ranks|etymology|maps|atlases')],
];
/** Description fallback (present on ~90% of the sample). */
export const DESCRIPTION_RULES: Rules = [
['Figure', /^(species|genus) of|\b(painter|politician|actor|actress|writer|player|singer|born|species|genus)\b/],
['Event', /\b(race|election|battle|match|protest|storm|war|competition)\b/],
['Location', /^(commune|village|town|municipality|river) in|\b(village|town|city|river|island|building|church|columbarium|station|park)\b/],
['Institution', /\b(company|band|film|album|organi[sz]ation|team|aircraft|ship|newspaper)\b/],
['Doctrine', /\b(concept|theory|structure|dessert|drink|dish|technique|class of)\b/],
];
/**
* On-chain data every block carries (protocol Article), used when the frozen profile is empty or
* missing: the mint-time `category` (server/wiki.ts buckets), the title and the extract.
*/
export interface ChainHints { title: string; extract?: string; category?: string }
/**
* Rules for an extract's definitional phrase ("is a village in …"). Broader than the short-description
* rules because lead sentences use more varied nouns. Order: Doctrine overrides, then as for labels.
*/
export const EXTRACT_RULES: Rules = [
['Doctrine', /\b(gene|protein|enzyme|disease|syndrome|disorder|theorem|conjecture|concept|theory|language|cuisine|dish|algebraic|mathematical|list of)\b/],
['Event', /\b(election|referendum|battle|war|siege|protest|riot|massacre|annexation|storm|hurricane|cyclone|tornado|tornadoes|earthquake|flood|season|tournament|championship|race|grand prix|match|festival|ceremony)\b/],
['Figure', /\b(actor|actress|politician|writer|author|poet|painter|artist|singer|musician|composer|director|producer|player|footballer|cricketer|athlete|boxer|scientist|engineer|bishop|priest|monarch|king|queen|sultan|businessman|businesswoman|family|dynasty|species|genus|breed|character|deity|god|goddess)\b/],
['Institution', /\b(company|corporation|business|manufacturer|organi[sz]ation|association|society|party|coalition|band|team|club|university|college|school|studio|newspaper|magazine|film|album|song|single|novel|book|series|video game|aircraft|airliner|ship|automobile|car|locomotive|tramway|railway line|bus route|typeface|software|position|office|award|diocese|council)\b/],
['Location', /\b(village|town|city|municipality|commune|parish|county|district|region|province|state|locality|hamlet|suburb|neighbourhood|neighborhood|settlement|community|census area|river|lake|island|mountain|plateau|valley|bay|peak|building|house|church|cathedral|mosque|temple|castle|ch[aâ]teau|palace|museum|pavilion|stadium|bridge|station|park|mall|shopping (centre|center)|road|street|square|monument)\b/],
];
/** Title patterns (checked after the extract's definitional phrase). */
export const TITLE_RULES: Rules = [
['Event', /\b(election|elections|referendum|straw poll|battle of|siege of|war|protests?|riots?|massacre|earthquake|hurricane|cyclone|typhoon|nor'easter|storm|flood|season|championship|tournament|grand prix|olympics|world cup|final)\b/i],
['Institution', /\((film|album|song|single|novel|book|band|tv series|television series|video game|magazine|newspaper|company|ship|aircraft|typeface|software)\)|\b(f\.?c\.?|company|corporation|university|college|school|party|club|association|society|records|airlines?)\b/i],
['Doctrine', /\((programming language|mathematics|disease|gene|chemistry|philosophy|religion)\)|\b(disease|syndrome|theorem|conjecture|cuisine)\b/i],
['Figure', /\((actor|actress|politician|footballer|cricketer|singer|musician|writer|author|painter|artist|boxer|wrestler|bishop|priest|judge|businessman|athlete|rugby union|rugby league|baseball|basketball)\)|\((plant|animal|bird|fish|moth|beetle|spider|fungus|genus)\)/i],
['Location', /\b(river|lake|mount|mountain|island|islands|county|village|township|parish|district|province|church|cathedral|chapel|castle|mosque|temple|abbey|bridge|station|house|park|street|road|square|tower|palace|fort|airport|dam|valley|bay)\b/i],
];
/** Mint-time category buckets that carry a type signal (History and Culture don't). */
export const CHAIN_CATEGORY_TYPE: Readonly<Record<string, CardType>> = {
People: 'Figure', Nature: 'Figure', Space: 'Location', Science: 'Doctrine',
};
/**
* The definitional phrase of an extract's first sentence: what follows "is a / was an / are the …",
* up to the next clause break. "Tom Ewell (1909–1994) was an American actor." → "american actor".
*/
export function definitionOf(extract: string | undefined): string {
const text = (extract ?? '').replace(/\s+/g, ' ').trim();
const m = /\b(?:is|was|are|were)\s+(?:an?|the|one of the)\s+([^.;:]{1,120})/i.exec(text);
return m ? m[1].toLowerCase() : '';
}
/** Lead-sentence life dates: "Name (born 1971)", "Name (1909–1994)", "Name (c. 1530 – 1548)". */
const LIFE_DATES = /^[^.(]{1,80}\((?:[^)]*;\s*)?(?:born\s+(?:[A-Z][a-z]+\s+)?(?:\d{1,2}\s+)?(?:[A-Z][a-z]+\s+)?\d{3,4}|(?:c\.\s*)?\d{3,4}\s*[–-]\s*(?:c\.\s*)?\d{3,4})/;
function firstRule(rules: Rules, texts: readonly string[]): [CardType, string] | null {
for (const [type, rx] of rules) for (const text of texts) if (rx.test(text)) return [type, text];
return null;
}
export function classify(profile: Pick<CardProfile, 'instanceOf' | 'subclassOf' | 'categories' | 'description'>,
chain?: ChainHints): Classification {
const p31 = profile.instanceOf ?? [];
const p279 = profile.subclassOf ?? [];
for (const c of p31) { const t = QID_ANCHORS[c.id]; if (t) return { type: t, source: 'qid', matched: c.id }; }
const p31Labels = p31.map(c => c.label.toLowerCase());
let hit = firstRule(LABEL_RULES, p31Labels);
if (hit) return { type: hit[0], source: 'p31', matched: hit[1] };
for (const c of p279) { const t = QID_ANCHORS[c.id]; if (t) return { type: t, source: 'p279-qid', matched: c.id }; }
hit = firstRule(LABEL_RULES, p279.map(c => c.label.toLowerCase()));
if (hit) return { type: hit[0], source: 'p279', matched: hit[1] };
const cats = (profile.categories ?? []).map(c => c.toLowerCase()).filter(c => !c.includes('stubs'));
hit = firstRule(CATEGORY_RULES, cats);
if (hit) return { type: hit[0], source: 'category', matched: hit[1] };
const desc = (profile.description ?? '').toLowerCase();
hit = firstRule(DESCRIPTION_RULES, desc ? [desc] : []);
if (hit) return { type: hit[0], source: 'description', matched: hit[1] };
if (chain) {
const extract = (chain.extract ?? '').replace(/\s+/g, ' ').trim();
const definition = definitionOf(extract);
hit = firstRule(EXTRACT_RULES, definition ? [definition] : []);
if (hit) return { type: hit[0], source: 'extract', matched: hit[1] };
if (LIFE_DATES.test(extract)) return { type: 'Figure', source: 'extract', matched: 'life dates' };
hit = firstRule(TITLE_RULES, chain.title ? [chain.title] : []);
if (hit) return { type: hit[0], source: 'title', matched: chain.title };
const t = chain.category ? CHAIN_CATEGORY_TYPE[chain.category] : undefined;
if (t) return { type: t, source: 'chain-category', matched: chain.category! };
}
return { type: 'Doctrine', source: 'fallback', matched: '' };
}
+325
View File
@@ -0,0 +1,325 @@
/**
* Duel card derivation: an on-chain card plus its frozen off-chain profile becomes a DuelCard
* (BRIEF "Stats", "Keywords", "Factions", "Connected"; data review §2 and §4; designer review §3).
* Pure and deterministic: no fetches, no clocks, no randomness. Every number is data in DERIVE_RULES.
* Owner: duel-cards.
*/
import type { Article } from '../protocol.ts';
import type { MintStatsSnapshot } from '../enrichment.ts';
import { rarity as rarityOf } from '../protocol.ts';
import { CARD_SAMPLE_PERCENTILES } from '../game/card-data.ts';
import { percentile } from '../game/derive.ts';
import { classify, type CardProfile, type CardType, type ClassifySource } from './classify.ts';
import { effectsFor, subtypeFor, type EffectSpec } from './effects.ts';
import { rulesTextFor } from './text.ts';
export type { CardProfile, CardType } from './classify.ts';
export type { EffectSpec } from './effects.ts';
export const DERIVE_VERSION = 'duel-derive-1';
import type { ConnectKeys as CoreConnectKeys, DuelCard as CoreDuelCard, Keyword, Portal } from './types.ts';
export type { Keyword, Portal } from './types.ts';
export { PORTALS } from './types.ts';
export type Rarity = NonNullable<CoreDuelCard['rarity']>;
/** What derive() reads from the chain: a minted block's article and stats snapshot. */
export interface CardOnChain {
tokenId: string;
/** `category` is the mint-time bucket (server/wiki.ts); only used when the profile is empty. */
article: Pick<Article, 'pageId' | 'title' | 'extract' | 'revisionId'> & { category?: string };
statsSnapshot: Pick<MintStatsSnapshot, 'pageBytes' | 'languageCount' | 'stats'>;
}
/** duel-core's ConnectKeys, with `cites` always present. */
export interface ConnectKeys extends CoreConnectKeys {
/** P17/P27 values, or normalised country names from text when Wikidata has none. */
countries: string[];
centuries: number[];
/** Outlink pageIds. */
links: number[];
/** P31 Q-ids, excluding human and taxon (the Kin tier). */
p31: string[];
/** This card's Wikidata item (omitted when it has none), and the item Q-ids its claims cite (Linked tier). */
qid?: string;
cites: string[];
}
/** duel-core's DuelCard (types.ts), with every field derive() always sets made required, plus audit fields. */
export interface DuelCard extends CoreDuelCard {
cardId: string;
pageId: number;
revisionId: number;
title: string;
/** Wikidata short description, for log first mentions (omitted when absent). */
description?: string;
type: CardType;
/** Template family within the type, e.g. 'conflict', 'election', 'organisation', 'pathology'. */
subtype: string | null;
portal: Portal;
cost: number;
/** Figures: power/toughness. Locations: 0 / Garrison. Others: null. */
power: number | null;
toughness: number | null;
/** Locations: Citations income ramp (the engine caps the total). */
territory: number;
keywords: Keyword[];
effects: EffectSpec[];
rulesText: string;
flavor: string;
connect: ConnectKeys;
rarity: Rarity;
deriveVersion: string;
/** Why the card got its type (for audit and the card's info panel). */
typedBy: ClassifySource;
/** The numbers behind cost and body, for the info panel and the simulator. */
basis: { pctAttention: number | null; pctDepth: number; pctReach: number; fame: number; magnitude: number };
}
export interface DeriveRules {
percentiles: Record<'attention' | 'depth' | 'reach', readonly number[]>;
/** fame → cost 1..6: 1 + number of thresholds ≤ fame. */
costThresholds: readonly number[];
/** P+T budget by cost (index = cost). MTG vanilla curve. */
bodyBudget: readonly number[];
maxKeywords: number;
/** Keywords that cost 1 point of body (from the larger stat, min 1 each). */
taxedKeywords: readonly Keyword[];
keywordOrder: readonly Keyword[];
featuredPct: number;
wellSourcedPct: number;
/** Translated: translatedPct ≤ pct_reach < multilingualPct. Multilingual: pct_reach ≥ multilingualPct. */
translatedPct: number;
multilingualPct: number;
stubBytes: number;
/** Garrison toughness = 1 + floor(pct_depth / garrisonStep). */
garrisonStep: number;
}
export const DERIVE_RULES: DeriveRules = {
percentiles: CARD_SAMPLE_PERCENTILES,
costThresholds: [26, 39, 51, 63, 78],
bodyBudget: [0, 3, 4, 6, 8, 10, 12],
maxKeywords: 2,
taxedKeywords: ['Protected', 'Featured', 'Legacy', 'Multilingual', 'Well-sourced'],
keywordOrder: ['Protected', 'Featured', 'Legacy', 'Multilingual', 'Translated', 'Well-sourced', 'Stub', 'Local'],
featuredPct: 85,
wellSourcedPct: 85,
translatedPct: 75,
multilingualPct: 90,
stubBytes: 3000,
garrisonStep: 25,
};
// ---------------------------------------------------------------- Portals (designer §3.2)
export const PORTAL_RULES: Readonly<Record<Exclude<Portal, 'Neutral'>, RegExp>> = {
Arts: /\b(actor|actress|singer|musician|rapper|band|album|song|single|film|novel|novelist|writer|poet|painter|artist|composer|television|tv series|music|theatre|theater|dance|dancer|video game|studio|animation|anime|fiction|character|literature|book|magazine|typeface|sculpt\w*|architect\w*|comedian|opera|orchestra)\b/g,
Earth: /\b(species|genus|genera|taxon|plant|plants|animal|bird|birds|fish|insect|moth|beetle|grasshopper|orchid|river|rivers|lake|mountain|island|islands|village|villages|commune|communes|geography|forest|park|ecology|breed|weather|storm|nor.easter|cyclone|earthquake|climate|flora|fauna|populated places|municipality|municipalities|county|township|parish|reef|valley|locality|oblast|freguesia|hamlet)\b/g,
History: /(\b\d+(st|nd|rd|th)-century\b|\b\d+ deaths\b|\b(sultan\w*|empire|castle|castles|medieval|ancient|dynasty|war|battle|battles|monarch|monarchs|king|queen|historic|archaeolog\w*|former|disestablish\w*|colonial|kingdom|museum|nobility|pharaoh)\b)/g,
Science: /\b(mathemat\w*|algebra\w*|programming|software|gene|genes|protein|chemi\w*|disease|diseases|scientist|physic\w*|astronom\w*|biolog\w*|medic\w*|engineer\w*|computer|computing|theorem|planet|galaxy|spacecraft|satellite|aircraft|technology|clinical|structure|structures|category theory|syndrome|virus|bacteri\w*)\b/g,
Society: /\b(politic\w*|politician|election|elections|party|government|law|court|sport|sports|football|cricket|basketball|baseball|olympic\w*|team|club|league|church|religio\w*|diocese|mosque|temple|school|university|company|companies|business|corporation|protest|protests|scandal|corruption|people from|living people|police|crime|cuisine|association|council)\b/g,
};
const PORTAL_TIE_ORDER: readonly Exclude<Portal, 'Neutral'>[] = ['History', 'Science', 'Arts', 'Society', 'Earth'];
export const TYPE_DEFAULT_PORTAL: Readonly<Record<CardType, Exclude<Portal, 'Neutral'>>> = {
Figure: 'Society', Location: 'Earth', Event: 'History', Institution: 'Arts', Doctrine: 'Science',
};
/** Count keyword hits over description + categories + P31 labels; ties go to the type default; no hits → Neutral. */
export function portalFor(profile: CardProfile, type: CardType): Portal {
const text = [profile.description ?? '', ...profile.categories, ...profile.instanceOf.map(c => c.label)]
.join(' | ').toLowerCase();
let best = 0; let tied: Exclude<Portal, 'Neutral'>[] = [];
for (const portal of PORTAL_TIE_ORDER) {
const hits = text.match(PORTAL_RULES[portal])?.length ?? 0;
if (hits > best) { best = hits; tied = [portal]; } else if (hits === best && hits > 0) tied.push(portal);
}
if (best === 0) return 'Neutral';
const fallback = TYPE_DEFAULT_PORTAL[type];
return tied.includes(fallback) ? fallback : tied[0];
}
// ---------------------------------------------------------------- Connected keys (data §4)
const COUNTRY_WORDS: readonly (readonly [RegExp, string])[] = ([
['United States|American', 'United States'], ['United Kingdom|British|England|English|Scotland|Scottish|Wales|Welsh', 'United Kingdom'],
['France|French', 'France'], ['Germany|German', 'Germany'], ['Japan|Japanese', 'Japan'], ['China|Chinese', 'China'],
['India|Indian', 'India'], ['Brazil|Brazilian', 'Brazil'], ['Poland|Polish', 'Poland'], ['Italy|Italian', 'Italy'],
['Spain|Spanish', 'Spain'], ['Austria|Austrian', 'Austria'], ['Canada|Canadian', 'Canada'], ['Australia|Australian', 'Australia'],
['Russia|Russian', 'Russia'], ['Mexico|Mexican', 'Mexico'], ['Iran|Iranian', 'Iran'], ['Pakistan|Pakistani', 'Pakistan'],
['Bangladesh|Bangladeshi', 'Bangladesh'], ['Sweden|Swedish', 'Sweden'], ['Norway|Norwegian', 'Norway'], ['Estonia|Estonian', 'Estonia'],
['Ukraine|Ukrainian', 'Ukraine'], ['Croatia|Croatian', 'Croatia'], ['Philippines|Filipino', 'Philippines'], ['Cuba|Cuban', 'Cuba'],
['Israel|Israeli', 'Israel'], ['Portugal|Portuguese', 'Portugal'], ['Ireland|Irish', 'Ireland'], ['Kazakhstan|Kazakh', 'Kazakhstan'],
['Malaysia|Malaysian', 'Malaysia'], ['Argentina|Argentine', 'Argentina'], ['Belgium|Belgian', 'Belgium'], ['Iceland|Icelandic', 'Iceland'],
['Thailand|Thai', 'Thailand'], ['Singapore', 'Singapore'], ['Sri Lanka|Sri Lankan', 'Sri Lanka'], ['Slovenia|Slovene|Slovenian', 'Slovenia'],
['Moldova', 'Moldova'], ['Cyprus|Cypriot', 'Cyprus'], ['North Macedonia|Macedonian', 'North Macedonia'], ['Mauritania', 'Mauritania'],
['Congo', 'Congo'], ['New Zealand', 'New Zealand'], ['Korea|Korean', 'Korea'], ['Indonesia|Indonesian|Aceh', 'Indonesia'],
['Czech', 'Czechia'], ['Netherlands|Dutch', 'Netherlands'], ['Greece|Greek', 'Greece'], ['Turkey|Turkish', 'Turkey'],
['Egypt|Egyptian', 'Egypt'], ['Nigeria|Nigerian', 'Nigeria'], ['Kenya|Kenyan', 'Kenya'], ['Ghana|Gold Coast', 'Ghana'],
['Finland|Finnish', 'Finland'], ['Denmark|Danish', 'Denmark'], ['Switzerland|Swiss', 'Switzerland'], ['Hungary|Hungarian', 'Hungary'],
['Romania|Romanian', 'Romania'], ['Serbia|Serbian', 'Serbia'], ['Bulgaria|Bulgarian', 'Bulgaria'], ['Vietnam|Vietnamese', 'Vietnam'],
['Sri Lanka', 'Sri Lanka'], ['Chile|Chilean', 'Chile'], ['Colombia|Colombian', 'Colombia'], ['Peru|Peruvian', 'Peru'],
] as const).map(([rx, name]) => [new RegExp(`\\b(${rx})\\b`), name] as const);
const YEAR = /\b(1[0-9]{3}|20[0-2][0-9])\b/g;
const CENTURY = /\b(\d{1,2})(st|nd|rd|th)[- ]century\b/gi;
export function connectKeysFor(title: string, profile: CardProfile): ConnectKeys {
const text = [profile.description ?? '', ...profile.categories].join(' | ');
const countries = profile.countries?.length
? [...new Set(profile.countries)]
: [...new Set(COUNTRY_WORDS.filter(([rx]) => rx.test(text)).map(([, name]) => name))];
const centuries = new Set<number>();
if (profile.years?.length) for (const y of profile.years) centuries.add(y > 0 ? Math.floor((y - 1) / 100) + 1 : -(Math.floor(-y / 100) + 1));
else {
for (const m of `${title} | ${text}`.matchAll(YEAR)) centuries.add(Math.floor((Number(m[1]) - 1) / 100) + 1);
for (const m of text.matchAll(CENTURY)) centuries.add(Number(m[1]));
}
return {
countries: countries.sort(),
centuries: [...centuries].sort((a, b) => a - b),
links: [...new Set(profile.links ?? [])].sort((a, b) => a - b),
p31: [...new Set(profile.instanceOf.map(c => c.id).filter(id => id !== 'Q5' && id !== 'Q16521'))].sort(),
...(profile.wikidataId ? { qid: profile.wikidataId } : {}),
cites: [...new Set(profile.cites ?? [])].sort(),
};
}
// ---------------------------------------------------------------- Flavour
/** First sentence of the on-chain extract (BRIEF "Flavour text"); the description if there is no extract. */
export function flavorFor(extract: string, description: string | null): string {
const text = extract.replace(/\s+/g, ' ').trim();
if (!text) return (description ?? '').trim();
// A sentence ends at . ! ? followed by a space and an uppercase letter or a quote, skipping
// common abbreviations and initials ("U.S.", "St.", "J. R. R.") so names are not cut.
const re = /[.!?](?=\s+["'“(\[]?[A-Z0-9])/g;
let m: RegExpExecArray | null;
while ((m = re.exec(text))) {
const before = text.slice(0, m.index);
const word = before.split(/\s/).pop() ?? '';
if (/^([A-Z]|[A-Z][a-z]{0,2}|[A-Z]\.[A-Z]|U\.S|U\.K|c|ca|St|Dr|Mr|Mrs|Ms|Jr|Sr|No|vs|etc|Inc|Ltd|Co|Mt|Ft|Gen|Col|Lt|Sgt|Rev|Prof)$/.test(word.replace(/\.$/, ''))) continue;
return text.slice(0, m.index + 1);
}
return text;
}
// ---------------------------------------------------------------- Stats and keywords (data §2, designer §3.3–3.4)
export interface Percentiles { attention: number | null; depth: number; reach: number }
export function percentilesFor(stats: MintStatsSnapshot['stats'], rules: DeriveRules = DERIVE_RULES): Percentiles {
return {
attention: stats.attention === null ? null : percentile(stats.attention, rules.percentiles.attention),
depth: percentile(stats.depth, rules.percentiles.depth),
reach: percentile(stats.reach, rules.percentiles.reach),
};
}
export function fameOf(p: Percentiles): number {
const values = [p.attention, p.depth, p.reach].filter((v): v is number => v !== null);
return Math.floor(values.reduce((a, b) => a + b, 0) / values.length + 0.5);
}
export function costForFame(fame: number, rules: DeriveRules = DERIVE_RULES): number {
return 1 + rules.costThresholds.filter(t => t <= fame).length;
}
/** Every keyword the data triggers, in priority order (before the cap). */
export function triggeredKeywords(chain: CardOnChain, profile: CardProfile, p: Percentiles, rules: DeriveRules = DERIVE_RULES): Keyword[] {
const cats = profile.categories;
const on: Record<Keyword, boolean> = {
Protected: cats.includes('Living people'),
Featured: p.attention !== null && p.attention >= rules.featuredPct,
Legacy: profile.died === true || cats.some(c => /^\d+s? (BC )?deaths$/.test(c)),
'Well-sourced': p.depth >= rules.wellSourcedPct,
// Two bands of the same reach axis: a card never has both (DUEL_DESIGN §4).
Multilingual: p.reach >= rules.multilingualPct,
Translated: p.reach >= rules.translatedPct && p.reach < rules.multilingualPct,
Stub: cats.some(c => c.toLowerCase().includes('stubs')) || chain.statsSnapshot.pageBytes < rules.stubBytes,
Local: chain.statsSnapshot.stats.reach === 0,
// Granted by Trending mode from frozen live data, never by derivation.
Trending: false,
};
return rules.keywordOrder.filter(k => on[k]);
}
export interface Body { power: number; toughness: number; keywords: Keyword[] }
/**
* Figure body (DUEL_DESIGN §3): take the first ≤2 triggered keywords in priority order, subtract 1
* from the cost's P+T budget per taxed keyword, then split by attention vs depth, each stat ≥ 1.
* A taxed keyword that would leave less than 2 points is skipped for the next one.
*/
export function figureBody(cost: number, p: Percentiles, keywords: readonly Keyword[], rules: DeriveRules = DERIVE_RULES): Body {
let budget = rules.bodyBudget[cost];
if (budget === undefined) throw new RangeError(`bodyBudget has no entry for cost ${cost}`);
const kept: Keyword[] = [];
for (const k of keywords) {
if (kept.length >= rules.maxKeywords) break;
if (rules.taxedKeywords.includes(k)) {
if (budget <= 2) continue;
budget--;
}
kept.push(k);
}
const a = p.attention ?? 50;
const power = Math.min(budget - 1, Math.max(1, Math.round(budget * a / Math.max(1, a + p.depth))));
return { power, toughness: budget - power, keywords: kept };
}
// ---------------------------------------------------------------- derive
export function derive(chain: CardOnChain, profile: CardProfile, rules: DeriveRules = DERIVE_RULES): DuelCard {
const { type, source } = classify(profile, chain.article);
const p = percentilesFor(chain.statsSnapshot.stats, rules);
const fame = fameOf(p);
const baseCost = costForFame(fame, rules);
const magnitude = Math.ceil(baseCost / 2);
const portal = portalFor(profile, type);
const subtype = subtypeFor(type, profile, chain.article);
let cost = baseCost, power: number | null = null, toughness: number | null = null, territory = 0;
let keywords: Keyword[] = [];
if (type === 'Figure') {
const body = figureBody(baseCost, p, triggeredKeywords(chain, profile, p, rules), rules);
({ power, toughness, keywords } = body);
} else if (type === 'Location') {
cost = magnitude;
power = 0;
toughness = 1 + Math.floor(p.depth / rules.garrisonStep);
territory = 1;
}
const effects = effectsFor(type, subtype, baseCost);
const card: DuelCard = {
cardId: chain.tokenId, pageId: chain.article.pageId, revisionId: chain.article.revisionId, title: chain.article.title,
type, subtype, portal, cost, power, toughness, territory, keywords, effects, rulesText: '',
flavor: flavorFor(chain.article.extract, profile.description),
connect: connectKeysFor(chain.article.title, profile),
rarity: rarityOf(chain.tokenId), deriveVersion: DERIVE_VERSION, typedBy: source,
basis: { pctAttention: p.attention, pctDepth: p.depth, pctReach: p.reach, fame, magnitude },
};
if (profile.description) card.description = profile.description;
card.rulesText = rulesTextFor(card);
return card;
}
// ---------------------------------------------------------------- Connected (data §4)
/** DUEL_DESIGN §6: Contemporary counts only between different types. */
export type ConnectedTier = 'Linked' | 'Compatriot' | 'Contemporary' | 'Kin';
/** The strongest Connected tier between two cards, or null. Linked gives +2/+2, the others +1/+1 (BRIEF). */
export function connectedTier(a: DuelCard, b: DuelCard,
tiers: readonly ConnectedTier[] = ['Linked', 'Compatriot', 'Contemporary', 'Kin']): ConnectedTier | null {
if (a.cardId === b.cardId) return null;
const meets = (x: readonly (string | number)[], y: readonly (string | number)[]) => x.some(v => y.includes(v));
for (const tier of tiers) {
if (tier === 'Linked' && (a.connect.links.includes(b.pageId) || b.connect.links.includes(a.pageId)
|| (b.connect.qid !== undefined && a.connect.cites.includes(b.connect.qid))
|| (a.connect.qid !== undefined && b.connect.cites.includes(a.connect.qid)))) return tier;
if (tier === 'Compatriot' && meets(a.connect.countries, b.connect.countries)) return tier;
if (tier === 'Contemporary' && a.type !== b.type && meets(a.connect.centuries, b.connect.centuries)) return tier;
if (tier === 'Kin' && meets(a.connect.p31, b.connect.p31)) return tier;
}
return null;
}
+116
View File
@@ -0,0 +1,116 @@
/**
* Effect templates by type and subtype (designer review §3.5; DUEL_DESIGN.md wins where they differ).
* Effects are plain data for duel-core's interpreter. k = ceil(cost / 2), 1–3, from the derived (fame) cost.
* Owner: duel-cards.
*/
import { definitionOf, type CardProfile, type CardType, type ChainHints } from './classify.ts';
import type { EffectSpec } from './types.ts';
export type { EffectOp, EffectSpec, EffectTrigger, TargetSpec as EffectTarget } from './types.ts';
type Subtypes = readonly (readonly [string, RegExp])[];
/**
* Subtype rules per type (DUEL_DESIGN §5), run over P31 labels, P279 labels, the description, then
* categories. First match in list order wins; no match is the type's default template.
* Additions beyond §5 (marked +): bands/associations count as organisations; 'flood' etc. as listed.
*/
export const SUBTYPE_RULES: Readonly<Record<CardType, Subtypes>> = {
Event: [
['conflict', /battle|war\b|siege|annexation|protest|riot|uprising|massacre|coup/],
['disaster', /storm|nor.easter|cyclone|hurricane|earthquake|flood|tornado|wildfire|eruption|famine|epidemic/],
['election', /election|referendum|straw poll/],
['sport', /match|final\b|season|tournament|championship|grand prix|\brace\b/],
],
Institution: [
['organisation', /company|organi[sz]ation|party|agency|studio|military|university|diocese|council|band\b|musical group|association|business|school|college|institute|manufacturer/],
['work', /film|album|song|\bbook|novel|series|video game|painting|software|typeface|newspaper|magazine/],
],
Doctrine: [
['pathology', /disease|clinical sign|pathogen|syndrome|disorder|toxin|poison/],
['language', /language|software|programming/],
['mathematics', /mathemat|theorem|algebra|geometr|polytope|polyhedron|equation|number theory|structure/],
['ideology', /ideology|religion|belief|doctrine|philosophy|theology/],
],
Figure: [],
Location: [],
};
/** Default template names, for the info panel (null subtype). */
export const DEFAULT_SUBTYPE: Readonly<Record<CardType, string | null>> = {
Figure: null, Location: null, Event: 'other', Institution: 'other', Doctrine: 'adopt',
};
export function subtypeFor(type: CardType, profile: Pick<CardProfile, 'instanceOf' | 'subclassOf' | 'description' | 'categories'>,
chain?: ChainHints): string | null {
const groups = [
[...profile.instanceOf.map(c => c.label), ...(profile.subclassOf ?? []).map(c => c.label)],
[profile.description ?? ''],
[...(profile.categories ?? []).filter(c => !/stubs$/i.test(c))],
// On-chain fallbacks, last: the extract's definitional phrase, then the title.
[definitionOf(chain?.extract), chain?.title ?? ''],
].map(g => g.map(t => t.toLowerCase()).filter(Boolean));
for (const texts of groups) for (const [name, rx] of SUBTYPE_RULES[type]) if (texts.some(t => rx.test(t))) return name;
return DEFAULT_SUBTYPE[type];
}
/** The effect list for a card (T1–T12). Figures and Locations have none beyond keywords and stats. */
/** DUEL_DESIGN §5 template id by type and subtype. */
export function templateFor(type: CardType, subtype: string | null): string | null {
switch (type) {
case 'Figure': return 'T1';
case 'Location': return 'T2';
case 'Event': return ({ conflict: 'T3', disaster: 'T4', election: 'T5', sport: 'T6' } as Record<string, string>)[subtype ?? ''] ?? 'T7';
case 'Institution': return subtype === 'organisation' ? 'T8' : subtype === 'work' ? 'T9' : 'T10';
case 'Doctrine': return subtype === 'pathology' ? 'T12' : 'T11';
}
}
export function effectsFor(type: CardType, subtype: string | null, cost: number): EffectSpec[] {
const template = templateFor(type, subtype);
return baseEffects(type, subtype, cost).map(e => (template ? { ...e, template } : e));
}
function baseEffects(type: CardType, subtype: string | null, cost: number): EffectSpec[] {
const k = Math.ceil(cost / 2);
switch (type) {
case 'Event':
switch (subtype) {
case 'conflict': return [{ trigger: 'onPlay', op: 'damage', target: 'figureOrLocation', amount: k + 1 }];
case 'disaster': return [{ trigger: 'onPlay', op: 'damageEach', target: 'each', amount: Math.max(1, k - 1) }];
case 'election': return [{ trigger: 'onPlay', op: 'createToken', amount: k,
token: { name: 'Elected Member', power: 1, toughness: 1, portal: 'Society' } }];
case 'sport': return [
{ trigger: 'onPlay', op: 'pump', target: 'ownFigure', power: k, toughness: 0, duration: 'turn' },
{ trigger: 'onPlay', op: 'fight', target: 'opponentFigure' },
];
default: return [{ trigger: 'onPlay', op: 'draw', amount: k }];
}
case 'Institution':
switch (subtype) {
case 'organisation': {
const token = { name: 'Staff Member', power: 1, toughness: 1, portal: 'Neutral' as const };
return cost >= 4
? [{ trigger: 'startOfTurn', op: 'createToken', amount: 1, token, condition: { maxTokens: 3 } }]
: [{ trigger: 'onEnter', op: 'createToken', amount: 1, token }];
}
case 'work': return [
{ trigger: 'onEnter', op: 'draw', amount: 1 },
{ trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 1, condition: { connected: true } },
];
default: return [{ trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 0, condition: { maxPower: 2 } }];
}
case 'Doctrine': {
// DUEL_API "Doctrine": `attach` picks the Figure; the buff is a static pump on `attached`.
const pathology = subtype === 'pathology';
const attach: EffectSpec = { trigger: 'onPlay', op: 'attach', target: pathology ? 'figure' : 'ownFigure' };
const buff: EffectSpec = { trigger: 'static', op: 'pump', target: 'attached', power: pathology ? -k : k, toughness: pathology ? -k : k };
if (pathology) return [attach, buff];
if (subtype === 'mathematics') return [attach, { ...buff, grant: ['Well-sourced'] }];
if (subtype === 'language') return [attach, buff, { trigger: 'onCombatDamageToPlayer', op: 'draw', amount: 1 }];
if (subtype === 'ideology') return [attach, buff, { trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 0, condition: { samePortal: true } }];
return [attach, buff];
}
default: return [];
}
}
+908
View File
@@ -0,0 +1,908 @@
/**
* WikiDeck Duel engine (off-chain, pure, deterministic). Spec: docs/game/DUEL_API.md.
* No stack, sorcery speed only, atomic actions, clone-on-apply.
*/
import { Rng } from '../game/rng.ts';
import { DEFAULT_DUEL_RULESET, parseDuelRuleset } from './ruleset.ts';
import type {
CardInstance, CardRef, ConnectedTier, DuelAction, DuelCard, DuelResult, DuelRuleset, DuelState, EffectSpec, EndReason,
Keyword, LogEvent, Permanent, PermanentView, PlayerState, PlayerView, Seat, SideView, TargetRef, TargetSpec,
} from './types.ts';
import { CARD_TYPES, KEYWORDS } from './types.ts';
type LogBody = LogEvent extends infer E ? (E extends LogEvent ? Omit<E, 'seq' | 'turn'> : never) : never;
type Source = Permanent | CardInstance;
const other = (seat: Seat): Seat => (seat === 0 ? 1 : 0);
const pw = (card: DuelCard) => card.power ?? 0;
const tg = (card: DuelCard) => card.toughness ?? 0;
const CHOSEN: ReadonlySet<TargetSpec> = new Set(['figure', 'figureOrLocation', 'ownFigure', 'opponentFigure', 'anyTarget']);
const NO_KIN = new Set(['Q5', 'Q16521']);
const MAX_COMBOS = 64;
function targetOf(e: EffectSpec): TargetSpec {
if (e.target) return e.target;
switch (e.op) {
case 'damage': return 'anyTarget';
case 'damageEach': return 'each';
case 'pump': return 'self';
case 'drain': return 'opponent';
case 'attach': return 'ownFigure';
case 'fight': return 'opponentFigure';
case 'destroy': case 'bounce': case 'tap': return 'opponentFigure';
default: return 'controller';
}
}
const isEntry = (e: EffectSpec) => e.trigger === 'onPlay' || e.trigger === 'onEnter';
// ---------------------------------------------------------------------------
// Decks
// ---------------------------------------------------------------------------
export function validateDeck(rules: DuelRuleset, cards: DuelCard[]): void {
if (!Array.isArray(cards)) throw new TypeError('Deck must be an array');
if (cards.length !== rules.deckSize) throw new RangeError(`Deck must have exactly ${rules.deckSize} cards (has ${cards.length})`);
const ids = new Set<string>();
const pages = new Map<number, number>();
for (const card of cards) {
if (!card || typeof card.cardId !== 'string' || !card.cardId) throw new TypeError('Card needs a cardId');
if (card.token) throw new RangeError(`Tokens can't be in decks (${card.cardId})`);
if (ids.has(card.cardId)) throw new RangeError(`Duplicate card ${card.cardId}`);
ids.add(card.cardId);
if (card.pageId !== null) {
const n = (pages.get(card.pageId) ?? 0) + 1;
if (n > rules.maxCopiesPerPage) throw new RangeError(`More than ${rules.maxCopiesPerPage} copies of page ${card.pageId}`);
pages.set(card.pageId, n);
}
if (!CARD_TYPES.includes(card.type)) throw new RangeError(`Bad card type ${card.type}`);
if (!Number.isInteger(card.cost) || card.cost < 0 || card.cost > 20) throw new RangeError(`Bad cost on ${card.cardId}`);
for (const n of [pw(card), tg(card)]) if (!Number.isInteger(n) || n < 0 || n > 50) throw new RangeError(`Bad stats on ${card.cardId}`);
if (card.type === 'Figure' && tg(card) < 1) throw new RangeError(`Figure ${card.cardId} needs toughness ≥ 1`);
if (!Array.isArray(card.keywords)) throw new TypeError(`Bad keywords on ${card.cardId}`);
// Trending is granted by the host at match start (applyLive) and doesn't count toward the limit.
if (card.keywords.filter(k => k !== 'Trending').length > rules.maxKeywords) throw new RangeError(`Too many keywords on ${card.cardId}`);
for (const k of card.keywords) if (!KEYWORDS.includes(k)) throw new RangeError(`Unknown keyword ${k}`);
if (!Array.isArray(card.effects) || card.effects.length > 4) throw new RangeError(`Bad effects on ${card.cardId}`);
if (card.territory !== undefined && (!Number.isInteger(card.territory) || card.territory < 0 || card.territory > 5)) throw new RangeError(`Bad territory on ${card.cardId}`);
}
}
// ---------------------------------------------------------------------------
// Creation
// ---------------------------------------------------------------------------
function emptyPlayer(rules: DuelRuleset, library: CardInstance[]): PlayerState {
return {
life: rules.startingLife, citations: 0, baseCitations: 0, library, hand: [], graveyard: [], mulligansTaken: 0, ready: false,
locationsThisTurn: 0, bankSeconds: rules.bankSeconds, timeouts: 0, fatigue: 0,
};
}
export function createDuel(rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string): DuelState {
const r = parseDuelRuleset(rules);
const rng = Rng.fromSeed(seed);
const firstSeat = rng.int(2) as Seat;
const players = ([0, 1] as Seat[]).map(seat => {
const instances = decks[seat].map((card, i) => ({ uid: `${seat}:${i}`, owner: seat, card: structuredClone(card) }));
return emptyPlayer(r, rng.shuffle(instances));
}) as [PlayerState, PlayerState];
const state: DuelState = {
engine: 'duel', rules: r, seed, rng: rng.state, turn: 0, active: firstSeat, firstSeat, phase: 'mulligan',
players, battlefield: [], combat: { attackers: [], blocks: {} }, log: [], result: null, version: 0, nextToken: 0, nextEntry: 0,
};
log(state, { kind: 'start', firstSeat });
for (const p of state.players) p.hand = p.library.splice(0, r.openingHand);
return state;
}
// ---------------------------------------------------------------------------
// Queries
// ---------------------------------------------------------------------------
export function toAct(state: DuelState): Seat | null {
if (state.result) return null;
if (state.phase === 'mulligan') {
for (const seat of [0, 1] as Seat[]) if (!state.players[seat].ready) return seat;
return null;
}
return state.phase === 'block' ? other(state.active) : state.active;
}
export const isOver = (state: DuelState) => state.result !== null;
export const result = (state: DuelState): DuelResult | null => state.result;
export const turnOf = (state: DuelState) => state.turn;
const find = (state: DuelState, uid: string) => state.battlefield.find(p => p.uid === uid);
export function maxCitations(state: DuelState, seat: Seat): number {
const territory = state.battlefield.filter(p => p.controller === seat && p.card.type === 'Location').reduce((n, p) => n + (p.card.territory ?? 0), 0);
return state.players[seat].baseCitations + Math.min(state.rules.territoryCap, territory);
}
/** Connected tier between two cards (DUEL_DESIGN §6), best tier first, limited to rules.connectedTiers. */
export function tierBetween(rules: DuelRuleset, a: DuelCard, b: DuelCard): { tier: ConnectedTier; via: string } | null {
const ca = a.connect, cb = b.connect;
if (!ca || !cb) return null;
const on = (t: ConnectedTier) => rules.connectedTiers.includes(t);
const linked = (b.pageId !== null && ca.links.includes(b.pageId)) || (a.pageId !== null && cb.links.includes(a.pageId));
const cited = (!!cb.qid && !!ca.cites?.includes(cb.qid)) || (!!ca.qid && !!cb.cites?.includes(ca.qid));
if (on('Linked') && (linked || cited)) return { tier: 'Linked', via: cited ? 'claim' : 'link' };
if (on('Compatriot')) { const c = ca.countries.find(x => cb.countries.includes(x)); if (c !== undefined) return { tier: 'Compatriot', via: `country: ${c}` }; }
if (on('Contemporary') && a.type !== b.type) { const c = ca.centuries.find(x => cb.centuries.includes(x)); if (c !== undefined) return { tier: 'Contemporary', via: `century: ${c}` }; }
if (on('Kin')) { const c = ca.p31.find(x => !NO_KIN.has(x) && cb.p31.includes(x)); if (c !== undefined) return { tier: 'Kin', via: `instance of: ${c}` }; }
return null;
}
function connectionOf(state: DuelState, perm: Permanent): { with: Permanent; tier: ConnectedTier; via: string; bonus: number } | null {
if (perm.card.type !== 'Figure' || !perm.card.connect) return null;
let best: { with: Permanent; tier: ConnectedTier; via: string; bonus: number } | null = null;
for (const mate of state.battlefield) {
if (mate.uid === perm.uid || mate.controller !== perm.controller) continue;
const t = tierBetween(state.rules, perm.card, mate.card);
if (!t) continue;
const bonus = t.tier === 'Linked' ? state.rules.linkedBonus : state.rules.connectedBonus;
if (!best || bonus > best.bonus) best = { with: mate, tier: t.tier, via: t.via, bonus };
}
return best;
}
/** Does a static effect of `src` apply to `perm`? Conditions use printed power (no feedback). */
function staticApplies(state: DuelState, src: Permanent, e: EffectSpec, perm: Permanent): boolean {
const fig = perm.card.type === 'Figure';
const t = targetOf(e);
const hit = t === 'attached' ? src.attachedTo === perm.uid
: t === 'self' ? src.uid === perm.uid
: t === 'ownFigures' ? fig && perm.controller === src.controller
: t === 'opponentFigures' ? fig && perm.controller !== src.controller
: t === 'each' ? fig || perm.card.type === 'Location' : false;
if (!hit) return false;
const c = e.condition;
if (!c) return true;
if (c.maxPower !== undefined && pw(perm.card) > c.maxPower) return false;
if (c.samePortal) {
const anchorUid = src.card.type === 'Doctrine' ? src.attachedTo : src.uid;
const anchor = anchorUid ? find(state, anchorUid) : undefined;
if (!anchor || perm.uid === anchor.uid || perm.card.portal !== anchor.card.portal) return false;
}
if (c.connected && !tierBetween(state.rules, perm.card, src.card)) return false;
return true;
}
function statics(state: DuelState, perm: Permanent): { p: number; t: number; grants: Keyword[] } {
let p = 0, t = 0;
const grants: Keyword[] = [];
for (const src of state.battlefield) {
for (const e of src.card.effects) {
if (e.trigger !== 'static' || !staticApplies(state, src, e, perm)) continue;
if (e.op === 'pump') { p += e.power ?? e.amount ?? 0; t += e.toughness ?? e.amount ?? 0; }
if (e.grant) grants.push(...e.grant);
}
}
return { p, t, grants };
}
export function keywordsOf(state: DuelState, perm: Permanent): Keyword[] {
const out = new Set<Keyword>([...perm.card.keywords, ...perm.permKeywords, ...perm.tempKeywords, ...statics(state, perm).grants]);
return KEYWORDS.filter(k => out.has(k));
}
const hasKw = (state: DuelState, perm: Permanent, k: Keyword) => keywordsOf(state, perm).includes(k);
export function statsOfPermanent(state: DuelState, perm: Permanent): { power: number; toughness: number } {
if (perm.card.type === 'Location') {
return { power: Math.max(0, perm.tempPower), toughness: tg(perm.card) > 0 ? tg(perm.card) + perm.tempToughness : 0 };
}
if (perm.card.type !== 'Figure') return { power: 0, toughness: 0 };
const s = statics(state, perm);
const c = connectionOf(state, perm)?.bonus ?? 0;
const kws = new Set([...perm.card.keywords, ...perm.permKeywords, ...perm.tempKeywords, ...s.grants]);
let local = 0;
if (kws.has('Local') && perm.card.connect?.countries.length) {
const mine = perm.card.connect.countries;
if (state.battlefield.some(l => l.controller === perm.controller && l.card.type === 'Location' && l.card.connect?.countries.some(x => mine.includes(x)))) local = 1;
}
const trend = kws.has('Trending') ? state.rules.trendingPower : 0;
const extra = perm.counters + c + local;
return {
power: Math.max(0, pw(perm.card) + extra + perm.permPower + perm.tempPower + s.p + trend),
toughness: tg(perm.card) + extra + perm.permToughness + perm.tempToughness + s.t,
};
}
export function statsOf(state: DuelState, uid: string): { power: number; toughness: number } {
const perm = find(state, uid);
if (!perm) throw new RangeError(`No permanent ${uid}`);
return statsOfPermanent(state, perm);
}
/** Figures, and Locations with a Garrison, can block and can be destroyed by damage. */
const isBody = (perm: Permanent) => perm.card.type === 'Figure' || (perm.card.type === 'Location' && tg(perm.card) > 0);
function canBlock(state: DuelState, blocker: Permanent, attacker: Permanent): boolean {
const ka = keywordsOf(state, attacker);
const kb = blocker.card.type === 'Figure' ? keywordsOf(state, blocker) : [];
if (ka.includes('Featured') && !kb.some(k => k === 'Featured' || k === 'Translated' || k === 'Multilingual')) return false;
if (ka.includes('Multilingual') && kb.includes('Local')) return false;
return true;
}
function candidates(state: DuelState, seat: Seat, card: DuelCard, e: EffectSpec): TargetRef[] {
const t = targetOf(e);
const out: TargetRef[] = [];
const shielded = (p: Permanent) => p.controller !== seat && (card.type === 'Event' || card.type === 'Doctrine') && hasKw(state, p, 'Protected');
for (const p of state.battlefield) {
const fig = p.card.type === 'Figure';
const ok = t === 'figure' ? fig
: t === 'figureOrLocation' || t === 'anyTarget' ? fig || (p.card.type === 'Location' && tg(p.card) > 0)
: t === 'ownFigure' ? fig && p.controller === seat
: t === 'opponentFigure' ? fig && p.controller !== seat : false;
if (!ok || shielded(p)) continue;
if (e.condition?.maxPower !== undefined && pw(p.card) > e.condition.maxPower) continue;
out.push({ kind: 'card', uid: p.uid });
}
if (t === 'anyTarget') out.push({ kind: 'player', seat: other(seat) }, { kind: 'player', seat });
return out;
}
/** All target combinations for playing `card` now (capped), [] if it can't be played, [[]] if it needs none. */
function targetCombos(state: DuelState, seat: Seat, card: DuelCard): TargetRef[][] {
const chosen = card.effects.filter(e => isEntry(e) && CHOSEN.has(targetOf(e)));
if (!chosen.length) return [[]];
const lists = chosen.map(e => candidates(state, seat, card, e));
const permanent = card.type !== 'Event' && card.type !== 'Doctrine';
if (lists.some(l => !l.length)) return permanent ? [[]] : [];
let combos: TargetRef[][] = [[]];
for (const list of lists) {
const next: TargetRef[][] = [];
for (const c of combos) for (const t of list) {
if (t.kind === 'card' && c.some(x => x.kind === 'card' && x.uid === t.uid)) continue;
if (next.length < MAX_COMBOS) next.push([...c, t]);
}
combos = next;
}
return combos.length ? combos : permanent ? [[]] : [];
}
export function legalActions(state: DuelState, seat: Seat): DuelAction[] {
if (toAct(state) !== seat) return [];
const p = state.players[seat];
switch (state.phase) {
case 'mulligan':
return p.mulligansTaken < state.rules.mulligans ? [{ type: 'keep' }, { type: 'mulligan' }] : [{ type: 'keep' }];
case 'main': {
const out: DuelAction[] = [];
for (const inst of p.hand) {
if (inst.card.cost > p.citations) continue;
if (inst.card.type === 'Location' && p.locationsThisTurn >= state.rules.locationsPerTurn) continue;
for (const targets of targetCombos(state, seat, inst.card)) {
out.push(targets.length ? { type: 'play', uid: inst.uid, targets } : { type: 'play', uid: inst.uid });
}
}
out.push({ type: 'endPhase' });
return out;
}
case 'attack': {
const out: DuelAction[] = [];
for (const perm of state.battlefield) {
if (perm.controller !== seat || perm.card.type !== 'Figure' || perm.tapped || state.combat.attackers.includes(perm.uid)) continue;
if (perm.sick && !hasKw(state, perm, 'Trending')) continue;
out.push({ type: 'toggleAttacker', uid: perm.uid });
}
out.push({ type: 'confirmAttack' });
return out;
}
case 'block':
return [...blockOptions(state), { type: 'confirmBlocks' }];
default:
return [];
}
}
function blockOptions(state: DuelState): DuelAction[] {
const defender = other(state.active);
const out: DuelAction[] = [];
const blocked = new Set(Object.values(state.combat.blocks));
for (const b of state.battlefield) {
if (b.controller !== defender || b.tapped || !isBody(b) || state.combat.blocks[b.uid]) continue;
for (const aUid of state.combat.attackers) {
if (blocked.has(aUid)) continue;
const a = find(state, aUid);
if (a && canBlock(state, b, a)) out.push({ type: 'block', blocker: b.uid, attacker: aUid });
}
}
return out;
}
// ---------------------------------------------------------------------------
// Mutation helpers (operate on a private clone)
// ---------------------------------------------------------------------------
function log(state: DuelState, body: LogBody): void {
state.log.push({ seq: state.log.length, turn: state.turn, ...body } as LogEvent);
}
function ref(state: DuelState, inst: Source): CardRef {
const out: CardRef = { uid: inst.uid, cardId: inst.card.cardId, title: inst.card.title, pageId: inst.card.pageId, type: inst.card.type };
const perm = find(state, inst.uid);
if (perm && isBody(perm)) Object.assign(out, statsOfPermanent(state, perm));
return out;
}
const life = (state: DuelState): [number, number] => [state.players[0].life, state.players[1].life];
function finish(state: DuelState, winner: Seat | null, reason: EndReason): void {
if (state.result) return;
state.result = { winner, reason };
state.phase = 'over';
log(state, { kind: 'gameOver', winner, reason, life: life(state) });
}
function draw(state: DuelState, seat: Seat, n: number): void {
const p = state.players[seat];
for (let i = 0; i < n && !state.result; i++) {
if (!p.library.length) {
const mode = state.rules.libraryEmpty;
if (mode === 'reshuffle' && p.graveyard.length) {
const rng = new Rng(state.rng);
p.library = rng.shuffle(p.graveyard);
p.graveyard = [];
state.rng = rng.state;
} else if (mode === 'fatigue') {
p.fatigue += 1;
log(state, { kind: 'fatigue', seat, amount: p.fatigue });
loseLife(state, seat, p.fatigue, null, false);
continue;
} else {
finish(state, other(seat), 'library');
return;
}
}
const inst = p.library.shift()!;
p.hand.push(inst);
log(state, { kind: 'draw', seat, card: ref(state, inst) });
}
}
function loseLife(state: DuelState, seat: Seat, amount: number, source: Source | null, combat: boolean): void {
if (amount <= 0) return;
const p = state.players[seat];
p.life -= amount;
log(state, { kind: 'playerDamage', source: source ? ref(state, source) : null, seat, amount, life: p.life, combat });
}
function gainLife(state: DuelState, seat: Seat, amount: number, source: Source): void {
if (amount <= 0) return;
const p = state.players[seat];
p.life += amount;
log(state, { kind: 'lifeGain', source: ref(state, source), seat, amount, life: p.life });
}
/** Returns damage actually dealt. */
function dealDamage(state: DuelState, source: Source, target: TargetRef, amount: number, combat: boolean): number {
if (amount <= 0) return 0;
if (target.kind === 'player') { loseLife(state, target.seat, amount, source, combat); return amount; }
const perm = find(state, target.uid);
if (!perm || !isBody(perm)) return 0;
let dmg = amount;
if (!perm.shielded && hasKw(state, perm, 'Well-sourced')) { perm.shielded = true; dmg -= 1; }
if (dmg <= 0) return 0;
perm.damage += dmg;
log(state, { kind: combat ? 'combatDamage' : 'effectDamage', source: ref(state, source), target: ref(state, perm), amount: dmg });
return dmg;
}
function leave(state: DuelState, uid: string): Permanent | null {
const i = state.battlefield.findIndex(p => p.uid === uid);
if (i < 0) return null;
const [perm] = state.battlefield.splice(i, 1);
delete state.combat.blocks[uid];
for (const [b, a] of Object.entries(state.combat.blocks)) if (a === uid) delete state.combat.blocks[b];
state.combat.attackers = state.combat.attackers.filter(a => a !== uid);
return perm;
}
const toInstance = (perm: Permanent): CardInstance => ({ uid: perm.uid, owner: perm.owner, card: perm.card });
/** Destroy a set of permanents at once, then fire their triggers (active player's first, then entry order). */
function destroyAll(state: DuelState, uids: string[]): void {
const gone: Permanent[] = [];
for (const uid of uids) {
const perm = find(state, uid);
if (!perm) continue;
const card = ref(state, perm);
leave(state, uid);
if (!perm.card.token) state.players[perm.owner].graveyard.push(toInstance(perm));
log(state, { kind: 'destroyed', card, owner: perm.owner });
gone.push(perm);
}
gone.sort((a, b) => Number(a.controller !== state.active) - Number(b.controller !== state.active) || a.entered - b.entered);
for (const perm of gone) {
if (state.result) return;
for (const e of perm.card.effects) if (e.trigger === 'onDestroyed') resolveEffect(state, perm, perm.controller, e, undefined, undefined);
if (perm.card.keywords.includes('Legacy') || perm.permKeywords.includes('Legacy')) draw(state, perm.controller, 1);
}
}
function bounce(state: DuelState, uid: string): void {
const perm = find(state, uid);
if (!perm) return;
const card = ref(state, perm);
leave(state, uid);
if (!perm.card.token) state.players[perm.owner].hand.push(toInstance(perm));
log(state, { kind: 'bounced', card, owner: perm.owner });
}
/** State-based checks to a fixpoint: lethal damage, orphaned Doctrines, life totals; then Connected logging. */
function settle(state: DuelState): void {
for (let guard = 0; guard < 100 && !state.result; guard++) {
const dead = state.battlefield.filter(p => {
if (p.card.type === 'Doctrine') return !p.attachedTo || !find(state, p.attachedTo);
if (!isBody(p)) return false;
const { toughness } = statsOfPermanent(state, p);
return toughness <= 0 || p.damage >= toughness;
}).map(p => p.uid);
if (!dead.length) break;
destroyAll(state, dead);
}
if (state.result) return;
const lost = ([0, 1] as Seat[]).filter(s => state.players[s].life <= 0);
if (lost.length === 2) finish(state, null, 'life');
else if (lost.length === 1) finish(state, other(lost[0]), 'life');
if (!state.result) logConnections(state);
}
function logConnections(state: DuelState): void {
for (const perm of state.battlefield) {
if (perm.connectedLogged) continue;
const c = connectionOf(state, perm);
if (!c) continue;
perm.connectedLogged = true;
log(state, { kind: 'connected', seat: perm.controller, card: ref(state, perm), with: ref(state, c.with), tier: c.tier, via: c.via, bonus: c.bonus });
}
}
/** Rivalry (log only): when a card enters, note its best Connected tie to an opposing permanent, once. */
function logRivalry(state: DuelState, perm: Permanent): void {
let best: { with: Permanent; tier: ConnectedTier; via: string } | null = null;
for (const o of state.battlefield) {
if (o.controller === perm.controller) continue;
const t = tierBetween(state.rules, perm.card, o.card);
if (t && (!best || state.rules.connectedTiers.indexOf(t.tier) < state.rules.connectedTiers.indexOf(best.tier))) best = { with: o, ...t };
}
if (best) log(state, { kind: 'rivalry', card: ref(state, perm), with: ref(state, best.with), tier: best.tier, via: best.via });
}
function autoTargets(state: DuelState, source: Source, seat: Seat, t: TargetSpec): TargetRef[] {
const cards = (pred: (p: Permanent) => boolean) => state.battlefield.filter(pred).map(p => ({ kind: 'card', uid: p.uid }) as TargetRef);
switch (t) {
case 'controller': return [{ kind: 'player', seat }];
case 'opponent': return [{ kind: 'player', seat: other(seat) }];
case 'self': return find(state, source.uid) ? [{ kind: 'card', uid: source.uid }] : [];
case 'attached': {
const at = find(state, source.uid)?.attachedTo;
return at && find(state, at) ? [{ kind: 'card', uid: at }] : [];
}
case 'each': return cards(p => p.card.type === 'Figure' || p.card.type === 'Location');
case 'ownFigures': return cards(p => p.card.type === 'Figure' && p.controller === seat);
case 'opponentFigures': return cards(p => p.card.type === 'Figure' && p.controller !== seat);
default: return [];
}
}
function makeToken(state: DuelState, seat: Seat, source: Source, e: EffectSpec): void {
const spec = e.token;
if (!spec) return;
const n = e.amount ?? 1;
for (let i = 0; i < n; i++) {
if (e.condition?.maxTokens !== undefined) {
const count = state.battlefield.filter(p => p.controller === seat && p.card.token).length;
if (count >= e.condition.maxTokens) return;
}
const id = state.nextToken++;
const card: DuelCard = {
cardId: `token:${id}`, pageId: null, title: spec.name, type: 'Figure', portal: spec.portal, cost: 0,
power: spec.power, toughness: spec.toughness, keywords: [], effects: [], rulesText: '', flavor: '', token: true,
};
const perm = enter(state, { uid: `t:${id}`, owner: seat, card }, seat);
log(state, { kind: 'tokenCreated', seat, card: ref(state, perm), source: ref(state, source) });
}
}
/** Resolve one effect. `chosen` is this effect's target (chosen effects); `prev` the previous chosen target (fight). */
function resolveEffect(state: DuelState, source: Source, seat: Seat, e: EffectSpec, chosen: TargetRef | undefined, prev: TargetRef | undefined): void {
if (state.result || e.trigger === 'static') return;
const t = targetOf(e);
let targets: TargetRef[];
if (CHOSEN.has(t)) {
if (!chosen) return; // fizzles (no target, or chosen targets in automatic triggers)
const still = chosen.kind === 'player' ? t === 'anyTarget'
: candidates(state, seat, source.card, e).some(x => x.kind === 'card' && x.uid === chosen.uid);
if (!still) return;
targets = [chosen];
} else {
targets = autoTargets(state, source, seat, t);
}
const needs = !['draw', 'gainLife', 'createToken'].includes(e.op);
if (needs && !targets.length) return;
log(state, { kind: 'effect', seat, source: ref(state, source), op: e.op, ...(e.template ? { template: e.template } : {}), targets });
const amount = e.amount ?? 0;
const permOf = (x: TargetRef) => (x.kind === 'card' ? find(state, x.uid) : undefined);
switch (e.op) {
case 'damage': case 'damageEach':
for (const x of targets) dealDamage(state, source, x, amount, false);
break;
case 'createToken': makeToken(state, seat, source, e); break;
case 'pump': {
const p = e.power ?? amount, q = e.toughness ?? amount;
for (const x of targets) {
const perm = permOf(x);
if (!perm) continue;
if (e.duration === 'permanent') { perm.permPower += p; perm.permToughness += q; if (e.grant) perm.permKeywords.push(...e.grant); }
else { perm.tempPower += p; perm.tempToughness += q; if (e.grant) perm.tempKeywords.push(...e.grant); }
}
break;
}
case 'fight': {
const a = prev?.kind === 'card' ? find(state, prev.uid) : find(state, source.uid);
const b = permOf(targets[0]);
if (!a || !b || a.uid === b.uid) break;
const [ap, bp] = [statsOfPermanent(state, a).power, statsOfPermanent(state, b).power];
dealDamage(state, a, { kind: 'card', uid: b.uid }, ap, false);
dealDamage(state, b, { kind: 'card', uid: a.uid }, bp, false);
break;
}
case 'draw': draw(state, t === 'opponent' ? other(seat) : seat, e.amount ?? 1); break;
case 'attach': {
const perm = find(state, source.uid);
const to = permOf(targets[0]);
if (perm && to) { perm.attachedTo = to.uid; log(state, { kind: 'adopt', seat, card: ref(state, perm), to: ref(state, to) }); }
break;
}
case 'gainLife': gainLife(state, seat, amount, source); break;
case 'drain':
for (const x of targets) {
const victim = x.kind === 'player' ? x.seat : permOf(x)?.controller;
if (victim === undefined) continue;
loseLife(state, victim, amount, source, false);
if (victim !== seat) gainLife(state, seat, amount, source);
}
break;
case 'destroy': destroyAll(state, targets.filter(x => x.kind === 'card').map(x => (x as { uid: string }).uid)); break;
case 'bounce': for (const x of targets) if (x.kind === 'card') bounce(state, x.uid); break;
case 'tap': for (const x of targets) { const perm = permOf(x); if (perm) perm.tapped = true; } break;
}
}
function enter(state: DuelState, inst: CardInstance, seat: Seat): Permanent {
const perm: Permanent = {
...inst, controller: seat, tapped: false, sick: true, damage: 0, counters: 0, permPower: 0, permToughness: 0,
tempPower: 0, tempToughness: 0, tempKeywords: [], permKeywords: [], shielded: false, entered: state.nextEntry++, connectedLogged: false,
};
state.battlefield.push(perm);
return perm;
}
/** Run a card's entry effects, feeding chosen targets in order. */
function runEntry(state: DuelState, source: Source, seat: Seat, targets: TargetRef[]): void {
let i = 0;
let prev: TargetRef | undefined;
for (const e of source.card.effects) {
if (!isEntry(e) || state.result) continue;
if (CHOSEN.has(targetOf(e))) {
const chosen = targets[i++];
resolveEffect(state, source, seat, e, chosen, prev);
prev = chosen;
} else {
resolveEffect(state, source, seat, e, undefined, prev);
}
}
}
// ---------------------------------------------------------------------------
// Turn structure
// ---------------------------------------------------------------------------
function totalPower(state: DuelState, seat: Seat): number {
return state.battlefield.filter(p => p.controller === seat && p.card.type === 'Figure').reduce((n, p) => n + statsOfPermanent(state, p).power, 0);
}
function startTurn(state: DuelState, seat: Seat): void {
if (state.rules.turnCap !== null && state.turn >= state.rules.turnCap) {
const [a, b] = life(state);
const [pa, pb] = [totalPower(state, 0), totalPower(state, 1)];
const winner: Seat = a !== b ? (a > b ? 0 : 1) : pa !== pb ? (pa > pb ? 0 : 1) : other(state.firstSeat);
finish(state, winner, 'turnCap');
return;
}
state.turn += 1;
state.active = seat;
state.phase = 'main';
state.combat = { attackers: [], blocks: {} };
const p = state.players[seat];
p.locationsThisTurn = 0;
p.baseCitations = Math.min(state.rules.maxCitations, p.baseCitations + state.rules.citationsPerTurn);
p.citations = maxCitations(state, seat);
if (state.turn === 2 && seat !== state.firstSeat) p.citations += state.rules.secondPlayerCitations;
for (const perm of state.battlefield) {
perm.shielded = false;
if (perm.controller === seat) { perm.tapped = false; perm.sick = false; }
}
log(state, { kind: 'turnStart', seat, citations: p.citations, life: life(state) });
const mine = state.battlefield.filter(x => x.controller === seat).sort((a, b) => a.entered - b.entered);
for (const perm of mine) {
if (!find(state, perm.uid) || state.result) continue;
if (perm.card.keywords.includes('Stub') && perm.counters < state.rules.stubMax) perm.counters += 1;
for (const e of perm.card.effects) if (e.trigger === 'startOfTurn' && find(state, perm.uid)) resolveEffect(state, perm, seat, e, undefined, undefined);
}
settle(state);
if (state.result) return;
if (!(state.turn === 1 && !state.rules.firstPlayerDraws)) draw(state, seat, 1);
settle(state);
}
function endTurn(state: DuelState): void {
for (const perm of state.battlefield) { perm.damage = 0; perm.tempPower = 0; perm.tempToughness = 0; perm.tempKeywords = []; }
state.combat = { attackers: [], blocks: {} };
const seat = state.active;
const p = state.players[seat];
while (p.hand.length > state.rules.handSize) {
let worst = p.hand.length - 1;
for (let i = p.hand.length - 1; i >= 0; i--) if (p.hand[i].card.cost > p.hand[worst].card.cost) worst = i;
const [inst] = p.hand.splice(worst, 1);
p.graveyard.push(inst);
log(state, { kind: 'discard', seat, card: ref(state, inst) });
}
settle(state);
if (!state.result) startTurn(state, other(seat));
}
function play(state: DuelState, seat: Seat, uid: string, targets: TargetRef[]): void {
const p = state.players[seat];
const [inst] = p.hand.splice(p.hand.findIndex(c => c.uid === uid), 1);
p.citations -= inst.card.cost;
if (inst.card.type === 'Event') {
log(state, { kind: 'cast', seat, card: ref(state, inst), targets });
runEntry(state, inst, seat, targets);
p.graveyard.push(inst);
settle(state);
return;
}
if (inst.card.type === 'Location') p.locationsThisTurn += 1;
const perm = enter(state, inst, seat);
if (inst.card.type !== 'Doctrine') log(state, { kind: 'deploy', seat, card: ref(state, perm) });
logRivalry(state, perm);
runEntry(state, perm, seat, targets);
settle(state);
}
function confirmAttack(state: DuelState): void {
const seat = state.active;
if (!state.combat.attackers.length) { endTurn(state); return; }
const attackers = state.combat.attackers.map(uid => find(state, uid)).filter((x): x is Permanent => !!x);
for (const a of attackers) a.tapped = true;
log(state, { kind: 'attack', seat, attackers: attackers.map(a => ref(state, a)) });
for (const a of attackers) for (const e of a.card.effects) if (e.trigger === 'onAttack' && find(state, a.uid)) resolveEffect(state, a, seat, e, undefined, undefined);
settle(state);
if (state.result) return;
if (!state.combat.attackers.length) { endTurn(state); return; }
state.phase = 'block';
if (!blockOptions(state).length) resolveCombat(state);
}
function resolveCombat(state: DuelState): void {
const defender = other(state.active);
const pairs = Object.entries(state.combat.blocks)
.map(([b, a]) => ({ blocker: find(state, b), attacker: find(state, a) }))
.filter((x): x is { blocker: Permanent; attacker: Permanent } => !!x.blocker && !!x.attacker);
if (pairs.length) log(state, { kind: 'block', seat: defender, blocks: pairs.map(x => ({ blocker: ref(state, x.blocker), attacker: ref(state, x.attacker) })) });
// Simultaneous: compute every amount first, then apply.
const hits: { source: Permanent; target: TargetRef; amount: number }[] = [];
const blockerOf = new Map(pairs.map(x => [x.attacker.uid, x.blocker]));
for (const uid of state.combat.attackers) {
const a = find(state, uid);
if (!a) continue;
const ap = statsOfPermanent(state, a).power;
const b = blockerOf.get(uid);
if (b) {
hits.push({ source: a, target: { kind: 'card', uid: b.uid }, amount: ap });
hits.push({ source: b, target: { kind: 'card', uid: a.uid }, amount: statsOfPermanent(state, b).power });
} else {
hits.push({ source: a, target: { kind: 'player', seat: defender }, amount: ap });
}
}
const toPlayer: Permanent[] = [];
for (const h of hits) if (dealDamage(state, h.source, h.target, h.amount, true) > 0 && h.target.kind === 'player') toPlayer.push(h.source);
for (const a of toPlayer) {
for (const e of a.card.effects) if (e.trigger === 'onCombatDamageToPlayer') resolveEffect(state, a, a.controller, e, undefined, undefined);
for (const d of state.battlefield.filter(x => x.card.type === 'Doctrine' && x.attachedTo === a.uid)) {
for (const e of d.card.effects) if (e.trigger === 'onCombatDamageToPlayer') resolveEffect(state, d, d.controller, e, undefined, undefined);
}
}
settle(state);
if (!state.result) endTurn(state);
}
// ---------------------------------------------------------------------------
// applyAction
// ---------------------------------------------------------------------------
/**
* Structural clone for clone-on-apply. DuelCards, CardInstances, log events and the
* ruleset are never mutated after creation, so they are shared between states;
* Permanents, players and combat are copied. (structuredClone was 85% of runtime.)
*/
function cloneState(s: DuelState): DuelState {
const player = (p: PlayerState): PlayerState => ({ ...p, library: p.library.slice(), hand: p.hand.slice(), graveyard: p.graveyard.slice() });
return {
...s,
players: [player(s.players[0]), player(s.players[1])],
battlefield: s.battlefield.map(p => ({ ...p, tempKeywords: p.tempKeywords.slice(), permKeywords: p.permKeywords.slice() })),
combat: { attackers: s.combat.attackers.slice(), blocks: { ...s.combat.blocks } },
log: s.log.slice(),
result: s.result ? { ...s.result } : null,
};
}
function normalize(action: DuelAction): DuelAction {
// Canonical key order so deep-equal against legalActions is stable.
switch (action.type) {
case 'play': {
const targets = (action.targets ?? []).map(t => (t.kind === 'card' ? { kind: 'card' as const, uid: t.uid } : { kind: 'player' as const, seat: t.seat }));
return targets.length ? { type: 'play', uid: action.uid, targets } : { type: 'play', uid: action.uid };
}
case 'toggleAttacker': return { type: 'toggleAttacker', uid: action.uid };
case 'block': return { type: 'block', blocker: action.blocker, attacker: action.attacker };
default: return { type: action.type } as DuelAction;
}
}
export function applyAction(input: DuelState, seat: Seat, action: DuelAction): DuelState {
if (input.result) throw new Error('Match is over');
if (seat !== 0 && seat !== 1) throw new RangeError('Bad seat');
if (!action || typeof action !== 'object' || typeof (action as { type?: unknown }).type !== 'string') throw new TypeError('Bad action');
if (action.type === 'concede') {
const state = cloneState(input);
state.version += 1;
log(state, { kind: 'concede', seat });
finish(state, other(seat), 'concede');
return state;
}
if (toAct(input) !== seat) throw new Error('Not your turn to act');
if (action.type === 'timeout') {
const state = cloneState(input);
state.version += 1;
log(state, { kind: 'timeout', seat });
const p = state.players[seat];
p.timeouts += 1;
if (p.timeouts >= state.rules.timeoutsToConcede) { finish(state, other(seat), 'timeout'); return state; }
switch (state.phase) {
case 'mulligan': keep(state, seat); break;
case 'main': case 'attack': state.combat.attackers = []; endTurn(state); break;
case 'block': resolveCombat(state); break;
}
return state;
}
const a = normalize(action);
const key = JSON.stringify(a);
if (!legalActions(input, seat).some(x => JSON.stringify(x) === key)) throw new Error(`Illegal action ${JSON.stringify(action)}`);
const state = cloneState(input);
state.version += 1;
state.players[seat].timeouts = 0;
switch (a.type) {
case 'keep': keep(state, seat); break;
case 'mulligan': mulligan(state, seat); break;
case 'play': play(state, seat, a.uid, a.targets ?? []); break;
case 'endPhase': state.phase = 'attack'; break;
case 'toggleAttacker': state.combat.attackers.push(a.uid); break;
case 'confirmAttack': confirmAttack(state); break;
case 'block': state.combat.blocks[a.blocker] = a.attacker; break;
case 'confirmBlocks': resolveCombat(state); break;
}
return state;
}
function keep(state: DuelState, seat: Seat): void {
const p = state.players[seat];
for (let i = 0; i < p.mulligansTaken && p.hand.length; i++) p.library.push(p.hand.pop()!);
p.ready = true;
log(state, { kind: 'keep', seat, handSize: p.hand.length });
if (state.players[0].ready && state.players[1].ready) startTurn(state, state.firstSeat);
}
function mulligan(state: DuelState, seat: Seat): void {
const p = state.players[seat];
const rng = new Rng(state.rng);
p.library = rng.shuffle([...p.library, ...p.hand]);
state.rng = rng.state;
p.hand = p.library.splice(0, state.rules.openingHand);
p.mulligansTaken += 1;
log(state, { kind: 'mulligan', seat });
}
// ---------------------------------------------------------------------------
// Views, log, replay, serialisation
// ---------------------------------------------------------------------------
function side(state: DuelState, seat: Seat): SideView {
const p = state.players[seat];
return {
seat, life: p.life, citations: p.citations, maxCitations: maxCitations(state, seat), handSize: p.hand.length,
librarySize: p.library.length, graveyard: structuredClone(p.graveyard), bankSeconds: p.bankSeconds, ready: p.ready, mulligansTaken: p.mulligansTaken,
};
}
export function viewFor(state: DuelState, seat: Seat): PlayerView {
const battlefield: PermanentView[] = state.battlefield.map(perm => {
const { power, toughness } = statsOfPermanent(state, perm);
const c = connectionOf(state, perm);
return {
uid: perm.uid, owner: perm.owner, controller: perm.controller, card: structuredClone(perm.card), tapped: perm.tapped, sick: perm.sick,
damage: perm.damage, counters: perm.counters, ...(perm.attachedTo ? { attachedTo: perm.attachedTo } : {}), power, toughness,
keywords: keywordsOf(state, perm), ...(c ? { connected: { with: c.with.uid, tier: c.tier, via: c.via, bonus: c.bonus } } : {}),
};
});
return {
engine: 'duel', seat, turn: state.turn, active: state.active, phase: state.phase, toAct: toAct(state),
you: { ...side(state, seat), hand: structuredClone(state.players[seat].hand) },
opponent: side(state, other(seat)),
battlefield, combat: structuredClone(state.combat), result: state.result, version: state.version, rules: structuredClone(state.rules),
};
}
export function logFor(state: DuelState, seat: Seat): LogEvent[] {
return state.log.map(e => {
if (e.kind === 'draw' && e.seat !== seat) return { seq: e.seq, turn: e.turn, kind: 'draw', seat: e.seat } as LogEvent;
return structuredClone(e);
});
}
export function replay(rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string, actions: { seat: Seat; action: DuelAction }[]): DuelState {
let state = createDuel(rules, decks, seed);
for (const { seat, action } of actions) state = applyAction(state, seat, action);
return state;
}
export const serialize = (state: DuelState): string => JSON.stringify(state);
export function deserialize(text: string): DuelState {
const value = JSON.parse(text) as DuelState;
if (!value || value.engine !== 'duel') throw new TypeError('Not a duel state');
return value;
}
// ---------------------------------------------------------------------------
// Host binding: structurally an EnginePort<DuelRuleset, DuelCard, DuelState, DuelAction>
// (server/game/engine-port.ts). shared/ must not import server/, so host-pvp types it there.
// ---------------------------------------------------------------------------
export const duelEnginePort = {
defaultRuleset: DEFAULT_DUEL_RULESET,
parseRuleset: (value: unknown) => parseDuelRuleset(value),
deckSize: (rules: DuelRuleset) => rules.deckSize,
starterDeck(_rules?: DuelRuleset, _seed?: string): DuelCard[] { throw new Error('Duel has no starter decks: every card must be owned (BRIEF decision 2)'); },
previewPool(_rules?: DuelRuleset, _seed?: string, _size?: number): DuelCard[] { throw new Error('Duel draft pools come from both players’ collections, not previews'); },
validateDeck,
cardPower: (card: DuelCard) => pw(card),
withPower: (card: DuelCard, power: number): DuelCard => ({ ...card, power: Math.max(0, Math.round(power)) }),
cardPageId: (card: DuelCard) => card.pageId,
cardSummary: (card: DuelCard) => ({
cardId: card.cardId, pageId: card.pageId, title: card.title, type: card.type, portal: card.portal, cost: card.cost,
power: card.power, toughness: card.toughness, keywords: card.keywords, rulesText: card.rulesText,
}),
createMatch: (rules: DuelRuleset, decks: [DuelCard[], DuelCard[]], seed: string) => createDuel(rules, decks, seed),
legalActions,
applyAction,
concedeAction: (_seat: Seat): DuelAction => ({ type: 'concede' }),
timeoutAction: (_seat: Seat): DuelAction => ({ type: 'timeout' }),
turnSeconds: (rules: DuelRuleset) => rules.turnSeconds,
turnOf,
/** Trending mode (DUEL_DESIGN §4): a frozen live ▲ ≥ +25% grants Trending (haste, +trendingPower/+0 in play). */
applyLive(_rules: DuelRuleset, card: DuelCard, live: { trendPercent: number | null }): DuelCard {
if (live.trendPercent === null || live.trendPercent < 25 || card.type !== 'Figure' || card.keywords.includes('Trending')) return card;
return { ...card, keywords: [...card.keywords, 'Trending'] };
},
isOver,
result: (state: DuelState) => state.result ?? { winner: null, reason: 'in progress' },
viewFor,
logFor,
};
+40
View File
@@ -0,0 +1,40 @@
/**
* 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';
export * from './engine.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 };
}
import * as engine from './engine.ts';
/** Compile-time check that engine.ts implements the contract. */
export const duelEngine: DuelEngineApi = engine;
+114
View File
@@ -0,0 +1,114 @@
/**
* Building the frozen CardProfile (data review §3) from data the host already has or fetches once
* through the polite Wikimedia client. Pure: this file never fetches. The host:
* 1. takes the cached PageEnrichment (description, wikidataId, categories),
* 2. fetches the item once with wikidataEntityParams([qid, …]) (≤ 50 ids per request),
* 3. fetches the labels of the P31/P279 classes it doesn't know with wikidataLabelParams(ids),
* 4. optionally adds outlinks (prop=links, ns0) as pageIds,
* 5. calls profileFromSources() and stores the result per tokenId forever.
* Owner: duel-cards.
*/
import type { PageEnrichment } from '../enrichment.ts';
import type { CardProfile, WikidataClass } from './classify.ts';
export const PROFILE_PROPERTIES = {
instanceOf: 'P31', subclassOf: 'P279', country: 'P17', citizenship: 'P27',
birth: 'P569', death: 'P570', inception: 'P571', start: 'P580', pointInTime: 'P585',
} as const;
/** Properties whose item values count as "cited" for the Linked tier (DUEL_DESIGN §6). */
export const CITE_PROPERTIES = ['P17', 'P27', 'P131', 'P361', 'P527', 'P463', 'P102', 'P108', 'P69', 'P19', 'P20', 'P710', 'P1344', 'P276'] as const;
/** Action API parameters for wbgetentities (claims only, so the payload stays small). */
export function wikidataEntityParams(qids: readonly string[]): Record<string, string> {
if (qids.length < 1 || qids.length > 50) throw new RangeError('wbgetentities takes 1 to 50 ids');
return { action: 'wbgetentities', ids: [...qids].sort().join('|'), props: 'claims', format: 'json', formatversion: '2' };
}
/** Action API parameters for class labels (English). */
export function wikidataLabelParams(qids: readonly string[]): Record<string, string> {
if (qids.length < 1 || qids.length > 50) throw new RangeError('wbgetentities takes 1 to 50 ids');
return { action: 'wbgetentities', ids: [...qids].sort().join('|'), props: 'labels', languages: 'en', format: 'json', formatversion: '2' };
}
/** The slice of a wbgetentities entity this module reads. Unknown shapes are ignored, never thrown on. */
export interface WikidataEntity {
id?: string;
claims?: Record<string, readonly {
rank?: string;
mainsnak?: { snaktype?: string; datavalue?: { type?: string; value?: unknown } };
}[]>;
}
function claimValues(entity: WikidataEntity | null | undefined, property: string): unknown[] {
const statements = entity?.claims?.[property];
if (!Array.isArray(statements)) return [];
return statements
.filter(s => s?.rank !== 'deprecated' && s?.mainsnak?.snaktype === 'value')
.map(s => s.mainsnak?.datavalue?.value)
.filter(v => v !== undefined);
}
function itemIds(entity: WikidataEntity | null | undefined, property: string): string[] {
return claimValues(entity, property)
.map(v => (v && typeof v === 'object' && 'id' in v && typeof (v as { id: unknown }).id === 'string') ? (v as { id: string }).id : null)
.filter((id): id is string => id !== null && /^Q\d+$/.test(id));
}
/** Years from Wikidata time values ("+1909-04-29T00:00:00Z", "-0044-03-15T…"). */
function years(entity: WikidataEntity | null | undefined, property: string): number[] {
return claimValues(entity, property)
.map(v => (v && typeof v === 'object' && 'time' in v) ? String((v as { time: unknown }).time) : '')
.map(t => /^([+-])0*(\d{1,6})-/.exec(t))
.filter((m): m is RegExpExecArray => m !== null)
.map(m => (m[1] === '-' ? -1 : 1) * Number(m[2]))
.filter(y => y !== 0);
}
/** Q-ids whose labels the host must look up to classify this entity. */
export function classIdsOf(entity: WikidataEntity | null | undefined): string[] {
return [...new Set([...itemIds(entity, 'P31'), ...itemIds(entity, 'P279')])].sort();
}
export interface ProfileSources {
enrichment: Pick<PageEnrichment, 'description' | 'wikidataId' | 'categories' | 'revisionId'>;
/** The card's own wbgetentities entity, or null when it has no item or the fetch is pending. */
entity?: WikidataEntity | null;
/** English labels for class Q-ids; missing labels are kept as the bare Q-id. */
labels?: Readonly<Record<string, string>>;
/** Superclass chain for the P31 classes (P279, up to 4 hops), nearest first, if the host resolved it. */
superclasses?: readonly WikidataClass[];
/** ns0 outlinks resolved to pageIds. */
links?: readonly number[];
}
export function profileFromSources(src: ProfileSources): CardProfile {
const { enrichment, entity, labels = {} } = src;
const label = (id: string): WikidataClass => ({ id, label: labels[id] ?? id });
const countries = [...new Set([...itemIds(entity, 'P17'), ...itemIds(entity, 'P27')])].sort();
const yrs = [...new Set(['P569', 'P570', 'P571', 'P580', 'P585'].flatMap(p => years(entity, p)))].sort((a, b) => a - b);
const cites = [...new Set(CITE_PROPERTIES.flatMap(p => itemIds(entity, p)))].sort();
const subclassOf = [...itemIds(entity, 'P279').map(label), ...(src.superclasses ?? [])];
const profile: CardProfile = {
wikidataId: enrichment.wikidataId,
description: enrichment.description,
categories: [...enrichment.categories],
instanceOf: itemIds(entity, 'P31').map(label),
fetchedRevisionId: enrichment.revisionId,
};
if (subclassOf.length) profile.subclassOf = subclassOf;
if (countries.length) profile.countries = countries;
if (yrs.length) profile.years = yrs;
if (claimValues(entity, 'P570').length) profile.died = true;
if (cites.length) profile.cites = cites;
if (src.links?.length) profile.links = [...new Set(src.links)].sort((a, b) => a - b);
return profile;
}
/** A canonical JSON string of a profile, for storing, hashing and logging in the match record. */
export function canonicalProfile(profile: CardProfile): string {
const sortKeys = (v: unknown): unknown => Array.isArray(v) ? v.map(sortKeys)
: v && typeof v === 'object' ? Object.fromEntries(Object.keys(v).sort().map(k => [k, sortKeys((v as Record<string, unknown>)[k])]))
: v;
return JSON.stringify(sortKeys(profile));
}
+78
View File
@@ -0,0 +1,78 @@
/**
* 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(),
secondPlayerCitations: int(0, 5),
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,
secondPlayerCitations: 1, // balance v1 (#64): first player 60.1% → 54.7%
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: 40, // balance v1 (#64): 3.9% of games decided at the cap
}) 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>) });
}
+41
View File
@@ -0,0 +1,41 @@
/**
* Fixture: docs/game/card-sample.json (236 real random cards) → DuelCard[], for sim-balance, the UI
* and tests. The sample has no on-chain extract, so flavour falls back to the description, and its
* tokenIds are synthetic (the pageId as 64 hex digits). Owner: duel-cards.
*/
import type { CardProfile } from './classify.ts';
import { derive, DERIVE_RULES, type CardOnChain, type DeriveRules, type DuelCard } from './derive.ts';
/** The fields of a card-sample.json card that derivation reads. */
export interface SampleCard {
pageId: number; title: string; description: string | null; wikidataId: string | null; revisionId: number;
pageBytes: number; languageCount: number; categories: string[];
stats: { attention: number | null; depth: number; reach: number };
instanceOf: { id: string; label: string }[];
extract?: string;
/** The on-chain mint-time category (server/wiki.ts bucket). */
legacyCategory?: string;
}
export function sampleTokenId(pageId: number): string {
return pageId.toString(16).padStart(64, '0');
}
export function sampleInputs(card: SampleCard): { chain: CardOnChain; profile: CardProfile } {
return {
chain: {
tokenId: sampleTokenId(card.pageId),
article: { pageId: card.pageId, title: card.title, extract: card.extract ?? '', revisionId: card.revisionId,
...(card.legacyCategory ? { category: card.legacyCategory } : {}) },
statsSnapshot: { pageBytes: card.pageBytes, languageCount: card.languageCount, stats: card.stats },
},
profile: {
wikidataId: card.wikidataId, description: card.description, categories: card.categories,
instanceOf: card.instanceOf, fetchedRevisionId: card.revisionId,
},
};
}
export function deriveSample(cards: readonly SampleCard[], rules: DeriveRules = DERIVE_RULES): DuelCard[] {
return cards.map(card => { const { chain, profile } = sampleInputs(card); return derive(chain, profile, rules); });
}
+117
View File
@@ -0,0 +1,117 @@
/**
* Adapter: duel-core's LogEvent[] (shared/duel/types.ts) → story MatchRecord (DUEL_DESIGN §8).
* Pure. Pass the omniscient `state.log` for recaps, or `logFor(state, seat)` output for a seat's log
* (hidden draws there have no `card`, and stay hidden).
*/
import type { CardInstance, CardRef, LogEvent } from '../types.ts';
import type { MatchRecord, Seat, StoryCard, StoryEvent, StoryPlayer } from './types.ts';
export interface FromDuelInput {
matchId: string;
/** Story seed, opaque: the host derives it (sha256(engineSeed + ':story')). Never the engine seed. */
storySeed: string;
/** ISO YYYY-MM-DD. */
date: string;
players: [StoryPlayer, StoryPlayer];
/** Every card instance of both decks (tokens are picked up from the log). */
instances: CardInstance[];
log: LogEvent[];
startingLife?: number;
hostName?: string;
ratingChange?: [number, number];
}
function storyCard(inst: CardInstance): StoryCard {
const c = inst.card;
return {
id: inst.uid, title: c.title, description: c.description, type: c.type, cost: c.cost, portal: c.portal,
revisionId: c.token ? undefined : c.revisionId, tokenId: c.token ? undefined : c.cardId, owner: inst.owner,
token: c.token || undefined,
};
}
export function fromDuel(input: FromDuelInput): MatchRecord {
const cards: Record<string, StoryCard> = {};
for (const inst of input.instances) cards[inst.uid] = storyCard(inst);
/** Tokens (and anything not in the decks) come from their log CardRef: never cited. */
const ref = (r: CardRef, owner: Seat): string => {
if (!cards[r.uid]) cards[r.uid] = { id: r.uid, title: r.title, type: r.type, cost: 0, owner, token: true };
return r.uid;
};
const events: StoryEvent[] = [];
let lastTurn = 0;
for (const e of input.log) {
switch (e.kind) {
case 'turnStart':
lastTurn = e.turn;
events.push({ kind: 'turnStart', turn: e.turn, seat: e.seat });
break;
case 'draw':
events.push(e.card ? { kind: 'draw', seat: e.seat, card: ref(e.card, e.seat) } : { kind: 'draw', seat: e.seat });
break;
case 'deploy':
events.push({ kind: 'deploy', seat: e.seat, card: ref(e.card, e.seat) });
break;
case 'cast':
events.push({ kind: 'cast', seat: e.seat, card: ref(e.card, e.seat) });
break;
case 'adopt':
events.push({
kind: 'adopt', seat: e.seat, doctrine: ref(e.card, e.seat), figure: ref(e.to, e.seat),
power: e.to.power ?? 0, toughness: e.to.toughness ?? 0,
});
break;
case 'tokenCreated': {
const prev = events[events.length - 1];
const src = ref(e.source, e.seat);
ref(e.card, e.seat);
if (prev && prev.kind === 'tokenCreated' && prev.source === src && prev.token === e.card.title) prev.count += 1;
else events.push({ kind: 'tokenCreated', seat: e.seat, source: src, token: e.card.title, count: 1 });
break;
}
case 'connected':
events.push({ kind: 'connected', seat: e.seat, a: ref(e.card, e.seat), b: ref(e.with, e.seat), reason: e.via });
break;
case 'rivalry':
events.push({ kind: 'rivalry', a: ref(e.card, 0), b: ref(e.with, 1), reason: e.via });
break;
case 'attack':
for (const a of e.attackers) events.push({ kind: 'attack', seat: e.seat, card: ref(a, e.seat), power: a.power ?? 0, toughness: a.toughness ?? 0 });
break;
case 'block':
for (const b of e.blocks) {
events.push({
kind: 'block', seat: e.seat, blocker: ref(b.blocker, e.seat), attacker: ref(b.attacker, e.seat === 0 ? 1 : 0),
power: b.blocker.power ?? 0, toughness: b.blocker.toughness ?? 0,
});
}
break;
case 'lifeGain':
events.push({ kind: 'lifeGain', seat: e.seat, source: ref(e.source, e.seat), amount: e.amount, life: e.life });
break;
case 'effectDamage':
events.push({ kind: 'effectDamage', source: ref(e.source, 0), target: ref(e.target, 0), amount: e.amount });
break;
case 'playerDamage':
events.push({ kind: 'playerDamage', seat: e.seat, source: e.source ? ref(e.source, e.seat === 0 ? 1 : 0) : undefined, amount: e.amount, life: e.life });
break;
case 'destroyed':
events.push({ kind: 'destroyed', card: ref(e.card, e.owner) });
break;
case 'discard':
events.push({ kind: 'discard', seat: e.seat, card: ref(e.card, e.seat) });
break;
case 'gameOver':
events.push({ kind: 'gameOver', winner: e.winner, reason: e.reason, turn: e.turn || lastTurn, life: e.life });
break;
// start, mulligan, keep, effect, combatDamage, bounced, fatigue, concede, timeout:
// not narrated in v1 (combat outcomes are told by destroyed/playerDamage; gameOver covers concede/timeout).
default:
break;
}
}
return {
matchId: input.matchId, seed: input.storySeed, date: input.date, players: input.players, cards, events,
startingLife: input.startingLife, hostName: input.hostName, ratingChange: input.ratingChange,
};
}
+6
View File
@@ -0,0 +1,6 @@
/** Story layer for the duel (DUEL_DESIGN.md §8): match log and battle recap templates. */
export * from './types.ts';
export { LOG_TEMPLATES, BANNED_WORDS, FOOTER, fill, numberWord, ordinalWord } from './templates.ts';
export { Narrator, renderEvent, renderLog, logParagraphs, gloss, articleUrl, variantIndex, tokenName } from './log.ts';
export { recap, battleName, battleTitle, longDate } from './recap.ts';
export type { RecapDoc, RecapInfobox, RecapSection } from './recap.ts';
+196
View File
@@ -0,0 +1,196 @@
/**
* Deterministic match log (DUEL_DESIGN.md §8.2). Pure: the same MatchRecord always gives the
* same lines, so `replay` and stored records regenerate the log exactly. No network, no clock.
*/
import { Rng } from '../../game/rng.ts';
import { LOG_TEMPLATES, fill, numberWord, type TemplateKey } from './templates.ts';
import type { LogLine, MatchRecord, Reference, Seat, StoryCard, StoryEvent } from './types.ts';
/** Deterministic variant choice: one fresh mulberry32 per (seed, salt, event index). */
export function variantIndex(seed: number | string, salt: string, index: number, n: number): number {
return Rng.fromSeed(`${seed}|${salt}|${index}`).int(n);
}
/** "American actor (1909–1994)" → "American actor, 1909–1994". Verbatim otherwise. */
export function gloss(description: string | undefined): string {
const d = (description ?? '').trim();
if (!d) return '';
const m = /^(.*\S)\s*\(([^()]+)\)$/.exec(d);
return m ? `${m[1]}, ${m[2]}` : d;
}
export function articleUrl(title: string, revisionId: number): string {
return `https://en.wikipedia.org/w/index.php?title=${encodeURIComponent(title.replace(/ /g, '_'))}&oldid=${revisionId}`;
}
/**
* Tracks first mentions and reference numbers for one rendering (a log view or a recap).
* The first mention of a card in a rendering adds its description and the next [n].
*/
export class Narrator {
readonly record: MatchRecord;
readonly salt: string;
readonly references: Reference[] = [];
private refByCard = new Map<string, number>();
private pending: number[] = [];
constructor(record: MatchRecord, salt: string) {
this.record = record;
this.salt = salt;
}
card(id: string): StoryCard {
const c = this.record.cards[id];
if (!c) throw new Error(`story: unknown card id ${id}`);
return c;
}
player(seat: Seat): string { return this.record.players[seat].name; }
/** Assigns a reference number without mentioning the card (e.g. for the References list). Tokens get none (0). */
cite(id: string): number {
let n = this.refByCard.get(id);
if (n === undefined) {
const c = this.card(id);
if (c.token || c.revisionId === undefined) return 0;
n = this.references.length + 1;
this.refByCard.set(id, n);
this.references.push({
n, cardId: id, title: c.title, revisionId: c.revisionId, tokenId: c.tokenId,
url: articleUrl(c.title, c.revisionId),
text: `"${c.title}". Wikipedia. Revision ${c.revisionId}.${c.tokenId ? ` Minted as token ${c.tokenId}.` : ''}`,
});
}
return n;
}
/** A card's name for a sentence: italic, with its description on first mention. */
mention(id: string): string {
const c = this.card(id);
if (c.token || c.revisionId === undefined) return c.title;
const first = !this.refByCard.has(id);
const n = this.cite(id);
if (!first) return `*${c.title}*`;
this.pending.push(n);
const g = gloss(c.description);
return g ? `*${c.title}* (${g})` : `*${c.title}*`;
}
/** Take the citations of first mentions made since the last sentence. */
flush(): number[] {
const refs = this.pending;
this.pending = [];
return refs;
}
/** Fill a variant of `key` and append the citations of first mentions made while filling. */
sentence(key: TemplateKey, index: number, values: Record<string, () => string | number>, must: string[] = []): { text: string; refs: number[] } {
const fits = (t: string) => [...t.matchAll(/\{(\w+)\}/g)].every(m => m[1] in values);
const all = LOG_TEMPLATES[key].filter(fits);
const preferred = all.filter(t => must.every(k => t.includes(`{${k}}`)));
const usable = preferred.length ? preferred : all;
if (!usable.length) throw new Error(`story: no usable template for ${key}`);
const template = usable[variantIndex(this.record.seed, `${this.salt}:${key}`, index, usable.length)];
// Evaluate placeholders in template order so first mentions are numbered left to right.
const filled: Record<string, string | number> = {};
for (const m of template.matchAll(/\{(\w+)\}/g)) if (!(m[1] in filled)) filled[m[1]] = values[m[1]]();
const refs = this.flush();
const body = fill(template, filled);
return { text: body + refs.map(r => `[${r}]`).join(''), refs };
}
}
/** Pluralise a fixed token name ("Staff Member" → "Staff Members"). */
export function tokenName(token: string, count: number): string {
return count === 1 ? token : `${token}s`;
}
/**
* Render one event as a sentence, or null if it is not shown to this viewer.
* `viewer` null = omniscient (post-match, spectators after the end).
*/
export interface RenderOptions {
/** Prefer variants that name the source card (the recap uses this for damage lines). */
preferSource?: boolean;
}
export function renderEvent(nar: Narrator, ev: StoryEvent, index: number, viewer: Seat | null, opts: RenderOptions = {}): { text: string; refs: number[] } | null {
const P = (s: Seat) => () => nar.player(s);
const M = (id: string) => () => nar.mention(id);
const N = (n: number) => () => n;
const other = (s: Seat): Seat => (s === 0 ? 1 : 0);
switch (ev.kind) {
case 'turnStart':
return { text: `Turn ${ev.turn}.`, refs: [] };
case 'deploy':
return nar.sentence('deploy', index, { player: P(ev.seat), card: M(ev.card) });
case 'cast':
return nar.sentence('cast', index, { player: P(ev.seat), card: M(ev.card) });
case 'adopt':
return nar.sentence('adopt', index, { player: P(ev.seat), doctrine: M(ev.doctrine), figure: M(ev.figure), p: N(ev.power), t: N(ev.toughness) });
case 'attack':
return nar.sentence('attack', index, { player: P(ev.seat), opponent: P(other(ev.seat)), card: M(ev.card), p: N(ev.power), t: N(ev.toughness) });
case 'block':
return nar.sentence('block', index, { player: P(ev.seat), blocker: M(ev.blocker), attacker: M(ev.attacker), p: N(ev.power), t: N(ev.toughness) });
case 'playerDamage': {
const v: Record<string, () => string | number> = { player: P(ev.seat), n: N(ev.amount), life: N(Math.max(0, ev.life)) };
if (ev.source) v.source = M(ev.source);
return nar.sentence('playerDamage', index, v, opts.preferSource && ev.source ? ['source'] : []);
}
case 'lifeGain':
return nar.sentence('lifeGain', index, { player: P(ev.seat), source: M(ev.source), n: N(ev.amount), life: N(ev.life) });
case 'effectDamage':
return nar.sentence('effectDamage', index, { source: M(ev.source), target: M(ev.target), n: N(ev.amount) });
case 'destroyed':
return nar.sentence('destroyed', index, { card: M(ev.card) });
case 'tokenCreated':
return nar.sentence('tokenCreated', index, {
source: M(ev.source), count: () => numberWord(ev.count), token: () => tokenName(ev.token, ev.count),
});
case 'draw': {
const count = ev.count ?? 1;
const visible = ev.card !== undefined && (viewer === null || viewer === ev.seat);
if (visible) return nar.sentence('drawKnown', index, { player: P(ev.seat), card: M(ev.card as string) });
if (count > 1) return nar.sentence('drawHiddenMany', index, { player: P(ev.seat), count: () => numberWord(count) });
return nar.sentence('drawHidden', index, { player: P(ev.seat) });
}
case 'discard':
return nar.sentence('discard', index, { player: P(ev.seat), card: M(ev.card) });
case 'connected':
return nar.sentence('connected', index, { a: M(ev.a), b: M(ev.b), reason: () => ev.reason });
case 'rivalry':
return nar.sentence('rivalry', index, { a: M(ev.a), b: M(ev.b), reason: () => ev.reason });
case 'gameOver': {
if (ev.winner === null) return nar.sentence('gameOverDraw', index, { turn: N(ev.turn) });
const key = ({ life: 'gameOverLife', library: 'gameOverLibrary', concede: 'gameOverConcede', timeout: 'gameOverTimeout', turnCap: 'gameOverTurnCap' } as const)[ev.reason];
return nar.sentence(key, index, { winner: P(ev.winner), loser: P(other(ev.winner)), turn: N(ev.turn) });
}
}
}
/** The match log for one viewer (DUEL_DESIGN §8.2). Hidden draws by the opponent stay hidden. */
export function renderLog(record: MatchRecord, viewer: Seat | null = null): { lines: LogLine[]; references: Reference[] } {
const nar = new Narrator(record, 'log');
const lines: LogLine[] = [];
let turn = 0;
record.events.forEach((ev, i) => {
if (ev.kind === 'turnStart') turn = ev.turn;
const out = renderEvent(nar, ev, i, viewer);
if (out) lines.push({ turn, ...out });
});
return { lines, references: nar.references };
}
/** Join lines into one paragraph per turn: "Turn 5. alice deployed …". */
export function logParagraphs(lines: LogLine[]): string[] {
const out: string[] = [];
let cur: string[] = [];
let curTurn = -1;
for (const l of lines) {
if (l.turn !== curTurn && cur.length) { out.push(cur.join(' ')); cur = []; }
curTurn = l.turn;
cur.push(l.text);
}
if (cur.length) out.push(cur.join(' '));
return out;
}
+290
View File
@@ -0,0 +1,290 @@
/**
* "Battle of X (2026)" recap (DUEL_DESIGN.md §8.3). Pure and deterministic: input is the
* match record only. Output is structured data; ui-pvp renders it. All prose is templates
* filled with real card and match data. No LLM, no invented facts.
*/
import { Narrator, renderEvent, variantIndex } from './log.ts';
import { FOOTER, numberWord, ordinalWord } from './templates.ts';
import type { GameOverReason, MatchRecord, Reference, Seat, StoryCard, StoryEvent } from './types.ts';
export interface RecapInfobox {
date: string;
location: string;
result: string;
belligerents: [string, string];
commanders: [string, string];
strength: [string, string];
casualties: [string, string];
}
export interface RecapSection {
heading: string;
paragraphs: string[];
}
export interface RecapDoc {
matchId: string;
/** Path of the shareable page. */
url: string;
masthead: 'WikiDeck';
title: string;
/** Card the battle is named after, if any. */
nameCardId?: string;
infobox: RecapInfobox;
/** Lead paragraph, then Background, Course of the battle, Aftermath, See also. */
lead: string;
sections: RecapSection[];
references: Reference[];
footer: string;
}
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
/** "2026-11-17" → "17 November 2026". */
export function longDate(iso: string): string {
const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso);
if (!m) throw new Error(`recap: date must be ISO YYYY-MM-DD, got ${iso}`);
return `${Number(m[3])} ${MONTHS[Number(m[2]) - 1]} ${m[1]}`;
}
interface Played { id: string; seat: Seat; order: number }
interface Facts {
/** For a draw: seat 0, with `draw` set. */
winner: Seat;
draw: boolean;
loser: Seat;
reason: GameOverReason;
turns: number;
life: [number, number];
played: Played[];
destroyed: string[];
}
function facts(record: MatchRecord): Facts {
const over = [...record.events].reverse().find((e): e is Extract<StoryEvent, { kind: 'gameOver' }> => e.kind === 'gameOver');
if (!over) throw new Error('recap: match has no gameOver event');
const start = record.startingLife ?? 20;
const life: [number, number] = [start, start];
const played: Played[] = [];
const destroyed: string[] = [];
record.events.forEach((e, i) => {
if (e.kind === 'playerDamage' || e.kind === 'lifeGain') life[e.seat] = Math.max(0, e.life);
if (e.kind === 'deploy' || e.kind === 'cast') played.push({ id: e.card, seat: e.seat, order: i });
if (e.kind === 'adopt') played.push({ id: e.doctrine, seat: e.seat, order: i });
if (e.kind === 'destroyed') destroyed.push(e.card);
});
if (over.life) { life[0] = Math.max(0, over.life[0]); life[1] = Math.max(0, over.life[1]); }
const winner: Seat = over.winner ?? 0;
return { winner, draw: over.winner === null, loser: winner === 0 ? 1 : 0, reason: over.reason, turns: over.turn, life, played, destroyed };
}
/** Highest cost wins; ties go to the card played first. */
function best(cands: Played[], cards: Record<string, StoryCard>): Played | undefined {
let top: Played | undefined;
for (const c of cands) if (!top || cards[c.id].cost > cards[top.id].cost) top = c;
return top;
}
/** DUEL_DESIGN §8.3 naming order. */
export function battleName(record: MatchRecord, f: Facts = facts(record)): StoryCard | undefined {
const C = record.cards;
const of = (seat: Seat | null, type?: StoryCard['type']) =>
f.played.filter(p => (seat === null || p.seat === seat) && (!type || C[p.id].type === type));
const pick = best(of(f.winner, 'Location'), C) ?? best(of(f.loser, 'Location'), C)
?? best(of(null, 'Event'), C) ?? best(of(f.winner), C) ?? best(of(f.loser), C);
return pick ? C[pick.id] : undefined;
}
export function battleTitle(record: MatchRecord, f: Facts = facts(record)): string {
const card = battleName(record, f);
const year = record.date.slice(0, 4);
if (!card) return `WikiDeck match of ${longDate(record.date)}`;
if (card.type === 'Figure') return `${card.title} campaign (${year})`;
const each = Math.ceil(f.turns / 2);
const prefix = each <= 6 ? 'Skirmish at' : each >= 13 ? 'Siege of' : 'Battle of';
return `${prefix} ${card.title} (${year})`;
}
function resultText(record: MatchRecord, f: Facts): string {
const w = record.players[f.winner].name;
if (f.draw) return 'Inconclusive';
switch (f.reason) {
case 'concede': case 'timeout': return `${w} victory by withdrawal`;
case 'library': return `${w} victory by attrition`;
case 'turnCap': return `${w} victory by decision`;
case 'life': {
if (f.life[f.winner] <= 3) return `Pyrrhic ${w} victory`;
if (f.life[f.winner] - f.life[f.loser] >= 10) return `Decisive ${w} victory`;
return `${w} victory`;
}
}
}
const LEAD_VARIANTS = [
'The {title} was a WikiDeck engagement fought on {date} between the forces of {a} and {b}. It lasted {turns} turns and ended in {result}.',
'The {title} was fought on {date} between {a} and {b}, and lasted {turns} turns. It ended in {result}.',
'The {title} took place on {date}. The forces of {a} and {b} engaged for {turns} turns; the engagement ended in {result}.',
];
const FIRST_DEPLOY_VARIANTS = [
'Contemporary accounts note the deployment of {card} in the {ordinal} turn.',
'Records list {card} as the first Figure deployed, in the {ordinal} turn.',
'The first Figure to enter play was {card}, in the {ordinal} turn.',
];
function pickVariant(record: MatchRecord, salt: string, list: readonly string[]): string {
return list[variantIndex(record.seed, `recap:${salt}`, 0, list.length)];
}
function sub(t: string, v: Record<string, string | number>): string {
return t.replace(/\{(\w+)\}/g, (_, k: string) => String(v[k]));
}
/** The result as a phrase for the lead: "a Pyrrhic victory for bob". */
function resultPhrase(record: MatchRecord, f: Facts): string {
const w = record.players[f.winner].name;
if (f.draw) return 'a draw';
switch (f.reason) {
case 'concede': case 'timeout': return `a victory for ${w} by withdrawal`;
case 'library': return `a victory for ${w} by attrition`;
case 'turnCap': return `a victory for ${w} by decision`;
case 'life': {
if (f.life[f.winner] <= 3) return `a Pyrrhic victory for ${w}`;
if (f.life[f.winner] - f.life[f.loser] >= 10) return `a decisive victory for ${w}`;
return `a victory for ${w}`;
}
}
}
export function recap(record: MatchRecord): RecapDoc {
const f = facts(record);
const C = record.cards;
const nar = new Narrator(record, 'recap');
const [a, b] = [record.players[0].name, record.players[1].name];
const nameCard = battleName(record, f);
const title = battleTitle(record, f);
const result = resultText(record, f);
// Lead: cite the name card first so it is reference [1].
const nameRef = nameCard ? `[${nar.cite(nameCard.id)}]` : '';
let lead = sub(pickVariant(record, 'lead', LEAD_VARIANTS), {
title: `**${title}**`, date: longDate(record.date), a, b, turns: numberWord(f.turns), result: resultPhrase(record, f),
}) + nameRef;
const firstFig = record.events.findIndex(e => e.kind === 'deploy' && C[e.card].type === 'Figure');
if (firstFig >= 0) {
const ev = record.events[firstFig] as Extract<StoryEvent, { kind: 'deploy' }>;
const turn = turnAt(record.events, firstFig);
const t = pickVariant(record, 'firstDeploy', FIRST_DEPLOY_VARIANTS);
const card = nar.mention(ev.card);
const refs = nar.flush();
lead += ' ' + sub(t, { card, ordinal: ordinalWord(turn) }) + refs.map(r => `[${r}]`).join('');
}
// Background: Portal mix of the cards each side played.
const background: string[] = [];
for (const seat of [0, 1] as Seat[]) {
const mine = f.played.filter(p => p.seat === seat);
if (!mine.length) { background.push(`${record.players[seat].name} played no cards.`); continue; }
const counts = new Map<string, number>();
for (const p of mine) { const k = C[p.id].portal ?? 'Neutral'; counts.set(k, (counts.get(k) ?? 0) + 1); }
const sorted = [...counts.entries()].sort((x, y) => y[1] - x[1] || x[0].localeCompare(y[0]));
const max = sorted[0][1];
const tops = sorted.filter(([, n]) => n === max).map(([k]) => k);
const name = record.players[seat].name;
const played = `${numberWord(mine.length)} ${mine.length === 1 ? 'card' : 'cards'} played`;
if (tops.length === 1) background.push(`${tops[0]} was the largest Portal in the force of ${name} (${numberWord(max)} of ${played}).`);
else background.push(`${listJoin(tops)} were equally represented in the force of ${name} (${numberWord(max)} ${max === 1 ? 'card' : 'cards'} each, of ${played}).`);
}
// Course of the battle: the largest Notability swings and destroyed cards of cost ≥ 4.
const swings = record.events
.map((e, i) => ({ e, i }))
.filter(x => x.e.kind === 'playerDamage')
.sort((x, y) => (y.e as { amount: number }).amount - (x.e as { amount: number }).amount || x.i - y.i)
.slice(0, 5).map(x => x.i);
const big = record.events.map((e, i) => ({ e, i }))
.filter(x => x.e.kind === 'destroyed' && C[(x.e as { card: string }).card].cost >= 4).map(x => x.i);
const chosen = [...new Set([...swings, ...big])].sort((x, y) => x - y);
const course: string[] = [];
let curTurn = -1;
let para: string[] = [];
for (const i of chosen) {
const t = turnAt(record.events, i);
if (t !== curTurn && para.length) { course.push(para.join(' ')); para = []; }
if (t !== curTurn) para.push(`In the ${ordinalWord(t)} turn,`);
curTurn = t;
const out = renderEvent(nar, record.events[i], i, null, { preferSource: true });
if (out) para.push(out.text);
}
if (para.length) course.push(para.join(' '));
const over = record.events.findIndex(e => e.kind === 'gameOver');
const end = renderEvent(nar, record.events[over], over, null);
if (end) course.push(end.text);
// Aftermath.
const aftermath = [f.draw
? `Both ${a} and ${b} ended the engagement with ${f.life[0]} Notability.`
: `${record.players[f.winner].name} ended the engagement with ${f.life[f.winner]} Notability; ${record.players[f.loser].name} ended with ${f.life[f.loser]}.`,
];
if (record.ratingChange) {
const fmt = (n: number) => (n >= 0 ? `+${n}` : `${n}`);
aftermath.push(`Ratings changed by ${fmt(record.ratingChange[0])} for ${a} and ${fmt(record.ratingChange[1])} for ${b}.`);
}
// See also: Connected pairs and rivalries.
const seeAlso: string[] = [];
for (const e of record.events) {
if (e.kind === 'connected' || e.kind === 'rivalry') seeAlso.push(`*${C[e.a].title}* – *${C[e.b].title}* (${e.reason})`);
}
// References: every card played, in first-mention order.
for (const p of f.played) nar.cite(p.id);
const perSeat = (fn: (s: Seat) => string): [string, string] => [fn(0), fn(1)];
const infobox: RecapInfobox = {
date: longDate(record.date),
location: nameCard?.type === 'Location' ? nameCard.title : `WikiDeck host ${record.hostName ?? 'unknown'}`,
result,
belligerents: [a, b],
commanders: perSeat(s => {
const c = best(f.played.filter(p => p.seat === s && C[p.id].type === 'Figure'), C);
return c ? C[c.id].title : 'None recorded';
}),
strength: perSeat(s => cards(f.played.filter(p => p.seat === s).length)),
casualties: perSeat(s => {
const lost = f.destroyed.filter(id => C[id].owner === s).map(id => C[id].title);
return lost.length ? `${cards(lost.length)} destroyed: ${lost.join(', ')}` : 'None';
}),
};
const sections: RecapSection[] = [
{ heading: 'Background', paragraphs: background },
{ heading: 'Course of the battle', paragraphs: course },
{ heading: 'Aftermath', paragraphs: aftermath },
];
if (seeAlso.length) sections.push({ heading: 'See also', paragraphs: seeAlso });
return {
matchId: record.matchId,
url: `/recap/${encodeURIComponent(record.matchId)}`,
masthead: 'WikiDeck',
title,
nameCardId: nameCard?.id,
infobox,
lead,
sections,
references: nar.references,
footer: FOOTER,
};
}
function listJoin(xs: string[]): string {
return xs.length <= 1 ? xs.join('') : `${xs.slice(0, -1).join(', ')} and ${xs[xs.length - 1]}`;
}
function cards(n: number): string { return `${n} ${n === 1 ? 'card' : 'cards'}`; }
function turnAt(events: StoryEvent[], index: number): number {
for (let i = index; i >= 0; i--) { const e = events[i]; if (e.kind === 'turnStart') return e.turn; }
return 0;
}
+156
View File
@@ -0,0 +1,156 @@
/**
* Match-log sentence templates (DUEL_DESIGN.md §8.2). Data only.
*
* Tone (BRIEF decision 5, DUEL_DESIGN §8.1): past tense, encyclopedic, deadpan. No adjectives
* about cards or players, no exclamation marks, never comment on the matchup. Placeholders
* are filled only with real card and match data. `tests/duel-design-story.test.ts` lints this file.
*
* Placeholders: {player} {opponent} {card} {doctrine} {figure} {attacker} {blocker} {source}
* {target} {token} {a} {b} {reason} {winner} {loser} {n} {count} {p} {t} {life} {turn}.
*/
export const LOG_TEMPLATES = {
deploy: [
'{player} deployed {card}.',
'{card} was deployed by {player}.',
'{player} brought {card} into play.',
'{card} entered play under {player}.',
],
cast: [
'{player} cited {card}.',
'{card} was cited by {player}.',
'{player} invoked {card}.',
],
adopt: [
'{doctrine} was adopted by {figure}, which became a {p}/{t}.',
'{figure} adopted {doctrine} and became a {p}/{t}.',
'{player} attached {doctrine} to {figure} ({p}/{t}).',
],
attack: [
'{card} ({p}/{t}) attacked.',
'{player} sent {card} ({p}/{t}) into combat.',
'{card} ({p}/{t}) advanced on {opponent}.',
],
block: [
'{blocker} ({p}/{t}) blocked {attacker}.',
'{attacker} was blocked by {blocker} ({p}/{t}).',
'{blocker} ({p}/{t}) intercepted {attacker}.',
],
playerDamage: [
'{player} lost {n} Notability ({life} remaining).',
'{source} dealt {n} damage to {player}, leaving {life} Notability.',
"{player}'s Notability fell to {life}.",
],
lifeGain: [
'{player} gained {n} Notability from {source} ({life} total).',
'{source} restored {n} Notability to {player}.',
"{player}'s Notability rose to {life} ({source}).",
],
effectDamage: [
'{source} dealt {n} damage to {target}.',
'{target} took {n} damage from {source}.',
'{source} inflicted {n} damage on {target}.',
],
destroyed: [
'{card} was destroyed.',
'{card} was moved to Deleted.',
'{card} was removed from play.',
'{card} did not survive the turn.',
],
tokenCreated: [
'{source} produced {count} {token}.',
'{source} brought {count} {token} into play.',
'{source} created {count} {token}.',
],
drawKnown: [
'{player} drew {card}.',
'{card} was drawn by {player}.',
'{player} added {card} to their hand.',
],
drawHidden: [
'{player} drew a card.',
'{player} drew one card.',
'{player} added a card to their hand.',
],
drawHiddenMany: [
'{player} drew {count} cards.',
'{player} added {count} cards to their hand.',
'{player} took {count} cards into hand.',
],
discard: [
'{player} discarded {card}.',
'{card} was discarded by {player}.',
'{player} moved {card} from hand to Deleted.',
],
connected: [
'{a} and {b} were Connected ({reason}).',
'{a} was Connected to {b} through {reason}.',
'Records link {a} and {b} ({reason}).',
],
rivalry: [
'{a} and {b} are both listed under {reason}.',
'{a} and {b} share {reason}.',
'The two sides were linked through {reason}.',
],
gameOverLife: [
'{loser} was nominated for deletion. The result was **delete**.',
'{loser} was reduced to 0 Notability. {winner} won.',
'{winner} won on turn {turn}.',
],
gameOverDraw: [
'Both sides were reduced to 0 Notability. The engagement ended in a draw.',
'The engagement ended in a draw on turn {turn}.',
'Neither side retained any Notability. No winner was recorded.',
],
gameOverLibrary: [
'{loser} could not draw a card and lost.',
'{loser} ran out of cards. {winner} won.',
"{loser}'s library was exhausted. {winner} won.",
],
gameOverConcede: [
'{loser} withdrew.',
'{loser} withdrew. {winner} won.',
'{loser} conceded on turn {turn}.',
],
gameOverTimeout: [
'{loser} did not respond in time and withdrew.',
'{loser} ran out of time. {winner} won.',
"{loser}'s clock expired on turn {turn}.",
],
gameOverTurnCap: [
'{winner} won on Notability at the turn limit.',
'The turn limit was reached. {winner} won on Notability.',
'The engagement reached the turn limit; {winner} held more Notability.',
],
} as const satisfies Record<string, readonly string[]>;
export type TemplateKey = keyof typeof LOG_TEMPLATES;
/** Words the generator must never emit (critic S7 failure modes). Lowercase; whole words. */
export const BANNED_WORDS = [
'brutal', 'brutally', 'heroic', 'heroically', 'humiliating', 'humiliated', 'bloodiest', 'bloody',
'surprising', 'surprisingly', 'ironically', 'unlikely', 'hilarious', 'tragic', 'tragically', 'sadly',
'unfortunately', 'poor', 'epic', 'crushed', 'squashed', 'killed', 'murdered', 'destroyed utterly', 'lol',
];
export const FOOTER =
'This page records a WikiDeck match. Card names refer to Wikipedia articles; the events described are game events.';
const NUMBER_WORDS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty'];
export function numberWord(n: number): string {
return Number.isInteger(n) && n >= 0 && n < NUMBER_WORDS.length ? NUMBER_WORDS[n] : String(n);
}
const ORDINALS = ['zeroth', 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth',
'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth', 'twentieth'];
export function ordinalWord(n: number): string {
if (Number.isInteger(n) && n >= 0 && n < ORDINALS.length) return ORDINALS[n];
const s = n % 100 >= 11 && n % 100 <= 13 ? 'th' : ({ 1: 'st', 2: 'nd', 3: 'rd' } as Record<number, string>)[n % 10] ?? 'th';
return `${n}${s}`;
}
export function fill(template: string, values: Record<string, string | number>): string {
return template.replace(/\{(\w+)\}/g, (whole, key: string) => {
if (!(key in values)) throw new Error(`story template is missing a value for {${key}}: ${template}`);
return String(values[key]);
});
}
+98
View File
@@ -0,0 +1,98 @@
/**
* Story input contract (DUEL_DESIGN.md §8). This is the minimal, engine-agnostic shape the
* match-log and recap templates read. `fromDuel.ts` (added after duel-core's
* shared/duel/types.ts merges) maps engine LogEvents onto it. Everything is plain JSON,
* so a stored match record can regenerate its log and recap exactly.
*/
export type Seat = 0 | 1;
export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
/** One card instance in the match, frozen from its derived profile. Only real data. */
export interface StoryCard {
/** Engine instance id, unique within the match. */
id: string;
/** Article title, verbatim. */
title: string;
/** Wikidata short description, verbatim ('' or undefined if none). */
description?: string;
type: CardType;
cost: number;
/** Portal (faction): Arts, Earth, History, Science, Society or Neutral. */
portal?: string;
/** The article revision the card was minted from (on-chain). Absent for tokens: they are never cited. */
revisionId?: number;
/** Tokens (Elected Member, Staff Member): generic, not articles, never cited or glossed. */
token?: boolean;
/** On-chain token id of the mint, if known. */
tokenId?: string;
/** Seat that owns the card in this match. */
owner: Seat;
}
export type GameOverReason = 'life' | 'library' | 'concede' | 'timeout' | 'turnCap';
export type StoryEvent =
| { kind: 'turnStart'; turn: number; seat: Seat }
| { kind: 'deploy'; seat: Seat; card: string }
| { kind: 'cast'; seat: Seat; card: string }
| { kind: 'adopt'; seat: Seat; doctrine: string; figure: string; power: number; toughness: number }
| { kind: 'attack'; seat: Seat; card: string; power: number; toughness: number }
| { kind: 'block'; seat: Seat; blocker: string; attacker: string; power: number; toughness: number }
/** `seat` is the player who lost Notability; `life` is what remains. */
| { kind: 'playerDamage'; seat: Seat; source?: string; amount: number; life: number }
/** `life` is the new total. */
| { kind: 'lifeGain'; seat: Seat; source: string; amount: number; life: number }
| { kind: 'effectDamage'; source: string; target: string; amount: number }
| { kind: 'destroyed'; card: string }
| { kind: 'tokenCreated'; seat: Seat; source: string; token: string; count: number }
/** `card` set when the drawn card is known to the viewer's record; hidden draws omit it. */
| { kind: 'draw'; seat: Seat; card?: string; count?: number }
/** Deleted is public (DUEL_DESIGN §2.3): discards are always named. */
| { kind: 'discard'; seat: Seat; card: string }
| { kind: 'connected'; seat: Seat; a: string; b: string; reason: string }
| { kind: 'rivalry'; a: string; b: string; reason: string }
/** winner null = draw (both players reached 0 at once). */
/** `life`: final Notability per seat, authoritative when present (duel-core carries it). */
| { kind: 'gameOver'; winner: Seat | null; reason: GameOverReason; turn: number; life?: [number, number] };
export interface StoryPlayer {
/** Display name of the seat (account display name or "Bot (Normal)"). */
name: string;
}
export interface MatchRecord {
matchId: string;
/**
* Story seed: drives template variants only. NOT the engine seed: a client rendering
* logFor text must never learn the engine seed (it would reveal library order). The host
* derives it, e.g. sha256(engineSeed + ':story'). Recaps after the match may use either.
*/
seed: number | string;
/** Match date, ISO `YYYY-MM-DD`. No clock is read by the story code. */
date: string;
players: [StoryPlayer, StoryPlayer];
cards: Record<string, StoryCard>;
events: StoryEvent[];
startingLife?: number;
hostName?: string;
/** Ranked matches: rating change per seat. */
ratingChange?: [number, number];
}
export interface LogLine {
turn: number;
text: string;
/** Reference numbers cited by this line, in order. */
refs: number[];
}
export interface Reference {
n: number;
cardId: string;
title: string;
revisionId: number;
tokenId?: string;
url: string;
/** Rendered citation line, without the leading number. */
text: string;
}
+149
View File
@@ -0,0 +1,149 @@
/**
* Rules text in MTG's terse register (designer review §3.4–3.5, critic S7, BRIEF decision 5).
* Deterministic templates filled only with the card's own derived numbers and keyword names.
* No prose about the subject, no invented facts: flavour text is the article's own first sentence.
* Owner: duel-cards.
*/
import type { DuelCard, Keyword } from './derive.ts';
import type { EffectSpec } from './effects.ts';
/** Reminder text per keyword (DUEL_DESIGN §4). */
export const KEYWORD_REMINDER: Readonly<Record<Keyword, string>> = {
Protected: 'Can\'t be the target of Events or Doctrines an opponent controls.',
Featured: 'Can\'t be blocked except by Featured, Translated or Multilingual Figures.',
Legacy: 'When this is destroyed, draw a card.',
Multilingual: 'Can block Featured Figures. Can\'t be blocked by Local Figures.',
Translated: 'Can block Featured Figures.',
'Well-sourced': 'Prevent the first 1 damage that would be dealt to this each turn.',
Stub: 'At the start of your turn, put a +1/+1 counter on this, to a maximum of 2.',
Local: 'Gets +1/+1 while you control a Compatriot Location.',
Trending: 'Can attack the turn it enters. Gets +1/+0.',
};
const NUMBER_WORDS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six'];
const word = (n: number) => NUMBER_WORDS[n] ?? String(n);
const signed = (n: number) => (n >= 0 ? `+${n}` : `−${-n}`);
const pt = (p = 0, t = 0) => `${signed(p)}/${signed(t)}`;
const TARGET_NOUN: Readonly<Record<string, string>> = {
figure: 'target Figure', figureOrLocation: 'target Figure or Location', ownFigure: 'target Figure you control',
opponentFigure: 'target Figure you don\'t control', each: 'each Figure and each Location', self: 'this',
attached: 'adopted Figure', ownFigures: 'Figures you control',
};
function keywordsAsText(keywords: readonly Keyword[]): string {
return keywords.join(', ');
}
function staticText(e: EffectSpec): string {
const c = e.condition ?? {};
let who = 'Figures you control';
if (c.maxPower !== undefined) who = `Figures you control with power ${c.maxPower} or less`;
if (c.connected) who = 'Figures you control that are Connected to this';
if (c.samePortal) who = 'Other Figures you control of its Portal';
if (e.grant?.length && !e.power && !e.toughness) {
return `${who} have ${keywordsAsText(e.grant)}.`;
}
return `${who} get ${pt(e.power, e.toughness)}.`;
}
function tokenText(e: EffectSpec): string {
const t = e.token!;
const n = e.amount ?? 1;
const portal = t.portal === 'Neutral' ? '' : `${t.portal} `;
const body = `${t.power}/${t.toughness} ${portal}Figure token${n === 1 ? '' : 's'} named ${t.name}`;
return n === 1 ? `create a ${body}` : `create ${word(n)} ${body}`;
}
function actionText(e: EffectSpec): string {
switch (e.op) {
case 'damage': return `deal ${e.amount} damage to ${TARGET_NOUN[e.target ?? 'figure']}`;
case 'damageEach': return `deal ${e.amount} damage to each Figure and each Location`;
case 'createToken': return tokenText(e);
case 'pump': return `${TARGET_NOUN[e.target ?? 'figure']} gets ${pt(e.power, e.toughness)}${e.duration === 'turn' ? ' until end of turn' : ''}`;
case 'fight': return `it fights ${TARGET_NOUN[e.target ?? 'opponentFigure']}`;
case 'draw': return e.amount === 1 ? 'draw a card' : `draw ${word(e.amount ?? 1)} cards`;
case 'gainLife': return `you gain ${e.amount} Notability`;
case 'attach': return '';
case 'drain': return `each opponent loses ${e.amount} Notability and you gain ${e.amount} Notability`;
case 'destroy': return `destroy ${TARGET_NOUN[e.target ?? 'figure'] ?? 'target permanent'}`;
case 'bounce': return `return ${TARGET_NOUN[e.target ?? 'figure'] ?? 'target permanent'} to its owner's hand`;
case 'tap': return `tap ${TARGET_NOUN[e.target ?? 'figure'] ?? 'target permanent'}`;
}
}
const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
/** One sentence per effect, in effect order. */
export function effectText(effects: readonly EffectSpec[]): string[] {
const lines: string[] = [];
for (let i = 0; i < effects.length; i++) {
const e = effects[i];
if (e.op === 'attach') {
// The Doctrine's buff is the static pump on `attached` that follows (DUEL_API "Doctrine").
const next = effects[i + 1];
const buff = next && next.trigger === 'static' && next.op === 'pump' && next.target === 'attached' ? next : null;
let line = `Attach to ${e.target === 'figure' ? 'target Figure' : 'target Figure you control'}.`;
if (buff) {
const grant = buff.grant?.length ? ` and has ${keywordsAsText(buff.grant)}` : '';
line += ` It gets ${pt(buff.power, buff.toughness)}${grant}.`;
i++;
}
lines.push(line);
continue;
}
if (e.op === 'fight' && i > 0 && effects[i - 1].op === 'pump') {
lines[lines.length - 1] = lines[lines.length - 1].replace(/\.$/, `, then ${actionText(e)}.`);
continue;
}
switch (e.trigger) {
case 'static': lines.push(staticText(e)); break;
case 'onPlay': lines.push(`${cap(actionText(e))}.`); break;
case 'onEnter': lines.push(`When this enters, ${actionText(e)}.`); break;
case 'onDestroyed': lines.push(`When this is destroyed, ${actionText(e)}.`); break;
case 'startOfTurn': {
const max = e.condition?.maxTokens;
const cond = max !== undefined ? `, if you control fewer than ${max} tokens` : '';
lines.push(`At the start of your turn${cond}, ${actionText(e)}.`);
break;
}
case 'onCombatDamageToPlayer':
// On a Doctrine the trigger belongs to the attached Figure ("it"); on a Figure, to "this".
lines.push(`Whenever ${effects.some(x => x.op === 'attach') ? 'it' : 'this'} deals combat damage to a player, ${actionText(e)}.`);
break;
}
}
return lines;
}
/** The type line, e.g. "Figure — Society" or "Event — History". */
export function typeLine(card: Pick<DuelCard, 'type' | 'portal'>): string {
return card.portal === 'Neutral' ? card.type : `${card.type} — ${card.portal}`;
}
/** Full rules text: keyword line, Location lines, effect lines. Newline-separated. */
export function rulesTextFor(card: Pick<DuelCard, 'type' | 'keywords' | 'effects' | 'territory' | 'toughness'>): string {
const lines: string[] = [];
if (card.keywords.length) lines.push(`${keywordsAsText(card.keywords)}.`);
if (card.type === 'Location') {
if (card.territory) lines.push('Territory.');
lines.push(`Garrison 0/${card.toughness}.`);
}
lines.push(...effectText(card.effects));
return lines.join('\n');
}
export const RULE_WORD_REMINDER: Readonly<Record<'Territory' | 'Garrison', string>> = {
Territory: 'Your Citation maximum is 1 higher while you control this, to at most +2 from Territory.',
Garrison: 'This can block like a Figure with power 0. It can\'t attack.',
};
/** Rules text with reminder text for keywords and rule words, for the tap-to-expand view. */
export function rulesTextWithReminders(card: Pick<DuelCard, 'type' | 'keywords' | 'effects' | 'territory' | 'toughness'>): string {
const lines = card.keywords.map(k => `${k}. (${KEYWORD_REMINDER[k]})`);
for (const line of rulesTextFor({ ...card, keywords: [] }).split('\n').filter(Boolean)) {
const word = line.match(/^(Territory|Garrison)\b/)?.[1] as keyof typeof RULE_WORD_REMINDER | undefined;
lines.push(word ? `${line} (${RULE_WORD_REMINDER[word]})` : line);
}
return lines.join('\n');
}
+398
View File
@@ -0,0 +1,398 @@
/**
* 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
secondPlayerCitations: number; // 1 (balance v1): extra Citations on the second player's first turn (designer's "Second Opinion" lever)
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
/** 40 (balance v1); null = none. 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;
}
+45 -8
View File
@@ -11,7 +11,17 @@
*/
import { z } from 'zod';
export const MODE_SCHEMA_VERSION = 'wikideck.mode/1' as const;
export const MODE_SCHEMA_VERSION = 'wikideck.mode/2' as const;
/** Night 1 schema: rejected with a clear message (BRIEF "Modes": versioned schema). */
export const LEGACY_MODE_SCHEMA_VERSIONS: readonly string[] = ['wikideck.mode/1'];
/**
* Which rules engine a mode runs on. `editwar` is the Night 1 simultaneous-reveal game
* (shared/game); `duel` is the Night 2 Magic-style duel (shared/duel). A host may not
* register every engine; modes for an engine it lacks fail at startup.
*/
export const ENGINE_IDS = ['editwar', 'duel'] as const;
export const EngineIdSchema = z.enum(ENGINE_IDS);
export type EngineId = z.infer<typeof EngineIdSchema>;
/** Upper bound on the JSON size of one mode document, before parsing. */
export const MAX_MODE_BYTES = 8 * 1024;
/** Upper bound on modes one node may publish (and that discovery accepts from one peer). */
@@ -60,14 +70,25 @@ export type CardMapping = z.infer<typeof CardMappingSchema>;
/** Where match decks come from. Matches never move or burn NFTs, whatever the policy. */
export const DeckPolicySchema = z.discriminatedUnion('kind', [
/** Each player brings a deck (starter deck or own cards, validated by the engine). */
z.object({ kind: z.literal('constructed'), allowStarter: z.boolean().default(true) }).strict(),
/** Host-seeded starter decks only: everyone gets the engine's `starterDeck(seed)`. */
/**
* Each player brings exactly `deckSize` NFTs they own (token ids), verified server-side
* against the chain and built from their blocks. Requires an eom.dev account seat.
*/
z.object({ kind: z.literal('constructed'),
/** Confirmations each card's mint (or last transfer) needs; rated modes should use ≥ 3. */
minConfirmations: z.number().int().min(0).max(100).default(1),
}).strict(),
/** Host-seeded starter decks only (Edit War engine only: the duel has no loaners). */
z.object({ kind: z.literal('starter') }).strict(),
/** Snake draft from a host-seeded pool of non-NFT preview cards. */
/** Snake draft from a host-seeded pool. */
z.object({ kind: z.literal('draft'),
/**
* `preview`: the engine's non-NFT preview cards (Edit War only).
* `collections`: both players' owned cards, used for this match only; nothing moves on-chain.
*/
source: z.enum(['preview', 'collections']).default('preview'),
/** Cards in the shared pool; must be at least 2 × the ruleset's deck size. */
poolSize: z.number().int().min(8).max(64).default(30),
poolSize: z.number().int().min(8).max(200).default(30),
/** Seconds per pick before the host auto-picks the first card. */
pickSeconds: z.number().int().min(5).max(120).default(30),
}).strict(),
@@ -81,6 +102,10 @@ export const ModeLimitsSchema = z.object({
turnSeconds: z.number().int().min(10).max(600).default(90),
/** Lobbies with no opponent expire after this many minutes. */
lobbyMinutes: z.number().int().min(1).max(120).default(15),
/** Ranked: Elo moves only when both seats are eom.dev accounts. */
rated: z.boolean().default(false),
/** Seats must be eom.dev accounts (always true for constructed and collection-draft modes). */
accountsOnly: z.boolean().default(false),
}).strict();
export type ModeLimits = z.infer<typeof ModeLimitsSchema>;
@@ -93,11 +118,13 @@ export const ModeSchema = z.object({
name: text(48),
description: text(400),
tags: z.array(slug).max(5).default([]),
/** The rules engine this mode runs on. Required: there is no safe default across engines. */
engine: EngineIdSchema,
/** Overrides on top of the engine's DEFAULT_RULESET. */
rules: RuleOverridesSchema.default({}),
cards: CardMappingSchema.default({ preset: 'standard' }),
decks: DeckPolicySchema.default({ kind: 'constructed', allowStarter: true }),
limits: ModeLimitsSchema.default({ maxConcurrentMatches: 32, turnSeconds: 90, lobbyMinutes: 15 }),
decks: DeckPolicySchema.default({ kind: 'constructed', minConfirmations: 1 }),
limits: ModeLimitsSchema.default({ maxConcurrentMatches: 32, turnSeconds: 90, lobbyMinutes: 15, rated: false, accountsOnly: false }),
}).strict();
export type ModeDocument = z.infer<typeof ModeSchema>;
export type ModeInput = z.input<typeof ModeSchema>;
@@ -145,6 +172,10 @@ export function parseModeJson(json: string): ModeDocument {
}
export function parseMode(value: unknown): ModeDocument {
assertInertKeys(value);
const schema = (value as { schema?: unknown } | null)?.schema;
if (typeof schema === 'string' && LEGACY_MODE_SCHEMA_VERSIONS.includes(schema)) {
throw new Error(`Mode schema ${schema} (Night 1) is no longer accepted: use ${MODE_SCHEMA_VERSION} with an "engine" field (see docs/game/HOSTING.md)`);
}
const mode = ModeSchema.parse(value);
if (byteLength(JSON.stringify(mode)) > MAX_MODE_BYTES) throw new Error(`Mode document exceeds ${MAX_MODE_BYTES} bytes`);
return mode;
@@ -163,6 +194,12 @@ export function parseModeList(json: string): { list: ModeList; rejected: number
return { list: ModeListSchema.parse({ ...raw, modes }), rejected };
}
/** Whether a mode's seats must be eom.dev accounts (owned cards always need one). */
export function requiresAccount(mode: ModeDocument): boolean {
return mode.limits.accountsOnly || mode.decks.kind === 'constructed' ||
(mode.decks.kind === 'draft' && mode.decks.source === 'collections');
}
/** Stable key for a mode on a host: `<origin>#<id>@<version>`. */
export function modeKey(origin: string, mode: Pick<ModeDocument, 'id' | 'version'>): string {
return `${origin}#${mode.id}@${mode.version}`;
+26 -5
View File
@@ -10,12 +10,16 @@ import { Card, samples, imageCredit, type CardData } from './Card.tsx';
import { WalletPanel } from './WalletPanel.tsx';
import { useModalFocus } from './useModalFocus.ts';
import { ThemePicker } from './ThemePicker.tsx';
import { LoginButton } from './auth/LoginButton.tsx';
import { LoginButton, useAccount } from './auth/LoginButton.tsx';
import { TradeDesk } from './TradeDesk.tsx';
import { IS_MAINNET, NETWORK_GENESIS_TIME, NETWORK_LABEL } from '../shared/network.ts';
import { StateClient } from '../shared/rpc-client.ts';
import { PlaySection } from './game/PlaySection.tsx';
import { inviteFromPath } from './game/online.ts';
import { BattleRecap, matchIdFromPath } from './game/recap/BattleRecap.tsx';
import './game/recap/recap.css';
import { isNativeApp } from './native.ts';
import { MobileMiningPanel } from './MobileMiningPanel.tsx';
import { Landing } from './Landing.tsx';
import './App.css';
import './testnet.css';
@@ -47,7 +51,18 @@ function transferProblem(state: TestnetSnapshot, card: CardData, address: string
}
export default function App() {
const [view, setView] = useState<View>('Discover');
// Deep links (Night 2, ui-pvp): /play/invite/<code> opens Play with the invite; /recap/<id> (or /battle/<id>) is a recap page.
const [invite] = useState(() => inviteFromPath(location.pathname));
const [battle, setBattle] = useState(() => matchIdFromPath(location.pathname));
const [view, setView] = useState<View>(() => (invite ? 'Play' : 'Discover'));
const linkedAccount = useAccount();
const openRecap = (id: string) => { history.pushState(null, '', `/recap/${encodeURIComponent(id)}`); setBattle(id); };
const closeRecap = () => { history.pushState(null, '', '/'); setBattle(''); };
useEffect(() => {
const pop = () => setBattle(matchIdFromPath(location.pathname));
window.addEventListener('popstate', pop);
return () => window.removeEventListener('popstate', pop);
}, []);
const [wallet, setWallet] = useState<Wallet>();
const [snapshot, setSnapshot] = useState<TestnetSnapshot>();
const [rpcAvailable, setRpcAvailable] = useState(false);
@@ -127,7 +142,10 @@ export default function App() {
} catch (e) { setTransferError(message(e)); }
finally { transferInFlight.current = false; setTransferBusy(false); }
};
const owned = snapshot?.blocks.filter(b => wallet && testnetOwnerOf(snapshot, b.tokenId) === wallet.address) ?? [];
// Every canonical card owned by this browser's wallet or any wallet linked to the eom.dev account (#57).
// The full canonical chain is paged in by StateClient, so nothing is capped at 128 blocks.
const mine = new Set([wallet?.address, ...(linkedAccount?.wallets ?? []).map(w => w.address)].filter(Boolean));
const owned = snapshot?.blocks.filter(b => mine.has(testnetOwnerOf(snapshot, b.tokenId) ?? '')) ?? [];
const visibleCards = view === 'My collection' ? owned.map(asCard)
: snapshot?.blocks.length ? [...snapshot.blocks].reverse().slice(0, 12).map(asCard) : samples;
const filtered = visibleCards.filter(c => (category === 'All cards' || c.article.category === category) &&
@@ -161,6 +179,8 @@ export default function App() {
catch (e) { setError(message(e)); }
};
// /recap/<id>: a standalone, shareable recap page (no hero or mining panel around it).
if (battle) return <main className="recap-shell"><BattleRecap key={battle} matchId={battle} onExit={closeRecap} /></main>;
return <div className="app-shell">
<aside className="sidebar">
<a href="#" className="brand" onClick={e => { e.preventDefault(); setView('Discover'); }}><span className="brand-mark" aria-hidden="true">W<span>✦</span></span>wikideck<span className="brand-dot">.</span></a>
@@ -190,7 +210,8 @@ export default function App() {
<div><span className="metric-icon"><WalletIcon size={19} /></span><div><span>Confirmed ownership</span><strong>{wallet && snapshot ? owned.length : '—'}<small>in your wallet</small></strong></div></div>
<div><span className="metric-icon"><Cpu size={19} /></span><div><span>Proof of work</span><strong className="algorithm">{snapshot?.algorithm ?? 'RandomX'}<small>native CPU mining</small></strong></div></div>
</section>
<section className="mining-panel native-mining" ref={minerPanel} hidden={isNativeApp()}>
{isNativeApp() && <MobileMiningPanel ref={minerPanel} wallet={wallet} onAccepted={() => { void refresh().catch(() => {}); }} />}
<section className="mining-panel native-mining" ref={isNativeApp() ? undefined : minerPanel} hidden={isNativeApp()}>
<div className="mining-description"><div className="section-eyebrow"><span className="idle-dot" /> RANDOMX · DESIGNED FOR GENERAL-PURPOSE CPUS</div><h2>Mining should be for more people.</h2><p>Wikideck and Monero use RandomX, an algorithm designed to resist specialized ASICs and keep general-purpose CPUs competitive. That can make mining more accessible—not make every machine equally powerful or promise rewards. Each accepted Wikideck block earns its miner a distinct illustrated Wikipedia card. Wikideck is its own independent network.</p><div className="mining-meta"><span><Cpu size={13} /> Mine with a CPU</span><span><Shield size={13} /> Independently validating peers</span></div><details className="mining-details"><summary>Hardware, rewards &amp; network details</summary><div className="native-memory"><strong>Light · default</strong><span>256 MiB cache plus scratchpad and process overhead.</span><strong>Fast · --fast</strong><span>About 2 GiB dataset plus cache; budget over 2.3 GiB per process. Mining uses CPU, memory, electricity and time. ASIC resistance is a design goal, not a guarantee; results depend on hardware and network difficulty. Wikideck does not share Monero’s network, hashpower or security.</span></div></details></div>
<div className="miner-controls"><div className="miner-display"><div><span>NEXT WIKIPEDIA ARTICLE</span><strong>{snapshot ? 'Chosen when the miner requests work' : `Waiting for ${NETWORK_LABEL} RPC…`}</strong></div></div><p className="muted">The miner selects a random illustrated English Wikipedia article. The same article can appear again; each card keeps its own mint-time statistics.</p><details className="mining-details"><summary>Want to run a miner? Setup &amp; safety details</summary><ol className="native-steps"><li>Build <code>wikideck-randomx</code> using the repository’s native build instructions.</li><li>Save your encrypted backup and keep its password separate.</li><li>Replace <code>&lt;backup.json&gt;</code> with your local file path (quote paths with spaces), then run:</li></ol><pre className="native-command"><code>{nativeCommand}</code></pre><p className="miner-footnote">Node: {window.location.origin}. The command connects to this node; use HTTPS for remote nodes. Password entry stays local—never put it in the command. It defaults to one worker and at most one block. Ctrl+C stops the native miner; closing this page does not.</p></details><button className="button dark full" onClick={openWallet}><Download size={16} /> Download wallet backup</button><button className="text-button" onClick={() => setDialog('guide')}>Read the {NETWORK_LABEL.toLowerCase()} field guide <ArrowRight size={14} /></button></div>
</section>
@@ -200,7 +221,7 @@ export default function App() {
<article><ArrowLeftRight size={22}/><div className="section-eyebrow">TRADE · PLAYER TO PLAYER</div><h2>Swap cards directly.</h2><p>Prepare a signed offer for another collector and exchange card bundles atomically when the trade is mined. No prices or checkout.</p><button className="text-button" onClick={()=>setView('Trade cards')}>Trade cards <ArrowRight size={14}/></button></article>
</section>
</>}
{view === 'Play' ? <PlaySection owned={owned} /> : view === 'Trade cards' ? <TradeDesk wallet={wallet} snapshot={snapshot} rpcAvailable={rpcAvailable} onNotice={setToast} /> : view !== 'Block explorer' ? <section className="discover-section">
{view === 'Play' ? <PlaySection owned={owned} onMine={goMine} invite={invite} onRecap={openRecap} /> : view === 'Trade cards' ? <TradeDesk wallet={wallet} snapshot={snapshot} rpcAvailable={rpcAvailable} onNotice={setToast} /> : view !== 'Block explorer' ? <section className="discover-section">
<div className="section-heading"><div><div className="section-eyebrow">{view === 'My collection' ? 'YOUR PERSONAL ENCYCLOPEDIA' : 'AN ENCYCLOPEDIA, REIMAGINED'}</div><h2>{view === 'My collection' ? 'Your cabinet of curiosities' : 'A world of possible discoveries'}<span className="count-badge">{visibleCards.length}</span></h2><p>{view === 'My collection' ? 'Confirmed native NFT ownership. Pending transfers stay here until mined.' : snapshot?.blocks.length ? 'Recent native NFTs on this node’s canonical chain.' : 'Sample previews only; mined NFTs use random Wikipedia pages with pictures. The same page may be minted more than once.'}</p></div>{view === 'Discover' && <button className="text-button" onClick={() => setView('My collection')}>My collection <ArrowRight size={16} /></button>}</div>
<div className="filter-bar"><div className="category-tabs">{['All cards', 'Nature', 'Space', 'Science', 'People', 'History', 'Culture'].map(c => <button key={c} className={category === c ? 'selected' : ''} onClick={() => setCategory(c)}>{c}</button>)}</div><label className="search-input"><Search size={15} /><input aria-label="Search cards" placeholder="Find a discovery…" value={query} onChange={e => setQuery(e.target.value)} /></label></div>
{filtered.length ? <div className="card-grid">{filtered.map(c => <div className="card-wrap" key={c.block?.tokenId ?? c.hash}><Card card={c} onClick={() => { setSelected(c); setTransferError(''); }} /><div className="card-list-caption"><span>{c.block ? `Block #${c.block.height}` : 'Example discovery'}</span><span className="caption-dot" />{c.block && snapshot ? short(testnetOwnerOf(snapshot, c.block.tokenId) ?? '') : 'Not owned'}</div>{c.block && snapshot?.pendingTransfers.some(tx => transactionCardIds(tx).includes(c.block!.tokenId)) && <span className="pending-label">Transfer or trade pending mining</span>}</div>)}</div> : <div className="empty-state"><img className="empty-state-logo" src="/original-logo.svg" alt="Wikideck" /><h3>{query || category !== 'All cards' ? 'No discoveries here. Yet.' : 'Your first discovery is waiting.'}</h3><p>{query || category !== 'All cards' ? 'Try another search or explore a different category.' : 'Use the native miner or receive a mined transfer on this chain. Restore a backup to access an existing wallet.'}</p><button className="button dark" onClick={goMine}><Pickaxe size={16} /> Explore native mining</button></div>}
+144
View File
@@ -0,0 +1,144 @@
// Android (sideload build) mining panel. Rendered only inside the native app; see docs/night2/MOBILE_MINING.md.
import { forwardRef, useEffect, useRef, useState } from 'react';
import { registerPlugin, type PluginListenerHandle } from '@capacitor/core';
import { Cpu, Pickaxe, Square } from 'lucide-react';
import { IS_MAINNET, NETWORK_LABEL } from '../shared/network.ts';
import { expectedChainIdentity } from '../shared/chain-identity.ts';
import { sign, touchWallet, type Wallet } from './wallet.ts';
import { nodeHref } from './native.ts';
import { MobileMiner, type MinerEngine, type MinerStatus, type MineResult } from './mobile-miner.ts';
import './mobile-mining.css';
type Conditions = { powerSave: boolean; thermalStatus: number; batteryTempC: number | null; batteryPercent: number;
charging: boolean; cores: number; abi: string; engineInstalled: boolean; blocked: string | null };
interface MinerPlugin {
conditions(): Promise<Conditions>;
selfTest(): Promise<{ ok: boolean; output: string }>;
start(o: { threads: number }): Promise<{ threads: number }>;
stop(): Promise<void>;
mine(o: { lane: number; key: string; blob: string; target: string; nonceOffset: number; maxAttempts: number }): Promise<MineResult>;
addListener(event: 'halted', fn: (e: { reason: string }) => void): Promise<PluginListenerHandle>;
}
const Native = registerPlugin<MinerPlugin>('WikiDeckMiner');
const engine: MinerEngine = {
start: async threads => { await Native.start({ threads }); },
stop: () => Native.stop(),
mine: (lane, key, blob, target, nonceOffset, maxAttempts) => Native.mine({ lane, key, blob, target, nonceOffset, maxAttempts }),
};
const CONSENT_KEY = 'wikideck.mobileMining.consent.v1';
const INTENSITY_KEY = 'wikideck.mobileMining.intensity';
const INTENSITIES = {
low: { label: 'Low: 1 thread, rests between batches', threads: 1, idleMs: 400 },
normal: { label: 'Normal: 1 thread', threads: 1, idleMs: 0 },
high: { label: 'High: 2 threads (about 512 MiB)', threads: 2, idleMs: 0 },
max: { label: 'Max: 4 threads (about 1 GiB), only while charging', threads: 4, idleMs: 0 },
} as const;
type Intensity = keyof typeof INTENSITIES;
const REASONS: Record<string, string> = {
background: 'the app went to the background', 'battery-saver': 'battery saver is on', thermal: 'the device is warm',
'battery-hot': 'the battery is hot', 'battery-low': 'the battery is below 20% and not charging', 'max-needs-charging': 'Max intensity needs the charger', closed: 'the app closed',
};
const explain = (reason: string) => REASONS[reason] ?? reason;
async function api(path: string, body?: unknown): Promise<unknown> {
const url = path.startsWith('/p2p/') ? nodeHref(path) : path; // /api/... is routed to the node by native.ts
const res = await fetch(url, { method: body ? 'POST' : 'GET', cache: 'no-store', signal: AbortSignal.timeout(30000),
headers: body ? { 'Content-Type': 'application/json' } : {}, body: body ? JSON.stringify(body) : undefined });
const text = await res.text();
if (text.length > 262144) throw new Error('Node response too large');
const data = text ? JSON.parse(text) : {};
if (!res.ok) throw new Error(data.error ?? `Node rejected request (${res.status})`);
return data;
}
export const MobileMiningPanel = forwardRef<HTMLElement, { wallet?: Wallet; onAccepted?: () => void }>(function MobileMiningPanel({ wallet, onAccepted }, ref) {
const [consent, setConsent] = useState(() => localStorage.getItem(CONSENT_KEY) === 'yes');
const [intensity, setIntensity] = useState<Intensity>(() => (localStorage.getItem(INTENSITY_KEY) as Intensity) in INTENSITIES ? localStorage.getItem(INTENSITY_KEY) as Intensity : 'normal');
const [conditions, setConditions] = useState<Conditions>();
const [status, setStatus] = useState<MinerStatus>();
const [check, setCheck] = useState<{ ok: boolean; output: string }>();
const [error, setError] = useState('');
const miner = useRef<MobileMiner | undefined>(undefined);
const accepted = useRef(0);
const active = !!status && ['starting', 'requesting', 'mining', 'submitting'].includes(status.phase);
useEffect(() => {
let live = true;
const poll = () => Native.conditions().then(c => { if (live) setConditions(c); }).catch(() => {});
void poll();
const timer = setInterval(poll, 5000);
const halted = Native.addListener('halted', e => { void miner.current?.stop(`Paused: ${explain(e.reason)}`); });
const hide = () => { if (document.visibilityState !== 'visible') void miner.current?.stop(`Paused: ${explain('background')}`); };
document.addEventListener('visibilitychange', hide);
return () => { live = false; clearInterval(timer); void halted.then(h => h.remove()); document.removeEventListener('visibilitychange', hide); void miner.current?.stop(); };
}, []);
// A different (or locked) wallet must never keep mining to the previous address.
useEffect(() => { if (miner.current?.active) void miner.current.stop('Stopped: the wallet changed or locked.'); }, [wallet]);
const start = async () => {
setError('');
if (!wallet) { setError('Unlock your wallet first: cards are mined to its address.'); return; }
try {
let result = check;
if (!result?.ok) { result = await Native.selfTest(); setCheck(result); }
if (!result.ok) { setError('The RandomX engine failed its known-vector self-test on this device, so mining is disabled.'); return; }
const { chainId } = await expectedChainIdentity();
const preset = INTENSITIES[intensity];
const current = new MobileMiner({
engine, api, chainId, idleMs: preset.idleMs,
sign: message => sign(wallet, message),
blocked: async () => {
const c = await Native.conditions(); setConditions(c);
if (c.blocked) return explain(c.blocked);
if (preset.threads > 2 && !c.charging) return explain('max-needs-charging');
return document.visibilityState !== 'visible' ? explain('background') : undefined;
},
onStatus: s => {
// Mining runs only in the foreground with consent; keep the unlocked session alive so a found block can be signed.
touchWallet();
setStatus(s);
if (s.accepted > accepted.current) { accepted.current = s.accepted; onAccepted?.(); }
},
}, wallet);
miner.current = current;
void current.start(preset.threads);
} catch (e) { setError((e as Error).message); }
};
const stop = () => { void miner.current?.stop('Stopped.'); };
if (IS_MAINNET) return <section className="mining-panel mobile-mining" ref={ref}><h2>Mining</h2>
<p className="muted">This build mines on the private testnet only. Mainnet mining from the app is not enabled.</p></section>;
const blockedNow = conditions?.blocked;
return <section className="mining-panel mobile-mining" ref={ref} aria-label="Mine on this phone">
<div className="section-eyebrow"><Cpu size={14} /> RANDOMX LIGHT · {NETWORK_LABEL.toUpperCase()} · SIDELOAD BUILD</div>
<h2>Mine cards on this phone</h2>
<p>Each accepted block mints one Wikipedia card to your wallet. The phone runs the same pinned RandomX engine as the desktop miner, in light mode (about 256 MiB per thread). Mining runs only while this screen is open, and it stops by itself on battery saver, when the phone is warm, or below 20% battery when not charging.</p>
<label className="mobile-mining-consent"><input type="checkbox" checked={consent} disabled={active}
onChange={e => { setConsent(e.target.checked); localStorage.setItem(CONSENT_KEY, e.target.checked ? 'yes' : 'no'); }} />
<span>I understand that mining uses this phone's CPU and battery and can make it warm, and I want to mine to my wallet.</span></label>
<label className="mobile-mining-intensity">Intensity
<select value={intensity} disabled={active} onChange={e => { setIntensity(e.target.value as Intensity); localStorage.setItem(INTENSITY_KEY, e.target.value); }}>
{Object.entries(INTENSITIES).map(([k, v]) => <option key={k} value={k} disabled={(k === 'high' && (conditions?.cores ?? 0) < 4) || (k === 'max' && ((conditions?.cores ?? 0) < 4 || !conditions?.charging))}>{v.label}</option>)}
</select></label>
<div className="mobile-mining-actions">
{active ? <button className="button outline" onClick={stop}><Square size={15} /> Stop mining</button>
: <button className="button" onClick={() => void start()} disabled={!consent || !wallet || !!blockedNow || conditions?.engineInstalled === false}><Pickaxe size={15} /> Start mining</button>}
</div>
{!wallet && <p className="muted">Unlock or create your wallet to mine.</p>}
{conditions?.engineInstalled === false && <p className="error-text">This APK has no RandomX engine for {conditions.abi}.</p>}
{blockedNow && !active && <p className="muted">Paused: {explain(blockedNow)}.</p>}
{error && <p className="error-text" role="alert">{error}</p>}
<dl className="mobile-mining-stats" aria-live="polite">
<div><dt>Hashrate</dt><dd>{status ? `${status.hashrate.toFixed(1)} H/s` : '—'}</dd></div>
<div><dt>Status</dt><dd>{status?.phase ?? 'idle'}{status?.height ? ` · block #${status.height}` : ''}</dd></div>
<div><dt>Hashes</dt><dd>{status?.attempts.toLocaleString() ?? 0}</dd></div>
<div><dt>Accepted blocks</dt><dd>{status?.accepted ?? 0}</dd></div>
<div><dt>Battery</dt><dd>{conditions ? `${conditions.batteryPercent}%${conditions.charging ? ' charging' : ''}${conditions.batteryTempC !== null ? ` · ${conditions.batteryTempC.toFixed(1)} °C` : ''}` : '—'}</dd></div>
<div><dt>Engine check</dt><dd>{check ? check.ok ? 'known vector OK' : 'FAILED' : 'runs before first start'}</dd></div>
</dl>
{status?.article && active && <p className="muted">Mining for: {status.article}</p>}
{status?.message && <p className="muted">{status.message}</p>}
</section>;
});
+3
View File
@@ -43,6 +43,9 @@ export function account(): Account | undefined {
return current?.account;
}
/** The current Dex ID token, for same-origin game API calls (seats and collection, Night 2); undefined when logged out. */
export function idToken(): string | undefined { return account() ? current?.idToken : undefined; }
const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
const random = (n = 32) => b64url(crypto.getRandomValues(new Uint8Array(n)));
export async function pkceChallenge(verifier: string): Promise<string> {
+20
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react';
import { Server, Trophy } from 'lucide-react';
import type { GameMode } from './types.ts';
import { pvp, type LadderEntry } from './online.ts';
// Host credit (modes, #6): per-mode player leaderboard and the network's host leaderboard.
// Same-origin GETs only; every string is untrusted and rendered as text.
@@ -47,3 +48,22 @@ export function Leaderboards({ mode }: { mode: GameMode }) {
<p className="muted small">Run a WikiDeck node and host your own modes to appear here.</p></>}
</details>;
}
/** Night 2 ladder: Elo per mode keyed to the eom.dev account (host-pvp), W/L when Elo is cut. */
export function DuelLadder({ modeId, modeName }: { modeId: string; modeName: string }) {
const [entries, setEntries] = useState<LadderEntry[]>();
useEffect(() => {
let active = true;
pvp.ladder(modeId).then(e => { if (active) setEntries(e); }, () => { if (active) setEntries([]); });
return () => { active = false; };
}, [modeId]);
const rated = entries?.some(e => e.rating !== null);
return <section className="duel-ladder" aria-labelledby="ladder-title">
<h3 id="ladder-title" className="lobby-label"><Trophy size={14} /> {modeName} ladder</h3>
{entries === undefined ? <p className="muted small">Loading…</p>
: entries.length ? <ol className="ladder-list">{entries.map((e, i) => <li key={i}>
<small>{i + 1}</small><span>{e.name}</span>{rated ? <b>{e.rating ?? '–'}</b> : <b>{e.wins}W</b>}<small>{e.wins}–{e.losses}{e.draws ? `–${e.draws}` : ''}</small>
</li>)}</ol>
: <p className="muted small">No ranked matches yet.</p>}
</section>;
}
+119 -2
View File
@@ -1,11 +1,13 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { ArrowLeft, LoaderCircle, Plus, RefreshCw, Users } from 'lucide-react';
import { ArrowLeft, Copy, LoaderCircle, Plus, RefreshCw, Users } from 'lucide-react';
import { DEFAULT_RULESET, type Faction, type GameCard, type Stat } from '../../shared/game/index.ts';
import { engineAction, resultView, uiActions, viewFromPlayerView } from './adapter.ts';
import { toUICard } from './cards.ts';
import { GameCard as GameCardFace } from './GameCard.tsx';
import { MatchBoard } from './MatchBoard.tsx';
import { online, type LobbySeat, type LobbyStatus, type OpenLobby } from './online.ts';
import { DuelBoard } from './duel/DuelBoard.tsx';
import type { DuelAction, LogEvent, PlayerView as DuelPlayerView } from './duel/contract.ts';
import { inviteUrl, online, pvp, type DuelSeat, type DuelStatus, type LobbySeat, type LobbyStatus, type OpenLobby } from './online.ts';
import type { GameMode, ResultView, UIAction } from './types.ts';
const POLL_MS = 1000;
@@ -126,3 +128,118 @@ export function OnlinePlay({ mode, playerName, onExit, onFinish }: {
<div className="play-dock"><div className="play-actions"><button className="button outline" onClick={leave}><ArrowLeft size={16} /> {phase === 'expired' ? 'Back' : 'Cancel'}</button></div></div>
</section>;
}
// ----- Night 2: PvP duels (quick match, private lobby + invite link, join by invite) -----
export type DuelEntry = { kind: 'quick' } | { kind: 'private' } | { kind: 'invite'; code: string };
/** A minimal stand-in until ui-duel's board (src/game/duel) is on the branch: lists legal actions as buttons. */
function DuelBoardPlaceholder({ legal, onAct, opponent }: { legal: unknown[]; onAct: (a: unknown) => void; opponent: string }) {
const label = (a: unknown) => {
const o = (a && typeof a === 'object' ? a : {}) as Record<string, unknown>;
const parts = [o.type, o.uid, o.blocker, o.attacker].filter(x => typeof x === 'string' || typeof x === 'number');
return parts.join(' · ').slice(0, 60) || 'action';
};
return <div className="duel-placeholder">
<p className="muted small">Playing {opponent}. {legal.length ? 'Your move.' : 'Waiting for your opponent…'}</p>
<div className="pvp-grid">{legal.slice(0, 40).map((a, i) => <button key={i} className="pvp-tile" onClick={() => onAct(a)}><b>{label(a)}</b></button>)}</div>
</div>;
}
export function DuelOnlinePlay({ modeId, modeName, deck, entry, accountToken, onExit, onRecap }: {
modeId: string; modeName: string; deck: string[]; entry: DuelEntry; accountToken: string;
onExit: () => void; onRecap: (matchId: string) => void;
}) {
const [seat, setSeat] = useState<DuelSeat>();
const [status, setStatus] = useState<DuelStatus>();
const [error, setError] = useState('');
const [copied, setCopied] = useState('');
const inFlight = useRef(false);
const started = useRef(false);
const version = useRef(0);
const done = status?.phase === 'finished' || status?.phase === 'expired';
useEffect(() => {
if (started.current) return; // StrictMode double-invoke: one seat per entry
started.current = true;
const go = entry.kind === 'quick' ? pvp.quick(modeId, deck, accountToken)
: entry.kind === 'private' ? pvp.createPrivate(modeId, deck, accountToken)
: pvp.joinInvite(entry.code, deck, accountToken);
go.then(setSeat, e => setError(message(e)));
}, [entry, modeId, deck, accountToken]);
const apply = (s: DuelStatus | null) => { if (s) { version.current = s.version; setStatus(s); } setError(''); };
const poll = useCallback(async () => {
if (!seat || inFlight.current) return;
inFlight.current = true;
try { apply(await pvp.status(seat, version.current || undefined)); }
catch (e) { setError(message(e)); }
finally { inFlight.current = false; }
}, [seat]);
// Engineer §3: poll fast (500 ms) while waiting on the opponent, slowly (3 s) when it's our move.
const myMove = !!status?.legalActions?.length;
useEffect(() => {
if (!seat || done) return;
void poll();
const t = setInterval(() => { void poll(); }, myMove ? 3000 : status?.phase === 'waiting' ? 2000 : 500);
return () => clearInterval(t);
}, [seat, poll, done, myMove, status?.phase]);
const leave = async () => {
if (seat && status && !done) await pvp.resign(seat).catch(() => {});
onExit();
};
/** Resolves once the host accepts the action and rejects on error, so ui-duel's board can send a declaration sequence (#58). */
const act = async (a: unknown): Promise<void> => {
if (!seat) throw new Error('Not seated.');
try { apply(await pvp.act(seat, a)); }
catch (e) { setError(message(e)); void poll(); throw e; }
};
const invite = seat?.invite ?? status?.invite;
const link = invite ? inviteUrl(invite) : '';
const copy = async () => {
try {
if (navigator.share) await navigator.share({ title: 'WikiDeck duel', text: `Duel me in WikiDeck (${modeName}).`, url: link });
else { await navigator.clipboard.writeText(link); setCopied('Invite link copied.'); }
} catch { setCopied('Select the link above and copy it.'); }
};
const opp = status?.players.find((_, i) => i !== seat?.seat)?.name ?? 'Opponent';
const me = (seat ? status?.players[seat.seat]?.name : undefined) ?? 'You';
const eyebrow = `${modeName.toUpperCase()} · ${entry.kind === 'quick' ? 'QUICK MATCH' : entry.kind === 'private' ? 'PRIVATE LOBBY' : 'INVITE'}`;
if ((status?.phase === 'playing' || status?.phase === 'finished') && status.state && typeof status.state === 'object') {
// ui-duel's board (#58) on duel-core's PlayerView; it sends multi-step declarations through `act`, awaiting each.
const view = status.state as DuelPlayerView;
const events = (view as { log?: unknown }).log;
return <DuelBoard view={view} legal={(status.legalActions ?? []) as DuelAction[]} onAct={a => act(a)}
opponentName={opp} playerName={me} error={error || undefined}
logEvents={Array.isArray(events) ? events as LogEvent[] : undefined}
onExit={() => void leave()} onRecap={status.phase === 'finished' && status.matchId ? () => onRecap(status.matchId!) : undefined} />;
}
if (status?.phase === 'playing' || status?.phase === 'finished') {
const won = status.outcome && status.outcome.winner !== null && status.outcome.winner === seat?.seat;
return <section className="play-panel" aria-labelledby="duel-title">
<div className="section-eyebrow">{eyebrow}</div>
<h2 id="duel-title">{status.phase === 'finished' ? (status.outcome?.winner === null ? 'Draw' : won ? 'Victory' : 'Defeat') : `vs ${opp}`}</h2>
{status.phase === 'playing' && <DuelBoardPlaceholder legal={status.legalActions ?? []} onAct={a => { act(a).catch(() => {}); }} opponent={opp} />}
{error && <p className="dock-error small" role="alert">{error}</p>}
<div className="play-dock"><div className="play-actions">
<button className="button outline" onClick={leave}>{status.phase === 'finished' ? <><ArrowLeft size={16} /> Back</> : 'Resign'}</button>
{status.phase === 'finished' && status.matchId && <button className="button dark play-cta" onClick={() => onRecap(status.matchId!)}>Read the battle recap</button>}
</div></div>
</section>;
}
return <section className="play-panel" aria-labelledby="wait-title">
<div className="section-eyebrow">{eyebrow}</div>
<h2 id="wait-title">{status?.phase === 'expired' ? 'This lobby expired' : !seat ? (error ? 'Could not start' : 'Connecting…') : status?.phase === 'starting' ? 'Starting…' : status?.phase === 'drafting' ? 'Drafting…' : entry.kind === 'quick' ? 'Finding an opponent' : 'Waiting for your opponent'}</h2>
{seat && link && status?.phase !== 'expired' && <>
<p className="muted">Send this link to the person you want to play. It opens this lobby, and they bring their own {deck.length}-card deck.</p>
<div className="invite-box"><code aria-label="Invite link">{link}</code><button className="button outline" onClick={copy}><Copy size={14} /> {'share' in navigator ? 'Share' : 'Copy'}</button></div>
{copied && <p className="muted small" role="status">{copied}</p>}
</>}
{seat && !link && status?.phase !== 'expired' && <p className="muted"><LoaderCircle className="spin" size={14} /> {entry.kind === 'quick' ? 'Matching you with a player near your rating.' : 'Joining the lobby.'}</p>}
{status?.phase === 'expired' && <p className="muted">Nobody joined in time. Go back and try again.</p>}
{error && <p className="dock-error small" role="alert">{error}</p>}
<div className="play-dock"><div className="play-actions"><button className="button outline" onClick={leave}><ArrowLeft size={16} /> {status?.phase === 'expired' || !seat ? 'Back' : 'Cancel'}</button></div></div>
</section>;
}
+92 -98
View File
@@ -1,128 +1,122 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { CircleHelp, ExternalLink, Globe2, Layers3, Play, Server, Swords, UserRound, Users } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { Bot as BotIcon, Layers3, Link2, LoaderCircle, Lock, UserRound, Zap } from 'lucide-react';
import type { TestnetBlock } from '../../shared/testnet.ts';
import { Avatar } from '../auth/LoginButton.tsx';
import { BOTS, type Bot } from './bots.ts';
import { DEFAULT_STARTER, STARTERS, cardFromBlock, loanerPool, opponentDeck as botDeck, starterDeck } from './cards.ts';
import { DeckBuilder, deckProblem, deckWarning } from './DeckBuilder.tsx';
import { CategoryIcon } from './GameCard.tsx';
import { Leaderboards } from './Leaderboards.tsx';
import { MatchScreen } from './MatchScreen.tsx';
import { lobbyName } from './online.ts';
import { OnlinePlay } from './OnlinePlay.tsx';
import { Results } from './Results.tsx';
import { Tutorial } from './Tutorial.tsx';
import type { GameMode, ResultView } from './types.ts';
import { idToken, login } from '../auth/session.ts';
import { DeckPicker, EligibilityGate } from './collection/CollectionScreen.tsx';
import { deckProblem, eligibility, fillDeck } from './collection/collection.ts';
import { CLASSIC, parseDuelModes, type DuelMode } from './collection/duelModes.ts';
import { useCollection } from './collection/useCollection.ts';
import { DuelLadder } from './Leaderboards.tsx';
import { inviteCode } from './online.ts';
import { DuelOnlinePlay, type DuelEntry } from './OnlinePlay.tsx';
import { useAccount } from './useAccount.ts';
import { useModes } from './useModes.ts';
import './play.css';
import './collection/pvp.css';
type Screen = 'lobby' | 'deck' | 'match' | 'online' | 'results' | 'tutorial';
const DECK_KEY = 'wikideck-play-deck-v1';
const TUTORIAL_KEY = 'wikideck-play-tutorial-v1';
const STARTER_KEY = 'wikideck-play-starter-v1';
// Night 2 Play: PvP first (BRIEF decision 3). Every deck is 40 cards the player owns (decisions 1–2):
// under that, the screen shows progress and how to mine, and offers no borrowed or loaner decks.
type Screen = { kind: 'hub' } | { kind: 'deck' } | { kind: 'online'; entry: DuelEntry };
const DECK_KEY = 'wikideck-duel-deck-v1';
const store = {
get: (k: string) => { try { return localStorage.getItem(k); } catch { return null; } },
set: (k: string, v: string) => { try { localStorage.setItem(k, v); } catch { /* storage unavailable */ } },
};
const playsHere = (m: GameMode) => m.host.kind === 'local' || m.host.self;
export function PlaySection({ owned }: { owned: TestnetBlock[] }) {
const { modes, status } = useModes();
export function PlaySection({ owned, onMine, invite: initialInvite = '', onRecap }: {
owned: TestnetBlock[]; onMine: () => void; invite?: string; onRecap: (matchId: string) => void;
}) {
const account = useAccount();
const [screen, setScreen] = useState<Screen>(() => store.get(TUTORIAL_KEY) ? 'lobby' : 'tutorial');
const [modeId, setModeId] = useState('standard');
const [bot, setBot] = useState<Bot>(BOTS[0]);
const [savedIds, setSavedIds] = useState<string[] | null>(() => { try { return JSON.parse(store.get(DECK_KEY) ?? 'null'); } catch { return null; } });
const [seed, setSeed] = useState('');
const [starterId, setStarterId] = useState(() => { const s = store.get(STARTER_KEY); return STARTERS.some(d => d.id === s) ? s! : DEFAULT_STARTER; });
const [result, setResult] = useState<ResultView>();
const mode = modes.find(m => m.id === modeId) ?? modes[0];
const rules = mode.ruleset;
const pool = useMemo(() => [...loanerPool(rules), ...owned.map(b => cardFromBlock(b, rules))], [owned, rules]);
const { collection: base, status } = useCollection(owned);
const [modes, setModes] = useState<DuelMode[]>([CLASSIC]);
const [modeId, setModeId] = useState(CLASSIC.id);
const [screen, setScreen] = useState<Screen>({ kind: 'hub' });
const [pendingInvite, setPendingInvite] = useState(initialInvite);
const [joinText, setJoinText] = useState('');
const [saved, setSaved] = useState<string[]>(() => { try { const v = JSON.parse(store.get(DECK_KEY) ?? '[]'); return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []; } catch { return []; } });
// Rebuild the saved deck from current cards; NFTs you no longer own simply drop out.
const deck = useMemo(() => {
if (!savedIds) return starterDeck(rules, starterId);
const byId = new Map(pool.map(c => [c.id, c]));
return savedIds.flatMap(id => byId.get(id) ?? []);
}, [savedIds, pool, rules, starterId]);
const problem = deckProblem(deck, rules);
const warning = deckWarning(deck);
const opponent = useMemo(() => botDeck(seed, rules), [seed, rules]);
const [lastOnline, setLastOnline] = useState(false);
const start = () => { setLastOnline(false); setSeed(`${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`); setScreen('match'); };
const finish = useCallback((r: ResultView) => { setResult(r); setScreen('results'); }, []);
useEffect(() => { window.scrollTo?.({ top: 0 }); }, [screen]);
// While a match is on screen, hide the floating eom.dev account button (it sits over the dock on phones).
useEffect(() => {
document.documentElement.classList.toggle('wd-in-match', screen === 'match' || screen === 'online');
let active = true;
fetch('/api/game/modes', { cache: 'no-store', signal: AbortSignal.timeout(8000) })
.then(r => (r.ok && r.headers.get('content-type')?.includes('json') ? r.json() : Promise.reject(new Error('unavailable'))))
.then(d => { const m = parseDuelModes(d); if (active && m.length) { setModes(m); setModeId(id => (m.some(x => x.id === id) ? id : m[0].id)); } }, () => {});
return () => { active = false; };
}, []);
const mode = modes.find(m => m.id === modeId) ?? modes[0];
// A mode may set its own deckSize (testnet end-to-end mode only); production stays at 40.
const collection = useMemo(() => (mode.deckSize ? { ...base, deckSize: mode.deckSize } : base), [base, mode.deckSize]);
const elig = eligibility(collection);
const deck = useMemo(() => fillDeck(saved, collection), [saved, collection]);
const problem = deckProblem(deck, collection);
const token = idToken();
useEffect(() => { window.scrollTo?.({ top: 0 }); }, [screen.kind]);
useEffect(() => {
document.documentElement.classList.toggle('wd-in-match', screen.kind === 'online');
document.documentElement.classList.add('wd-play');
return () => document.documentElement.classList.remove('wd-in-match', 'wd-play');
}, [screen]);
}, [screen.kind]);
if (screen === 'tutorial') return <Tutorial onDone={() => { store.set(TUTORIAL_KEY, '1'); setScreen('lobby'); }} />;
if (screen === 'deck') return <DeckBuilder modeName={mode.name} pool={pool} deck={deck} ruleset={rules} onCancel={() => setScreen('lobby')}
onSave={d => { const ids = d.map(c => c.id); store.set(DECK_KEY, JSON.stringify(ids)); setSavedIds(ids); setScreen('lobby'); }} />;
if (screen === 'match') return <MatchScreen key={seed} mode={mode} deck={deck} opponentDeck={opponent} bot={bot} seed={seed} onFinish={finish} />;
if (screen === 'online') return <OnlinePlay key={mode.id} mode={mode} playerName={lobbyName(account?.name || account?.username)} onExit={() => setScreen('lobby')} onFinish={finish} />;
if (screen === 'results' && result) return <Results result={result} modeName={mode.name} onRematch={lastOnline ? () => setScreen('online') : start} onLobby={() => setScreen('lobby')} />;
const playOnline = (entry: DuelEntry) => { setPendingInvite(''); setScreen({ kind: 'online', entry }); };
if (screen.kind === 'deck') return <DeckPicker collection={collection} deck={deck} onCancel={() => setScreen({ kind: 'hub' })}
onSave={d => { store.set(DECK_KEY, JSON.stringify(d)); setSaved(d); setScreen({ kind: 'hub' }); }} />;
if (screen.kind === 'online' && token) return <DuelOnlinePlay key={JSON.stringify(screen.entry)} modeId={mode.id} modeName={mode.name} deck={deck}
entry={screen.entry} accountToken={token} onExit={() => setScreen({ kind: 'hub' })} onRecap={onRecap} />;
const remote = mode.host.kind === 'peer' && !mode.host.self ? mode.host : null;
const hosted = mode.host.kind === 'peer' && mode.host.self;
const ready = elig.eligible && !problem && !!token;
const why = !token ? 'Log in with your eom.dev account to play people.' : !elig.eligible ? '' : problem;
const joinCode = inviteCode(joinText);
return <section className="play-panel lobby" aria-labelledby="lobby-title">
<div className="lobby-head">
<div><div className="section-eyebrow">PLAY · OFF-CHAIN MATCHES</div><h2 id="lobby-title">Play WikiDeck</h2></div>
<div><div className="section-eyebrow">PLAY · OFF-CHAIN DUELS</div><h2 id="lobby-title">Play WikiDeck</h2></div>
<div className="account-chip" aria-label="eom.dev account">{account
? <><Avatar name={account.name || account.username} seed={account.sub} /><span>{account.name || account.username}</span></>
: <><UserRound size={15} /><span>Guest</span></>}
</div>
</div>
<p className="muted">Three Topics, six turns: win two Topics. Each Topic is judged on one Wikipedia stat, and cards are stronger on their home stat. New here? You already have a loaner starter deck. Matches never move or burn your cards.</p>
<p className="muted">A duel between two {collection.deckSize}-card decks built from cards you own. Matches never move or burn your cards.</p>
<h3 className="lobby-label">Mode</h3>
<div className="mode-list" role="radiogroup" aria-label="Game mode">
{modes.map(m => <button key={m.id} role="radio" aria-checked={m.id === mode.id} className={`mode ${m.id === mode.id ? 'selected' : ''}`} onClick={() => setModeId(m.id)}>
<span className="mode-icon">{m.host.kind === 'local' ? <Swords size={18} /> : <Server size={18} />}</span>
<span className="mode-copy"><b>{m.name}</b>{m.description && <small>{m.description}</small>}
<small className="mode-host">{m.host.kind === 'local' ? 'Built in · plays in your browser' : `Hosted by ${m.host.name}`}
{m.players !== undefined ? ` · ${m.players} online` : ''}{m.matchesPlayed !== undefined ? ` · ${m.matchesPlayed} played` : ''}</small></span>
</button>)}
{status === 'loading' && <p className="muted small"><Globe2 size={13} /> Looking for peer-hosted modes…</p>}
{status === 'unavailable' && <p className="muted small"><Globe2 size={13} /> No peer-hosted modes reachable from this node.</p>}
</div>
{status === 'ok' && <Leaderboards key={mode.id} mode={mode} />}
{pendingInvite && <div className="eligibility" role="status">
<b>You have been invited to a duel.</b>
<p className="muted small">{ready ? 'Your saved deck is ready.' : why || `You need ${collection.deckSize} cards of your own to accept.`}</p>
<div className="eligibility-actions">
<button className="button dark" disabled={!ready} onClick={() => playOnline({ kind: 'invite', code: pendingInvite })}><Link2 size={16} /> Accept invite</button>
<button className="button outline" onClick={() => setPendingInvite('')}>Dismiss</button>
</div>
</div>}
{remote ? <>
<p className="muted small">This mode runs on {remote.name}’s node. Open it there to play; your eom.dev account works on every node.</p>
<div className="play-dock"><div className="play-actions">
<button className="button outline" aria-label="How to play" onClick={() => setScreen('tutorial')}><CircleHelp size={16} /><span className="hide-narrow">How to play</span></button>
{remote.url ? <a className="button dark play-cta" href={remote.url} target="_blank" rel="noopener noreferrer">Play on {remote.name} <ExternalLink size={16} /></a>
: <button className="button dark play-cta" disabled>Host address unavailable</button>}
</div></div>
</> : <>
<h3 className="lobby-label">Opponent</h3>
<div className="category-tabs">{BOTS.map(b => <button key={b.id} className={bot.id === b.id ? 'selected' : ''} onClick={() => setBot(b)}>{b.name} bot</button>)}</div>
{modes.length > 1 && <><h3 className="lobby-label">Mode</h3>
<div className="category-tabs" role="radiogroup" aria-label="Game mode">{modes.map(m =>
<button key={m.id} role="radio" aria-checked={m.id === mode.id} className={m.id === mode.id ? 'selected' : ''} onClick={() => setModeId(m.id)}>{m.name}</button>)}</div></>}
<h3 className="lobby-label">Deck <span className="count-badge">{deck.length}</span></h3>
<button className="deck-summary" onClick={() => setScreen('deck')} aria-label="Edit deck">
<span className="deck-fan" aria-hidden="true">{deck.slice(0, 4).map(c => <span key={c.id} className={`fan-chip cat-${c.category.toLowerCase()}`}><CategoryIcon category={c.category} size={14} /></span>)}</span>
<span><b>{savedIds ? 'Your deck' : `Starter: ${STARTERS.find(d => d.id === starterId)?.name}`}</b><small>{deck.filter(c => c.source === 'nft').length} NFTs · {deck.filter(c => c.source === 'starter').length} loaners</small></span>
<Layers3 size={18} />
</button>
{!savedIds && <div className="category-tabs starter-picks" role="radiogroup" aria-label="Starter deck">{STARTERS.map(d =>
<button key={d.id} role="radio" aria-checked={starterId === d.id} className={starterId === d.id ? 'selected' : ''}
onClick={() => { setStarterId(d.id); store.set(STARTER_KEY, d.id); }}>{d.name}</button>)}</div>}
{savedIds && <button className="text-button" onClick={() => { setSavedIds(null); try { localStorage.removeItem(DECK_KEY); } catch { /* ignore */ } }}>Use a starter deck instead</button>}
{problem ? <p className="dock-error small">{problem} Edit your deck to play {mode.name}.</p>
: warning && <p className="deck-warning small">{warning}</p>}
{status === 'loading' ? <p className="muted"><LoaderCircle className="spin" size={14} /> Counting your cards…</p>
: !elig.eligible ? <EligibilityGate collection={collection} onMine={onMine} guest={!account} onLogin={() => void login()} />
: <>
<h3 className="lobby-label">Deck <span className={`count-badge ${problem ? '' : 'ok'}`}>{deck.length} / {collection.deckSize}</span></h3>
<button className="deck-summary" onClick={() => setScreen({ kind: 'deck' })} aria-label="Edit deck">
<span><b>{saved.length ? 'Your deck' : 'Auto-built from your collection'}</b><small>{collection.cards.length} cards owned · {elig.playable} playable</small></span>
<Layers3 size={18} />
</button>
{status === 'fallback' && <p className="muted small">Showing this browser’s wallet. The host checks every card you own before a match.</p>}
{why && <p className="dock-error small">{why}</p>}
{!token && <button className="button outline" onClick={() => void login()}>Log in with eom.dev</button>}
<div className="play-dock"><div className="play-actions">
<button className="button outline" aria-label="How to play" onClick={() => setScreen('tutorial')}><CircleHelp size={16} /><span className="hide-narrow">How to play</span></button>
{hosted && <button className="button outline" aria-label="Play a person online" onClick={() => { setLastOnline(true); setScreen('online'); }}><Users size={16} /><span className="hide-narrow">Play a person</span><span className="show-narrow">Online</span></button>}
<button className="button dark play-cta" aria-label={`Play vs ${bot.name}`} disabled={!!problem} onClick={start}><Play size={16} /><span className="hide-narrow">Play vs {bot.name}</span><span className="show-narrow">Play</span></button>
</div></div>
</>}
<h3 className="lobby-label">Play a person</h3>
<div className="pvp-grid">
<button className="pvp-tile primary" disabled={!ready} onClick={() => playOnline({ kind: 'quick' })}><Zap size={20} />
<span><b>Quick match</b><small>{mode.ranked ? 'Ranked · paired near your rating' : 'Paired with the next player waiting'}</small></span></button>
<button className="pvp-tile" disabled={!ready} onClick={() => playOnline({ kind: 'private' })}><Lock size={20} />
<span><b>Private lobby</b><small>Get an invite link to send a friend</small></span></button>
</div>
<form className="pvp-join" onSubmit={e => { e.preventDefault(); if (joinCode && ready) playOnline({ kind: 'invite', code: joinCode }); }}>
<input value={joinText} onChange={e => setJoinText(e.target.value)} placeholder="Paste an invite link" aria-label="Invite link or code" />
<button className="button outline" type="submit" disabled={!ready || !joinCode}><Link2 size={14} /> Join</button>
</form>
<h3 className="lobby-label">Practice</h3>
<button className="pvp-tile" disabled><BotIcon size={20} /><span><b>Bot match</b><small>Opens with the duel board</small></span></button>
</>}
<DuelLadder key={mode.id} modeId={mode.id} modeName={mode.name} />
</section>;
}
+69
View File
@@ -0,0 +1,69 @@
import { useState } from 'react';
import { Check, ExternalLink, Pickaxe, RotateCcw, Search } from 'lucide-react';
import { deckProblem, eligibility, fillDeck, progressLabel, type Collection, type CollectionCard } from './collection.ts';
/** Under deckSize playable cards: progress and how to mine. No borrowed decks (BRIEF decision 2). */
export function EligibilityGate({ collection, onMine, guest, onLogin }: {
collection: Collection; onMine: () => void; guest: boolean; onLogin?: () => void;
}) {
const e = eligibility(collection);
const pct = Math.round((Math.min(e.playable, e.deckSize) / e.deckSize) * 100);
const dupes = e.owned - e.playable;
return <div className="eligibility" aria-labelledby="eligibility-title">
<h3 id="eligibility-title" className="eligibility-count">{progressLabel(e)}. Mine to play</h3>
<div className="eligibility-bar" role="progressbar" aria-valuemin={0} aria-valuemax={e.deckSize} aria-valuenow={Math.min(e.playable, e.deckSize)}
aria-label={`${progressLabel(e)} owned`}><span style={{ width: `${pct}%` }} /></div>
<p className="muted">A WikiDeck deck is exactly {e.deckSize} cards, and every one is a card you mined or traded for. You need {e.needed} more{dupes > 0 ? ` (${dupes} of your cards are extra copies over the ${collection.copyLimit}-per-article limit)` : ''}. Each accepted block mints one card.</p>
{guest && <p className="muted small">Log in with your eom.dev account to count cards in every wallet you have linked.</p>}
<div className="eligibility-actions">
<button className="button dark" onClick={onMine}><Pickaxe size={16} /> Mine cards</button>
{guest && onLogin && <button className="button outline" onClick={onLogin}>Log in</button>}
</div>
</div>;
}
const byTitle = (a: CollectionCard, b: CollectionCard) => a.title.localeCompare(b.title) || a.tokenId.localeCompare(b.tokenId);
/** Constructed deck from owned cards only: exactly deckSize, at most copyLimit per article. */
export function DeckPicker({ collection, deck, onSave, onCancel }: {
collection: Collection; deck: string[]; onSave: (deck: string[]) => void; onCancel: () => void;
}) {
const [draft, setDraft] = useState<string[]>(() => deck.filter(id => collection.cards.some(c => c.tokenId === id)));
const [query, setQuery] = useState('');
const inDeck = new Set(draft);
const perPage = new Map<number, number>();
for (const c of collection.cards) if (inDeck.has(c.tokenId)) perPage.set(c.pageId, (perPage.get(c.pageId) ?? 0) + 1);
const shown = collection.cards.filter(c => c.title.toLowerCase().includes(query.trim().toLowerCase())).sort(byTitle);
const problem = deckProblem(draft, collection);
const full = draft.length >= collection.deckSize;
const toggle = (c: CollectionCard) => setDraft(d => d.includes(c.tokenId) ? d.filter(x => x !== c.tokenId)
: d.length >= collection.deckSize || (perPage.get(c.pageId) ?? 0) >= collection.copyLimit ? d : [...d, c.tokenId]);
return <section className="play-panel deck-picker" aria-labelledby="picker-title">
<div className="section-eyebrow">CONSTRUCTED · YOUR CARDS ONLY</div>
<h2 id="picker-title">Your deck <span className={`count-badge ${problem ? '' : 'ok'}`}>{draft.length} / {collection.deckSize}</span></h2>
<p className="muted small">Pick exactly {collection.deckSize} of your {collection.cards.length} cards. At most {collection.copyLimit} copies of one article.</p>
<div className="picker-tools">
<label className="picker-search"><Search size={14} /><input value={query} onChange={e => setQuery(e.target.value)} placeholder="Search your cards" aria-label="Search your cards" /></label>
<button className="button outline" onClick={() => setDraft(fillDeck(draft, collection))} disabled={full}>Fill</button>
<button className="button outline" aria-label="Clear deck" onClick={() => setDraft([])}><RotateCcw size={14} /></button>
</div>
<ul className="picker-list">{shown.map(c => {
const on = inDeck.has(c.tokenId);
const blocked = !on && (full || (perPage.get(c.pageId) ?? 0) >= collection.copyLimit);
return <li key={c.tokenId}>
<button className={`picker-row ${on ? 'selected' : ''}`} aria-pressed={on} disabled={blocked} onClick={() => toggle(c)}>
<span className="picker-check" aria-hidden="true">{on && <Check size={14} />}</span>
<span className="picker-title">{c.title}</span>
<small>{c.category ?? ''}{c.height !== undefined ? ` · #${c.height}` : ''}</small>
</button>
{c.url && <a className="picker-link" href={c.url} target="_blank" rel="noopener noreferrer" aria-label={`${c.title} on Wikipedia`}><ExternalLink size={13} /></a>}
</li>;
})}</ul>
{problem && <p className="dock-error small" role="status">{problem}</p>}
<div className="play-dock"><div className="play-actions">
<button className="button outline" onClick={onCancel}>Cancel</button>
<button className="button dark play-cta" disabled={!!problem} onClick={() => onSave(draft)}><Check size={16} /> Save deck</button>
</div></div>
</section>;
}
+108
View File
@@ -0,0 +1,108 @@
// Collection and 40-card eligibility (Night 2, BRIEF decisions 1–2). Every deck card is an NFT the
// player owns: no loaners, Basics or proxies. The server (ownership's GET /api/game/collection) is the
// authority; the browser copy is only a fallback view while that endpoint is unavailable, and the
// host re-verifies every deck on the server anyway. Every response is untrusted input.
import type { TestnetBlock } from '../../../shared/testnet.ts';
export const DEFAULT_DECK_SIZE = 40;
export const DEFAULT_COPY_LIMIT = 4;
export type CollectionCard = {
tokenId: string; pageId: number; title: string; revisionId?: number;
url?: string; imageUrl?: string; extract?: string; category?: string; height?: number;
/** Server-derived, frozen duel profile (ownership adds it for ui-duel's bot match, #58). Passed through untouched. */
duel?: unknown;
};
export type Collection = {
deckSize: number; copyLimit: number; cards: CollectionCard[];
/** 'server' = ownership API (authoritative); 'local' = this browser's wallet view (fallback). */
source: 'server' | 'local';
};
const str = (v: unknown, max = 300) => (typeof v === 'string' ? v.slice(0, max) : '');
const int = (v: unknown, min = 0, max = Number.MAX_SAFE_INTEGER) =>
(typeof v === 'number' && Number.isInteger(v) && v >= min && v <= max ? v : undefined);
const httpUrl = (v: unknown) => { const s = str(v, 2000); return /^https:\/\//i.test(s) ? s : undefined; };
/** Parse ownership's collection response. Unknown fields are ignored, bad cards dropped, duplicates by tokenId removed. */
export function parseCollection(v: unknown): Collection {
const o = v && typeof v === 'object' ? v as Record<string, unknown> : {};
const list = Array.isArray(o.cards) ? o.cards : [];
const seen = new Set<string>();
const cards: CollectionCard[] = [];
for (const raw of list.slice(0, 5000)) {
if (!raw || typeof raw !== 'object') continue;
const c = raw as Record<string, unknown>;
const tokenId = str(c.tokenId, 128);
const pageId = int(c.pageId, 1);
if (!tokenId || pageId === undefined || seen.has(tokenId)) continue;
seen.add(tokenId);
cards.push({ tokenId, pageId, title: str(c.title, 200) || `Page ${pageId}`, revisionId: int(c.revisionId, 1),
url: httpUrl(c.url), imageUrl: httpUrl(c.imageUrl ?? c.image), extract: str(c.extract, 600) || undefined,
category: str(c.category, 40) || undefined, height: int(c.height), ...(c.duel && typeof c.duel === 'object' ? { duel: c.duel } : {}) });
}
return { deckSize: int(o.deckSize, 1, 200) ?? DEFAULT_DECK_SIZE, copyLimit: int(o.copyLimit, 1, 200) ?? DEFAULT_COPY_LIMIT, cards, source: 'server' };
}
/** Fallback while the ownership API isn't reachable: the confirmed blocks this browser's wallet owns. */
export function collectionFromBlocks(blocks: TestnetBlock[], deckSize = DEFAULT_DECK_SIZE, copyLimit = DEFAULT_COPY_LIMIT): Collection {
return { deckSize, copyLimit, source: 'local', cards: blocks.map(b => ({
tokenId: b.tokenId, pageId: b.article.pageId, title: b.article.title, revisionId: b.article.revisionId,
url: b.article.url, imageUrl: b.article.image, extract: b.article.extract, category: b.article.category, height: b.height,
})) };
}
/** Cards that can go into one deck: at most `copyLimit` per article (pageId). */
export function playableCount(c: Pick<Collection, 'cards' | 'copyLimit'>): number {
const per = new Map<number, number>();
for (const card of c.cards) per.set(card.pageId, (per.get(card.pageId) ?? 0) + 1);
let n = 0;
for (const k of per.values()) n += Math.min(k, c.copyLimit);
return n;
}
export type Eligibility = { eligible: boolean; owned: number; playable: number; needed: number; deckSize: number };
export function eligibility(c: Collection): Eligibility {
const playable = playableCount(c);
return { eligible: playable >= c.deckSize, owned: c.cards.length, playable, needed: Math.max(0, c.deckSize - playable), deckSize: c.deckSize };
}
/** "23 / 40 cards" progress copy. */
export const progressLabel = (e: Eligibility) => `${Math.min(e.playable, e.deckSize)} / ${e.deckSize} cards`;
/** Why a deck (a list of tokenIds) can't be played, or '' when it is a legal constructed deck. */
export function deckProblem(deck: string[], c: Collection): string {
if (deck.length !== c.deckSize) return `A deck needs exactly ${c.deckSize} cards (${deck.length} now).`;
const byId = new Map(c.cards.map(card => [card.tokenId, card]));
const seen = new Set<string>();
const per = new Map<number, number>();
for (const id of deck) {
const card = byId.get(id);
if (!card) return 'Your deck includes a card you no longer own. Remove it and pick another.';
if (seen.has(id)) return 'The same card is in your deck twice.';
seen.add(id);
const n = (per.get(card.pageId) ?? 0) + 1;
per.set(card.pageId, n);
if (n > c.copyLimit) return `At most ${c.copyLimit} copies of “${card.title}” fit in one deck.`;
}
return '';
}
/**
* Keep the saved deck's cards that are still owned and fill to deckSize from the rest of the
* collection, respecting the copy limit. Deterministic (collection order), so the result is stable.
*/
export function fillDeck(saved: string[], c: Collection): string[] {
const byId = new Map(c.cards.map(card => [card.tokenId, card]));
const per = new Map<number, number>();
const out: string[] = [];
const add = (card: CollectionCard) => {
if (out.length >= c.deckSize || out.includes(card.tokenId)) return;
const n = per.get(card.pageId) ?? 0;
if (n >= c.copyLimit) return;
per.set(card.pageId, n + 1); out.push(card.tokenId);
};
for (const id of saved) { const card = byId.get(id); if (card) add(card); }
for (const card of c.cards) add(card);
return out;
}
+21
View File
@@ -0,0 +1,21 @@
// Duel modes hosted by this node (host-pvp adds `engine: 'duel'` to modes, #56). Until that lands,
// or when the list is unreachable, Classic (constructed, ranked) is assumed. Untrusted input.
export type DuelMode = { id: string; name: string; description: string; ranked: boolean; deckSize?: number };
export const CLASSIC: DuelMode = { id: 'classic', name: 'Classic', description: 'Constructed from your own 40 cards. Ranked.', ranked: true };
const str = (v: unknown, max: number) => (typeof v === 'string' ? v.slice(0, max) : '');
const obj = (v: unknown) => (v && typeof v === 'object' && !Array.isArray(v) ? v as Record<string, unknown> : undefined);
export function parseDuelModes(data: unknown): DuelMode[] {
const list = obj(data)?.modes;
if (!Array.isArray(list)) return [];
return list.slice(0, 16).flatMap((entry): DuelMode[] => {
const m = obj(obj(entry)?.mode) ?? obj(entry);
if (!m || m.engine !== 'duel') return [];
const id = str(m.id, 64), name = str(m.name, 60);
if (!/^[A-Za-z0-9_-]+$/.test(id) || !name) return [];
const rules = obj(m.rules), limits = obj(m.limits);
const deckSize = typeof rules?.deckSize === 'number' && Number.isInteger(rules.deckSize) && rules.deckSize > 0 ? rules.deckSize : undefined;
return [{ id, name, description: str(m.description, 280), ranked: limits?.rated === true || m.rated === true, ...(deckSize ? { deckSize } : {}) }];
});
}
+37
View File
@@ -0,0 +1,37 @@
/* PvP hub, eligibility gate and constructed deck picker (ui-pvp). 360 px first. */
.eligibility{border:1px solid var(--theme-border);border-radius:12px;padding:14px;background:var(--ctp-base);margin:12px 0}
.eligibility-count{font-size:20px;margin:0 0 8px}
.eligibility-bar{height:10px;border-radius:5px;background:var(--ctp-surface0);overflow:hidden;margin-bottom:10px}
.eligibility-bar span{display:block;height:100%;background:var(--ctp-green);border-radius:5px}
.eligibility-actions{display:flex;gap:8px;flex-wrap:wrap}
.eligibility-actions .button{min-height:44px}
.pvp-grid{display:grid;grid-template-columns:1fr;gap:8px;margin:10px 0}
.pvp-tile{display:flex;align-items:center;gap:12px;text-align:left;min-height:56px;padding:10px 12px;border:1px solid var(--theme-border);border-radius:10px;background:var(--ctp-base);color:var(--ctp-text);cursor:pointer;font:inherit;width:100%}
.pvp-tile:disabled{opacity:.55;cursor:not-allowed}
.pvp-tile b{display:block;font-size:14px}
.pvp-tile small{display:block;font-size:11px;color:var(--ctp-subtext0)}
.pvp-tile.primary{border-color:var(--ctp-mauve);background:var(--ctp-surface0)}
.pvp-join{display:flex;gap:6px}
.pvp-join input,.picker-search input{flex:1;min-width:0;min-height:44px;padding:8px 10px;border-radius:8px;border:1px solid var(--theme-border);background:var(--ctp-base);color:var(--ctp-text);font:inherit;font-size:14px}
.invite-box{display:flex;gap:6px;align-items:stretch;margin:8px 0}
.invite-box code{flex:1;min-width:0;overflow-wrap:anywhere;padding:10px;border-radius:8px;background:var(--ctp-base);border:1px solid var(--theme-border);font-size:12px}
.ladder-list{list-style:none;padding:0;margin:6px 0;font-size:13px}
.ladder-list li{display:grid;grid-template-columns:24px 1fr auto auto;gap:8px;padding:6px 4px;border-bottom:1px solid var(--theme-border)}
.ladder-list li b{font-variant-numeric:tabular-nums}
.ladder-list li small{color:var(--ctp-subtext0);font-variant-numeric:tabular-nums}
.picker-tools{display:flex;gap:6px;margin:8px 0}
.picker-tools .button{min-height:44px;padding:8px 12px}
.picker-search{flex:1;display:flex;align-items:center;gap:6px;min-width:0}
.picker-list{list-style:none;padding:0;margin:0 0 8px;max-height:55vh;overflow:auto}
.picker-list li{display:flex;align-items:center;gap:4px;border-bottom:1px solid var(--theme-border)}
.picker-row{flex:1;display:grid;grid-template-columns:22px 1fr auto;align-items:center;gap:8px;min-height:44px;padding:6px 4px;background:none;border:0;color:var(--ctp-text);font:inherit;text-align:left;cursor:pointer;min-width:0}
.picker-row:disabled{opacity:.45;cursor:not-allowed}
.picker-row.selected .picker-check{background:var(--ctp-green);color:var(--ctp-base);border-color:var(--ctp-green)}
.picker-check{width:20px;height:20px;border-radius:5px;border:1px solid var(--theme-border);display:grid;place-items:center}
.picker-title{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px}
.picker-row small{font-size:11px;color:var(--ctp-subtext0)}
.picker-link{padding:10px;color:var(--ctp-subtext0)}
.duel-placeholder{border:1px dashed var(--theme-border);border-radius:10px;padding:14px;margin:10px 0;font-size:13px}
@media (min-width:640px){.pvp-grid{grid-template-columns:1fr 1fr}}
.lobby .deck-summary b,.lobby .deck-summary small{display:block}
.eligibility-bar+p{margin-bottom:12px}
+33
View File
@@ -0,0 +1,33 @@
import { useEffect, useMemo, useState } from 'react';
import type { TestnetBlock } from '../../../shared/testnet.ts';
import { idToken } from '../../auth/session.ts';
import { useAccount } from '../useAccount.ts';
import { collectionFromBlocks, parseCollection, type Collection } from './collection.ts';
export type CollectionState = { collection: Collection; status: 'loading' | 'ok' | 'fallback' | 'guest' };
/**
* The player's owned cards. Logged in: ownership's GET /api/game/collection (all linked wallets,
* no snapshot cap). Logged out or API unavailable: this browser wallet's confirmed cards, shown
* as a view only (the host still verifies on the server before any match).
*/
export function useCollection(owned: TestnetBlock[]): CollectionState {
const account = useAccount();
const local = useMemo(() => collectionFromBlocks(owned), [owned]);
const [server, setServer] = useState<{ sub: string; c?: Collection; failed?: boolean }>();
const sub = account?.sub ?? '';
useEffect(() => {
const token = idToken();
if (!sub || !token) { setServer(undefined); return; }
let active = true;
setServer({ sub });
fetch('/api/game/collection', { cache: 'no-store', headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(15000) })
.then(r => (r.ok && r.headers.get('content-type')?.includes('json') ? r.json() : Promise.reject(new Error(String(r.status)))))
.then(d => { if (active) setServer({ sub, c: parseCollection(d) }); }, () => { if (active) setServer({ sub, failed: true }); });
return () => { active = false; };
}, [sub]);
if (!sub) return { collection: local, status: 'guest' };
if (server?.sub === sub && server.c) return { collection: server.c, status: 'ok' };
if (server?.sub === sub && server.failed) return { collection: local, status: 'fallback' };
return { collection: local, status: 'loading' };
}
+39
View File
@@ -0,0 +1,39 @@
import { useMemo, useState } from 'react';
import type { DuelAction, LogEvent, PlayerView } from './contract.ts';
import { boardFromView, expand, legalFromActions, plainLog, type Articles } from './adapter.ts';
import { DuelTable } from './DuelTable.tsx';
import type { DuelUIAction } from './model.ts';
/**
* The duel board on duel-core's types, for any controller (ui-pvp's OnlinePlay, the local bot match).
* One board intent can be several atomic actions (toggleAttacker × N, confirmAttack): they go out
* through `onAct` in order, each awaited, each an element of `legal` or legal once the previous ones apply.
*/
export function DuelBoard({ view, legal, onAct, opponentName, playerName = 'You', error, busy, log, logEvents, articles, clock, onExit, onRecap }: {
view: PlayerView; legal: DuelAction[]; onAct: (a: DuelAction) => void | Promise<void>;
opponentName: string; playerName?: string; error?: string; busy?: boolean;
/** Rendered log lines (duel-design's story renderer). If absent, `logEvents` are shown with plain templates. */
log?: string[]; logEvents?: LogEvent[];
/** cardId → article image/url, from the chain. */
articles?: Articles;
clock?: { turn: number; bank: number };
onExit?: () => void; onRecap?: () => void;
}) {
const [sending, setSending] = useState(false);
const [sendError, setSendError] = useState<string>();
const names = useMemo<[string, string]>(() => (view.seat === 0 ? [playerName, opponentName] : [opponentName, playerName]), [view.seat, playerName, opponentName]);
const lines = useMemo(() => log ?? plainLog(logEvents ?? [], names), [log, logEvents, names]);
const board = useMemo(() => boardFromView(view, names, lines, articles, clock), [view, names, lines, articles, clock]);
const boardLegal = useMemo(() => legalFromActions(legal), [legal]);
const act = async (ui: DuelUIAction) => {
const seq = expand(ui, legal);
setSending(true); setSendError(undefined);
try { for (const a of seq) await onAct(a); }
catch (e) { setSendError(e instanceof Error ? e.message : 'That move was not accepted.'); }
finally { setSending(false); }
};
return <DuelTable view={board} legal={boardLegal} onAct={ui => { void act(ui); }} busy={busy || sending}
error={error ?? sendError} onExit={onExit} onRecap={onRecap} />;
}
+80
View File
@@ -0,0 +1,80 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { DuelAction, DuelCard, DuelEngineLike, DuelRulesetLike, Seat } from './contract.ts';
import type { Articles } from './adapter.ts';
import { DuelBoard } from './DuelBoard.tsx';
import { DuelGate } from './DuelGate.tsx';
import { botDeck, hash, mulberry, playerDeck, type BotMatchCard, type DuelBot } from './decks.ts';
export type { BotMatchCard, DuelBot };
const HUMAN: Seat = 0, BOT: Seat = 1;
const BOT_STEP_MS = 300;
/**
* A bot match in the browser, for eligible players only (BRIEF decisions 2–3): the deck must be
* exactly `deckSize` cards the player owns. Off-chain; nothing moves or burns.
* Unrated by design: the whole DuelState (bot hand, library order) lives in the page, so `onFinish` never
* gets a match id and a browser-hosted result must never feed Elo or the ladder (night-review, #79).
*/
export function DuelBotMatch<S, R extends DuelRulesetLike>({ deck, cards, onExit, onFinish, engine, bot, botPool, rules, playerName = 'You', onMine }: {
deck: string[]; cards: BotMatchCard[]; onExit: () => void; onFinish: (matchId?: string) => void;
engine: DuelEngineLike<S, R>; bot: DuelBot; botPool: readonly DuelCard[]; rules: R; playerName?: string; onMine?: () => void;
}) {
const mine = useMemo(() => playerDeck(deck, cards, rules.deckSize), [deck, cards, rules.deckSize]);
const [seed] = useState(() => `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`);
const [state, setState] = useState<S | null>(null);
const [error, setError] = useState<string>();
const rng = useRef(mulberry(hash(seed)));
const current = useRef<S | null>(null);
current.current = state;
useEffect(() => {
if (!mine.cards.length) return;
try { setState(engine.createDuel(rules, [mine.cards, botDeck(botPool, rules.deckSize, seed)], seed)); }
catch (e) { setError(e instanceof Error ? e.message : 'This deck can’t be played.'); }
}, [engine, rules, mine.cards, botPool, seed]);
// The bot moves one atomic action at a time, so the board shows its plays and declarations.
useEffect(() => {
if (!state || engine.toAct(state) !== BOT) return;
const t = setTimeout(() => {
const legal = engine.legalActions(state, BOT);
if (!legal.length) return;
let a: DuelAction;
try { a = bot.choose(engine.viewFor(state, BOT), legal, rng.current); } catch { a = legal[0]; }
if (!legal.some(l => JSON.stringify(l) === JSON.stringify(a))) a = legal[0];
if (current.current !== state) return;
const next = engine.applyAction(state, BOT, a);
current.current = next;
setState(next);
}, BOT_STEP_MS);
return () => clearTimeout(t);
}, [state, engine, bot]);
// Applied synchronously through a ref, so a confirmed declaration (toggleAttacker × N, confirmAttack)
// sees each previous action, and an illegal action throws back to DuelBoard, which shows the error.
const onAct = useCallback((a: DuelAction) => {
const s = current.current;
if (!s) return;
const next = engine.applyAction(s, HUMAN, a);
current.current = next;
setError(undefined);
setState(next);
}, [engine]);
const articles = useMemo<Articles>(() => Object.fromEntries(cards.map(c => [c.tokenId, { image: c.imageUrl, url: c.url, extract: c.extract }])), [cards]);
if (!mine.cards.length) {
if (deck.length < rules.deckSize || mine.missing.length) return <DuelGate owned={deck.length - mine.missing.length} deckSize={rules.deckSize} onExit={onExit} onMine={onMine} />;
return <section className="duel-gate"><h2>Card profiles pending</h2>
<p className="muted">These cards don’t have a duel profile yet, so they can’t be played: {mine.pending.join(', ')}. Pick other cards for your deck, or try again shortly.</p>
<div className="play-actions"><button className="button outline" onClick={onExit}>Back</button></div></section>;
}
if (!state) return error ? <section className="duel-gate"><h2>Can’t start this match</h2><p className="muted">{error}</p>
<div className="play-actions"><button className="button outline" onClick={onExit}>Back</button></div></section> : null;
const view = engine.viewFor(state, HUMAN);
return <DuelBoard view={view} legal={engine.legalActions(state, HUMAN)} onAct={onAct} opponentName={`Bot (${bot.name})`} playerName={playerName}
logEvents={engine.logFor(state, HUMAN)} articles={articles} busy={engine.toAct(state) === BOT} error={error}
onExit={engine.isOver(state) ? () => onFinish() : onExit} />;
}
+90
View File
@@ -0,0 +1,90 @@
import { BookMarked, BookOpen, Building2, CalendarClock, Globe2, Home, Hourglass, Languages, Link2, MapPin, Shield, ShieldCheck, Sparkles, Sprout, Star, Swords, TrendingUp, UserRound } from 'lucide-react';
import type { BoardCard, DuelCardType } from './model.ts';
import { cardSummary, typeLine } from './model.ts';
const TYPE_ICONS: Record<DuelCardType, typeof UserRound> = {
Figure: UserRound, Location: MapPin, Event: CalendarClock, Institution: Building2, Doctrine: BookOpen,
};
export const TypeIcon = ({ type, size = 12 }: { type: DuelCardType; size?: number }) => {
const Icon = TYPE_ICONS[type] ?? BookOpen;
return <Icon size={size} aria-hidden="true" />;
};
/** Keyword icons for the board face, where a word doesn't fit 62 px. The words are in the label and the zoom face. */
const KEYWORD_ICONS: Record<string, typeof Star> = {
protected: ShieldCheck, featured: Star, translated: Languages, legacy: Hourglass, stub: Sprout,
'well-sourced': BookMarked, multilingual: Globe2, local: Home, trending: TrendingUp, connected: Link2,
};
export const KeywordIcon = ({ keyword, size = 11 }: { keyword: string; size?: number }) => {
const Icon = KEYWORD_ICONS[keyword.toLowerCase()] ?? Sparkles;
return <Icon size={size} aria-hidden="true" />;
};
export type FaceSize = 'board' | 'hand' | 'zoom';
export type FaceState = { selected?: boolean; attacking?: boolean; blocking?: boolean; target?: boolean; dim?: boolean; fresh?: boolean };
const statClass = (now?: number, base?: number) => (now === undefined || base === undefined ? '' : now > base ? 'up' : now < base ? 'down' : '');
function Stats({ card }: { card: BoardCard }) {
if (card.power === undefined) return null;
const tough = (card.toughness ?? 0) - (card.damage ?? 0);
return <span className="dface-pt" aria-hidden="true">
<b className={statClass(card.power, card.basePower)}>{card.power}</b>/<b className={card.damage ? 'down' : statClass(card.toughness, card.baseToughness)}>{tough}</b>
</span>;
}
function Art({ card, iconSize }: { card: BoardCard; iconSize: number }) {
return <span className="dface-art" aria-hidden="true">
{card.image ? <img src={card.image} alt="" loading="lazy" decoding="async" referrerPolicy="no-referrer"
onError={e => { e.currentTarget.style.display = 'none'; }} /> : null}
<TypeIcon type={card.type} size={iconSize} />
</span>;
}
/**
* The duel card face (MTG layout). Board and hand faces show only what fits a phone: title (2-line
* clamp), cost, type icon, P/T and keyword chips. Rules text and flavour live in the zoom face,
* which the tap-to-zoom sheet shows (critic S4).
*/
export function DuelCardFace({ card, size = 'hand', state = {}, onClick, label, refNumber }: {
card: BoardCard; size?: FaceSize; state?: FaceState; onClick?: () => void; label?: string; refNumber?: number;
}) {
const cls = ['dface', `dface-${size}`, `portal-${card.portal.toLowerCase()}`,
card.tapped && 'is-tapped', card.pending && 'is-pending', state.selected && 'is-selected', state.attacking && 'is-attacking',
state.blocking && 'is-blocking', state.target && 'is-target', state.dim && 'is-dim', state.fresh && 'is-fresh', card.token && 'is-token']
.filter(Boolean).join(' ');
if (size === 'zoom') return <article className={cls} aria-label={cardSummary(card)}>
<div className="dface-namebar"><h3 className="dface-name">{card.title}</h3><span className="dface-cost" aria-label={`Cost ${card.cost} Citations`}>{card.cost}</span></div>
<Art card={card} iconSize={34} />
<p className="dface-typeline"><TypeIcon type={card.type} size={13} /> {typeLine(card)}<span className="dface-portal">{card.portal}</span></p>
<div className="dface-textbox">
{card.keywords.length > 0 && !card.keywords.every(k => card.rulesText.includes(k)) && <p className="dface-keywords">{card.keywords.join('. ')}.</p>}
{card.rulesText && <p className="dface-rules">{card.rulesText}</p>}
{card.flavour && <p className="dface-flavour">{card.flavour}{card.url
? <sup><a href={card.url} target="_blank" rel="noopener noreferrer" aria-label={`Wikipedia article: ${card.title}`}>[{refNumber ?? 1}]</a></sup>
: null}</p>}
</div>
<div className="dface-footer">
<span className="dface-rev">{card.revisionId ? `rev. ${card.revisionId}` : card.token ? 'Token' : ''}</span>
<Stats card={card} />
</div>
</article>;
const kwShown = card.keywords.slice(0, 2);
const Tag = onClick ? 'button' : 'div';
return <Tag {...(onClick ? { type: 'button' as const, onClick, 'aria-pressed': state.selected || state.attacking || state.blocking || undefined } : { role: 'img' })}
className={cls} aria-label={label ?? cardSummary(card)}>
<Art card={card} iconSize={size === 'board' ? 14 : 18} />
<span className="dface-cost" aria-hidden="true">{card.cost}</span>
{state.attacking && <span className="dface-flag attack" aria-hidden="true"><Swords size={11} /></span>}
{state.blocking && <span className="dface-flag block" aria-hidden="true"><Shield size={11} /></span>}
<span className="dface-title">{card.title}</span>
<span className="dface-bottom">
{size === 'board' || kwShown.length > 1
? kwShown.map(k => <span key={k} className="dface-kwicon" title={k}><KeywordIcon keyword={k} size={10} /></span>)
: kwShown.map(k => <span key={k} className="dface-chip">{k}</span>)}
<Stats card={card} />
</span>
</Tag>;
}
+24
View File
@@ -0,0 +1,24 @@
import { Pickaxe } from 'lucide-react';
import { eligibility } from './model.ts';
import './duel.css';
/**
* Shown instead of a board when the player doesn't own a full deck (BRIEF decisions 1–2). There is
* no practice with borrowed cards: the only way forward is mining (or trading) for real cards.
*/
export function DuelGate({ owned, deckSize, onMine, onExit }: { owned: number; deckSize: number; onMine?: () => void; onExit?: () => void }) {
const e = eligibility(owned, deckSize);
const pct = Math.round((Math.min(owned, deckSize) / deckSize) * 100);
return <section className="duel-gate" aria-labelledby="duel-gate-title">
<div className="section-eyebrow">DUEL · {deckSize}-CARD DECKS</div>
<h2 id="duel-gate-title">{e.label}</h2>
<div className="duel-gate-bar" role="progressbar" aria-valuemin={0} aria-valuemax={deckSize} aria-valuenow={Math.min(owned, deckSize)} aria-label="Cards owned"><i style={{ width: `${pct}%` }} /></div>
<p className="muted">A duel deck is exactly {deckSize} cards, and every one is an NFT you own. You need {e.needed} more.
Each block you mine is a new card: a random Wikipedia article, frozen with its stats at the moment it was mined.
Trades with other players count too. Matches never move or burn your cards.</p>
<div className="play-actions">
{onExit && <button className="button outline" onClick={onExit}>Back</button>}
{onMine && <button className="button dark" onClick={onMine}><Pickaxe size={16} /> Mine cards</button>}
</div>
</section>;
}
+27
View File
@@ -0,0 +1,27 @@
import { useState } from 'react';
import { DuelCardFace } from './DuelCardFace.tsx';
import { DuelTable } from './DuelTable.tsx';
import { PREVIEW_POOL, previewView } from './mock.ts';
import type { DuelUIAction } from './model.ts';
type Scene = 'main' | 'attack' | 'block' | 'over' | 'cards';
const SCENES: Scene[] = ['main', 'attack', 'block', 'over', 'cards'];
const ZOOM = ['Jess Harnell', 'Agda (programming language)', "April 2021 nor'easter", 'Pathrail Mosque', 'Hiroshima Electric Railway', 'Heart rot'];
/** Static board scenes from card-sample.json, for screenshots and review (`#duel-preview/<scene>`). Not a match. */
export function DuelPreview() {
const initial = (location.hash.split('/')[1] as Scene) || 'main';
const [scene, setScene] = useState<Scene>(SCENES.includes(initial) ? initial : 'main');
const [acted, setActed] = useState<string[]>([]);
const { view, legal } = previewView(scene === 'cards' ? 'main' : scene);
const onAct = (a: DuelUIAction) => setActed(l => [...l, JSON.stringify(a)]);
return <div className="duel-preview-page" style={{ padding: 0 }}>
<nav className="category-tabs" aria-label="Preview scene" style={{ padding: '4px 8px', display: location.hash.includes('clean') ? 'none' : undefined }}>
{SCENES.map(s => <button key={s} className={s === scene ? 'selected' : ''} onClick={() => { setScene(s); location.hash = `duel-preview/${s}`; }}>{s}</button>)}
{acted.length > 0 && <small style={{ marginLeft: 8 }}>last action: {acted.at(-1)}</small>}
</nav>
{scene === 'cards' ? <div className="duel" style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill,minmax(280px,1fr))', gap: 16, padding: 12 }}>
{ZOOM.map(t => PREVIEW_POOL.find(c => c.title === t)).filter(c => !!c).map((c, i) => <DuelCardFace key={c.id} card={c} size="zoom" refNumber={i + 1} />)}
</div> : <DuelTable key={scene} view={{ ...view, log: [...view.log, ...acted.map(a => `(preview) ${a}`)] }} legal={legal} onAct={onAct} />}
</div>;
}

Some files were not shown because too many files have changed in this diff Show More