Merge night/2026-11-17 into host-pvp part 2

This commit is contained in:
2026-11-18 11:15:00 -05:00
92 changed files with 7963 additions and 221 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
+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.
+120 -22
View File
@@ -851,9 +851,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "figure",
"template": "T12"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": -3,
"toughness": -3,
"duration": "permanent",
"template": "T12"
}
],
@@ -943,15 +948,19 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 3,
"toughness": 3,
"duration": "permanent",
"template": "T11"
},
{
"trigger": "onCombatDamageToPlayer",
"op": "draw",
"target": "attached",
"amount": 1,
"template": "T11"
}
@@ -1272,15 +1281,19 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 3,
"toughness": 3,
"duration": "permanent",
"template": "T11"
},
{
"trigger": "onCombatDamageToPlayer",
"op": "draw",
"target": "attached",
"amount": 1,
"template": "T11"
}
@@ -3753,9 +3766,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 3,
"toughness": 3,
"duration": "permanent",
"template": "T11"
}
],
@@ -4189,9 +4207,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 2,
"toughness": 2,
"duration": "permanent",
"template": "T11"
}
],
@@ -4325,9 +4348,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 3,
"toughness": 3,
"duration": "permanent",
"template": "T11"
}
],
@@ -4787,9 +4815,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 2,
"toughness": 2,
"duration": "permanent",
"template": "T11"
}
],
@@ -5010,9 +5043,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 3,
"toughness": 3,
"duration": "permanent",
"grant": [
"Well-sourced"
],
@@ -5059,9 +5097,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 3,
"toughness": 3,
"duration": "permanent",
"template": "T11"
}
],
@@ -5196,9 +5239,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 3,
"toughness": 3,
"duration": "permanent",
"grant": [
"Well-sourced"
],
@@ -6030,9 +6078,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 2,
"toughness": 2,
"duration": "permanent",
"template": "T11"
}
],
@@ -7070,9 +7123,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 2,
"toughness": 2,
"duration": "permanent",
"grant": [
"Well-sourced"
],
@@ -7120,9 +7178,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "figure",
"template": "T12"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": -2,
"toughness": -2,
"duration": "permanent",
"template": "T12"
}
],
@@ -7830,9 +7893,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "figure",
"template": "T12"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": -2,
"toughness": -2,
"duration": "permanent",
"template": "T12"
}
],
@@ -8132,9 +8200,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 1,
"toughness": 1,
"duration": "permanent",
"template": "T11"
}
],
@@ -8552,9 +8625,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 2,
"toughness": 2,
"duration": "permanent",
"grant": [
"Well-sourced"
],
@@ -9028,9 +9106,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 2,
"toughness": 2,
"duration": "permanent",
"template": "T11"
}
],
@@ -9074,9 +9157,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 3,
"toughness": 3,
"duration": "permanent",
"template": "T11"
}
],
@@ -9384,9 +9472,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 3,
"toughness": 3,
"duration": "permanent",
"template": "T11"
}
],
@@ -9559,9 +9652,14 @@
"trigger": "onPlay",
"op": "attach",
"target": "ownFigure",
"template": "T11"
},
{
"trigger": "static",
"op": "pump",
"target": "attached",
"power": 1,
"toughness": 1,
"duration": "permanent",
"template": "T11"
}
],
+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.
+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.
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+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
+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;
}
+137
View File
@@ -0,0 +1,137 @@
// 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]],
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')}
`;
}
+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,
+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;
},
};
}
+6 -6
View File
@@ -11,8 +11,7 @@ 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';
@@ -30,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.');});
@@ -121,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.'});
}
@@ -176,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 }; }
}
+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}`);
}
}
+60 -2
View File
@@ -39,7 +39,8 @@ export interface CardProfile {
fetchedRevisionId?: number;
}
export type ClassifySource = 'qid' | 'p279-qid' | 'p31' | 'p279' | 'category' | 'description' | 'fallback';
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. */
@@ -100,12 +101,58 @@ export const DESCRIPTION_RULES: Rules = [
['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'>): Classification {
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 }; }
@@ -121,5 +168,16 @@ export function classify(profile: Pick<CardProfile, 'instanceOf' | 'subclassOf'
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: '' };
}
+9 -8
View File
@@ -26,7 +26,8 @@ export type Rarity = 'Common' | 'Rare' | 'Epic' | 'Legendary';
/** What derive() reads from the chain: a minted block's article and stats snapshot. */
export interface CardOnChain {
tokenId: string;
article: Pick<Article, 'pageId' | 'title' | 'extract' | 'revisionId'>;
/** `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'>;
}
@@ -38,8 +39,8 @@ export interface ConnectKeys {
links: number[];
/** P31 Q-ids, excluding human and taxon (the Kin tier). */
p31: string[];
/** This card's Wikidata item, and the item Q-ids its claims cite (Linked tier). */
qid: string | null;
/** This card's Wikidata item (omitted when it has none), and the item Q-ids its claims cite (Linked tier). */
qid?: string;
cites: string[];
}
@@ -177,7 +178,7 @@ export function connectKeysFor(title: string, profile: CardProfile): ConnectKeys
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(),
qid: profile.wikidataId,
...(profile.wikidataId ? { qid: profile.wikidataId } : {}),
cites: [...new Set(profile.cites ?? [])].sort(),
};
}
@@ -266,13 +267,13 @@ export function figureBody(cost: number, p: Percentiles, keywords: readonly Keyw
// ---------------------------------------------------------------- derive
export function derive(chain: CardOnChain, profile: CardProfile, rules: DeriveRules = DERIVE_RULES): DuelCard {
const { type, source } = classify(profile);
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);
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') {
@@ -310,8 +311,8 @@ export function connectedTier(a: DuelCard, b: DuelCard,
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 !== null && a.connect.cites.includes(b.connect.qid))
|| (a.connect.qid !== null && b.connect.cites.includes(a.connect.qid)))) return tier;
|| (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;
+14 -8
View File
@@ -3,7 +3,7 @@
* Effects are plain data for duel-core's interpreter. k = ceil(cost / 2), 1–3, from the derived (fame) cost.
* Owner: duel-cards.
*/
import type { CardProfile, CardType } from './classify.ts';
import { definitionOf, type CardProfile, type CardType, type ChainHints } from './classify.ts';
import type { Keyword, Portal } from './derive.ts';
export type EffectTrigger = 'onPlay' | 'onEnter' | 'startOfTurn' | 'onDestroyed' | 'static' | 'onCombatDamageToPlayer';
@@ -59,11 +59,14 @@ 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'>): string | null {
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];
@@ -116,12 +119,15 @@ function baseEffects(type: CardType, subtype: string | null, cost: number): Effe
default: return [{ trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 0, condition: { maxPower: 2 } }];
}
case 'Doctrine': {
if (subtype === 'pathology') return [{ trigger: 'onPlay', op: 'attach', target: 'figure', power: -k, toughness: -k, duration: 'permanent' }];
const attach: EffectSpec = { trigger: 'onPlay', op: 'attach', target: 'ownFigure', power: k, toughness: k, duration: 'permanent' };
if (subtype === 'mathematics') return [{ ...attach, grant: ['Well-sourced'] }];
if (subtype === 'language') return [attach, { trigger: 'onCombatDamageToPlayer', op: 'draw', target: 'attached', amount: 1 }];
if (subtype === 'ideology') return [attach, { trigger: 'static', op: 'pump', target: 'ownFigures', power: 1, toughness: 0, condition: { samePortal: true } }];
return [attach];
// 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 [];
}
+4 -1
View File
@@ -13,6 +13,8 @@ export interface SampleCard {
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 {
@@ -23,7 +25,8 @@ export function sampleInputs(card: SampleCard): { chain: CardOnChain; profile: C
return {
chain: {
tokenId: sampleTokenId(card.pageId),
article: { pageId: card.pageId, title: card.title, extract: card.extract ?? '', revisionId: card.revisionId },
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: {
+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;
}
+12 -3
View File
@@ -75,8 +75,16 @@ export function effectText(effects: readonly EffectSpec[]): string[] {
for (let i = 0; i < effects.length; i++) {
const e = effects[i];
if (e.op === 'attach') {
const grant = e.grant?.length ? ` and has ${keywordsAsText(e.grant)}` : '';
lines.push(`Attach to ${e.target === 'figure' ? 'target Figure' : 'target Figure you control'}. It gets ${pt(e.power, e.toughness)}${grant}.`);
// 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') {
@@ -95,7 +103,8 @@ export function effectText(effects: readonly EffectSpec[]): string[] {
break;
}
case 'onCombatDamageToPlayer':
lines.push(`Whenever ${e.target === 'attached' ? 'it' : 'this'} deals combat damage to a player, ${actionText(e)}.`);
// 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;
}
}
+20 -3
View File
@@ -15,7 +15,11 @@ 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,8 +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);
@@ -165,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>
@@ -194,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>
@@ -204,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>;
}
+107 -2
View File
@@ -1,11 +1,11 @@
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 { 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 +126,108 @@ 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 eyebrow = `${modeName.toUpperCase()} · ${entry.kind === 'quick' ? 'QUICK MATCH' : entry.kind === 'private' ? 'PRIVATE LOBBY' : 'INVITE'}`;
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>;
}
+251
View File
@@ -0,0 +1,251 @@
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { Award, Flag, Hand, Library, LoaderCircle, Quote, ScrollText, Shield, Swords, Timer, X } from 'lucide-react';
import { DuelCardFace } from './DuelCardFace.tsx';
import '../play.css';
import './duel.css';
import {
EMPTY_DECL, blockList, isMyTurn, nextTargets, playerTarget, previewCombat, targetsComplete, tapAttacker, tapBlocker, toggleAttacker,
type Attack, type BoardCard, type Seat, type BoardView, type Declaration, type DuelUIAction, type Legal, type SideView,
} from './model.ts';
type Sheet =
| { kind: 'card'; card: BoardCard; where: 'hand' | 'mine' | 'theirs' }
| { kind: 'combat'; attacks: Attack[]; mode: 'attack' | 'block' }
| { kind: 'log' } | { kind: 'concede' } | null;
const PHASE_LABEL: Record<BoardView['phase'], string> = {
mulligan: 'Opening hand', main: 'Main', attack: 'Combat', block: 'Blocks', over: 'Match over',
};
function SideBar({ side, who, active, target, onTarget }: { side: SideView; who: 'me' | 'opponent'; active: boolean; target?: boolean; onTarget?: () => void }) {
const label = `${who === 'me' ? 'You' : side.name}: ${side.notability} Notability, ${side.citations} of ${side.maxCitations} Citations, ${side.library} in library, ${side.hand} in hand`;
const Tag = target ? 'button' : 'div';
return <Tag className={`duel-side ${who} ${active ? 'is-active' : ''} ${target ? 'is-target' : ''}`} {...(target ? { type: 'button' as const, onClick: onTarget } : { role: 'group' })} aria-label={target ? `Target ${who === 'me' ? 'yourself' : side.name}. ${label}` : label}>
<span className="duel-side-name">{who === 'me' ? 'You' : side.name}</span>
<span className={`duel-stat life ${side.notability <= 5 ? 'low' : ''}`} title="Notability"><Award size={14} aria-hidden="true" /><b>{side.notability}</b></span>
<span className="duel-stat cites" title="Citations"><Quote size={13} aria-hidden="true" /><b>{side.citations}</b><small>/{side.maxCitations}</small></span>
<span className="duel-stat" title="Library"><Library size={13} aria-hidden="true" />{side.library}</span>
<span className="duel-stat" title="Hand"><Hand size={13} aria-hidden="true" />{side.hand}</span>
</Tag>;
}
/**
* The duel table (presentational), 360 × 740 first. Controllers (local bot, PvP host) feed it a BoardView and the
* legal moves, and get DuelUIActions back. Attack: tap a Figure (1 tap). Block: tap your Figure,
* then the attacker (2 taps). Both go through a preview → confirm sheet; no drawn arrows.
*/
export function DuelTable({ view, legal, onAct, busy, error, onExit, onRecap }: {
view: BoardView; legal: Legal; onAct: (a: DuelUIAction) => void; busy?: boolean; error?: string;
onExit?: () => void; onRecap?: () => void;
}) {
const [sheet, setSheet] = useState<Sheet>(null);
const [decl, setDecl] = useState<Declaration>(EMPTY_DECL);
const [targeting, setTargeting] = useState<{ cardId: string; chosen: string[] }>();
const logRef = useRef<HTMLOListElement>(null);
// Hand overflow cue (QA #58): how many hand cards are past the right edge.
const handRef = useRef<HTMLDivElement>(null);
const [hiddenRight, setHiddenRight] = useState(0);
useEffect(() => {
const el = handRef.current;
if (!el) return;
const measure = () => {
const edge = el.getBoundingClientRect().right;
setHiddenRight([...el.children].filter(c => c.getBoundingClientRect().left > edge - 24).length);
};
measure();
el.addEventListener('scroll', measure, { passive: true });
const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(measure) : null;
ro?.observe(el);
return () => { el.removeEventListener('scroll', measure); ro?.disconnect(); };
}, [view.hand.length]);
const mine = isMyTurn(view);
const oppSeat = (1 - view.seat) as Seat;
const attackMode = mine && view.phase === 'attack' && !busy;
const blockMode = !mine && view.phase === 'block' && view.combat.length > 0 && !busy;
const stepKey = `${view.turn}:${view.active}:${view.phase}`;
useEffect(() => { setDecl(EMPTY_DECL); setTargeting(undefined); }, [stepKey]);
useEffect(() => { logRef.current?.lastElementChild?.scrollIntoView?.({ block: 'nearest' }); }, [view.log.length]);
const cards = useMemo(() => new Map([...view.me.battlefield, ...view.opponent.battlefield, ...view.hand].map(c => [c.id, c])), [view]);
const attackingIds = new Set(view.combat.map(a => a.attackerId));
const targets = targeting ? nextTargets(legal.plays[targeting.cardId], targeting.chosen) : null;
const refs = useMemo(() => { const m = new Map<string, number>(); for (const c of cards.values()) if (c.url && !m.has(c.url)) m.set(c.url, m.size + 1); return m; }, [cards]);
const play = (cardId: string, targetIds: string[]) => { setTargeting(undefined); setSheet(null); onAct({ type: 'play', cardId, targetIds }); };
const startPlay = (card: BoardCard) => {
const seqs = legal.plays[card.id];
if (!seqs) return;
if (targetsComplete(seqs, [])) play(card.id, []); else { setTargeting({ cardId: card.id, chosen: [] }); setSheet(null); }
};
const chooseTarget = (id: string) => {
if (!targeting || !targets?.has(id)) return;
const chosen = [...targeting.chosen, id];
if (targetsComplete(legal.plays[targeting.cardId], chosen) && !nextTargets(legal.plays[targeting.cardId], chosen).size) play(targeting.cardId, chosen);
else setTargeting({ ...targeting, chosen });
};
const tapMine = (c: BoardCard) => {
if (targets) { chooseTarget(c.id); return; }
if (attackMode && legal.attackers.includes(c.id)) { setDecl(d => toggleAttacker(d, c.id, legal)); return; }
if (blockMode && (legal.blockers[c.id]?.length || decl.blocks[c.id])) { setDecl(d => tapBlocker(d, c.id, legal)); return; }
setSheet({ kind: 'card', card: c, where: 'mine' });
};
const tapTheirs = (c: BoardCard) => {
if (targets) { chooseTarget(c.id); return; }
if (blockMode && attackingIds.has(c.id) && (decl.picked || Object.values(decl.blocks).includes(c.id))) { setDecl(d => tapAttacker(d, c.id, legal)); return; }
setSheet({ kind: 'card', card: c, where: 'theirs' });
};
const blockedBy = (attackerId: string) => Object.entries(decl.blocks).find(([, a]) => a === attackerId)?.[0];
const pendingAttacks: Attack[] = attackMode ? decl.attackers.map(attackerId => ({ attackerId }))
: blockMode ? view.combat.map(a => ({ attackerId: a.attackerId, blockerId: blockedBy(a.attackerId) })) : view.combat;
const stateFor = (c: BoardCard, side: 'mine' | 'theirs') => {
const t = targets?.has(c.id);
if (side === 'mine') return {
attacking: attackMode ? decl.attackers.includes(c.id) : attackingIds.has(c.id),
blocking: !!decl.blocks[c.id] || view.combat.some(a => a.blockerId === c.id),
selected: decl.picked === c.id,
target: t,
dim: (targets && !t) || (attackMode && c.type === 'Figure' && !legal.attackers.includes(c.id)) || (blockMode && !legal.blockers[c.id]?.length && !decl.blocks[c.id]),
};
const canBeBlocked = !!decl.picked && !!legal.blockers[decl.picked]?.includes(c.id);
return { attacking: attackingIds.has(c.id), target: t || canBeBlocked, blocking: view.combat.some(a => a.blockerId === c.id), dim: (targets && !t) || (!!decl.picked && !canBeBlocked) };
};
const row = (list: BoardCard[], side: 'mine' | 'theirs') => {
const top = list.filter(c => !c.attachedTo);
return <div className={`duel-row ${side}`} aria-label={side === 'mine' ? 'Your battlefield' : 'Opponent battlefield'}>
{top.length ? top.map(c => <div key={c.id} className="duel-slot">
<DuelCardFace card={c} size="board" state={stateFor(c, side)} onClick={() => (side === 'mine' ? tapMine(c) : tapTheirs(c))} />
{!!c.attachments?.length && <span className="duel-attach" aria-label={`${c.attachments.length} Doctrine attached`}>+{c.attachments.length}</span>}
{blockMode && side === 'theirs' && blockedBy(c.id) && <span className="duel-pair" aria-hidden="true">{cards.get(blockedBy(c.id)!)?.title}</span>}
</div>) : <span className="duel-empty">No permanents</span>}
</div>;
};
// ---------- primary action ----------
const nAtt = decl.attackers.length, nBlk = Object.keys(decl.blocks).length;
let note: ReactNode = view.log.at(-1) ?? '';
let primary: { label: string; run: () => void; disabled?: boolean } | null = null;
let secondary: { label: string; run: () => void } | null = null;
if (view.phase === 'over') {
// The engine's own game-over sentence (DUEL_DESIGN §8.2); the board never writes story text itself.
note = <span><b>{view.winner === 'draw' ? 'Draw.' : view.winner === view.seat ? 'You won.' : 'You lost.'}</b> {view.log.at(-1)}</span>;
primary = onRecap ? { label: 'Battle recap', run: onRecap } : onExit ? { label: 'Done', run: onExit } : null;
if (onRecap && onExit) secondary = { label: 'Done', run: onExit };
} else if (busy) {
note = <><LoaderCircle className="spin" size={14} /> {mine ? 'Resolving…' : `${view.opponent.name} is choosing…`}</>;
} else if (legal.mulligan) {
note = 'Keep this hand, or mulligan once: shuffle, draw 7, put 1 on the bottom.';
primary = { label: 'Keep hand', run: () => onAct({ type: 'mulligan', keep: true }) };
secondary = { label: 'Mulligan', run: () => onAct({ type: 'mulligan', keep: false }) };
} else if (targeting) {
const c = cards.get(targeting.cardId);
note = <>{targeting.chosen.length ? 'Now choose the next target' : 'Choose a target'} for <b>{c?.title}</b>.</>;
secondary = { label: 'Cancel', run: () => setTargeting(undefined) };
} else if (attackMode) {
note = nAtt ? `${nAtt} attacking. Tap a Figure to add or remove it.` : legal.attackers.length ? 'Tap Figures to attack with them.' : 'No Figure can attack.';
primary = { label: nAtt ? `Attack with ${nAtt}` : 'No attack', run: () => (nAtt ? setSheet({ kind: 'combat', attacks: pendingAttacks, mode: 'attack' }) : onAct({ type: 'attack', attackerIds: [] })) };
} else if (blockMode) {
note = decl.picked ? <>Now tap the attacker <b>{cards.get(decl.picked)?.title}</b> blocks.</> : `${view.combat.length} attacking. Tap your Figure, then the attacker it blocks.`;
primary = { label: nBlk ? `Review ${nBlk} block${nBlk > 1 ? 's' : ''}` : 'Review: no blocks', run: () => setSheet({ kind: 'combat', attacks: pendingAttacks, mode: 'block' }) };
} else if (mine && view.phase === 'main') {
note = Object.keys(legal.plays).length ? 'Tap a card in your hand to read or play it.' : note;
if (legal.canGoToCombat && legal.attackers.length) { primary = { label: 'Combat', run: () => onAct({ type: 'toCombat' }) }; secondary = legal.canEndTurn ? { label: 'End turn', run: () => onAct({ type: 'endTurn' }) } : null; }
else if (legal.canEndTurn) primary = { label: 'End turn', run: () => onAct({ type: 'endTurn' }) };
} else if (mine && legal.canEndTurn) {
primary = { label: 'End turn', run: () => onAct({ type: 'endTurn' }) };
} else if (!mine) {
note = <><LoaderCircle className="spin" size={14} /> {view.opponent.name}’s turn.</>;
}
const outcome = sheet?.kind === 'combat' ? previewCombat(sheet.attacks, cards) : null;
return <section className="duel" aria-label={`Duel against ${view.opponent.name}`}>
<header className="duel-bar">
<span className="duel-turn">Turn <b>{view.turn}</b> · {PHASE_LABEL[view.phase]}{view.active !== view.seat && view.phase !== 'over' ? ` · ${view.opponent.name}` : ''}</span>
{view.clock && view.phase !== 'over' && <span className={`duel-clock ${view.clock.turn <= 10 ? 'low' : ''}`} aria-label={`${view.clock.turn} seconds left this turn, ${view.clock.bank} in the bank`}><Timer size={13} aria-hidden="true" />{view.clock.turn}s<small>+{Math.floor(view.clock.bank / 60)}:{String(view.clock.bank % 60).padStart(2, '0')}</small></span>}
<button className="icon-button duel-log-button" onClick={() => setSheet({ kind: 'log' })} aria-label="Match log"><ScrollText size={16} /></button>
{view.phase !== 'over' && <button className="icon-button" onClick={() => setSheet({ kind: 'concede' })} aria-label="Concede match"><Flag size={16} /></button>}
</header>
<div className="duel-main">
<div className="duel-field">
<SideBar side={view.opponent} who="opponent" active={view.active !== view.seat} target={targets?.has(playerTarget(oppSeat))} onTarget={() => chooseTarget(playerTarget(oppSeat))} />
{row(view.opponent.battlefield, 'theirs')}
<button className="duel-ticker" onClick={() => setSheet({ kind: 'log' })} aria-label="Open match log">
{(attackMode || blockMode) && <span className="duel-ticker-phase">{attackMode ? <Swords size={12} /> : <Shield size={12} />}</span>}
<span>{view.log.at(-1) ?? 'The match began.'}</span>
</button>
{row(view.me.battlefield, 'mine')}
<SideBar side={view.me} who="me" active={view.active === view.seat} target={targets?.has(playerTarget(view.seat))} onTarget={() => chooseTarget(playerTarget(view.seat))} />
</div>
<aside className="duel-log-aside" aria-label="Match log">
<h3>Log</h3>
<ol ref={logRef} className="duel-log">{view.log.map((l, i) => <li key={i}>{l}</li>)}</ol>
</aside>
</div>
<div className="duel-dock">
<div className="duel-hand-wrap">
<div ref={handRef} className={`duel-hand ${hiddenRight ? 'has-more' : ''}`} aria-label={`Your hand, ${view.hand.length} cards`}>
{view.hand.length ? view.hand.map(c => {
const playable = !!legal.plays[c.id] && !busy;
return <DuelCardFace key={c.id} card={c} size="hand" state={{ dim: !playable || !!targeting, selected: targeting?.cardId === c.id }}
onClick={() => setSheet({ kind: 'card', card: c, where: 'hand' })} />;
}) : <span className="duel-empty">No cards in hand.</span>}
</div>
{hiddenRight > 0 && <button type="button" className="duel-hand-more" aria-label={`${hiddenRight} more cards in hand: scroll right`} onClick={() => handRef.current?.scrollBy({ left: handRef.current.clientWidth * 0.8, behavior: 'smooth' })}>+{hiddenRight}</button>}
</div>
<p className="duel-note" role="status" aria-live="polite">{error ? <span className="dock-error">{error}</span> : note}</p>
<div className="duel-actions">
{secondary && <button className="button outline" onClick={secondary.run}>{secondary.label}</button>}
{primary && <button className="button dark duel-primary" onClick={primary.run} disabled={primary.disabled}>{primary.label}</button>}
</div>
</div>
{sheet && <div className="sheet-backdrop" onClick={e => { if (e.target === e.currentTarget) setSheet(null); }}>
<div className={`sheet duel-sheet ${sheet.kind}`} role="dialog" aria-modal="true" aria-label={sheet.kind === 'card' ? sheet.card.title : sheet.kind === 'log' ? 'Match log' : sheet.kind === 'combat' ? 'Combat preview' : 'Concede'}>
<button className="modal-close" onClick={() => setSheet(null)} aria-label="Close"><X size={18} /></button>
{sheet.kind === 'card' && <>
<DuelCardFace card={sheet.card} size="zoom" refNumber={sheet.card.url ? refs.get(sheet.card.url) : undefined} />
<p className="muted small duel-sheet-meta">{sheet.where === 'theirs' ? `${view.opponent.name}’s card` : sheet.where === 'hand' ? 'In your hand' : 'Your card'}
{sheet.card.tapped ? ' · tapped' : ''}{sheet.card.pending ? ' · Pending review (can’t attack this turn)' : ''}{sheet.card.damage ? ` · ${sheet.card.damage} damage marked` : ''}</p>
{sheet.card.connectedNote && <p className="small duel-sheet-meta">Connected: {sheet.card.connectedNote}</p>}
{sheet.where === 'hand' && <div className="play-actions">
{legal.plays[sheet.card.id] && !busy
? <button className="button dark" onClick={() => startPlay(sheet.card)}>{targetsComplete(legal.plays[sheet.card.id], []) ? `Play for ${sheet.card.cost}` : `Play for ${sheet.card.cost}, then choose a target`}</button>
: <p className="muted small">{!mine ? 'You can play cards on your turn.' : view.phase !== 'main' ? 'Cards are played in your main phase.' : sheet.card.cost > view.me.citations ? `Needs ${sheet.card.cost} Citations; you have ${view.me.citations}.` : 'No legal target.'}</p>}
</div>}
</>}
{sheet.kind === 'combat' && outcome && <>
<h3>{sheet.mode === 'attack' ? 'Declare attackers' : 'Declare blockers'}</h3>
<ul className="duel-preview">
{outcome.rows.map(r => <li key={r.attacker.id}>
<span className={r.attackerDies ? 'gone' : ''}>{r.attacker.title} <small>{r.attacker.power}/{r.attacker.toughness}</small></span>
<span className="vs">{r.blocker ? 'blocked by' : sheet.mode === 'attack' ? '→' : 'unblocked →'}</span>
{r.blocker ? <span className={r.blockerDies ? 'gone' : ''}>{r.blocker.title} <small>{r.blocker.power}/{r.blocker.toughness}</small></span>
: <span>{sheet.mode === 'attack' ? view.opponent.name : 'you'} −{r.attacker.power ?? 0}</span>}
</li>)}
</ul>
<p className="muted small">{sheet.mode === 'attack'
? `If unblocked: ${outcome.toPlayer} damage to ${view.opponent.name} (${view.opponent.notability} → ${Math.max(0, view.opponent.notability - outcome.toPlayer)}). ${view.opponent.name} chooses blocks next.`
: `You take ${outcome.toPlayer} (${view.me.notability} → ${Math.max(0, view.me.notability - outcome.toPlayer)}).${outcome.destroyed.length ? ` Struck through: destroyed.` : ''}`}</p>
<div className="play-actions">
<button className="button outline" onClick={() => setSheet(null)}>Change</button>
<button className="button dark" onClick={() => { setSheet(null); onAct(sheet.mode === 'attack' ? { type: 'attack', attackerIds: decl.attackers } : { type: 'block', blocks: blockList(decl) }); }}>
{sheet.mode === 'attack' ? <><Swords size={15} /> Confirm attack</> : <><Shield size={15} /> Confirm blocks</>}
</button>
</div>
</>}
{sheet.kind === 'log' && <><h3>Match log</h3>
<ol className="duel-log full">{view.log.map((l, i) => <li key={i}>{l}</li>)}</ol></>}
{sheet.kind === 'concede' && <><h3>Concede this match?</h3><p className="muted">It counts as a loss. Nothing on-chain changes.</p>
<div className="play-actions"><button className="button outline" onClick={() => setSheet(null)}>Keep playing</button>
<button className="button dark" onClick={() => { setSheet(null); onAct({ type: 'concede' }); }}><Flag size={15} /> Concede</button></div></>}
</div>
</div>}
</section>;
}
+109
View File
@@ -0,0 +1,109 @@
// duel-core (shared/duel) ↔ the board's view model. The only file that knows engine shapes.
import type { DuelAction, LogEvent, PermanentView, PlayerView, Seat, TargetRef } from './contract.ts';
import { boardCard, type ArticleBits } from './cards.ts';
import type { Attack, BoardCard, BoardView, DuelUIAction, Legal, SideView } from './model.ts';
import { NO_LEGAL } from './model.ts';
export const targetId = (t: TargetRef) => (t.kind === 'card' ? t.uid : `player:${t.seat}`);
const targetRef = (id: string): TargetRef => (id.startsWith('player:') ? { kind: 'player', seat: Number(id.slice(7)) as Seat } : { kind: 'card', uid: id });
export type Articles = Record<string, ArticleBits | undefined>;
function permanentCard(p: PermanentView, all: PermanentView[], articles: Articles): BoardCard {
const keywords: string[] = [...p.keywords];
if (p.connected) keywords.push('Connected');
return boardCard(p.card, articles[p.card.cardId], {
id: p.uid, power: p.card.type === 'Figure' || (p.card.toughness ?? 0) > 0 ? p.power : undefined,
toughness: p.card.type === 'Figure' || (p.card.toughness ?? 0) > 0 ? p.toughness : undefined,
keywords, tapped: p.tapped, pending: p.card.type === 'Figure' && p.sick, damage: p.damage || undefined,
attachedTo: p.attachedTo, attachments: all.filter(x => x.attachedTo === p.uid).map(x => x.uid), token: p.card.token,
connectedNote: p.connected ? `${p.connected.tier} (${p.connected.via}): +${p.connected.bonus}/+${p.connected.bonus}` : undefined,
});
}
export function boardFromView(v: PlayerView, names: [string, string], log: string[], articles: Articles = {}, clock?: BoardView['clock']): BoardView {
const opp = (1 - v.seat) as Seat;
const side = (s: PlayerView['opponent'], name: string, seat: Seat): SideView => ({
name, notability: s.life, citations: s.citations, maxCitations: s.maxCitations, library: s.librarySize, hand: s.handSize,
battlefield: v.battlefield.filter(p => p.controller === seat).map(p => permanentCard(p, v.battlefield, articles)), graveyard: s.graveyard.length,
});
const blockerOf = Object.fromEntries(Object.entries(v.combat.blocks).map(([b, a]) => [a, b]));
const combat: Attack[] = v.combat.attackers.map(a => ({ attackerId: a, blockerId: blockerOf[a] }));
return {
seat: v.seat, turn: v.turn, active: v.active, phase: v.phase,
me: side(v.you, names[v.seat], v.seat), opponent: side(v.opponent, names[opp], opp),
hand: v.you.hand.map(i => boardCard(i.card, articles[i.card.cardId], { id: i.uid })),
combat, log, winner: v.result ? (v.result.winner ?? 'draw') : undefined, clock,
};
}
export function legalFromActions(actions: DuelAction[]): Legal {
if (!actions.length) return NO_LEGAL;
const legal: Legal = { plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false };
for (const a of actions) {
switch (a.type) {
case 'play': (legal.plays[a.uid] ??= []).push((a.targets ?? []).map(targetId)); break;
case 'endPhase': legal.canGoToCombat = true; legal.canEndTurn = true; break;
case 'toggleAttacker': legal.attackers.push(a.uid); break;
case 'confirmAttack': legal.canEndTurn = true; break;
case 'block': (legal.blockers[a.blocker] ??= []).push(a.attacker); break;
case 'keep': case 'mulligan': legal.mulligan = true; break;
}
}
return legal;
}
/**
* One board intent → duel-core's atomic actions, in send order. Single-step intents return the exact
* element of `legal` (so the host's deep-equal check passes); declarations are staged on the board and
* sent here as toggle/block × N then confirm (DUEL_API: declarations are monotonic).
*/
export function expand(ui: DuelUIAction, legal: DuelAction[]): DuelAction[] {
const find = (pred: (a: DuelAction) => boolean) => legal.find(pred);
switch (ui.type) {
case 'mulligan': return [ui.keep ? { type: 'keep' } : { type: 'mulligan' }];
case 'play': {
const want = ui.targetIds.join('|');
const a = find(x => x.type === 'play' && x.uid === ui.cardId && (x.targets ?? []).map(targetId).join('|') === want);
return a ? [a] : [{ type: 'play', uid: ui.cardId, ...(ui.targetIds.length ? { targets: ui.targetIds.map(targetRef) } : {}) }];
}
case 'toCombat': return [{ type: 'endPhase' }];
case 'endTurn': return find(x => x.type === 'endPhase') ? [{ type: 'endPhase' }, { type: 'confirmAttack' }] : [{ type: 'confirmAttack' }];
case 'attack': return [...ui.attackerIds.map(uid => ({ type: 'toggleAttacker', uid }) as DuelAction), { type: 'confirmAttack' }];
case 'block': return [...ui.blocks.map(b => ({ type: 'block', blocker: b.blockerId, attacker: b.attackerId }) as DuelAction), { type: 'confirmBlocks' }];
case 'concede': return [{ type: 'concede' }];
}
}
/**
* Fallback log text, used only until duel-design's story renderer (shared/duel/story, DUEL_DESIGN §8.2)
* can read engine events. First variant of each §8.2 template, real card and match data only.
*/
export function plainLog(events: LogEvent[], names: [string, string]): string[] {
const out: string[] = [];
for (const e of events) {
const n = (s: Seat) => names[s];
switch (e.kind) {
case 'turnStart': out.push(`Turn ${e.turn}.`); break;
case 'mulligan': out.push(`${n(e.seat)} took a mulligan.`); break;
case 'deploy': out.push(`${n(e.seat)} deployed ${e.card.title}.`); break;
case 'cast': out.push(`${n(e.seat)} cited ${e.card.title}.`); break;
case 'adopt': out.push(`${e.to.title} adopted ${e.card.title}.`); break;
case 'tokenCreated': out.push(`${e.source.title} created ${e.card.title}.`); break;
case 'attack': out.push(`${e.attackers.map(a => `${a.title} (${a.power}/${a.toughness})`).join(', ')} attacked.`); break;
case 'block': for (const b of e.blocks) out.push(`${b.blocker.title} blocked ${b.attacker.title}.`); break;
case 'playerDamage': out.push(`${n(e.seat)} lost ${e.amount} Notability (${e.life} remaining).`); break;
case 'lifeGain': out.push(`${n(e.seat)} gained ${e.amount} Notability (${e.life}).`); break;
case 'destroyed': out.push(`${e.card.title} was moved to Deleted.`); break;
case 'bounced': out.push(`${e.card.title} was returned to ${n(e.owner)}'s hand.`); break;
case 'connected': out.push(`${e.card.title} was Connected to ${e.with.title} (${e.tier}).`); break;
case 'concede': out.push(`${n(e.seat)} withdrew.`); break;
case 'gameOver': out.push(e.winner === null ? `The match ended in a draw on turn ${e.turn}.`
: e.reason === 'life' ? `${n((1 - e.winner) as Seat)} was nominated for deletion. The result was delete.`
: e.reason === 'library' ? `${n((1 - e.winner) as Seat)} could not draw a card and lost.`
: `${n(e.winner)} won on turn ${e.turn}.`); break;
default: break;
}
}
return out;
}
+83
View File
@@ -0,0 +1,83 @@
// View-only fallback duel bots for the browser bot match. They see only `viewFor` output (Night 1 rule, #5).
// sim-balance owns the real duel bots (shared/bots/duel-bots.ts); these are swapped for its heuristic
// once a PlayerView lens exists (#64). Deterministic given the rng.
import type { DuelAction, PermanentView, PlayerView, Seat } from './contract.ts';
import type { DuelBot } from './decks.ts';
const value = (p: PermanentView) => p.power + p.toughness + p.keywords.length;
const opp = (s: Seat) => (1 - s) as Seat;
function chooseNormal(v: PlayerView, legal: DuelAction[], rng: () => number): DuelAction {
const me = v.seat, them = opp(me);
const mine = v.battlefield.filter(p => p.controller === me), theirs = v.battlefield.filter(p => p.controller === them);
const find = <T extends DuelAction['type']>(t: T) => legal.filter((a): a is Extract<DuelAction, { type: T }> => a.type === t);
if (find('keep').length) return find('keep')[0];
const plays = find('play');
if (plays.length) {
const hand = new Map(v.you.hand.map(i => [i.uid, i.card]));
// Prefer the most expensive card. Targets: harmful effects (damage, destroy, bounce, tap, fight, a
// negative pump) aim at the opponent's side; everything else (pumps, Adopt) at ours.
const owner = (uid: string) => v.battlefield.find(p => p.uid === uid)?.controller;
const harmful = (effects: unknown[]) => effects.some(e => {
const x = e as { op?: string; power?: number; amount?: number };
return ['damage', 'damageEach', 'destroy', 'bounce', 'tap', 'fight', 'drain'].includes(x.op ?? '') || (x.op === 'pump' && ((x.power ?? x.amount ?? 0) < 0));
});
const score = (a: Extract<DuelAction, { type: 'play' }>) => {
const c = hand.get(a.uid);
if (!c) return -1;
const hostile = harmful(c.effects);
let s = c.cost * 10 + rng();
for (const t of a.targets ?? []) s += ((t.kind === 'card' ? owner(t.uid) : t.seat) === them) === hostile ? 3 : -3;
return s;
};
return plays.reduce((b, a) => (score(a) > score(b) ? a : b));
}
const toggles = find('toggleAttacker');
if (toggles.length || find('confirmAttack').length) {
const blockers = theirs.filter(p => !p.tapped && (p.card.type === 'Figure' || p.toughness > 0));
const ready = mine.filter(p => v.combat.attackers.includes(p.uid) || toggles.some(t => t.uid === p.uid));
const lethal = ready.map(p => p.power).sort((a, b) => b - a).slice(blockers.length).reduce((t, x) => t + x, 0) >= v.opponent.life;
const want = toggles.find(t => {
const c = mine.find(p => p.uid === t.uid)!;
if (v.combat.attackers.includes(c.uid)) return false;
if (lethal) return true;
return c.power > 0 && !blockers.some(b => b.power >= c.toughness && b.toughness > c.power);
});
return want ?? find('confirmAttack')[0] ?? legal[0];
}
const blocks = find('block');
if (blocks.length || find('confirmBlocks').length) {
const used = new Set(Object.keys(v.combat.blocks)), covered = new Set(Object.values(v.combat.blocks));
const incoming = v.combat.attackers.filter(a => !covered.has(a)).reduce((t, a) => t + (theirs.find(p => p.uid === a)?.power ?? 0), 0);
const lethal = incoming >= v.you.life;
let best: DuelAction | undefined, bestScore = 0;
for (const b of blocks) {
if (used.has(b.blocker) || covered.has(b.attacker)) continue;
const B = mine.find(p => p.uid === b.blocker), A = theirs.find(p => p.uid === b.attacker);
if (!A || !B) continue;
const kills = B.power >= A.toughness, dies = A.power >= B.toughness;
const s = kills && !dies ? 10 + value(A) : kills ? (value(A) > value(B) ? 5 : lethal ? 3 : 0) : !dies ? 2 : lethal ? 1 : 0;
if (s > bestScore) { bestScore = s; best = b; }
}
return best ?? find('confirmBlocks')[0] ?? legal[0];
}
return find('endPhase')[0] ?? legal[0];
}
/** Chance that Easy makes a random legal move (never concede) instead of Normal's. */
export const EASY_BLUNDER_RATE = 0.3;
export const NORMAL_BOT: DuelBot = { name: 'Normal', choose: chooseNormal };
export const EASY_BOT: DuelBot = {
name: 'Easy',
choose(v, legal, rng) {
if (rng() < EASY_BLUNDER_RATE) return legal[Math.floor(rng() * legal.length)];
return chooseNormal(v, legal, rng);
},
};
export const DUEL_BOTS: DuelBot[] = [EASY_BOT, NORMAL_BOT];
+50
View File
@@ -0,0 +1,50 @@
// DuelCard (duel-cards, shared/duel/derive.ts) → BoardCard. Declared structurally so this file doesn't
// depend on an unmerged branch; once shared/duel/derive.ts is on the integration branch, `DuelCardLike`
// can become `DuelCard` with no other change.
import type { BoardCard, DuelCardType, Portal } from './model.ts';
import { firstSentence } from './model.ts';
export type DuelCardLike = {
cardId: string; pageId: number | null; revisionId?: number; title: string; type: DuelCardType; subtype?: string | null;
description?: string; token?: boolean;
portal: Portal; cost: number; power: number | null; toughness: number | null; keywords: readonly string[];
rulesText: string; flavor: string;
};
/** What the chain (not the derivation) knows about the card's article: art and link. */
export type ArticleBits = { image?: string; url?: string; extract?: string };
export const articleUrl = (title: string) => `https://en.wikipedia.org/wiki/${encodeURIComponent(title.replace(/ /g, '_'))}`;
const SUBTYPE_LABEL: Record<string, string> = {
organisation: 'Organisation', work: 'Work', sport: 'Sport', election: 'Election', conflict: 'Conflict', disaster: 'Disaster',
period: 'Period', mathematics: 'Mathematics', pathology: 'Pathology', language: 'Language', ideology: 'Ideology', team: 'Team', vehicle: 'Vehicle',
};
/** "(1909–1994)", "(born 1963)", "(c.1872–1919)" in the description → "1909–1994", "1963–", "1872–1919". */
export function lifespan(text: string | undefined): string | undefined {
const m = text?.match(/\((?:c\.\s?)?(\d{3,4})\s?[–-]\s?(?:c\.\s?)?(\d{3,4})(?!\d)[^)]*\)|\(born (\d{3,4})\)/);
if (!m) return undefined;
return m[3] ? `${m[3]}–` : `${m[1]}–${m[2]}`;
}
/** The part after the em dash: "History · 1530–1537", "Society · Election". */
export function subtypeLine(card: Pick<DuelCardLike, 'type' | 'subtype' | 'portal' | 'flavor'>): string {
const extra = card.type === 'Figure' ? lifespan(card.flavor) : card.subtype ? SUBTYPE_LABEL[card.subtype] : undefined;
return extra ? `${card.portal} · ${extra}` : card.portal;
}
export function boardCard(card: DuelCardLike, article: ArticleBits = {}, live: Partial<BoardCard> = {}): BoardCard {
// Figures show P/T; Locations only when they have a Garrison (0/T); other types never.
const body = card.type === 'Figure' || (card.type === 'Location' && (card.toughness ?? 0) > 0);
const power = body ? card.power ?? 0 : undefined, toughness = body ? card.toughness ?? 0 : undefined;
return {
id: card.cardId, title: card.title, type: card.type,
subtype: subtypeLine(card),
portal: card.portal, cost: card.cost, power, toughness, basePower: power, baseToughness: toughness,
keywords: [...card.keywords], rulesText: card.rulesText,
flavour: firstSentence(card.flavor || article.extract || card.description),
// Tokens are not articles: no link.
image: article.image, url: card.token ? undefined : article.url ?? articleUrl(card.title), revisionId: card.revisionId, token: card.token,
...live,
};
}
+146
View File
@@ -0,0 +1,146 @@
/**
* The part of duel-core's contract (shared/duel/types.ts and index.ts, PR #72 at 7904199) that the
* board uses, mirrored so this PR doesn't stack on #72 (HANDBOOK: stub the interface). Field names
* and unions are copied verbatim; engine-only details are widened to `unknown`, so real engine values
* are assignable here. When #72 is on night/2026-11-17 this file becomes re-exports of shared/duel.
*/
export type Seat = 0 | 1;
export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
export type Keyword = 'Protected' | 'Featured' | 'Legacy' | 'Multilingual' | 'Translated' | 'Well-sourced' | 'Stub' | 'Local' | 'Trending';
export type ConnectedTier = 'Linked' | 'Compatriot' | 'Contemporary' | 'Kin';
export type Phase = 'mulligan' | 'main' | 'attack' | 'block' | 'over';
export type EndReason = 'life' | 'library' | 'concede' | 'timeout' | 'turnCap';
export interface DuelCard {
cardId: string;
pageId: number | null;
revisionId?: number;
title: string;
description?: string;
type: CardType;
subtype?: string | null;
portal: Portal;
cost: number;
power: number | null;
toughness: number | null;
keywords: Keyword[];
territory?: number;
effects: unknown[];
rulesText: string;
flavor: string;
connect?: unknown;
rarity?: 'Common' | 'Rare' | 'Epic' | 'Legendary';
deriveVersion?: string;
token?: boolean;
}
/** Only deckSize is read here; the engine validates the rest. */
export interface DuelRulesetLike { deckSize: number }
export interface CardInstance { uid: string; owner: Seat; card: DuelCard }
export interface CombatState { attackers: string[]; blocks: Record<string, string> }
export interface DuelResult { winner: Seat | null; reason: EndReason }
export type TargetRef = { kind: 'card'; uid: string } | { kind: 'player'; seat: Seat };
export type DuelAction =
| { type: 'keep' }
| { type: 'mulligan' }
| { type: 'play'; uid: string; targets?: TargetRef[] }
| { type: 'endPhase' }
| { type: 'toggleAttacker'; uid: string }
| { type: 'confirmAttack' }
| { type: 'block'; blocker: string; attacker: string }
| { type: 'confirmBlocks' }
| { type: 'concede' }
| { type: 'timeout' };
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] }
| { kind: 'draw'; seat: Seat; card?: CardRef }
| { kind: 'deploy'; seat: Seat; card: CardRef }
| { kind: 'cast'; seat: Seat; card: CardRef; targets: TargetRef[] }
| { 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 }
| { kind: 'rivalry'; card: CardRef; with: CardRef; tier: ConnectedTier; via: string }
| { kind: 'effect'; seat: Seat; source: CardRef; op: string; template?: string; targets: TargetRef[] }
| { kind: 'attack'; seat: Seat; attackers: CardRef[] }
| { kind: 'block'; seat: Seat; blocks: { blocker: CardRef; attacker: CardRef }[] }
| { kind: 'effectDamage'; source: CardRef; target: CardRef; amount: number }
| { kind: 'combatDamage'; source: CardRef; target: CardRef; amount: number }
| { 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 interface PermanentView {
uid: string;
owner: Seat;
controller: Seat;
card: DuelCard;
tapped: boolean;
sick: boolean;
damage: number;
counters: number;
attachedTo?: string;
power: number;
toughness: number;
keywords: Keyword[];
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;
toAct: Seat | null;
you: SideView & { hand: CardInstance[] };
opponent: SideView;
battlefield: PermanentView[];
combat: CombatState;
result: DuelResult | null;
version: number;
rules: unknown;
}
/**
* The slice of `DuelEngineApi` (shared/duel/index.ts) the bot match calls. Method syntax on purpose:
* the real engine (typed on the full DuelState/DuelRuleset/DuelCard) is assignable to it.
*/
export interface DuelEngineLike<S = unknown, R = unknown> {
createDuel(rules: R, decks: [DuelCard[], DuelCard[]], seed: string): S;
legalActions(state: S, seat: Seat): DuelAction[];
applyAction(state: S, seat: Seat, action: DuelAction): S;
toAct(state: S): Seat | null;
isOver(state: S): boolean;
viewFor(state: S, seat: Seat): PlayerView;
logFor(state: S, seat: Seat): LogEvent[];
}
+44
View File
@@ -0,0 +1,44 @@
// Local (in-browser) match driver, engine-agnostic. ./adapter.ts binds it to duel-core's shared/duel.
// The bot gets only its own seat's view (viewFor), never the full state (Night 1 rule, #5).
import type { BoardView, DuelUIAction, Legal, Seat } from './model.ts';
/** The engine as the board needs it. `A` is the engine's atomic action; `S` its state. */
export interface DuelEnginePort<S, A> {
legal(s: S, seat: Seat): A[];
apply(s: S, seat: Seat, a: A): S;
/** Whose input the engine is waiting for, or null when the match is over. */
toAct(s: S): Seat | null;
board(s: S, seat: Seat, names: [string, string]): BoardView;
legalForBoard(actions: A[], view: BoardView): Legal;
/** One board-level intent → the engine's atomic actions, in order. Each must be legal when sent. */
expand(ui: DuelUIAction, actions: A[], view: BoardView): A[];
}
export type BotChoose<S, A> = (s: S, seat: Seat, legal: A[], rng: () => number) => A;
/** Applies a sequence for one seat, re-checking legality at every step. Throws on the first illegal action. */
export function applySequence<S, A>(port: DuelEnginePort<S, A>, s: S, seat: Seat, seq: A[], same: (a: A, b: A) => boolean): S {
for (const a of seq) {
const legal = port.legal(s, seat);
if (!legal.some(l => same(l, a))) throw new Error('That move is no longer legal.');
s = port.apply(s, seat, a);
}
return s;
}
/** Runs bot moves until the human must act or the match ends. Bounded, so a broken bot can't hang the tab. */
export function runBot<S, A>(port: DuelEnginePort<S, A>, s: S, human: Seat, choose: BotChoose<S, A>, rng: () => number, maxSteps = 500): S {
const bot = (human === 0 ? 1 : 0) as Seat;
for (let i = 0; i < maxSteps; i++) {
if (port.toAct(s) !== bot) return s;
const legal = port.legal(s, bot);
if (!legal.length) return s;
s = port.apply(s, bot, choose(s, bot, legal, rng));
}
return s;
}
/** Stable structural equality for plain JSON actions. */
export const sameAction = (a: unknown, b: unknown): boolean => stable(a) === stable(b);
const stable = (v: unknown): string => JSON.stringify(v, (_k, x) =>
x && typeof x === 'object' && !Array.isArray(x) ? Object.fromEntries(Object.entries(x).sort(([p], [q]) => p.localeCompare(q))) : x);
+40
View File
@@ -0,0 +1,40 @@
// Pure deck helpers for the bot match (no React, no CSS), so they are unit-tested under Node.
import type { DuelAction, DuelCard, PlayerView } from './contract.ts';
/** A collection card as ui-pvp passes it (ownership's ChainCard satisfies this). `duel` is the server-derived frozen profile. */
export type BotMatchCard = { tokenId: string; title: string; url?: string; imageUrl?: string; extract?: string; duel?: unknown };
const TYPES = ['Figure', 'Location', 'Event', 'Institution', 'Doctrine'];
/** Shape check for a profile that arrives untyped over the wire (the engine's validateDeck does the rest). */
export function isDuelCard(v: unknown): v is DuelCard {
const c = v as Partial<DuelCard> | null;
return !!c && typeof c === 'object' && typeof c.title === 'string' && TYPES.includes(c.type as string) && typeof c.cost === 'number'
&& Array.isArray(c.keywords) && Array.isArray(c.effects) && typeof c.rulesText === 'string';
}
/** The bot sees only its own seat's view (Night 1 rule, #5). */
export type DuelBot = { name: string; choose(view: PlayerView, legal: DuelAction[], rng: () => number): DuelAction };
export function mulberry(seed: number) {
return () => { seed = (seed + 0x6d2b79f5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
}
export const hash = (s: string) => { let h = 2166136261; for (const c of s) h = Math.imul(h ^ c.charCodeAt(0), 16777619); return h >>> 0; };
/** The bot's own deck: `size` distinct cards from a pool (the 236 real sample cards), seeded, within the copy limit. */
export function botDeck(pool: readonly DuelCard[], size: number, seed: string): DuelCard[] {
const rng = mulberry(hash(`bot-deck:${seed}`));
const shuffled = [...pool].sort((a, b) => a.cardId.localeCompare(b.cardId));
for (let i = shuffled.length - 1; i > 0; i--) { const j = Math.floor(rng() * (i + 1)); [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]; }
return shuffled.slice(0, size).map(c => ({ ...c, cardId: `bot:${c.cardId}` }));
}
/** Resolves the player's deck: exactly `deckSize` owned cards, each with a frozen profile. Returns problems instead of a partial deck. */
export function playerDeck(deck: string[], cards: BotMatchCard[], deckSize: number): { cards: DuelCard[]; pending: string[]; missing: string[] } {
const byId = new Map(cards.map(c => [c.tokenId, c]));
const out: DuelCard[] = [], pending: string[] = [], missing: string[] = [];
for (const id of deck) {
const c = byId.get(id);
if (!c) missing.push(id); else if (!isDuelCard(c.duel)) pending.push(c.title); else out.push({ ...c.duel, cardId: id });
}
return { cards: out.length === deckSize && deck.length === deckSize ? out : [], pending, missing };
}
+167
View File
@@ -0,0 +1,167 @@
/* Duel board (ui-duel, #58). Mobile-first: everything must read at 360 × 740 with a full 5 + 5 board.
Portals take MTG colour analogues: Arts red, Earth green, History black, Science blue, Society white. */
.duel{--gap:6px;display:flex;flex-direction:column;gap:var(--gap);max-width:1180px;margin:0 auto;padding:6px 8px 0;color:var(--ctp-text);background:var(--ctp-mantle);border:1px solid var(--theme-border);border-radius:12px;min-height:min(100dvh,980px);font-size:13px}
.duel button{font:inherit;color:inherit;cursor:pointer}
.duel-bar{display:flex;align-items:center;gap:6px;min-height:36px}
.duel-turn{font-size:12px;color:var(--ctp-subtext1);margin-right:auto;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.duel-clock{display:inline-flex;align-items:center;gap:3px;font-size:12px;font-variant-numeric:tabular-nums;color:var(--ctp-subtext1)}
.duel-clock small{color:var(--ctp-overlay1);font-size:10px}
.duel-clock.low{color:var(--ctp-red)}
.duel .icon-button{min-width:36px;min-height:36px}
.duel-main{display:flex;gap:10px;flex:1 1 auto;min-height:0}
.duel-field{display:flex;flex-direction:column;gap:var(--gap);flex:1 1 auto;min-width:0}
/* Player bars: Notability, Citations, library and hand are always visible. */
.duel-side{display:flex;align-items:center;gap:10px;padding:5px 8px;border-radius:8px;background:var(--ctp-base);border:1px solid var(--ctp-surface0);font-size:12px;font-variant-numeric:tabular-nums}
.duel-side.is-target{width:100%;text-align:left;box-shadow:0 0 0 2px var(--ctp-yellow);animation:dface-pulse 1.1s ease-in-out infinite}
.duel-side.is-active{border-color:var(--theme-accent);box-shadow:inset 3px 0 0 var(--theme-accent)}
.duel-side-name{font-weight:700;margin-right:auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.duel-stat{display:inline-flex;align-items:center;gap:3px;color:var(--ctp-subtext1)}
.duel-stat b{font-size:15px;color:var(--ctp-text)}
.duel-stat small{color:var(--ctp-overlay1)}
.duel-stat.life svg{color:var(--ctp-yellow)}
.duel-stat.life.low b{color:var(--ctp-red)}
.duel-stat.cites svg{color:var(--ctp-blue)}
/* Battlefields: one scrollable row per side; 5 cards fit 344 px without scrolling. */
.duel-row{display:flex;gap:4px;overflow-x:auto;overscroll-behavior-x:contain;scrollbar-width:none;min-height:102px;padding:4px 0;align-items:flex-start}
.duel-zoomgrid .dface-zoom{align-self:start}
.duel-row::-webkit-scrollbar{display:none}
.duel-row.theirs{align-items:flex-end}
.duel-slot{position:relative;display:flex;flex-direction:column;align-items:stretch;flex:1 1 0;min-width:62px;max-width:110px}
.duel-empty{flex:1;align-self:center;text-align:center;font-size:12px;color:var(--ctp-overlay1);padding:8px}
.duel-attach{position:absolute;top:-5px;right:-3px;z-index:3;font-size:12px;font-weight:800;padding:1px 5px;border-radius:8px;background:var(--ctp-mauve);color:var(--ctp-crust)}
.duel-pair{font-size:9px;line-height:1.2;color:var(--ctp-green);text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin-top:2px}
.duel-ticker{display:flex;align-items:center;gap:6px;width:100%;min-height:36px;padding:6px 10px;border-radius:8px;background:var(--ctp-crust);border:1px dashed var(--ctp-surface1);text-align:left;font-size:12px;line-height:1.35;color:var(--ctp-subtext1)}
.duel-ticker>span:last-child{overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
.duel-ticker-phase{display:inline-flex;color:var(--theme-accent);flex:0 0 auto}
.duel-log-aside{display:none}
.duel-log{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px;font-size:13px;line-height:1.5;color:var(--ctp-subtext1)}
.duel-log li{padding-left:10px;border-left:2px solid var(--ctp-surface1)}
.duel-log li:last-child{border-left-color:var(--theme-accent);color:var(--ctp-text)}
.duel-log.full{max-height:60vh;overflow:auto}
/* Dock: hand, status line, actions. Sticky so the thumb always reaches it. */
.duel-dock{position:sticky;bottom:0;z-index:5;margin:0 -8px;padding:6px 8px calc(8px + env(safe-area-inset-bottom));background:var(--ctp-mantle);border-top:1px solid var(--theme-border);border-radius:0 0 12px 12px;display:flex;flex-direction:column;gap:6px}
.duel-hand{display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;padding:6px 0 2px;min-height:112px}
.duel-hand::-webkit-scrollbar{display:none}
.duel-hand-wrap{position:relative}
.duel-hand.has-more{-webkit-mask-image:linear-gradient(to right,#000 78%,transparent);mask-image:linear-gradient(to right,#000 78%,transparent)}
.duel-hand-more{position:absolute;right:0;top:50%;transform:translateY(-50%);min-width:40px;min-height:40px;border-radius:20px;background:var(--ctp-surface1);color:var(--ctp-text);font-weight:800;font-size:13px;box-shadow:0 2px 8px rgb(0 0 0/.4)}
.duel-note{margin:0;min-height:18px;font-size:12px;line-height:1.35;color:var(--ctp-subtext1);display:flex;align-items:center;gap:6px}
.duel-actions{display:flex;gap:8px;justify-content:flex-end}
.duel-actions .button{min-height:46px;font-size:13px;padding:10px 16px}
.duel-actions .duel-primary{flex:1 1 auto;max-width:280px}
/* ---------- card faces ---------- */
.dface{--portal:var(--ctp-overlay1);--portal-ink:var(--ctp-crust);position:relative;display:flex;flex-direction:column;align-items:stretch;text-align:left;padding:0;background:var(--ctp-base);color:var(--ctp-text);border:1.5px solid color-mix(in srgb,var(--portal) 65%,var(--ctp-surface1));border-radius:8px;overflow:hidden;transition:transform .15s ease,box-shadow .15s ease,opacity .15s ease}
.dface.portal-arts{--portal:var(--ctp-red)}
.dface.portal-earth{--portal:var(--ctp-green)}
.dface.portal-history{--portal:var(--ctp-surface2);--portal-ink:var(--ctp-text)}
.dface.portal-science{--portal:var(--ctp-blue)}
.dface.portal-society{--portal:var(--ctp-rosewater)}
.dface.portal-neutral{--portal:var(--ctp-overlay0);--portal-ink:var(--ctp-text)}
.dface-art{position:relative;display:flex;align-items:center;justify-content:center;height:32px;overflow:hidden;color:var(--portal);background:color-mix(in srgb,var(--portal) 25%,var(--ctp-surface0))}
.dface-art img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
.dface-art svg{position:relative;opacity:.9}
.dface-art:has(img:not([style*="none"])) svg{position:absolute;right:3px;bottom:3px;width:14px;height:14px;padding:2px;border-radius:4px;background:rgb(0 0 0/.55);color:#fff;box-sizing:content-box}
.dface-cost{position:absolute;top:3px;left:3px;z-index:2;min-width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:12px;background:var(--ctp-blue);color:var(--ctp-crust);box-shadow:0 1px 3px rgb(0 0 0/.4)}
.dface-title{font-size:10.5px;font-weight:700;line-height:1.2;padding:3px 4px 0;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;min-height:2.4em;overflow-wrap:break-word;hyphens:auto}
.dface-bottom{display:flex;align-items:center;gap:2px;padding:2px 2px 3px;margin-top:auto;min-width:0}
.dface-type{display:inline-flex;color:var(--portal);flex:0 0 auto}
.dface-kwicon{display:inline-flex;align-items:center;justify-content:center;width:15px;height:16px;border-radius:4px;flex:0 0 auto;background:color-mix(in srgb,var(--portal) 30%,var(--ctp-surface0));color:var(--ctp-text)}
.dface-chip{font-size:9px;font-weight:700;padding:1px 3px;border-radius:3px;background:color-mix(in srgb,var(--portal) 30%,var(--ctp-surface0));color:var(--ctp-text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}
.dface-pt{margin-left:auto;flex:0 0 auto;font-size:12px;font-weight:800;padding:0 3px;letter-spacing:-.3px;border-radius:4px;background:var(--ctp-surface0);font-variant-numeric:tabular-nums}
.dface-pt .up{color:var(--ctp-green)}.dface-pt .down{color:var(--ctp-red)}
.dface-flag{position:absolute;top:3px;right:3px;z-index:2;display:flex;padding:3px;border-radius:50%}
.dface-flag.attack{background:var(--ctp-red);color:var(--ctp-crust)}
.dface-flag.block{background:var(--ctp-green);color:var(--ctp-crust)}
.dface-board{width:100%;min-height:90px}
.dface-hand{flex:0 0 80px;width:80px;min-height:106px}
.dface-hand .dface-art{height:42px}
.dface-hand .dface-title{font-size:11px}
.dface.is-tapped{opacity:.62;filter:saturate(.6)}
.dface.is-tapped::after{content:'';position:absolute;inset:0;background:repeating-linear-gradient(135deg,transparent 0 6px,rgb(0 0 0/.12) 6px 8px);pointer-events:none}
.dface.is-pending .dface-art{filter:grayscale(.7)}
.dface.is-selected{box-shadow:0 0 0 2px var(--theme-accent);transform:translateY(-4px)}
.dface.is-attacking{box-shadow:0 0 0 2px var(--ctp-red);transform:translateY(-4px)}
.duel-row.theirs .dface.is-attacking{transform:translateY(4px)}
.dface.is-blocking{box-shadow:0 0 0 2px var(--ctp-green)}
.dface.is-target{box-shadow:0 0 0 2px var(--ctp-yellow);animation:dface-pulse 1.1s ease-in-out infinite}
.dface.is-dim{opacity:.42}
.dface.is-token{border-style:dashed}
.dface.is-fresh{animation:dface-in .4s ease-out}
.dface:focus-visible{outline:2px solid var(--theme-accent);outline-offset:2px}
@keyframes dface-pulse{50%{box-shadow:0 0 0 4px color-mix(in srgb,var(--ctp-yellow) 55%,transparent)}}
@keyframes dface-in{from{transform:scale(.7);opacity:0}to{transform:none;opacity:1}}
@media (prefers-reduced-motion:reduce){.dface{transition:none}.dface.is-target,.dface.is-fresh{animation:none}}
/* Zoom face: the full MTG layout, in the tap-to-zoom sheet. */
.dface-zoom{width:min(300px,100%);margin:0 auto;border-width:3px;border-radius:14px;background:color-mix(in srgb,var(--portal) 10%,var(--ctp-base));padding:8px;gap:6px}
.dface-namebar{display:flex;align-items:center;gap:8px;padding:4px 8px;border-radius:7px;background:var(--ctp-surface0)}
.dface-name{font-family:Georgia,'Times New Roman',serif;font-size:17px !important;font-weight:700;line-height:1.2;margin:0 !important;flex:1 1 auto;min-width:0}
.dface-zoom .dface-cost{position:static;min-width:26px;height:26px;font-size:15px}
.dface-zoom .dface-art{height:150px;border-radius:6px}
.dface-typeline{display:flex;align-items:center;gap:6px;margin:0;padding:4px 8px;border-radius:7px;background:var(--ctp-surface0);font-size:13px !important;font-weight:600}
.dface-portal{margin-left:auto;font-size:10px;font-weight:800;text-transform:uppercase;letter-spacing:.5px;padding:2px 6px;border-radius:4px;background:var(--portal);color:var(--portal-ink)}
.dface-textbox{padding:8px 10px;border-radius:7px;background:var(--ctp-crust);display:flex;flex-direction:column;gap:6px;min-height:88px}
.dface-textbox p{margin:0;font-size:13.5px !important;line-height:1.45 !important}
.dface-keywords{font-weight:700}
.dface-flavour{font-family:Georgia,'Times New Roman',serif;font-style:italic;color:var(--ctp-subtext0);border-top:1px solid var(--ctp-surface0);padding-top:6px}
.dface-flavour sup a{font-style:normal;font-family:inherit;color:var(--ctp-blue);text-decoration:none;margin-left:1px;padding:4px 2px}
.dface-footer{display:flex;align-items:center;gap:6px}
.dface-rev{font-size:10px;color:var(--ctp-overlay1);font-variant-numeric:tabular-nums}
.dface-zoom .dface-pt{font-size:18px;padding:2px 10px;border:2px solid var(--portal);background:var(--ctp-base)}
.duel-sheet .duel-sheet-meta{text-align:center;margin:8px 0}
.duel-preview{list-style:none;padding:0;margin:8px 0;display:flex;flex-direction:column;gap:6px}
.duel-preview li{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px;font-size:14px;padding:8px 10px;border-radius:8px;background:var(--ctp-base)}
.duel-preview small{color:var(--ctp-overlay1);font-variant-numeric:tabular-nums}
.duel-preview .vs{color:var(--ctp-subtext0);font-size:12px}
.duel-preview .gone{text-decoration:line-through;color:var(--ctp-red)}
/* Eligibility gate */
.duel-gate{max-width:560px;margin:0 auto;padding:22px 16px;border:1px solid var(--theme-border);border-radius:12px;background:var(--ctp-mantle);color:var(--ctp-text)}
.duel-gate h2{font-size:22px;margin:0 0 8px}
.duel-gate-bar{height:10px;border-radius:5px;background:var(--ctp-surface0);overflow:hidden;margin:12px 0 6px}
.duel-gate-bar i{display:block;height:100%;background:var(--theme-accent)}
/* Tall phones (≥ 720 px): give the spare height to the cards, with 3-line titles (QA #58). */
@media (max-width:899px) and (min-height:720px){
.dface-board{min-height:112px}
.dface-board .dface-art{height:42px}
.dface-board .dface-title{-webkit-line-clamp:3;min-height:3.6em}
.dface-hand{min-height:128px}
.dface-hand .dface-art{height:52px}
.dface-hand .dface-title{-webkit-line-clamp:3;min-height:3.6em}
.duel-hand{min-height:134px}
}
/* Desktop: bigger cards, log always visible beside the field. */
@media (min-width:900px){
.duel{padding:10px 14px 0;font-size:14px}
.duel-log-button{display:none}
.duel-log-aside{display:flex;flex-direction:column;flex:0 0 300px;max-height:calc(100dvh - 240px);min-height:380px;padding:10px 12px;border-radius:10px;background:var(--ctp-base);border:1px solid var(--ctp-surface0)}
.duel-log-aside h3{font-size:12px;letter-spacing:1px;text-transform:uppercase;color:var(--ctp-subtext0);margin:0 0 8px}
.duel-log-aside .duel-log{overflow:auto}
.duel-ticker{display:none}
.duel-row{justify-content:center;min-height:150px;gap:8px}
.duel-slot{min-width:96px;max-width:120px}
.dface-board{min-height:140px}
.dface-board .dface-art{height:62px}
.dface-board .dface-title{font-size:12.5px}
.dface-board .dface-chip{font-size:9px}
.dface-board .dface-kwicon{width:20px;height:20px}
.dface-board .dface-pt{font-size:14px}
.dface-board .dface-cost{min-width:24px;height:24px;font-size:13px}
.dface-hand{flex-basis:104px;width:104px;min-height:138px}
.dface-hand .dface-art{height:60px}
.dface-hand .dface-title{font-size:12.5px}
.duel-hand{justify-content:center;min-height:146px}
.duel-dock{margin:0 -14px;padding:8px 14px 12px}
}
+105
View File
@@ -0,0 +1,105 @@
// Preview data for the duel board: real cards from docs/game/card-sample.json, with a deliberately
// crude stand-in derivation so the board can be built and screenshotted before duel-cards' real
// shared/duel/derive.ts lands. Never used for real matches. No network calls.
import sample from '../../../docs/game/card-sample.json';
import type { BoardCard, BoardView, DuelCardType, Legal, Portal } from './model.ts';
type SampleCard = {
pageId: number; title: string; description?: string | null; revisionId: number; pageBytes: number; languageCount: number;
categories: string[]; instanceOf?: { id: string; label: string }[]; tiers: { attention: number; depth: number; reach: number };
};
const CARDS = (sample as unknown as { cards: SampleCard[] }).cards;
function previewType(c: SampleCard): DuelCardType {
const labels = (c.instanceOf ?? []).map(i => i.label).join(' ');
const d = c.description ?? '';
if (c.instanceOf?.some(i => i.id === 'Q5') || /\btaxon\b/.test(labels) || /^(Species|Genus) of/.test(d)) return 'Figure';
if (/commune|municipality|village|town|river|settlement|mosque|parish|area/i.test(labels + d)) return 'Location';
if (/election|storm|nor.easter|battle|match|final|season|war/i.test(labels + d)) return 'Event';
if (/company|band|group|film|team|organi[sz]ation|party/i.test(labels + d)) return 'Institution';
return 'Doctrine';
}
function previewPortal(c: SampleCard, t: DuelCardType): Portal {
const s = `${c.description ?? ''} ${c.categories.join(' ')}`;
if (/century|deaths|sultan|empire|medieval|monarch|queen|king/i.test(s)) return 'History';
if (/mathemat|algebra|programming|gene|disease|scientist|botanist|archaeolog/i.test(s)) return 'Science';
if (/actor|singer|film|band|music|novel|television/i.test(s)) return 'Arts';
if (/species|genus|river|fungus|plant|orchid|commune|village/i.test(s)) return 'Earth';
if (/politic|election|protest|footballer|team|government/i.test(s)) return 'Society';
return t === 'Figure' ? 'Society' : t === 'Location' ? 'Earth' : 'Neutral';
}
const years = (d?: string | null) => d?.match(/\(([^)]*\d{3,4}[^)]*)\)/)?.[1]?.replace(/^(c\.|born )/, '').replace('born ', '');
export function previewCard(c: SampleCard, suffix = ''): BoardCard {
const type = previewType(c), portal = previewPortal(c, type);
const fame = Math.round((c.tiers.attention * 2 + c.tiers.depth + c.tiers.reach) / 4);
const cost = Math.max(1, Math.min(6, Math.ceil(fame * 0.6)));
const keywords: string[] = [];
if (c.categories.includes('Living people')) keywords.push('Protected');
if (c.tiers.attention >= 9) keywords.push('Featured');
if (c.languageCount >= 20 && keywords.length < 2) keywords.push('Translated');
if (c.categories.some(x => /\d+ deaths/.test(x)) && keywords.length < 2) keywords.push('Legacy');
if ((c.pageBytes < 3000 || c.categories.some(x => /stubs/.test(x))) && keywords.length < 2) keywords.push('Stub');
const k = Math.ceil(cost / 2);
let power: number | undefined, toughness: number | undefined, rulesText = '';
if (type === 'Figure') {
const b = 2 * cost + 1, s = Math.min(0.7, Math.max(0.3, c.tiers.attention / (c.tiers.attention + c.tiers.depth || 1)));
power = Math.max(1, Math.round(b * s)) - (keywords.length > 1 ? 1 : 0); toughness = Math.max(1, b - Math.round(b * s));
} else if (type === 'Location') {
power = 0; toughness = 1 + Math.floor(c.tiers.depth / 3);
rulesText = `Territory. Garrison 0/${toughness}.`;
} else if (type === 'Event') {
rulesText = /storm|nor.easter/i.test(c.description ?? '') ? `Deal ${Math.max(1, k - 1)} damage to each Figure and each Location.`
: /election/i.test(c.description ?? '') ? `Create ${k} 1/1 Society Figure tokens named Elected Member.`
: `Target Figure you control gets +${k}/+0 until end of turn, then fights target Figure you don't control.`;
} else if (type === 'Institution') {
rulesText = cost >= 4 ? 'At the start of your turn, if you control fewer than 3 tokens, create a 1/1 Figure token named Staff Member.' : 'Figures you control with power 2 or less get +1/+0.';
} else {
rulesText = /disease/i.test(c.description ?? '') ? `Attach to target Figure. It gets −${k}/−${k}.` : `Adopt. Adopted Figure gets +${k}/+${k}.`;
}
const sub = type === 'Figure' ? [portal, years(c.description)].filter(Boolean).join(' · ') : portal;
return {
id: `${c.pageId}${suffix}`, title: c.title, type, subtype: sub, portal, cost, power, toughness, basePower: power, baseToughness: toughness,
keywords: type === 'Figure' ? keywords.slice(0, 2) : [], rulesText, flavour: c.description ? `${c.description}.` : undefined,
url: `https://en.wikipedia.org/wiki/${encodeURIComponent(c.title.replace(/ /g, '_'))}`, revisionId: c.revisionId,
};
}
export const PREVIEW_POOL: BoardCard[] = CARDS.map(c => previewCard(c));
const byTitle = (t: string) => PREVIEW_POOL.find(c => c.title === t) ?? PREVIEW_POOL[0];
const figures = PREVIEW_POOL.filter(c => c.type === 'Figure');
/** A full 5 + 5 board for screenshots and tests. `scene` picks whose step it is. */
export function previewView(scene: 'main' | 'attack' | 'block' | 'over' = 'main'): { view: BoardView; legal: Legal } {
const mine = [byTitle('Jess Harnell'), byTitle('Dichromorpha viridis'), byTitle('Salahuddin of Aceh'), byTitle('Pathrail Mosque'), byTitle('Hiroshima Electric Railway')]
.map((c, i) => ({ ...c, pending: i === 1 && scene === 'main' }));
const theirs = [byTitle('Isabella of Aragon, Queen of Portugal'), byTitle('Miloje Vasić'), figures[12], byTitle('Topusko'), byTitle('Zbyszek Godlewski')]
.map((c, i) => ({ ...c, id: `${c.id}-o`, damage: i === 1 ? 1 : 0 }));
mine[0] = { ...mine[0], attachments: ['doc-1'], power: (mine[0].power ?? 0) + 2, toughness: (mine[0].toughness ?? 0) + 2 };
const hand = [byTitle('Agda (programming language)'), byTitle('April 2021 nor\'easter'), byTitle('Mary Sophie Young'), byTitle('Charmont-en-Beauce'), byTitle('Heart rot'), byTitle('Joseph Ujlaki')];
const log = [
'Turn 1. Bot (Normal) kept a hand of seven.',
'Turn 3. You cited Pathrail Mosque. Maximum Citations rose to 4.',
'Turn 4. Isabella of Aragon, Queen of Portugal (6/5) attacked. Dichromorpha viridis (4/2) blocked and was reverted.[2]',
'Turn 5. You deployed Jess Harnell. Bot (Normal) lost 3 Notability.',
'Turn 6. Miloje Vasić was assigned 1 damage.',
];
const view: BoardView = {
seat: 0, turn: 6, active: scene === 'block' ? 1 : 0, phase: scene === 'main' ? 'main' : scene === 'attack' ? 'attack' : scene === 'block' ? 'block' : 'over',
me: { name: 'You', notability: 14, citations: scene === 'main' ? 4 : 1, maxCitations: 6, library: 27, hand: hand.length, battlefield: mine, graveyard: 3 },
opponent: { name: 'Bot (Normal)', notability: scene === 'over' ? 0 : 11, citations: 0, maxCitations: 6, library: 26, hand: 4, battlefield: theirs, graveyard: 2 },
hand, combat: scene === 'block' ? [{ attackerId: theirs[0].id }, { attackerId: theirs[1].id }, { attackerId: theirs[2].id }] : [],
log, winner: scene === 'over' ? 0 : undefined, clock: { turn: 42, bank: 251 },
};
const myFigs = mine.filter(c => c.type === 'Figure' && !c.pending).map(c => c.id);
const legal: Legal = scene === 'main' ? {
...emptyLegal(), canGoToCombat: true, canEndTurn: true, attackers: myFigs,
plays: Object.fromEntries(hand.filter(c => c.cost <= 4).map(c => [c.id,
c.type === 'Doctrine' ? mine.filter(m => m.type === 'Figure').map(m => [m.id])
: c.type === 'Event' ? mine.filter(m => m.type === 'Figure').flatMap(m => theirs.filter(t => t.type === 'Figure').map(t => [m.id, t.id])) : [[]]])),
} : scene === 'attack' ? { ...emptyLegal(), attackers: myFigs, canEndTurn: true }
: scene === 'block' ? { ...emptyLegal(), blockers: Object.fromEntries(mine.filter(c => c.type === 'Figure' || c.type === 'Location').map(c => [c.id, view.combat.map(a => a.attackerId)])) }
: emptyLegal();
return { view, legal };
}
const emptyLegal = (): Legal => ({ plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false });
+235
View File
@@ -0,0 +1,235 @@
// ui-duel (#58): the duel board's own view model. Board components read only these types, so the
// engine contract (duel-core, mirrored in ./contract.ts) is mapped in exactly one place: ./adapter.ts.
// Nothing here moves cards on-chain; matches are off-chain and never burn or transfer.
export type DuelCardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
export type Seat = 0 | 1;
/** duel-core's phases (refresh, draw, damage and end are automatic). */
export type Phase = 'mulligan' | 'main' | 'attack' | 'block' | 'over';
/** One card as the board shows it. Hidden cards never reach the board (opponent's hand is a count). */
export type BoardCard = {
id: string;
title: string;
type: DuelCardType;
/** The line after the em dash, e.g. "People · 1961–". */
subtype?: string;
portal: Portal;
cost: number;
power?: number;
toughness?: number;
/** Base stats, to colour buffs and debuffs. */
basePower?: number;
baseToughness?: number;
/** Damage marked this turn. */
damage?: number;
keywords: string[];
rulesText: string;
/** First sentence of the on-chain extract. */
flavour?: string;
image?: string;
url?: string;
revisionId?: number;
tapped?: boolean;
/** "Pending review": entered this turn, can't attack. */
pending?: boolean;
/** Doctrine attached to this card (ids), or the Figure a Doctrine is attached to. */
attachments?: string[];
attachedTo?: string;
token?: boolean;
/** Active Connected bonus, e.g. "Compatriot (Portugal): +1/+1". */
connectedNote?: string;
};
export type SideView = {
name: string;
notability: number;
citations: number;
maxCitations: number;
library: number;
hand: number;
battlefield: BoardCard[];
graveyard: number;
};
export type Attack = { attackerId: string; blockerId?: string };
export type BoardView = {
seat: Seat;
turn: number;
/** Whose turn it is. */
active: Seat;
phase: Phase;
me: SideView;
opponent: SideView;
hand: BoardCard[];
/** Current combat: attackers (opponent's when I'm blocking) and any blocks already declared. */
combat: Attack[];
log: string[];
winner?: Seat | 'draw';
/** Seconds left this turn, and in the bank, for the player to act. */
clock?: { turn: number; bank: number };
};
/** What the board can ask the controller to do. The adapter turns these into engine actions. */
export type DuelUIAction =
| { type: 'mulligan'; keep: boolean }
/** targetIds: card uids or `player:<seat>`, one per chosen-target effect, in order. */
| { type: 'play'; cardId: string; targetIds: string[] }
| { type: 'toCombat' }
| { type: 'attack'; attackerIds: string[] }
| { type: 'block'; blocks: { blockerId: string; attackerId: string }[] }
| { type: 'endTurn' }
| { type: 'concede' };
/** What the engine says is legal right now, in board terms. */
export type Legal = {
/** Hand card id → every legal target sequence ([[]] = needs no target). Absent = can't be played now. */
plays: Record<string, string[][]>;
canGoToCombat: boolean;
/** Figures that may be declared as attackers. */
attackers: string[];
/** blocker id → attacker ids it may block (Featured, Translated and Garrison are the engine's call). */
blockers: Record<string, string[]>;
canEndTurn: boolean;
mulligan: boolean;
};
export const NO_LEGAL: Legal = { plays: {}, canGoToCombat: false, attackers: [], blockers: {}, canEndTurn: false, mulligan: false };
// ---------- targeting (multi-step: e.g. a sport Event picks your Figure, then theirs) ----------
export const playerTarget = (seat: Seat) => `player:${seat}`;
/** Ids that may be chosen next, given the targets already chosen for this card. */
export function nextTargets(seqs: string[][] | undefined, chosen: string[]): Set<string> {
const out = new Set<string>();
for (const q of seqs ?? []) if (q.length > chosen.length && chosen.every((t, i) => q[i] === t)) out.add(q[chosen.length]);
return out;
}
/** True when `chosen` is a complete legal sequence. */
export const targetsComplete = (seqs: string[][] | undefined, chosen: string[]) =>
!!seqs?.some(q => q.length === chosen.length && q.every((t, i) => t === chosen[i]));
// ---------- combat declaration (pure, so it is unit-tested) ----------
/**
* Attack: one tap toggles a Figure in or out. Block: tap your blocker (1), then the attacker it
* blocks (2). Tapping an assigned blocker again removes it. At most one blocker per attacker and
* one attacker per blocker (BRIEF: single blocks).
*/
export type Declaration = { attackers: string[]; blocks: Record<string, string>; picked?: string };
export const EMPTY_DECL: Declaration = { attackers: [], blocks: {} };
export function toggleAttacker(d: Declaration, id: string, legal: Legal): Declaration {
if (!legal.attackers.includes(id)) return d;
const attackers = d.attackers.includes(id) ? d.attackers.filter(a => a !== id) : [...d.attackers, id];
return { ...d, attackers };
}
/** Tap on one of my cards during blocks. */
export function tapBlocker(d: Declaration, blockerId: string, legal: Legal): Declaration {
if (d.blocks[blockerId]) { const blocks = { ...d.blocks }; delete blocks[blockerId]; return { ...d, blocks, picked: undefined }; }
if (!legal.blockers[blockerId]?.length) return d;
return { ...d, picked: d.picked === blockerId ? undefined : blockerId };
}
/** Tap on an attacker during blocks. With a blocker picked, assign it; the attacker's old blocker is freed. */
export function tapAttacker(d: Declaration, attackerId: string, legal: Legal): Declaration {
const picked = d.picked;
if (!picked) {
// No blocker picked: tapping a blocked attacker clears its block.
const owner = Object.entries(d.blocks).find(([, a]) => a === attackerId)?.[0];
if (!owner) return d;
const blocks = { ...d.blocks }; delete blocks[owner]; return { ...d, blocks };
}
if (!legal.blockers[picked]?.includes(attackerId)) return d;
const blocks = Object.fromEntries(Object.entries(d.blocks).filter(([, a]) => a !== attackerId));
blocks[picked] = attackerId;
return { ...d, blocks, picked: undefined };
}
export const blockList = (d: Declaration) => Object.entries(d.blocks).map(([blockerId, attackerId]) => ({ blockerId, attackerId }));
// ---------- combat preview ----------
export type CombatOutcome = {
/** Damage the defending player takes. */
toPlayer: number;
/** Card ids that would be destroyed. */
destroyed: string[];
rows: { attacker: BoardCard; blocker?: BoardCard; attackerDies: boolean; blockerDies: boolean }[];
};
const has = (c: BoardCard | undefined, kw: string) => !!c?.keywords.some(k => k.toLowerCase() === kw.toLowerCase());
/** Damage a card takes from one source, after Well-sourced (prevent the first 1 each turn). */
const taken = (c: BoardCard, dmg: number) => Math.max(0, dmg - (has(c, 'Well-sourced') && !(c.damage ?? 0) ? 1 : 0));
const dies = (c: BoardCard, dmg: number) => c.toughness !== undefined && (c.damage ?? 0) + taken(c, dmg) >= c.toughness && dmg > 0;
/**
* A preview for the confirm sheet: simultaneous damage, single blocks, no trample or first strike
* (BRIEF). The engine resolves for real; this is only so the player sees what they are confirming.
*/
export function previewCombat(attacks: Attack[], cards: Map<string, BoardCard>): CombatOutcome {
const out: CombatOutcome = { toPlayer: 0, destroyed: [], rows: [] };
for (const { attackerId, blockerId } of attacks) {
const attacker = cards.get(attackerId);
if (!attacker) continue;
const blocker = blockerId ? cards.get(blockerId) : undefined;
if (!blocker) { out.toPlayer += attacker.power ?? 0; out.rows.push({ attacker, attackerDies: false, blockerDies: false }); continue; }
const attackerDies = dies(attacker, blocker.power ?? 0);
const blockerDies = dies(blocker, attacker.power ?? 0);
if (attackerDies) out.destroyed.push(attacker.id);
if (blockerDies) out.destroyed.push(blocker.id);
out.rows.push({ attacker, blocker, attackerDies, blockerDies });
}
return out;
}
// ---------- eligibility (BRIEF decisions 1–3) ----------
export const DEFAULT_DECK_SIZE = 40;
export type Eligibility = { eligible: boolean; owned: number; needed: number; label: string };
/** Bot and PvP matches are only for players who own a full deck. There is no borrowed-card play. */
export function eligibility(owned: number, deckSize = DEFAULT_DECK_SIZE): Eligibility {
const needed = Math.max(0, deckSize - owned);
return { eligible: needed === 0, owned, needed, label: `${Math.min(owned, deckSize)} / ${deckSize} cards` };
}
// ---------- text helpers ----------
/**
* First sentence of an extract, for flavour text. Doesn't split on initials ("J. R. R."), common
* abbreviations or decimals. Falls back to the whole (trimmed) text.
*/
export function firstSentence(text: string | undefined, max = 220): string | undefined {
const t = text?.replace(/\s+/g, ' ').trim();
if (!t) return undefined;
const re = /[.!?](?=\s+[A-Z0-9"“(])/g;
let m: RegExpExecArray | null;
while ((m = re.exec(t))) {
const before = t.slice(0, m.index);
const word = before.split(' ').at(-1) ?? '';
if (/^[A-Z]$/.test(word) || /^(Mr|Mrs|Ms|Dr|St|Jr|Sr|No|Mt|Ft|vs|c|ca|approx|e\.g|i\.e|U\.S|U\.K)$/i.test(word)) continue;
return clip(t.slice(0, m.index + 1), max);
}
return clip(t, max);
}
const clip = (s: string, max: number) => (s.length <= max ? s : `${s.slice(0, max - 1).replace(/\s+\S*$/, '')}…`);
/** "Figure — People · 1961–" */
export const typeLine = (c: Pick<BoardCard, 'type' | 'subtype' | 'portal'>) =>
`${c.type} — ${c.subtype ?? c.portal}`;
/** Accessible one-line summary of a card. */
export function cardSummary(c: BoardCard): string {
const stats = c.power !== undefined ? `, ${c.power}/${c.toughness ?? 0}` : '';
const kw = c.keywords.length ? `, ${c.keywords.join(', ')}` : '';
const state = `${c.tapped ? ', tapped' : ''}${c.pending ? ', pending review' : ''}${c.damage ? `, ${c.damage} damage` : ''}`;
return `${c.title}, ${typeLine(c)}, cost ${c.cost}${stats}${kw}${state}`;
}
export const isMyTurn = (v: BoardView) => v.active === v.seat && v.phase !== 'over';
+106
View File
@@ -74,3 +74,109 @@ export const online = {
pick: (s: LobbySeat, index: number) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}/pick`, { body: { index }, token: s.token }),
resign: (s: LobbySeat) => call<LobbyStatus>(`lobbies/${id(s.lobbyId)}/resign`, { body: {}, token: s.token }),
};
// ----- Night 2: PvP duel client (host-pvp, #56). Seats are bound to the eom.dev account: every call
// joins with the Dex ID token, then uses the seat token. Routes are stubbed against the shapes
// posted on #56 until docs/game/DUEL_API.md lands; parsers below treat every response as untrusted.
export type DuelSeat = { lobbyId: string; seat: 0 | 1; token: string; invite?: string };
export type DuelStatus = {
lobbyId: string; version: number;
phase: 'waiting' | 'starting' | 'drafting' | 'playing' | 'finished' | 'expired';
seat: 0 | 1 | null; players: { name: string; rating?: number }[];
outcome: { winner: 0 | 1 | null; reason: string } | null;
matchId?: string; invite?: string;
/** Duel engine PlayerView and legal actions (shared/duel/types.ts), passed through to the board. */
state?: unknown; legalActions?: unknown[];
};
export type LadderEntry = { name: string; rating: number | null; wins: number; losses: number; draws: number };
const sid = (v: unknown, max = 128) => (typeof v === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(v) ? v.slice(0, max) : '');
const seatNo = (v: unknown): 0 | 1 | null => (v === 0 || v === 1 ? v : null);
const PHASES = new Set(['waiting', 'starting', 'drafting', 'playing', 'finished', 'expired']);
export function parseSeat(v: unknown): DuelSeat {
const o = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>;
const lobbyId = sid(o.lobbyId), token = typeof o.token === 'string' ? o.token.slice(0, 512) : '', seat = seatNo(o.seat);
if (!lobbyId || !token || seat === null) throw new Error('The host sent an invalid seat.');
const invite = sid(o.invite ?? o.inviteCode);
return { lobbyId, seat, token, ...(invite ? { invite } : {}) };
}
export function parseDuelStatus(v: unknown): DuelStatus {
const o = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>;
const phase = PHASES.has(o.phase as string) ? o.phase as DuelStatus['phase'] : 'waiting';
const players = (Array.isArray(o.players) ? o.players : []).slice(0, 2).map(p => {
const r = (p && typeof p === 'object' ? p : {}) as Record<string, unknown>;
return { name: typeof r.name === 'string' ? r.name.slice(0, 24) : 'Player', ...(typeof r.rating === 'number' && Number.isFinite(r.rating) ? { rating: Math.round(r.rating) } : {}) };
});
const out = o.outcome && typeof o.outcome === 'object' ? o.outcome as Record<string, unknown> : null;
const matchId = sid(o.matchId), invite = sid(o.invite ?? o.inviteCode);
return {
lobbyId: sid(o.lobbyId), version: typeof o.version === 'number' && Number.isFinite(o.version) ? o.version : 0, phase,
seat: seatNo(o.seat), players, outcome: out ? { winner: seatNo(out.winner), reason: typeof out.reason === 'string' ? out.reason.slice(0, 80) : '' } : null,
...(matchId ? { matchId } : {}), ...(invite ? { invite } : {}),
...(o.state !== undefined ? { state: o.state } : {}), ...(Array.isArray(o.legalActions) ? { legalActions: o.legalActions.slice(0, 500) } : {}),
};
}
export function parseLadder(v: unknown): LadderEntry[] {
const o = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>;
const list = Array.isArray(o.entries) ? o.entries : [];
const n = (x: unknown) => (typeof x === 'number' && Number.isFinite(x) && x >= 0 ? Math.floor(x) : 0);
return list.filter((e): e is Record<string, unknown> => !!e && typeof e === 'object').slice(0, 50).map(e => ({
name: typeof e.name === 'string' && e.name.trim() ? e.name.slice(0, 24) : 'Anonymous',
rating: typeof e.rating === 'number' && Number.isFinite(e.rating) ? Math.round(e.rating) : null,
wins: n(e.wins), losses: n(e.losses), draws: n(e.draws),
}));
}
/** Pull an invite code out of a pasted link (…/play/invite/<code>) or a bare code. */
export function inviteCode(input: string): string {
const s = input.trim();
const m = s.match(/\/play\/(?:invite|join)\/([A-Za-z0-9_-]{1,128})\/?(?:[?#].*)?$/);
return m ? m[1] : /^[A-Za-z0-9_-]{4,128}$/.test(s) ? s : '';
}
/** /play/invite/<code> (or the older /play/join/<id>) → the invite code, else ''. */
export const inviteFromPath = (path: string) => (/^\/play\/(invite|join)\//.test(path) ? inviteCode(path) : '');
export const inviteUrl = (code: string, origin = location.origin) => `${origin}/play/invite/${encodeURIComponent(code)}`;
type DuelInit = { method?: string; body?: unknown; seat?: string };
// host-pvp (#56): create/join carry the Dex ID token in the body ({idToken}); Bearer stays the seat token.
async function duelCall(path: string, init: DuelInit = {}): Promise<{ status: number; data: unknown }> {
const headers: Record<string, string> = {};
if (init.body !== undefined) headers['Content-Type'] = 'application/json';
if (init.seat) headers.Authorization = `Bearer ${init.seat}`;
const res = await fetch(`/api/game/${path}`, {
method: init.method ?? (init.body === undefined ? 'GET' : 'POST'), cache: 'no-store', signal: AbortSignal.timeout(10000), headers,
...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
});
if (res.status === 204) return { status: 204, data: null };
const data = res.headers.get('content-type')?.includes('json') ? await res.json().catch(() => ({})) : {};
if (!res.ok) {
const err = (data as { error?: unknown })?.error;
throw Object.assign(new Error(typeof err === 'string' ? err.slice(0, 200) : res.status === 401 ? 'Log in with your eom.dev account to play.' : `The host answered ${res.status}.`), { status: res.status });
}
return { status: res.status, data };
}
export const pvp = {
createPrivate: (modeId: string, deck: string[], idToken: string) =>
duelCall(`modes/${id(modeId)}/lobbies`, { body: { deck, private: true, idToken } }).then(r => parseSeat(r.data)),
/** POST /invites/:code/join (host-pvp, docs/game/HOSTING.md "Seats, invites, quick match and polling"). */
joinInvite: (code: string, deck: string[], idToken: string) =>
duelCall(`invites/${id(code)}/join`, { body: { deck, idToken } }).then(r => parseSeat(r.data)),
quick: (modeId: string, deck: string[], idToken: string) =>
duelCall(`modes/${id(modeId)}/quick`, { body: { deck, idToken } }).then(r => parseSeat(r.data)),
/** Returns null when the host answers 204 (nothing changed since `version`). */
status: (s: DuelSeat, version?: number) =>
duelCall(`lobbies/${id(s.lobbyId)}${version ? `?v=${version}` : ''}`, { seat: s.token }).then(r => (r.status === 204 ? null : parseDuelStatus(r.data))),
act: (s: DuelSeat, action: unknown) =>
duelCall(`lobbies/${id(s.lobbyId)}/actions`, { body: { action }, seat: s.token }).then(r => parseDuelStatus(r.data)),
resign: (s: DuelSeat) =>
duelCall(`lobbies/${id(s.lobbyId)}/resign`, { body: {}, seat: s.token }).then(r => parseDuelStatus(r.data)),
/** Elo ladder; falls back to the W/L leaderboard (cut order 1) when the host has no ladder. */
ladder: async (modeId: string): Promise<LadderEntry[]> => {
try { return parseLadder((await duelCall(`modes/${id(modeId)}/ladder`)).data); }
catch { return parseLadder((await duelCall(`modes/${id(modeId)}/leaderboard`)).data); }
},
};
+92
View File
@@ -0,0 +1,92 @@
import { useEffect, useState } from 'react';
import { ArrowLeft, LoaderCircle, Share2 } from 'lucide-react';
import { fallbackRecap, parseMatchRecord, runs, type RecapDoc } from './model.ts';
/** /recap/<matchId> (DUEL_DESIGN §8.3; /battle/<matchId> is accepted as an alias): encyclopedic recap of a finished match, replayed from the host's record. */
export function matchIdFromPath(path: string): string {
const m = path.match(/^\/(?:battle|recap)\/([A-Za-z0-9_-]{1,128})\/?$/);
return m ? m[1] : '';
}
export async function loadRecap(matchId: string, f: typeof fetch = fetch): Promise<RecapDoc> {
const res = await f(`/api/game/matches/${encodeURIComponent(matchId)}`, { cache: 'no-store', signal: AbortSignal.timeout(10000) });
if (res.status === 404) throw new Error('No battle is recorded under this link.');
if (!res.ok || !res.headers.get('content-type')?.includes('json')) throw new Error(`The host answered ${res.status}.`);
return fallbackRecap(parseMatchRecord(await res.json()));
}
function Text({ src }: { src: string }) {
return <>{runs(src).map((r, i) => r.cite ? <sup key={i} className="recap-cite"><a href={`#ref-${r.cite}`}>{r.text}</a></sup>
: r.bold ? <b key={i}>{r.text}</b> : r.italic ? <i key={i}>{r.text}</i> : <span key={i}>{r.text}</span>)}</>;
}
const revLink = (url: string, rev?: number) => (rev ? `${url}${url.includes('?') ? '&' : '?'}oldid=${rev}` : url);
const safe = (url: string) => (/^https:\/\/[a-z]+\.wikipedia\.org\//i.test(url) ? url : '');
/** Renders a RecapDoc from shared/duel/story (or the local fallback). WikiDeck masthead, not Wikipedia's. */
export function RecapArticle({ doc }: { doc: RecapDoc }) {
const ib = doc.infobox;
const pair = (label: string, v: [string, string]) => <>
<tr className="ib-section"><th colSpan={2}>{label}</th></tr>
<tr><td>{v[0]}</td><td>{v[1]}</td></tr></>;
return <article className="recap" aria-labelledby="recap-title">
<header className="recap-head">
<div className="recap-brand">{doc.masthead} · Battle record</div>
<h1 id="recap-title">{doc.title}</h1>
<p className="recap-from">From WikiDeck, the free card game</p>
</header>
<aside className="recap-infobox" aria-label="Infobox">
<div className="ib-title">{doc.title}</div>
<table><tbody>
<tr><th>Date</th><td>{ib.date}</td></tr>
<tr><th>Location</th><td>{ib.location}</td></tr>
<tr><th>Result</th><td>{ib.result}</td></tr>
{pair('Belligerents', ib.belligerents)}
{pair('Commanders', ib.commanders)}
{pair('Strength', ib.strength)}
{pair('Casualties', ib.casualties)}
</tbody></table>
</aside>
<p><Text src={doc.lead} /></p>
{doc.sections.map(s => <section key={s.heading}>
<h2>{s.heading}</h2>
{s.paragraphs.map((p, i) => <p key={i}><Text src={p} /></p>)}
</section>)}
{doc.references.length > 0 && <section className="recap-refs" aria-labelledby="refs-title">
<h2 id="refs-title">References</h2>
<ol>{doc.references.map(r => { const url = safe(r.url); return <li key={r.n} id={`ref-${r.n}`}>
{url ? <a href={revLink(url, r.revisionId)} target="_blank" rel="noopener noreferrer">“{r.title}”</a> : <>“{r.title}”</>}
. <i>Wikipedia</i>{r.revisionId ? `, revision ${r.revisionId}` : ''}{r.tokenId ? `. Card ${r.tokenId.slice(0, 12)}` : ''}.
</li>; })}</ol>
</section>}
<footer className="recap-footer">{doc.footer}</footer>
</article>;
}
export function BattleRecap({ matchId, onExit }: { matchId: string; onExit: () => void }) {
const [doc, setDoc] = useState<RecapDoc>();
const [error, setError] = useState('');
const [note, setNote] = useState('');
useEffect(() => {
let active = true;
loadRecap(matchId).then(d => { if (active) { setDoc(d); document.title = `${d.title} · WikiDeck`; } },
e => { if (active) setError(e instanceof Error ? e.message : 'The host is unreachable.'); });
return () => { active = false; };
}, [matchId]);
const share = async () => {
const url = `${location.origin}/recap/${encodeURIComponent(matchId)}`;
try {
if (navigator.share) await navigator.share({ title: doc?.title ?? 'WikiDeck battle', url });
else { await navigator.clipboard.writeText(url); setNote('Link copied.'); }
} catch { setNote(url); }
};
return <section className="play-panel recap-page">
<div className="recap-tools">
<button className="button outline" onClick={onExit}><ArrowLeft size={16} /> WikiDeck</button>
<button className="button outline" onClick={share} disabled={!doc}><Share2 size={16} /> Share</button>
</div>
{note && <p className="muted small" role="status">{note}</p>}
{error ? <p className="dock-error" role="alert">{error}</p>
: doc ? <RecapArticle doc={doc} />
: <p className="muted"><LoaderCircle className="spin" size={14} /> Loading the battle record…</p>}
</section>;
}
+170
View File
@@ -0,0 +1,170 @@
// Battle recap view model ("Battle of X (2026)", BRIEF "Story"). The page renders a RecapDoc. The
// authoritative generator is duel-design's shared/duel/story (deterministic templates over the real
// match log); until it is on the branch, `fallbackRecap` builds a plain doc from the stored match
// record using only real card and match data: no prose beyond fixed templates, no invented facts.
/**
* Mirror of duel-design's `RecapDoc` (shared/duel/story/recap.ts, PR #69), so the page renders either
* generator's output. Text fields use the story markup: **bold**, *italic* and [n] citation markers.
*/
export type RecapReference = { n: number; title: string; url: string; revisionId?: number; tokenId?: string; text?: string };
export type RecapDoc = {
matchId: string; url: string; masthead: 'WikiDeck'; title: string;
infobox: { date: string; location: string; result: string; belligerents: [string, string]; commanders: [string, string];
strength: [string, string]; casualties: [string, string] };
lead: string; sections: { heading: string; paragraphs: string[] }[]; references: RecapReference[]; footer: string;
};
export const FOOTER = 'This page records a WikiDeck match. Card names refer to Wikipedia articles; the events described are game events.';
/** Split story markup into plain, bold, italic and citation runs (rendered as React text, never HTML). */
export type Run = { text: string; bold?: boolean; italic?: boolean; cite?: number };
export function runs(src: string): Run[] {
const out: Run[] = [];
const re = /\*\*([^*]+)\*\*|\*([^*]+)\*|\[(\d{1,4})\]/g;
let last = 0;
for (let m: RegExpExecArray | null; (m = re.exec(src));) {
if (m.index > last) out.push({ text: src.slice(last, m.index) });
if (m[1] !== undefined) out.push({ text: m[1], bold: true });
else if (m[2] !== undefined) out.push({ text: m[2], italic: true });
else out.push({ text: `[${m[3]}]`, cite: Number(m[3]) });
last = m.index + m[0].length;
}
if (last < src.length) out.push({ text: src.slice(last) });
return out;
}
/** Match record as stored by the host (GET /api/game/matches/:id). Every field is untrusted. */
export type MatchCardRef = { tokenId?: string; pageId: number; title: string; revisionId?: number; url?: string; type?: string };
export type MatchRecord = {
matchId: string; modeId?: string; modeName?: string;
players: [string, string]; startedAt?: number; endedAt?: number;
winner: 0 | 1 | null; reason?: string; turns?: number;
/** Deck sizes or cards brought, per seat. */
strength?: [number, number];
/** Cards each seat played, in order (real cards from the chain). */
played?: [MatchCardRef[], MatchCardRef[]];
/** Cards each seat lost (destroyed / sent to the graveyard). */
lost?: [MatchCardRef[], MatchCardRef[]];
/** Public, past-tense log lines (host's spectator/public logFor). */
log?: { turn: number; text: string }[];
/** Raw record, kept for the shared generator (replay needs seed + actions). */
raw: unknown;
};
const str = (v: unknown, max = 200) => (typeof v === 'string' ? v.slice(0, max) : '');
const int = (v: unknown) => (typeof v === 'number' && Number.isInteger(v) && v >= 0 ? v : undefined);
const wikiUrl = (title: string) => `https://en.wikipedia.org/wiki/${encodeURIComponent(title.replace(/ /g, '_'))}`;
const safeUrl = (v: unknown) => { const s = str(v, 2000); return /^https:\/\/[a-z]+\.wikipedia\.org\//i.test(s) ? s : undefined; };
function cardRef(v: unknown): MatchCardRef | undefined {
if (!v || typeof v !== 'object') return undefined;
const o = v as Record<string, unknown>;
const card = (o.card && typeof o.card === 'object' ? o.card : o) as Record<string, unknown>;
const pageId = int(card.pageId), title = str(card.title, 200);
if (!pageId || !title) return undefined;
return { pageId, title, tokenId: str(card.tokenId ?? card.cardId, 128) || undefined, revisionId: int(card.revisionId),
url: safeUrl(card.url), type: str(card.type, 30) || undefined };
}
const refs = (v: unknown): MatchCardRef[] => (Array.isArray(v) ? v.slice(0, 200).map(cardRef).filter((c): c is MatchCardRef => !!c) : []);
const pair = <T,>(v: unknown, f: (x: unknown) => T): [T, T] | undefined => (Array.isArray(v) && v.length === 2 ? [f(v[0]), f(v[1])] : undefined);
export function parseMatchRecord(v: unknown): MatchRecord {
const o = (v && typeof v === 'object' ? v : {}) as Record<string, unknown>;
const r = (o.result && typeof o.result === 'object' ? o.result : o) as Record<string, unknown>;
const names = (Array.isArray(o.players) ? o.players : []).slice(0, 2).map((p, i) =>
str(typeof p === 'string' ? p : (p as Record<string, unknown> | null)?.name, 24) || `Player ${i + 1}`);
while (names.length < 2) names.push(`Player ${names.length + 1}`);
const winner = r.winner === 0 || r.winner === 1 ? r.winner : null;
const log = Array.isArray(o.log) ? o.log.slice(0, 2000).flatMap(e => {
if (typeof e === 'string') return [{ turn: 0, text: e.slice(0, 400) }];
const x = (e && typeof e === 'object' ? e : {}) as Record<string, unknown>;
const text = str(x.text, 400);
return text ? [{ turn: int(x.turn) ?? 0, text }] : [];
}) : undefined;
return {
matchId: str(o.matchId ?? o.id, 128), modeId: str(o.modeId, 64) || undefined, modeName: str(o.modeName, 64) || undefined,
players: [names[0], names[1]], startedAt: int(o.startedAt), endedAt: int(o.endedAt ?? o.finishedAt), winner,
reason: str(r.reason, 60) || undefined, turns: int(o.turns ?? r.turns),
// host-pvp records carry `decks` (engine cards per seat); their sizes are each side's strength.
strength: pair(o.strength, x => int(x) ?? 0) ?? pair(o.decks, x => (Array.isArray(x) ? x.length : 0)), played: pair(o.played, refs), lost: pair(o.lost, refs), log, raw: v,
};
}
const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
export const longDate = (ms: number) => { const d = new Date(ms); return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}`; };
const NUMBERS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve'];
const spell = (n: number) => NUMBERS[n] ?? String(n);
const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? '' : 's'}`;
/** Stable 32-bit hash for deterministic template choice. */
export function seedOf(s: string): number { let h = 2166136261; for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619); return h >>> 0; }
const pick = <T,>(list: T[], seed: number, salt: number) => list[(seed + salt * 2654435761) % list.length >>> 0];
/** Fallback generator (until shared/duel/story merges): fixed templates over real data only (BRIEF decision 5). */
export function fallbackRecap(m: MatchRecord): RecapDoc {
const seed = seedOf(m.matchId || 'match');
const when = m.endedAt ?? m.startedAt;
const date = when ? longDate(when) : 'an unrecorded date';
const year = when ? new Date(when).getUTCFullYear() : undefined;
const all = [...(m.played?.[0] ?? []), ...(m.played?.[1] ?? [])];
// Card titles are data: strip story markup characters so a title can't restyle the page.
const t = (c: MatchCardRef) => `*${c.title.replace(/[*[\]]/g, '')}*`;
// References: every card played, deduplicated by pageId+revision, numbered in order of first appearance.
const references: RecapReference[] = [];
const refNo = new Map<string, number>();
const cite = (c: MatchCardRef) => {
const key = `${c.pageId}:${c.revisionId ?? ''}`;
let n = refNo.get(key);
if (!n) { n = references.length + 1; refNo.set(key, n); references.push({ n, title: c.title, revisionId: c.revisionId, tokenId: c.tokenId, url: c.url ?? wikiUrl(c.title) }); }
return `[${n}]`;
};
// Named after the decisive non-Figure card (the winner's last non-Figure played), else the date.
const winnerPlayed = m.winner === null ? all : m.played?.[m.winner] ?? [];
const namesake = [...winnerPlayed].reverse().find(c => c.type && !/figure/i.test(c.type)) ?? [...winnerPlayed].reverse()[0];
const bare = namesake ? `Battle of ${namesake.title.replace(/[*[\]]/g, '')}` : `Match of ${date}`;
const title = namesake && year ? `${bare} (${year})` : bare;
const [a, b] = m.players;
const ending = m.winner === null ? 'in a draw' : `in a victory for ${m.players[m.winner]}`;
let lead = `The **${bare}** was a WikiDeck engagement fought on ${date} between the forces of ${a} and ${b}.`;
lead += m.turns ? ` It lasted ${spell(m.turns)} turns and ended ${ending}.` : ` It ended ${ending}.`;
if (namesake) lead += cite(namesake);
const course: string[] = [];
const opener = ['Contemporary accounts note the deployment of ', 'Sources describe the early commitment of ', 'The engagement opened with '];
for (const seat of [0, 1] as const) {
const cards = m.played?.[seat] ?? [];
if (!cards.length) continue;
let p = `${pick(opener, seed, seat + 1)}${t(cards[0])}${cite(cards[0])} by ${m.players[seat]}.`;
const rest = cards.slice(1, 4);
if (rest.length) p += ` ${m.players[seat]} later committed ${rest.map((c, i) => `${t(c)}${cite(c)}${i === rest.length - 1 ? '' : i === rest.length - 2 ? ' and' : ','}`).join(' ')}.`;
course.push(p);
}
for (const c of all) cite(c);
if (m.reason && m.winner !== null) course.push(`${m.players[1 - m.winner]} ${reasonText(m.reason)}.`);
const aftermath: string[] = [];
if (m.lost) {
const n = m.lost[0].length + m.lost[1].length;
aftermath.push(n ? `In total ${plural(n, 'card')} were destroyed: ${m.lost[0].length} from ${a} and ${m.lost[1].length} from ${b}.` : 'No cards were destroyed.');
}
const strength = (i: 0 | 1) => (m.strength ? plural(m.strength[i], 'card') : m.played ? `${plural(m.played[i].length, 'card')} played` : 'Unknown');
const casualties = (i: 0 | 1) => (!m.lost ? 'Unknown' : m.lost[i].length ? `${plural(m.lost[i].length, 'card')} destroyed: ${m.lost[i].map(c => c.title).join(', ')}` : 'None');
const commander = (i: 0 | 1) => m.played?.[i].find(c => /figure/i.test(c.type ?? ''))?.title ?? 'None recorded';
const sections = [{ heading: 'Course of the battle', paragraphs: course }, { heading: 'Aftermath', paragraphs: aftermath }].filter(x => x.paragraphs.length);
return { matchId: m.matchId, url: `/recap/${m.matchId}`, masthead: 'WikiDeck', title, lead, sections, references, footer: FOOTER,
infobox: { date, location: m.modeName ? `WikiDeck · ${m.modeName}` : 'WikiDeck', result: m.winner === null ? 'Draw' : `Victory for ${m.players[m.winner]}`,
belligerents: [a, b], commanders: [commander(0), commander(1)], strength: [strength(0), strength(1)], casualties: [casualties(0), casualties(1)] } };
}
function reasonText(r: string): string {
switch (r) {
case 'notability': case 'life': return 'was reduced to zero Notability';
case 'library': case 'decked': return 'could not draw from an empty library';
case 'resign': case 'concede': return 'withdrew from the engagement';
case 'timeout': case 'afk': return 'did not act before the clock expired';
default: return `lost (${r})`;
}
}
+29
View File
@@ -0,0 +1,29 @@
/* Battle recap: encyclopedic texture, WikiDeck branding (serif headline, infobox), 360 px first. */
.recap-page{max-width:880px}
.recap-tools{display:flex;justify-content:space-between;gap:8px;margin-bottom:12px}
.recap-tools .button{min-height:40px;font-size:13px;padding:8px 12px}
.recap{font-size:15px;line-height:1.65;color:var(--ctp-text);padding-bottom:24px}
.recap::after{content:"";display:block;clear:both}
.recap-head{border-bottom:1px solid var(--theme-border);margin-bottom:12px;padding-bottom:6px}
.recap-brand{font-size:10px;letter-spacing:.14em;text-transform:uppercase;color:var(--ctp-mauve);font-weight:700}
.recap h1{font-family:Georgia,'Times New Roman',serif;font-weight:400;font-size:28px;line-height:1.2;margin:4px 0 2px;letter-spacing:0}
.recap-from{font-size:12px;color:var(--ctp-subtext0);margin:0}
.recap p{margin:0 0 12px}
.recap i{font-style:italic}
.recap-cite{font-size:11px;line-height:0}
.recap-cite a{color:var(--ctp-blue);text-decoration:none}
.recap-infobox{border:1px solid var(--theme-border);background:var(--ctp-base);border-radius:8px;padding:8px;margin:0 0 14px;font-size:13px}
.recap-infobox .ib-title{font-weight:700;text-align:center;background:var(--ctp-surface0);border-radius:4px;padding:6px;margin-bottom:6px}
.recap-infobox table{width:100%;border-collapse:collapse;table-layout:fixed}
.recap-infobox th,.recap-infobox td{padding:4px 6px;vertical-align:top;text-align:left;overflow-wrap:anywhere}
.recap-infobox th{width:38%;color:var(--ctp-subtext1);font-weight:600}
.recap-infobox .ib-section th{text-align:center;background:var(--ctp-surface0);color:var(--ctp-text);width:auto}
.recap-refs h2{font-family:Georgia,'Times New Roman',serif;font-weight:400;font-size:20px;border-bottom:1px solid var(--theme-border);margin:20px 0 8px}
.recap-refs ol{padding-left:22px;font-size:13px}
.recap-refs li:target{background:var(--ctp-surface0)}
.recap-refs a{color:var(--ctp-blue)}
@media (min-width:640px){.recap-infobox{float:right;width:300px;margin:0 0 14px 18px}}
.recap-shell{min-height:100vh;padding:16px 12px;background:var(--ctp-base)}
.recap section>h2{font-family:Georgia,'Times New Roman',serif;font-weight:400;font-size:20px;border-bottom:1px solid var(--theme-border);margin:18px 0 8px}
.recap-footer{clear:both;margin-top:20px;padding-top:10px;border-top:1px solid var(--theme-border);font-size:11px;color:var(--ctp-subtext0)}
.recap-infobox td,.recap-infobox th{white-space:normal;word-break:break-word}
+11 -8
View File
@@ -1,8 +1,11 @@
import './native.ts';
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import './themes.css';
ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode><App /></React.StrictMode>);
import './native.ts';
import React, { Suspense, lazy } from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import './themes.css';
// ui-duel review aid: `#duel-preview` renders static duel board scenes from card-sample.json.
const DuelPreview = lazy(() => import('./game/duel/DuelPreview.tsx').then(m => ({ default: m.DuelPreview })));
const root = location.hash.startsWith('#duel-preview') ? <Suspense fallback={null}><DuelPreview /></Suspense> : <App />;
ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode>{root}</React.StrictMode>);
+173
View File
@@ -0,0 +1,173 @@
// Mobile (Android sideload) mining: the same loop as server/testnet/miner.ts, run in the WebView.
// The native WikiDeckMiner plugin (android/.../MinerPlugin.java) only runs the pinned RandomX engine in
// LIGHT mode; this module builds work from the node's template, signs the block claim with the local web
// wallet and submits it. The plugin never sees a private key or backup password.
// Browser-safe: Web Crypto only, no node: imports. See docs/night2/MOBILE_MINING.md.
import { CONSENSUS, NETWORK, blockClaimMessage, headerMessage, statsSnapshotTuple,
type BlockHeader, type MiningTemplate, type TestnetBlock } from '../shared/testnet.ts';
export type MineResult = { found: false } | { found: true; hash: string; nonce: string };
/** The RandomX engine as seen from the WebView (the Capacitor plugin, or a fake in tests). */
export interface MinerEngine {
start(threads: number): Promise<void>;
stop(): Promise<void>;
mine(lane: number, key: string, blobHex: string, target: string, nonceOffset: number, maxAttempts: number): Promise<MineResult>;
}
export interface MinerIdentity { address: string; publicKey: string }
export interface MinerDeps {
engine: MinerEngine;
/** POST/GET JSON against the node (relative paths such as /api/mining/template). */
api: (path: string, body?: unknown) => Promise<unknown>;
/** Sign a message with the unlocked web wallet. */
sign: (message: string) => Promise<string>;
chainId: string;
/** Checked before every batch; return a reason to stop (battery saver, thermal, background...). */
blocked?: () => string | undefined | Promise<string | undefined>;
onStatus?: (status: MinerStatus) => void;
now?: () => number;
/** Pause between batches per lane (ms): intensity control. */
idleMs?: number;
random?: () => number;
}
export type MinerPhase = 'idle' | 'starting' | 'requesting' | 'mining' | 'submitting' | 'stopped' | 'error';
export interface MinerStatus {
phase: MinerPhase; hashrate: number; attempts: number; height?: number; article?: string;
accepted: number; rejected: number; lastBlock?: { height: number; tokenId: string; title: string };
message?: string;
}
export const BATCH = 16;
const hex = (bytes: Uint8Array) => Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('');
export function hexToBytes(value: string): Uint8Array {
if (!/^([0-9a-f]{2})*$/i.test(value)) throw new Error('Invalid hex');
const out = new Uint8Array(value.length / 2);
for (let i = 0; i < out.length; i++) out[i] = parseInt(value.slice(2 * i, 2 * i + 2), 16);
return out;
}
export async function sha256Hex(data: string | Uint8Array): Promise<string> {
const bytes = typeof data === 'string' ? new TextEncoder().encode(data) : data;
return hex(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes as BufferSource)));
}
/** Same bytes as consensus `miningBlob`: sha256(headerMessage) || nonce as uint64 little-endian. */
export async function miningBlobHex(header: BlockHeader): Promise<string> {
const nonce = new Uint8Array(8);
new DataView(nonce.buffer).setBigUint64(0, BigInt(header.nonce), true);
return await sha256Hex(headerMessage(header)) + hex(nonce);
}
/** Same value as consensus `mintId`, with the chain id taken from the (verified) header. */
export function mintIdOf(h: BlockHeader): Promise<string> {
return sha256Hex(JSON.stringify([NETWORK, h.chainId, 'mint', h.previousHash, h.height, h.owner,
h.article.pageId, statsSnapshotTuple(h.statsSnapshot)]));
}
export function meetsTarget(hash: string, target: string): boolean {
return BigInt(`0x${hash}`) <= BigInt(`0x${target}`);
}
/** Check a node template before spending CPU on it. */
export async function checkTemplate(t: MiningTemplate, chainId: string, me: MinerIdentity): Promise<void> {
const h = t?.header;
if (!h || h.network !== NETWORK || h.chainId !== chainId || t.nonceOffset !== 32) throw new Error('Node returned work for another network');
if (h.owner !== me.address || h.publicKey !== me.publicKey) throw new Error('Node returned work for another wallet');
if (!/^[0-9a-f]{64}$/.test(h.key) || !/^[0-9a-f]{64}$/.test(h.target)) throw new Error('Node returned malformed work');
if (typeof t.blob === 'string' && t.blob.slice(0, 64) !== (await miningBlobHex({ ...h, nonce: 0 })).slice(0, 64)) {
throw new Error('Node work blob does not match its header');
}
}
/** Assemble the block exactly as server/testnet/miner.ts does. */
export async function buildBlock(t: MiningTemplate, nonce: number, powHash: string, sign: (m: string) => Promise<string>): Promise<TestnetBlock> {
const header: BlockHeader = { ...t.header, nonce };
const blob = await miningBlobHex(header);
const hash = await sha256Hex(hexToBytes(blob));
const signature = await sign(blockClaimMessage(hash));
return { ...header, hash, tokenId: await mintIdOf(header), powHash, signature, transactions: t.transactions };
}
/** Runs until stop() or a safeguard trips. One instance per app. */
export class MobileMiner {
private stopping = false;
private running?: Promise<void>;
status: MinerStatus = { phase: 'idle', hashrate: 0, attempts: 0, accepted: 0, rejected: 0 };
private readonly deps: MinerDeps;
private readonly me: MinerIdentity;
constructor(deps: MinerDeps, me: MinerIdentity) { this.deps = deps; this.me = me; }
private set(patch: Partial<MinerStatus>) { this.status = { ...this.status, ...patch }; this.deps.onStatus?.(this.status); }
get active() { return !!this.running; }
start(threads = 1, maxBlocks = Infinity): Promise<void> {
if (this.running) return this.running;
this.stopping = false;
this.running = this.loop(Math.max(1, Math.min(4, Math.floor(threads))), maxBlocks)
.finally(() => { this.running = undefined; });
return this.running;
}
async stop(reason?: string): Promise<void> {
this.stopping = true;
if (reason) this.set({ message: reason });
await this.deps.engine.stop().catch(() => {});
await this.running?.catch(() => {});
}
private async loop(threads: number, maxBlocks: number) {
const { engine, api } = this.deps;
const now = this.deps.now ?? Date.now, random = this.deps.random ?? Math.random;
this.set({ phase: 'starting', message: undefined, hashrate: 0 });
try {
const reason = await this.deps.blocked?.();
if (reason) throw new Error(`Mining is paused: ${reason}`);
await engine.start(threads);
let accepted = 0;
while (!this.stopping && accepted < maxBlocks) {
this.set({ phase: 'requesting' });
const template = await api('/api/mining/template', { owner: this.me.address, publicKey: this.me.publicKey }) as MiningTemplate;
await checkTemplate(template, this.deps.chainId, this.me);
const h = template.header;
this.set({ phase: 'mining', height: h.height, article: h.article.title });
const started = now();
let attempts = 0, lastCheck = now(), stale = false;
let solution: { nonce: number; hash: string } | undefined;
const lane = async (index: number) => {
let nonce = Math.floor(random() * 2 ** 32);
while (!this.stopping && !solution && !stale) {
const blob = await miningBlobHex({ ...h, nonce });
const result = await engine.mine(index, h.key, blob, h.target, 32, BATCH);
attempts += BATCH;
if (result.found) {
const n = Number(result.nonce);
if (!Number.isSafeInteger(n) || !meetsTarget(result.hash, h.target)) throw new Error('Engine returned an invalid solution');
solution ??= { nonce: n, hash: result.hash };
return;
}
nonce += BATCH;
const elapsed = (now() - started) / 1000;
this.set({ attempts: this.status.attempts + BATCH, hashrate: elapsed > 0 ? attempts / elapsed : 0 });
if (index === 0 && now() - lastCheck >= 2000) {
lastCheck = now();
const reason = await this.deps.blocked?.();
if (reason) { this.stopping = true; this.set({ message: `Paused: ${reason}` }); return; }
const status = await api('/p2p/status') as { tip?: string };
if (status.tip !== h.previousHash || now() / 1000 - h.createdAt > CONSENSUS.targetSeconds * 2) stale = true;
}
if (this.deps.idleMs) await new Promise(r => setTimeout(r, this.deps.idleMs));
}
};
await Promise.all(Array.from({ length: threads }, (_, i) => lane(i)));
if (this.stopping || !solution) continue;
this.set({ phase: 'submitting' });
const block = await buildBlock(template, solution.nonce, solution.hash, this.deps.sign);
try {
const result = await api('/api/blocks', block) as { accepted?: boolean; reason?: string };
if (result.accepted === false) throw new Error(result.reason ?? 'Block not accepted');
accepted++;
this.set({ accepted: this.status.accepted + 1, lastBlock: { height: block.height, tokenId: block.tokenId, title: block.article.title },
message: `Accepted block #${block.height}: ${block.article.title}` });
} catch (error) {
this.set({ rejected: this.status.rejected + 1, message: (error as Error).message });
}
}
this.set({ phase: 'stopped' });
} catch (error) {
this.set({ phase: this.stopping ? 'stopped' : 'error', message: this.stopping ? this.status.message : (error as Error).message });
} finally {
await engine.stop().catch(() => {});
}
}
}
+10
View File
@@ -0,0 +1,10 @@
.mobile-mining { display: grid; gap: 12px; }
.mobile-mining h2 { margin: 0; }
.mobile-mining-consent { display: flex; gap: 10px; align-items: flex-start; }
.mobile-mining-consent input { margin-top: 4px; min-width: 20px; min-height: 20px; }
.mobile-mining-intensity { display: grid; gap: 6px; }
.mobile-mining-intensity select { min-height: 44px; }
.mobile-mining-actions .button { min-height: 44px; display: inline-flex; gap: 8px; align-items: center; }
.mobile-mining-stats { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px 16px; margin: 0; }
.mobile-mining-stats dt { font-size: 0.75rem; opacity: 0.7; }
.mobile-mining-stats dd { margin: 0; font-variant-numeric: tabular-nums; }
+52 -2
View File
@@ -71,7 +71,7 @@ test('costs, bodies and keyword caps stay in range', () => {
if (c.type === 'Figure') {
assert.ok(c.cost >= 1 && c.cost <= 6, c.title);
const taxed = c.keywords.filter(k => DERIVE_RULES.taxedKeywords.includes(k)).length;
assert.ok(c.connect.qid === null || /^Q\d+$/.test(c.connect.qid));
assert.ok(c.connect.qid === undefined || /^Q\d+$/.test(c.connect.qid));
assert.equal(c.power! + c.toughness!, DERIVE_RULES.bodyBudget[c.cost] - taxed, c.title);
assert.ok(c.power! >= 1 && c.toughness! >= 1, c.title);
} else if (c.type === 'Location') {
@@ -181,7 +181,7 @@ test('Portals: keyword hits decide, ties go to the type default, no hits is Neut
test('Connected: Linked beats Compatriot beats Contemporary beats Kin; a card is never connected to itself', () => {
const base = (id: string, pageId: number, connect: Partial<DuelCard['connect']>, type: DuelCard['type'] = 'Event'): DuelCard =>
({ ...byTitle('Tom Ewell'), cardId: id, pageId, type, connect: { countries: [], centuries: [], links: [], p31: [], qid: null, cites: [], ...connect } });
({ ...byTitle('Tom Ewell'), cardId: id, pageId, type, connect: { countries: [], centuries: [], links: [], p31: [], cites: [], ...connect } });
const a = base('a', 1, { links: [2], countries: ['France'], centuries: [20], p31: ['Q1'], qid: 'Q100' }, 'Figure');
assert.equal(connectedTier(a, base('g', 7, { cites: ['Q100'] })), 'Linked');
assert.equal(connectedTier(a, base('h', 8, { centuries: [20] }, 'Figure')), null, 'Contemporary needs different types');
@@ -203,3 +203,53 @@ test('Connected fires in a plausible share of sample pairs (BRIEF target 15–30
const rate = hits / pairs;
assert.ok(rate > 0.1 && rate < 0.4, `rate ${rate}`);
});
test('Doctrines use the engine encoding: attach picks the Figure, a static pump on `attached` carries ±k (DUEL_API)', () => {
for (const c of CARDS.filter(x => x.type === 'Doctrine')) {
assert.equal(c.effects[0].op, 'attach', c.title);
const buff = c.effects[1];
assert.equal(buff.trigger, 'static', c.title);
assert.equal(buff.op, 'pump');
assert.equal(buff.target, 'attached');
const magnitude = c.basis.magnitude;
const sign = c.subtype === 'pathology' ? -1 : 1;
assert.deepEqual([buff.power, buff.toughness], [sign * magnitude, sign * magnitude], c.title);
assert.equal(c.effects[0].target, c.subtype === 'pathology' ? 'figure' : 'ownFigure');
}
assert.deepEqual(byTitle('Heart rot').effects.map(e => [e.trigger, e.op, e.target, e.power ?? null]),
[['onPlay', 'attach', 'figure', null], ['static', 'pump', 'attached', -3]]);
});
test('chain-only fallback: an empty profile still types from the on-chain title, category and extract', () => {
const empty = profile({});
const chain = (title: string, extract = '', category?: string) => ({ title, extract, ...(category ? { category } : {}) });
assert.equal(classify(empty, chain('Tom Ewell', 'Tom Ewell (born Samuel Yewell Tompkins; April 29, 1909 – September 12, 1994) was an American actor.')).type, 'Figure');
assert.equal(classify(empty, chain('Buky', 'Buky is a village in Cherkasy Oblast, Ukraine.')).type, 'Location');
assert.equal(classify(empty, chain('Heart rot', 'Heart rot is a fungal disease of trees.')).type, 'Doctrine');
assert.equal(classify(empty, chain('1954 Gold Coast general election')).source, 'title');
assert.equal(classify(empty, chain('1954 Gold Coast general election')).type, 'Event');
assert.equal(classify(empty, chain('Zzyzx', '', 'People')).type, 'Figure');
assert.equal(classify(empty, chain('Zzyzx', '', 'Culture')).source, 'fallback');
assert.equal(classify(empty).source, 'fallback', 'no chain hints: unchanged');
// derive() passes chain.article through, so hosts need no extra argument.
const { chain: c } = sampleInputs(SAMPLE.find(s => s.title === '1954 Gold Coast general election')!);
const card = derive(c, empty);
assert.deepEqual([card.type, card.typedBy, card.subtype], ['Event', 'title', 'election']);
});
test('chain-only typing over the sample agrees with the full classifier on most cards', () => {
// The sample has no extracts and tests can't fetch, so this uses a lead-sentence proxy:
// "<Title> is a <description>." (Wikipedia leads usually open this way). Labelled as a proxy.
const empty = profile({});
let agree = 0; const types: Record<string, number> = {};
for (const s of SAMPLE) {
const extract = s.description ? `${s.title} is a ${s.description[0].toLowerCase()}${s.description.slice(1)}.` : '';
const t = classify(empty, { title: s.title, extract, ...(s.legacyCategory ? { category: s.legacyCategory } : {}) }).type;
types[t] = (types[t] ?? 0) + 1;
if (t === classify(s).type) agree++;
}
assert.ok(agree / SAMPLE.length >= 0.8, `agree ${agree}/${SAMPLE.length}`);
assert.ok(types.Figure / SAMPLE.length > 0.3 && types.Figure / SAMPLE.length < 0.42, JSON.stringify(types));
assert.ok(types.Location / SAMPLE.length > 0.22 && types.Location / SAMPLE.length < 0.38, JSON.stringify(types));
assert.ok(types.Doctrine / SAMPLE.length < 0.25, JSON.stringify(types));
});
+50
View File
@@ -0,0 +1,50 @@
{
"log": [
"Turn 1. alice brought *Pathrail Mosque* (Mosque in Faridpur, Bangladesh) into play.[1]",
"Turn 2. bob added *1954 Gold Coast general election* to their hand.[2]",
"Turn 3. alice added *Dichromorpha viridis* (Species of grasshopper) to their hand.[3] *Dichromorpha viridis* entered play under alice.",
"Turn 4. bob added a card to their hand. *1954 Gold Coast general election* was cited by bob. *1954 Gold Coast general election* brought two Elected Members into play.",
"Turn 5. alice drew one card. alice sent *Dichromorpha viridis* (4/2) into combat. bob lost 4 Notability (16 remaining).",
"Turn 6. bob drew one card. bob cited *April 2021 nor'easter* (Slow-moving nor'easter in April 2021).[4] *Dichromorpha viridis* took 1 damage from *April 2021 nor'easter*. *April 2021 nor'easter* dealt 1 damage to *Pathrail Mosque*. *Dichromorpha viridis* was removed from play.",
"Turn 7. alice added a card to their hand. *Zbyszek Godlewski* (Polish protester, 1952–1970) entered play under alice.[5]",
"Turn 8. bob added a card to their hand. *Marc Fesneau* (French politician, born 1971) entered play under bob.[6]",
"Turn 9. alice drew one card. *Zbyszek Godlewski* (6/3) attacked. *Zbyszek Godlewski* was blocked by *Marc Fesneau* (5/4). *Zbyszek Godlewski* was removed from play. *Marc Fesneau* was removed from play. alice drew one card.",
"Turn 10. bob added a card to their hand. bob discarded *Agda (programming language)* (Functional programming language).[7] bob deployed *Pallas's cat* (Species of small wild cat).[8]",
"Turn 11. alice drew one card. alice deployed *Tom Ewell* (American actor, 1909–1994).[9]",
"Turn 12. bob added a card to their hand. bob attached *Heart rot* (Fungal disease of trees) to *Tom Ewell* (2/2).[10] *Pallas's cat* (5/5) advanced on alice. *Pallas's cat* dealt 5 damage to alice, leaving 15 Notability.",
"Turn 13. alice added a card to their hand. *Monoid* (Algebraic structure with an associative operation and an identity element) was adopted by *Tom Ewell*, which became a 5/5.[11] alice sent *Tom Ewell* (5/5) into combat. bob lost 5 Notability (11 remaining).",
"Turn 14. bob drew one card. bob invoked *2025 Tehreek-e-Labbaik Pakistan protests* (Gaza war protests in Pakistan).[12] *2025 Tehreek-e-Labbaik Pakistan protests* inflicted 3 damage on *Tom Ewell*. bob brought *Tatsunoko Production* (Japanese animation studio) into play.[13] bob sent *Pallas's cat* (5/5) into combat. alice's Notability fell to 10.",
"Turn 15. alice drew a card. *Tom Ewell* (5/5) advanced on bob. bob lost 5 Notability (6 remaining).",
"Turn 16. bob drew a card. bob sent *Pallas's cat* (5/5) into combat. alice lost 5 Notability (5 remaining).",
"Turn 17. alice drew one card. *Tom Ewell* (5/5) advanced on bob. bob's Notability fell to 1.",
"Turn 18. bob drew one card. bob sent *Pallas's cat* (5/5) into combat. alice lost 5 Notability (0 remaining). alice was reduced to 0 Notability. bob won."
],
"lead": "The **Battle of Pathrail Mosque (2026)** was a WikiDeck engagement fought on 17 November 2026 between the forces of alice and bob. It lasted eighteen turns and ended in a Pyrrhic victory for bob.[1] Contemporary accounts note the deployment of *Dichromorpha viridis* (Species of grasshopper) in the third turn.[2]",
"sections": [
{
"heading": "Background",
"paragraphs": [
"Arts, Earth, History, Science and Society were equally represented in the force of alice (one card each, of five cards played).",
"Society was the largest Portal in the force of bob (three of seven cards played)."
]
},
{
"heading": "Course of the battle",
"paragraphs": [
"In the ninth turn, *Zbyszek Godlewski* (Polish protester, 1952–1970) was destroyed.[3] *Marc Fesneau* (French politician, born 1971) was removed from play.[4]",
"In the twelfth turn, *Pallas's cat* (Species of small wild cat) dealt 5 damage to alice, leaving 15 Notability.[5]",
"In the thirteenth turn, *Tom Ewell* (American actor, 1909–1994) dealt 5 damage to bob, leaving 11 Notability.[6]",
"In the fourteenth turn, *Pallas's cat* dealt 5 damage to alice, leaving 10 Notability.",
"In the fifteenth turn, *Tom Ewell* dealt 5 damage to bob, leaving 6 Notability.",
"In the sixteenth turn, *Pallas's cat* dealt 5 damage to alice, leaving 5 Notability.",
"alice was nominated for deletion. The result was **delete**."
]
},
{
"heading": "Aftermath",
"paragraphs": [
"bob ended the engagement with 1 Notability; alice ended with 0."
]
}
]
}
+256
View File
@@ -0,0 +1,256 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync, readdirSync } from 'node:fs';
import {
BANNED_WORDS, FOOTER, LOG_TEMPLATES, gloss, logParagraphs, longDate, recap, renderLog,
type CardType, type MatchRecord, type StoryCard, type StoryEvent,
} from '../shared/duel/story/index.ts';
// Real cards from docs/game/card-sample.json (no network). Types, costs and Portals are the
// DUEL_DESIGN.md §9 worked examples.
const sample = JSON.parse(readFileSync(new URL('../docs/game/card-sample.json', import.meta.url), 'utf8')) as {
cards: { title: string; description: string | null; revisionId: number; pageId: number }[];
};
const byTitle = new Map(sample.cards.map(c => [c.title, c]));
function card(id: string, title: string, type: CardType, cost: number, portal: string, owner: 0 | 1): StoryCard {
const c = byTitle.get(title);
if (!c) throw new Error(`not in sample: ${title}`);
return { id, title, description: c.description ?? '', type, cost, portal, revisionId: c.revisionId, tokenId: `tok-${c.pageId}`, owner };
}
const cards: Record<string, StoryCard> = Object.fromEntries([
card('a1', 'Dichromorpha viridis', 'Figure', 2, 'Earth', 0),
card('a2', 'Pathrail Mosque', 'Location', 2, 'Society', 0),
card('a3', 'Zbyszek Godlewski', 'Figure', 5, 'History', 0),
card('a4', 'Monoid', 'Doctrine', 6, 'Science', 0),
card('a5', 'Tom Ewell', 'Figure', 6, 'Arts', 0),
card('b1', '1954 Gold Coast general election', 'Event', 3, 'Society', 1),
card('b2', "April 2021 nor'easter", 'Event', 3, 'Earth', 1),
card('b3', 'Marc Fesneau', 'Figure', 5, 'Society', 1),
card('b4', "Pallas's cat", 'Figure', 6, 'Earth', 1),
card('b5', 'Heart rot', 'Doctrine', 5, 'Science', 1),
card('b6', '2025 Tehreek-e-Labbaik Pakistan protests', 'Event', 5, 'Society', 1),
card('b7', 'Tatsunoko Production', 'Institution', 6, 'Arts', 1),
card('b8', 'Agda (programming language)', 'Doctrine', 6, 'Science', 1),
].map(c => [c.id, c]));
const T = (turn: number): StoryEvent => ({ kind: 'turnStart', turn, seat: turn % 2 === 1 ? 0 : 1 });
const events: StoryEvent[] = [
T(1), { kind: 'deploy', seat: 0, card: 'a2' },
T(2), { kind: 'draw', seat: 1, card: 'b1' },
T(3), { kind: 'draw', seat: 0, card: 'a1' }, { kind: 'deploy', seat: 0, card: 'a1' },
T(4), { kind: 'draw', seat: 1 }, { kind: 'cast', seat: 1, card: 'b1' },
{ kind: 'tokenCreated', seat: 1, source: 'b1', token: 'Elected Member', count: 2 },
T(5), { kind: 'draw', seat: 0 }, { kind: 'attack', seat: 0, card: 'a1', power: 4, toughness: 2 },
{ kind: 'playerDamage', seat: 1, source: 'a1', amount: 4, life: 16 },
T(6), { kind: 'draw', seat: 1 }, { kind: 'cast', seat: 1, card: 'b2' },
{ kind: 'effectDamage', source: 'b2', target: 'a1', amount: 1 },
{ kind: 'effectDamage', source: 'b2', target: 'a2', amount: 1 }, { kind: 'destroyed', card: 'a1' },
T(7), { kind: 'draw', seat: 0 }, { kind: 'deploy', seat: 0, card: 'a3' },
T(8), { kind: 'draw', seat: 1 }, { kind: 'deploy', seat: 1, card: 'b3' },
T(9), { kind: 'draw', seat: 0 }, { kind: 'attack', seat: 0, card: 'a3', power: 6, toughness: 3 },
{ kind: 'block', seat: 1, blocker: 'b3', attacker: 'a3', power: 5, toughness: 4 },
{ kind: 'destroyed', card: 'a3' }, { kind: 'destroyed', card: 'b3' }, { kind: 'draw', seat: 0 },
T(10), { kind: 'draw', seat: 1 }, { kind: 'discard', seat: 1, card: 'b8' }, { kind: 'deploy', seat: 1, card: 'b4' },
T(11), { kind: 'draw', seat: 0 }, { kind: 'deploy', seat: 0, card: 'a5' },
T(12), { kind: 'draw', seat: 1 }, { kind: 'adopt', seat: 1, doctrine: 'b5', figure: 'a5', power: 2, toughness: 2 },
{ kind: 'attack', seat: 1, card: 'b4', power: 5, toughness: 5 }, { kind: 'playerDamage', seat: 0, source: 'b4', amount: 5, life: 15 },
T(13), { kind: 'draw', seat: 0 }, { kind: 'adopt', seat: 0, doctrine: 'a4', figure: 'a5', power: 5, toughness: 5 },
{ kind: 'attack', seat: 0, card: 'a5', power: 5, toughness: 5 }, { kind: 'playerDamage', seat: 1, source: 'a5', amount: 5, life: 11 },
T(14), { kind: 'draw', seat: 1 }, { kind: 'cast', seat: 1, card: 'b6' },
{ kind: 'effectDamage', source: 'b6', target: 'a5', amount: 3 }, { kind: 'deploy', seat: 1, card: 'b7' },
{ kind: 'attack', seat: 1, card: 'b4', power: 5, toughness: 5 }, { kind: 'playerDamage', seat: 0, source: 'b4', amount: 5, life: 10 },
T(15), { kind: 'draw', seat: 0 }, { kind: 'attack', seat: 0, card: 'a5', power: 5, toughness: 5 },
{ kind: 'playerDamage', seat: 1, source: 'a5', amount: 5, life: 6 },
T(16), { kind: 'draw', seat: 1 }, { kind: 'attack', seat: 1, card: 'b4', power: 5, toughness: 5 },
{ kind: 'playerDamage', seat: 0, source: 'b4', amount: 5, life: 5 },
T(17), { kind: 'draw', seat: 0 }, { kind: 'attack', seat: 0, card: 'a5', power: 5, toughness: 5 },
{ kind: 'playerDamage', seat: 1, source: 'a5', amount: 5, life: 1 },
T(18), { kind: 'draw', seat: 1 }, { kind: 'attack', seat: 1, card: 'b4', power: 5, toughness: 5 },
{ kind: 'playerDamage', seat: 0, source: 'b4', amount: 5, life: 0 },
{ kind: 'gameOver', winner: 1, reason: 'life', turn: 18 },
];
const record: MatchRecord = {
matchId: 'golden-1', seed: 'golden-seed', date: '2026-11-17',
players: [{ name: 'alice' }, { name: 'bob' }], cards, events, hostName: 'testnet-r350',
};
test('recap: title, infobox and footer follow DUEL_DESIGN §8.3', () => {
const r = recap(record);
assert.equal(r.title, 'Battle of Pathrail Mosque (2026)'); // loser's Location; 9 turns each → "Battle of"
assert.equal(r.url, '/recap/golden-1');
assert.equal(r.masthead, 'WikiDeck');
assert.deepEqual(r.infobox, {
date: '17 November 2026',
location: 'Pathrail Mosque',
result: 'Pyrrhic bob victory',
belligerents: ['alice', 'bob'],
commanders: ['Tom Ewell', "Pallas's cat"],
strength: ['5 cards', '7 cards'],
casualties: ['2 cards destroyed: Dichromorpha viridis, Zbyszek Godlewski', '1 card destroyed: Marc Fesneau'],
});
assert.equal(r.footer, FOOTER);
assert.match(r.lead, /^The \*\*Battle of Pathrail Mosque \(2026\)\*\* .*17 November 2026.*alice.*bob.*eighteen turns.*a Pyrrhic victory for bob\.\[1\]/);
assert.match(r.lead, /\*Dichromorpha viridis\* \(Species of grasshopper\).* third turn\.\[2\]$/);
assert.deepEqual(r.sections.map(s => s.heading), ['Background', 'Course of the battle', 'Aftermath']);
assert.match(r.sections[2].paragraphs[0], /^bob ended the engagement with 1 Notability; alice ended with 0\.$/);
});
test('recap: references cite every card played with its revision id, in first-mention order', () => {
const r = recap(record);
assert.equal(r.references.length, 12);
assert.deepEqual(r.references.map(x => x.n), r.references.map((_, i) => i + 1));
assert.equal(r.references[0].title, 'Pathrail Mosque');
for (const ref of r.references) {
const c = cards[ref.cardId];
assert.equal(ref.revisionId, c.revisionId);
assert.ok(ref.url.endsWith(`&oldid=${c.revisionId}`), ref.url);
assert.ok(ref.url.startsWith('https://en.wikipedia.org/w/index.php?title='));
assert.match(ref.text, new RegExp(`Revision ${c.revisionId}\\. Minted as token tok-`));
}
// every [n] used in the text exists
const text = [r.lead, ...r.sections.flatMap(s => s.paragraphs)].join(' ');
for (const m of text.matchAll(/\[(\d+)\]/g)) assert.ok(Number(m[1]) <= r.references.length);
});
test('log: golden lines for the omniscient view', () => {
const { lines, references } = renderLog(record, null);
const paras = logParagraphs(lines);
assert.equal(paras.length, 18);
assert.equal(lines[0].text, 'Turn 1.');
assert.match(lines[1].text, /\*Pathrail Mosque\* \(Mosque in Faridpur, Bangladesh\).*\[1\]$/);
assert.ok(lines.some(l => /\*Zbyszek Godlewski\* \(Polish protester, 1952–1970\)/.test(l.text)));
assert.ok(lines.some(l => /two Elected Members/.test(l.text)));
assert.match(lines[lines.length - 1].text, /alice/);
// later mentions carry no gloss and no new citation
const later = lines.filter(l => l.text.includes('*Tom Ewell*'));
assert.ok(later.length >= 3);
assert.equal(later.filter(l => l.text.includes('American actor')).length, 1);
assert.equal(references.length, 13); // 12 played + the discarded Agda
// snapshot of the whole log text (golden): regenerate deliberately if templates change
assert.equal(paras.join('\n').length > 1500, true);
assert.deepEqual(renderLog(record, null), { lines, references });
});
test('log: logFor hides the opponent\'s draws', () => {
const forAlice = renderLog(record, 0).lines.map(l => l.text);
const forBob = renderLog(record, 1).lines.map(l => l.text);
const turn2Alice = forAlice[forAlice.indexOf('Turn 2.') + 1];
const turn2Bob = forBob[forBob.indexOf('Turn 2.') + 1];
assert.doesNotMatch(turn2Alice, /Gold Coast/);
assert.match(turn2Alice, /^bob (drew a card|drew one card|added a card to their hand)\.$/);
assert.match(turn2Bob, /Gold Coast/);
// alice sees her own draw of Dichromorpha viridis by name
assert.ok(forAlice.some(t => /alice.*Dichromorpha viridis|Dichromorpha viridis.*alice/.test(t) && /drew|drawn|hand/.test(t)));
});
test('log: discards are public (Deleted is a public zone)', () => {
const forAlice = renderLog(record, 0).lines.map(l => l.text);
assert.ok(forAlice.some(t => /Agda \(programming language\)/.test(t) && /discard|Deleted/.test(t)));
});
test('determinism: same seed gives the same text; another seed varies it', () => {
assert.deepEqual(recap(record), recap(structuredClone(record)));
const other = recap({ ...record, seed: 'another-seed' });
const a = renderLog(record).lines.map(l => l.text).join('\n');
const b = renderLog({ ...record, seed: 'another-seed' }).lines.map(l => l.text).join('\n');
assert.notEqual(a, b);
assert.equal(other.title, recap(record).title); // the name is data, not a variant
});
test('recap naming: Event fallback, Figure campaign, prefixes, and the decisive and withdrawal results', () => {
const base = { ...record, cards };
const short: MatchRecord = { ...base, events: [
T(1), { kind: 'cast', seat: 0, card: 'b6' }, { kind: 'deploy', seat: 0, card: 'a3' },
T(2), { kind: 'gameOver', winner: 0, reason: 'concede', turn: 2 },
] };
const r1 = recap(short);
assert.equal(r1.title, 'Skirmish at 2025 Tehreek-e-Labbaik Pakistan protests (2026)');
assert.equal(r1.infobox.result, 'alice victory by withdrawal');
assert.equal(r1.infobox.location, 'WikiDeck host testnet-r350');
const figOnly: MatchRecord = { ...base, events: [
T(1), { kind: 'deploy', seat: 1, card: 'b3' },
T(2), { kind: 'playerDamage', seat: 0, amount: 20, life: 0 }, { kind: 'gameOver', winner: 1, reason: 'life', turn: 2 },
] };
const r2 = recap(figOnly);
assert.equal(r2.title, 'Marc Fesneau campaign (2026)');
assert.equal(r2.infobox.result, 'Decisive bob victory');
const empty: MatchRecord = { ...base, events: [T(1), { kind: 'gameOver', winner: 1, reason: 'timeout', turn: 1 }] };
assert.equal(recap(empty).title, 'WikiDeck match of 17 November 2026');
});
test('tone lint: templates are deadpan (DUEL_DESIGN §8.1, critic S7)', () => {
for (const [key, variants] of Object.entries(LOG_TEMPLATES)) {
assert.ok(variants.length >= 3 && variants.length <= 4, `${key} has ${variants.length} variants`);
for (const v of variants) {
assert.doesNotMatch(v, /!/, `${key}: no exclamation marks`);
for (const w of BANNED_WORDS) assert.doesNotMatch(v.toLowerCase(), new RegExp(`\\b${w}\\b`), `${key}: banned word ${w}`);
assert.doesNotMatch(v, /[\u{1F300}-\u{1FAFF}]/u, `${key}: no emoji`);
}
}
const r = recap(record);
const prose = [r.lead, ...r.sections.flatMap(s => s.paragraphs)].join(' ')
.replace(/\*[^*]+\*/g, 'CARD'); // card titles are data; lint only our words
for (const w of BANNED_WORDS) assert.doesNotMatch(prose.toLowerCase(), new RegExp(`\\b${w}\\b`));
assert.doesNotMatch(prose, /!/);
assert.doesNotMatch(prose, /Wikipedia|Wikimedia/); // branding: only in references and the footer
});
test('every sample description glosses without throwing; dates format', () => {
for (const c of sample.cards) assert.equal(typeof gloss(c.description ?? ''), 'string');
assert.equal(gloss('American actor (1909–1994)'), 'American actor, 1909–1994');
assert.equal(gloss(''), '');
assert.equal(longDate('2026-01-05'), '5 January 2026');
});
test('story code is pure: no network or clock access', () => {
const dir = new URL('../shared/duel/story/', import.meta.url);
for (const f of readdirSync(dir)) {
const src = readFileSync(new URL(f, dir), 'utf8');
assert.doesNotMatch(src, /\bfetch\(|XMLHttpRequest|node:http|Date\.now|new Date\(|Math\.random/, f);
}
});
test('golden: full log and recap prose match tests/duel-design-story.golden.json', () => {
// To regenerate after a deliberate template change, dump { log, lead, sections } and review the diff.
const golden = JSON.parse(readFileSync(new URL('./duel-design-story.golden.json', import.meta.url), 'utf8'));
const r = recap(record);
assert.deepEqual({ log: logParagraphs(renderLog(record).lines), lead: r.lead, sections: r.sections }, golden);
});
test('tokens are named plainly and never cited; draws are recorded as inconclusive', () => {
const withToken: MatchRecord = {
...record,
cards: { ...cards, 't:1': { id: 't:1', title: 'Elected Member', type: 'Figure', cost: 0, portal: 'Society', owner: 1, token: true } },
events: [
T(1), { kind: 'cast', seat: 1, card: 'b1' },
{ kind: 'tokenCreated', seat: 1, source: 'b1', token: 'Elected Member', count: 1 },
T(2), { kind: 'attack', seat: 1, card: 't:1', power: 1, toughness: 1 },
{ kind: 'playerDamage', seat: 0, source: 't:1', amount: 20, life: 0 },
{ kind: 'playerDamage', seat: 1, amount: 20, life: 0 },
{ kind: 'gameOver', winner: null, reason: 'life', turn: 2 },
],
};
const { lines, references } = renderLog(withToken);
assert.ok(lines.some(l => /Elected Member \(1\/1\)/.test(l.text) && !/\*Elected Member\*/.test(l.text)));
assert.deepEqual(references.map(r => r.title), ['1954 Gold Coast general election']);
assert.match(lines[lines.length - 1].text, /draw|No winner/);
const r = recap(withToken);
assert.equal(r.infobox.result, 'Inconclusive');
assert.match(r.lead, /ended in a draw\./);
assert.ok(r.references.every(x => x.revisionId !== undefined));
});
test('final Notability: lifeGain is tracked, and gameOver.life wins when present', () => {
const ev: StoryEvent[] = [
T(1), { kind: 'deploy', seat: 0, card: 'a2' },
{ kind: 'playerDamage', seat: 0, amount: 18, life: 2 },
{ kind: 'lifeGain', seat: 0, source: 'a2', amount: 10, life: 12 },
{ kind: 'playerDamage', seat: 1, amount: 20, life: 0 },
{ kind: 'gameOver', winner: 0, reason: 'life', turn: 1 },
];
const r = recap({ ...record, events: ev });
assert.equal(r.infobox.result, 'Decisive alice victory'); // 12 vs 0, not Pyrrhic at 2
assert.ok(renderLog({ ...record, events: ev }).lines.some(l => /Notability/.test(l.text) && /12/.test(l.text)));
const withFinal = recap({ ...record, events: [...ev.slice(0, -1), { kind: 'gameOver', winner: 0, reason: 'life', turn: 1, life: [3, 0] }] });
assert.equal(withFinal.infobox.result, 'Pyrrhic alice victory');
});
+88
View File
@@ -0,0 +1,88 @@
// Playwright smoke test for the ui-pvp screens (not part of `npm test`: Playwright isn't a repo dependency).
// Every /api call is stubbed in the browser, so it makes zero network calls beyond localhost.
// Run: npm run build && npx vite preview --port 4179 & then
// PLAYWRIGHT_FROM=<dir containing node_modules/playwright>/ node tests/e2e/ui-pvp-smoke.mjs http://localhost:4179 <out-dir>
import { createRequire } from 'node:module';
import { readFileSync, mkdirSync } from 'node:fs';
import assert from 'node:assert/strict';
const { chromium } = createRequire(process.env.PLAYWRIGHT_FROM ? `${process.env.PLAYWRIGHT_FROM.replace(/\/?$/, '/')}x.js` : import.meta.url)('playwright');
const base = process.argv[2] ?? 'http://localhost:4179';
const out = process.argv[3] ?? 'screenshots';
mkdirSync(out, { recursive: true });
const sample = JSON.parse(readFileSync(new URL('../../docs/game/card-sample.json', import.meta.url), 'utf8')).cards;
const cards = n => sample.slice(0, n).map((c, i) => ({ tokenId: `tok${i}`, pageId: c.pageId, title: c.title, revisionId: c.revisionId,
url: `https://en.wikipedia.org/wiki/${encodeURIComponent(c.title.replace(/ /g, '_'))}`, category: 'People', height: 10 + i, confirmations: 3 }));
const account = { sub: 'alice-sub', issuer: 'https://dex.eom.dev', name: 'alice', username: 'alice', wallets: [{ address: 'a'.repeat(64), linkedAt: 1 }] };
const match = { matchId: 'm_smoke', modeName: 'Classic', players: [{ name: 'alice' }, { name: 'bob' }], turns: 9,
startedAt: Date.UTC(2026, 10, 17, 23, 40), endedAt: Date.UTC(2026, 10, 18, 0, 2), result: { winner: 0, reason: 'notability' }, strength: [40, 40],
played: [sample.slice(0, 4).map(c => ({ ...c, type: 'Figure' })).concat([{ ...sample[10], type: 'Doctrine' }]), sample.slice(4, 8).map(c => ({ ...c, type: 'Figure' }))],
lost: [[sample[1]], [sample[4], sample[5]]] };
async function page(browser, { width, height, owned }) {
const ctx = await browser.newContext({ viewport: { width, height }, deviceScaleFactor: 2 });
await ctx.addInitScript(a => {
sessionStorage.setItem('wikideck.auth.session', JSON.stringify({ idToken: 'test-token', expiresAt: Date.now() + 3600e3, account: a }));
localStorage.setItem('wikideck-play-tutorial-v1', '1');
}, account);
let lobbyPolls = 0;
await ctx.route('**/api/**', async route => {
const url = new URL(route.request().url());
const p = url.pathname, json = (body, status = 200) => route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) });
if (p === '/api/game/collection') return json({ deckSize: 40, copyLimit: 4, cards: cards(owned) });
if (p === '/api/account/me') return json(account);
if (p === '/api/game/modes') return json({ modes: [{ mode: { id: 'classic', name: 'Classic', engine: 'duel', limits: { rated: true } } }] });
if (p.endsWith('/ladder')) return json({ entries: [{ name: 'alice', rating: 1236, wins: 4, losses: 1 }, { name: 'bob', rating: 1188, wins: 1, losses: 3 }, { name: 'carol', rating: 1176, wins: 0, losses: 1 }] });
if (p === '/api/game/modes/classic/lobbies') return json({ lobbyId: 'L1', seat: 0, token: 'seat-tok', invite: 'Inv7Qx2' });
if (p === '/api/game/lobbies/L1') { lobbyPolls++; return json({ lobbyId: 'L1', version: 1, phase: 'waiting', seat: 0, players: [{ name: 'alice' }], outcome: null, invite: 'Inv7Qx2' }); }
if (p === '/api/game/matches/m_smoke') return json(match);
return route.fulfill({ status: 503, contentType: 'application/json', body: '{"error":"stubbed"}' });
});
return { ctx, page: await ctx.newPage(), polls: () => lobbyPolls };
}
const openPlay = async p => {
await p.goto(base + '/');
await p.getByRole('navigation', { name: 'Main navigation' }).getByText('Play', { exact: true }).first().click();
};
const browser = await chromium.launch();
try {
// 1. Under 40 cards: progress + mine, no borrowed decks.
{ const { ctx, page: p } = await page(browser, { width: 360, height: 740, owned: 23 });
await openPlay(p);
await p.getByText('23 / 40 cards. Mine to play').waitFor();
assert.equal(await p.getByRole('button', { name: /Quick match/ }).count(), 0, 'no play buttons below 40 cards');
assert.equal(await p.getByText(/loaner|starter deck/i).count(), 0, 'no loaners offered');
await p.screenshot({ path: `${out}/1-eligibility-360.png`, fullPage: true }); await ctx.close(); }
// 2. 44 cards: PvP hub with quick match, private lobby, join, ladder.
{ const { ctx, page: p, polls } = await page(browser, { width: 360, height: 740, owned: 44 });
await openPlay(p);
await p.getByRole('button', { name: /Quick match/ }).waitFor();
await p.getByText('40 / 40').waitFor();
await p.getByText('1236').waitFor();
await p.screenshot({ path: `${out}/2-pvp-hub-360.png`, fullPage: true });
await p.getByRole('button', { name: 'Edit deck' }).click();
await p.getByText(/Pick exactly 40/).waitFor();
await p.screenshot({ path: `${out}/3-deck-picker-360.png` });
await p.getByRole('button', { name: 'Cancel' }).click();
await p.getByRole('button', { name: /Private lobby/ }).click();
await p.getByLabel('Invite link').getByText(/\/play\/invite\/Inv7Qx2$/).waitFor();
await p.waitForTimeout(2500);
assert.ok(polls() >= 1, 'the lobby polls the host');
await p.screenshot({ path: `${out}/4-private-lobby-360.png`, fullPage: true }); await ctx.close(); }
// 3. Invite deep link.
{ const { ctx, page: p } = await page(browser, { width: 360, height: 740, owned: 44 });
await p.goto(base + '/play/invite/Inv7Qx2');
await p.getByText('You have been invited to a duel.').waitFor();
await p.screenshot({ path: `${out}/5-invite-360.png` }); await ctx.close(); }
// 4. Battle recap at 360 and desktop.
for (const [w, h, name] of [[360, 740, '6-recap-360'], [1280, 900, '7-recap-desktop']]) {
const { ctx, page: p } = await page(browser, { width: w, height: h, owned: 44 });
await p.goto(base + (w === 360 ? '/recap/m_smoke' : '/battle/m_smoke'));
await p.getByRole('heading', { level: 1, name: /^Battle of / }).waitFor();
await p.getByRole('heading', { name: 'References' }).waitFor();
assert.ok(await p.locator('.recap-refs li').count() >= 8);
await p.screenshot({ path: `${out}/${name}.png`, fullPage: true }); await ctx.close();
}
console.log('ui-pvp smoke: OK');
} finally { await browser.close(); }
+1 -1
View File
@@ -54,7 +54,7 @@ test('fixed HTTPS sources, encoded title, hidden categories, lower bounds and pl
assert.equal(init.redirect, 'error');
assert.ok(init.signal instanceof AbortSignal);
assert.equal(new Headers(init.headers).get('accept'), 'application/json');
assert.match(new Headers(init.headers).get('user-agent')!, /Wikideck/);
assert.match(new Headers(init.headers).get('user-agent')!, /WikiDeck/i);
assert.equal(new Headers(init.headers).has('origin'), false); // Server-side requests need no CORS workaround.
}
assert.equal(result.title, title);
+121
View File
@@ -0,0 +1,121 @@
// mobile-mining: the WebView mining loop must build blocks byte-identical to server/testnet/miner.ts.
// No network calls: the node API and the RandomX engine are in-process fakes.
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash, generateKeyPairSync, sign } from 'node:crypto';
import { CHAIN_ID, MAX_TARGET, address, makeTemplate, miningBlob, mintId, sha256, validateBlock } from '../server/testnet/consensus.ts';
import { type MiningTemplate, type TestnetBlock } from '../shared/testnet.ts';
import { deriveStats } from '../shared/enrichment.ts';
import type { PowEngine } from '../server/testnet/randomx.ts';
import { MobileMiner, buildBlock, checkTemplate, meetsTarget, miningBlobHex, mintIdOf, type MinerEngine, type MineResult } from '../src/mobile-miner.ts';
const keys = generateKeyPairSync('ec', { namedCurve: 'prime256v1' });
const publicKey = keys.publicKey.export({ format: 'der', type: 'spki' }).toString('base64');
const me = { publicKey, address: address(publicKey) };
const signer = async (message: string) => sign('sha256', Buffer.from(message), { key: keys.privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64');
const fakeHash = (key: string, blob: Uint8Array) => createHash('sha256').update(Buffer.concat([Buffer.from(key, 'hex'), Buffer.from(blob)])).digest('hex');
// Test-only stand-in for RandomX on both sides (production has no fake PoW).
const pow: PowEngine = { hash: async (key, blob) => fakeHash(key, blob), close() {} };
function template(target = MAX_TARGET): MiningTemplate {
const pageBytes = 2048, languageCount = 3;
const stats = { capturedAt: '2026-11-17T00:00:00.000Z', revisionId: 7, pageBytes, languageCount, languagesTruncated: false,
pageviews: { status: 'unavailable' as const, months: [], latestMonth: '2026-10', total: null, dailyAverage: null, trendPercent: null },
stats: deriveStats(pageBytes, languageCount, null) };
const article = { pageId: 4242, title: 'Tetrated dodecahedron', extract: 'A deterministic test article.', image: 'https://upload.wikimedia.org/wikipedia/commons/test.jpg',
url: 'https://en.wikipedia.org/?curid=4242', revisionId: 7, source: 'live' as const, category: 'Science' };
const t = makeTemplate([], {}, me.address, me.publicKey, [], article, stats, Math.floor(Date.now() / 1000));
t.header.target = target;
t.blob = miningBlob(t.header).toString('hex');
return t;
}
/** Fake engine that speaks the plugin's mine contract with the fake hash. */
class FakeEngine implements MinerEngine {
started = 0; stopped = 0; calls = 0;
async start() { this.started++; }
async stop() { this.stopped++; }
async mine(_lane: number, key: string, blobHex: string, target: string, offset: number, max: number): Promise<MineResult> {
this.calls++;
const blob = Buffer.from(blobHex, 'hex');
let nonce = blob.readBigUInt64LE(offset);
for (let i = 0; i < max; i++, nonce++) {
blob.writeBigUInt64LE(nonce, offset);
const hash = fakeHash(key, blob);
if (meetsTarget(hash, target)) return { found: true, hash, nonce: nonce.toString() };
}
return { found: false };
}
}
test('browser blob and mint id match consensus', async () => {
const t = template();
for (const nonce of [0, 1, 2 ** 32 + 5, Number.MAX_SAFE_INTEGER]) {
const header = { ...t.header, nonce };
assert.equal(await miningBlobHex(header), miningBlob(header).toString('hex'));
}
assert.equal(await mintIdOf(t.header), mintId(t.header));
assert.equal(t.header.chainId, CHAIN_ID);
});
test('buildBlock produces a block the consensus validator accepts', async () => {
const t = template();
const header = { ...t.header, nonce: 0 };
while (!meetsTarget(fakeHash(header.key, miningBlob(header)), header.target)) header.nonce++;
const powHash = fakeHash(header.key, miningBlob(header));
const block = await buildBlock(t, header.nonce, powHash, signer);
assert.equal(block.hash, sha256(miningBlob(header)));
assert.equal(block.signature.length > 0, true);
const { block: valid } = await validateBlock(structuredClone(block), [], {}, pow);
assert.equal(valid.tokenId, mintId(header));
});
test('checkTemplate rejects work for another network or wallet', async () => {
const t = template();
await checkTemplate(t, CHAIN_ID, me);
await assert.rejects(checkTemplate(t, 'f'.repeat(64), me), /another network/);
await assert.rejects(checkTemplate(t, CHAIN_ID, { ...me, address: '0'.repeat(64) }), /another wallet/);
await assert.rejects(checkTemplate({ ...t, blob: '00'.repeat(40) }, CHAIN_ID, me), /does not match/);
});
test('MobileMiner mines, signs and submits one accepted block, then stops the engine', async () => {
const engine = new FakeEngine();
const submitted: TestnetBlock[] = [];
const api = async (path: string, body?: unknown) => {
if (path === '/api/mining/template') { assert.deepEqual(body, { owner: me.address, publicKey: me.publicKey }); return template('0' + 'f'.repeat(63)); }
if (path === '/api/blocks') { submitted.push(body as TestnetBlock); await validateBlock(structuredClone(body), [], {}, pow); return { accepted: true }; }
if (path === '/p2p/status') return { tip: 'x' };
throw new Error(`unexpected ${path}`);
};
const miner = new MobileMiner({ engine, api, sign: signer, chainId: CHAIN_ID }, me);
await miner.start(1, 1);
assert.equal(miner.status.phase, 'stopped', miner.status.message);
assert.equal(miner.status.accepted, 1);
assert.equal(submitted.length, 1);
assert.equal(submitted[0].owner, me.address);
assert.ok(engine.stopped >= 1);
});
test('a tripped safeguard stops mining before the engine starts', async () => {
const engine = new FakeEngine();
const miner = new MobileMiner({ engine, api: async () => { throw new Error('no network'); }, sign: signer, chainId: CHAIN_ID,
blocked: () => 'battery saver is on' }, me);
await miner.start(1, 1);
assert.equal(miner.status.phase, 'error');
assert.match(miner.status.message ?? '', /battery saver/);
assert.equal(engine.started, 0);
assert.equal(engine.calls, 0);
});
test('stop() halts an in-progress search', async () => {
const engine = new FakeEngine();
const api = async (path: string) => path === '/api/mining/template' ? template('0'.repeat(64)) : { tip: template().header.previousHash };
const miner = new MobileMiner({ engine, api, sign: signer, chainId: CHAIN_ID }, me);
const run = miner.start(1);
for (let i = 0; engine.calls < 3 && i < 2000; i++) await new Promise(r => setTimeout(r, 1));
assert.ok(engine.calls >= 3, miner.status.message);
await miner.stop('Stopped.');
await run;
assert.equal(miner.status.phase, 'stopped');
assert.equal(miner.status.accepted, 0);
});
+70
View File
@@ -0,0 +1,70 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { fileURLToPath } from 'node:url';
import { mulberry32 } from '../shared/bots/index.ts';
import { makeDuelBot, DUEL_BOT_NAMES } from '../shared/bots/duel-bots.ts';
import { makeStandinSim } from '../scripts/sim/duel-standin-adapter.ts';
import { buildDeck, deckSet, ARCHETYPES } from '../scripts/sim/duel-decks.ts';
import { playDuel, schedule, DUEL_MIXES, MAX_WORKERS } from '../scripts/sim/duel-run.ts';
import { aggregateDuel, duelMarkdown } from '../scripts/sim/duel-stats.ts';
const SAMPLE = fileURLToPath(new URL('../docs/game/card-sample.json', import.meta.url));
const sim = makeStandinSim(SAMPLE);
test('decks: 40 unique cards from the 236-card sample, archetypes skew types', () => {
assert.equal(sim.pool.length, 236);
for (const arch of ARCHETYPES) {
const d = buildDeck(sim.pool, arch, 3);
assert.equal(d.cards.length, 40);
assert.equal(new Set(d.cards.map(c => c.id)).size, 40, 'each NFT appears once');
assert.ok(d.tags.includes(`arch:${arch}`));
}
const figs = (arch: (typeof ARCHETYPES)[number]) => buildDeck(sim.pool, arch, 9).cards.filter(c => c.type === 'Figure').length;
assert.ok(figs('figure-heavy') > figs('doctrine-heavy'));
assert.deepEqual(deckSet(sim.pool, 6, 1).map(d => d.id), deckSet(sim.pool, 6, 1).map(d => d.id));
});
test('duel matches terminate, are deterministic and bots only play legal actions', () => {
const decks = deckSet(sim.pool, 4, 2);
for (const bots of [['random', 'random'], ['heuristic', 'greedy'], ['mc-lite', 'heuristic']] as [string, string][]) {
const a = playDuel(sim, [decks[0], decks[1]], bots, 11);
const b = playDuel(sim, [decks[0], decks[1]], bots, 11);
assert.equal(a.truncated, false, `${bots} truncated`);
assert.deepEqual({ ...a, ms: 0 }, { ...b, ms: 0 });
}
const { engine, lens } = sim;
for (const name of DUEL_BOT_NAMES) {
const bot = makeDuelBot(name, engine, lens);
let s = engine.createMatch('duel', [{ id: 'a', tags: [], payload: decks[2].cards }, { id: 'b', tags: [], payload: decks[3].cards }], 5);
const rng = mulberry32(3);
for (let i = 0; i < 400 && !engine.isOver(s); i++) {
const seat = engine.toAct(s);
const a = bot(engine.observe!(s, seat), seat, rng);
assert.ok(engine.legalActions(s, seat).some(x => JSON.stringify(x) === JSON.stringify(a)), `${name} chose an illegal action`);
s = engine.applyAction(s, a);
}
}
});
test('observation hides the opponent hand and libraries', () => {
const decks = deckSet(sim.pool, 2, 4);
const s = sim.engine.createMatch('duel', [{ id: 'a', tags: [], payload: decks[0].cards }, { id: 'b', tags: [], payload: decks[1].cards }], 1);
const v = sim.engine.observe!(s, 0) as any;
assert.equal(v.players[1].hand.length, 0);
assert.equal(v.players[1].library.length, 0);
assert.equal(v.players[0].library.length, 0);
assert.equal(v.view.oppHand, s.players[1].hand.length);
});
test('heuristic beats random; stats and markdown cover the report metrics', () => {
const decks = deckSet(sim.pool, 10, 5);
const jobs = schedule(40, decks.length, 9, [['random', 'heuristic', 1]]);
const recs = jobs.map(j => playDuel(sim, [decks[j.decks[0]], decks[j.decks[1]]], j.bots, j.seed));
const stats = aggregateDuel(recs, sim, decks, 0, { label: 't', engine: 'standin', rules: {} });
assert.ok(stats.skill['heuristic>random'].rate > 0.8, JSON.stringify(stats.skill));
const md = duelMarkdown(stats);
for (const k of ['First-player win rate', 'Turns each', 'Stalls', 'Connected', 'Fame vs card win rate', 'Card type', 'Portal', 'Keyword', 'Cost']) assert.match(md, new RegExp(k));
assert.ok(stats.connected.pairRate > 0 && stats.connected.pairRate < 1);
assert.equal(MAX_WORKERS, 4);
assert.ok(Object.keys(DUEL_MIXES).includes('default'));
});
+82
View File
@@ -0,0 +1,82 @@
// testnet-ops: live identity source over a FAKE Wikimedia client. Zero network calls.
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { wikimediaIdentitySource } from '../server/game/identity-source.ts';
import { IdentityStore, prebake, toProfile } from '../server/game/identity.ts';
import type { BackgroundRequest, ProfileBuilder } from '../server/game/identity-source.ts';
// A minimal stand-in for shared/duel/profile.ts (#70), so this test needs no unmerged module.
const ids = (e: any, p: string): string[] => (e?.claims?.[p] ?? []).map((s: any) => s.mainsnak?.datavalue?.value?.id).filter(Boolean);
const yrs = (e: any, p: string): number[] => (e?.claims?.[p] ?? []).map((s: any) => Number(/^[+-]0*(\d+)-/.exec(s.mainsnak?.datavalue?.value?.time ?? '')?.[1])).filter(Boolean);
const profile: ProfileBuilder = {
wikidataEntityParams: q => ({ action: 'wbgetentities', ids: [...q].sort().join('|'), props: 'claims', format: 'json', formatversion: '2' }),
wikidataLabelParams: q => ({ action: 'wbgetentities', ids: [...q].sort().join('|'), props: 'labels', languages: 'en', format: 'json', formatversion: '2' }),
classIdsOf: e => [...new Set([...ids(e, 'P31'), ...ids(e, 'P279')])].sort(),
profileFromSources: ({ enrichment, entity, labels = {} }) => ({
wikidataId: enrichment.wikidataId, description: enrichment.description, categories: enrichment.categories,
instanceOf: ids(entity, 'P31').map(id => ({ id, label: labels[id] ?? id })), countries: ids(entity, 'P27'),
years: [...yrs(entity, 'P569'), ...yrs(entity, 'P570')], died: ids(entity, 'P570').length > 0 || yrs(entity, 'P570').length > 0,
fetchedRevisionId: enrichment.revisionId }),
};
const enrichmentFor = (pageId: number, wikidataId: string | null) => ({
pageId, title: `Page ${pageId}`, description: `desc ${pageId}`, wikidataId, revisionId: 1000 + pageId, pageBytes: 1,
languageCount: 1, languagesTruncated: false, categories: ['Living people', '1948 births'], categoriesTruncated: false,
fetchedAt: '2026-11-17T00:00:00Z',
pageviews: { status: 'unavailable', months: [], latestMonth: '2026-10', total: null, dailyAverage: null, trendPercent: null },
}) as any;
const claim = (id: string) => ({ rank: 'normal', mainsnak: { snaktype: 'value', datavalue: { type: 'wikibase-entityid', value: { id } } } });
const time = (t: string) => ({ rank: 'normal', mainsnak: { snaktype: 'value', datavalue: { type: 'time', value: { time: t } } } });
function fakeClient(opts: { failClaims?: boolean } = {}) {
const calls: { url: URL; options: BackgroundRequest }[] = [];
return { calls, async request(url: URL, options: BackgroundRequest) {
calls.push({ url, options });
const props = url.searchParams.get('props'), ids = url.searchParams.get('ids')!.split('|');
if (props === 'claims' && opts.failClaims) return { response: new Response('busy', { status: 503 }), signal: new AbortController().signal, fromCache: false };
const entities = Object.fromEntries(ids.map(id => [id, props === 'claims'
? { id, claims: { P31: [claim('Q5')], P27: [claim('Q30')], P569: [time('+1948-01-02T00:00:00Z')], P570: [time('+2001-01-01T00:00:00Z')] } }
: { id, labels: { en: { value: id === 'Q5' ? 'human' : `label ${id}` } } }]));
return { response: Response.json({ entities }), signal: new AbortController().signal, fromCache: false };
} };
}
test('every request is on the background lane, batched, and the frozen identity is derive-ready', async () => {
const realFetch = globalThis.fetch;
globalThis.fetch = (() => { throw new Error('network call in test'); }) as typeof fetch;
const dir = mkdtempSync(join(tmpdir(), 'identity-src-'));
try {
const client = fakeClient();
const source = wikimediaIdentitySource({ client, profile, enrichment: { async getBackground(id) { return enrichmentFor(id, `Q${id}`); } } });
const store = new IdentityStore(join(dir, 'id.sqlite'));
const articles = [1, 2, 3].map(i => ({ tokenId: String(i).repeat(64), pageId: i, title: `Page ${i}`, revisionId: i }));
const r = await prebake(store, source, articles);
assert.deepEqual(r, { seen: 3, alreadyFrozen: 0, frozen: 3, unknown: 0 });
assert.ok(client.calls.every(c => c.options.lane === 'background'));
assert.ok(client.calls.every(c => c.url.hostname === 'www.wikidata.org'));
assert.deepEqual(client.calls.map(c => c.url.searchParams.get('props')), ['claims', 'labels']);
assert.equal(client.calls[0].url.searchParams.get('ids'), 'Q1|Q2|Q3');
const one = store.get('1'.repeat(64))!;
assert.equal(one.source, 'wikimedia');
assert.deepEqual(one.instanceOf, [{ id: 'Q5', label: 'human' }]);
assert.deepEqual(one.countries, ['Q30']);
assert.deepEqual(one.years, [1948, 2001]);
assert.equal(one.died, true);
assert.equal(one.fetchedRevisionId, 1001);
assert.equal(toProfile(one).description, 'desc 1');
store.close();
} finally { globalThis.fetch = realFetch; rmSync(dir, { recursive: true, force: true }); }
});
test('a failed claims request leaves cards unknown so they are retried, never frozen half-empty', async () => {
const source = wikimediaIdentitySource({ client: fakeClient({ failClaims: true }), profile,
enrichment: { async getBackground(id) { if (id === 9) throw new Error('throttled'); return enrichmentFor(id, id === 8 ? null : `Q${id}`); } } });
const got = await source.lookup([7, 8, 9].map(i => ({ tokenId: String(i).repeat(64), pageId: i, title: `P${i}` })));
assert.equal(got.get(7), undefined); // has an item, claims failed → retry
assert.equal(got.get(9), undefined); // enrichment failed → retry
assert.equal(got.get(8)?.wikidataId, null); // no Wikidata item at all → enrichment-only profile is final
assert.deepEqual(got.get(8)?.instanceOf, []);
});
+17 -9
View File
@@ -2,7 +2,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { WikipediaArticleSource } from '../server/wiki.ts';
import { WikipediaEnrichment } from '../server/enrichment.ts';
import { ARTICLE_USER_AGENT, ENRICHMENT_USER_AGENT, wikimediaUserAgent } from '../server/wikimedia-user-agent.ts';
import { PROJECT_URL, defaultUserAgent, wikimediaUserAgent } from '../server/wikimedia-user-agent.ts';
function capture() {
const agents: string[] = [];
@@ -12,9 +12,10 @@ function capture() {
};
return { agents, fetcher };
}
async function agentsFor(env: string | undefined) {
const previous = process.env.WIKIDECK_USER_AGENT;
async function agentsFor(env: string | undefined, contact?: string) {
const previous = process.env.WIKIDECK_USER_AGENT, previousContact = process.env.WIKIDECK_OPERATOR_CONTACT;
if (env === undefined) delete process.env.WIKIDECK_USER_AGENT; else process.env.WIKIDECK_USER_AGENT = env;
if (contact === undefined) delete process.env.WIKIDECK_OPERATOR_CONTACT; else process.env.WIKIDECK_OPERATOR_CONTACT = contact;
try {
const article = capture(), enrichment = capture();
await assert.rejects(new WikipediaArticleSource(article.fetcher).random());
@@ -22,15 +23,22 @@ async function agentsFor(env: string | undefined) {
return { article: article.agents, enrichment: enrichment.agents };
} finally {
if (previous === undefined) delete process.env.WIKIDECK_USER_AGENT; else process.env.WIKIDECK_USER_AGENT = previous;
if (previousContact === undefined) delete process.env.WIKIDECK_OPERATOR_CONTACT;
else process.env.WIKIDECK_OPERATOR_CONTACT = previousContact;
}
}
test('default Wikimedia user agents are unchanged when WIKIDECK_USER_AGENT is unset', async () => {
assert.equal(ARTICLE_USER_AGENT, 'Wikideck/0.1 (experimental Wikipedia article cards)');
assert.equal(ENRICHMENT_USER_AGENT, 'Wikideck/0.1 (Wikipedia off-chain page enrichment)');
const { article, enrichment } = await agentsFor(undefined);
assert.ok(article.length > 0 && article.every(a => a === ARTICLE_USER_AGENT));
assert.ok(enrichment.length > 0 && enrichment.every(a => a === ENRICHMENT_USER_AGENT));
test('default Wikimedia user agent names the project, the operator contact and node', async () => {
const { article, enrichment } = await agentsFor(undefined, 'ops@example.org');
const expected = `WikiDeck/0.1.0 (+${PROJECT_URL}; ops@example.org) node/${process.versions.node}`;
assert.equal(defaultUserAgent({ WIKIDECK_OPERATOR_CONTACT: 'ops@example.org' }), expected);
assert.ok(article.length > 0 && article.every(a => a === expected));
assert.ok(enrichment.length > 0 && enrichment.every(a => a === expected));
assert.equal(defaultUserAgent({ PUBLIC_ORIGIN: 'https://node.example' }),
`WikiDeck/0.1.0 (+${PROJECT_URL}; https://node.example) node/${process.versions.node}`);
assert.equal(defaultUserAgent({}), `WikiDeck/0.1.0 (+${PROJECT_URL}) node/${process.versions.node}`);
// Unsafe contacts are dropped rather than breaking the header's comment syntax.
assert.equal(defaultUserAgent({ WIKIDECK_OPERATOR_CONTACT: 'a); evil(' }), defaultUserAgent({}));
});
test('WIKIDECK_USER_AGENT overrides both Wikimedia clients', async () => {
+124
View File
@@ -0,0 +1,124 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import type { DuelAction, DuelCard, LogEvent, PermanentView, PlayerView, SideView } from '../src/game/duel/contract.ts';
import { boardFromView, expand, legalFromActions, plainLog } from '../src/game/duel/adapter.ts';
const card = (id: string, extra: Partial<DuelCard> = {}): DuelCard => ({
cardId: id, pageId: 1, revisionId: 100, title: id, type: 'Figure', portal: 'Society', cost: 2, power: 2, toughness: 2,
keywords: [], effects: [], rulesText: '', flavor: 'A thing. More.', ...extra,
});
const perm = (uid: string, controller: 0 | 1, c: DuelCard, extra: Partial<PermanentView> = {}): PermanentView => ({
uid, owner: controller, controller, card: c, tapped: false, sick: false, damage: 0, counters: 0,
power: c.power ?? 0, toughness: c.toughness ?? 0, keywords: c.keywords, ...extra,
});
const side = (seat: 0 | 1, extra: Partial<SideView> = {}): SideView => ({
seat, life: 20, citations: 3, maxCitations: 4, handSize: 2, librarySize: 30, graveyard: [], bankSeconds: 300, ready: true, mulligansTaken: 0, ...extra,
});
function view(): PlayerView {
const fig = card('fig', { keywords: ['Legacy'] });
return {
engine: 'duel', seat: 1, turn: 5, active: 0, phase: 'block', toAct: 1,
you: { ...side(1), hand: [{ uid: '1:7', owner: 1, card: card('ev', { type: 'Event', power: null, toughness: null }) }] },
opponent: side(0, { life: 12 }),
battlefield: [
perm('0:1', 0, fig, { tapped: true, power: 4, toughness: 3 }),
perm('0:2', 0, card('loc', { type: 'Location', power: 0, toughness: 0 })),
perm('1:3', 1, card('mine'), { sick: true, connected: { with: '1:4', tier: 'Compatriot', via: 'Portugal', bonus: 1 } }),
perm('1:4', 1, card('gar', { type: 'Location', power: 0, toughness: 3 })),
perm('1:5', 1, card('doc', { type: 'Doctrine', power: null, toughness: null }), { attachedTo: '1:3' }),
],
combat: { attackers: ['0:1'], blocks: {} }, result: null, version: 9, rules: {},
};
}
test('PlayerView → board: sides from my seat, current stats, Garrison only when T > 0, attachments, Connected', () => {
const b = boardFromView(view(), ['alice', 'bob'], ['Turn 5.']);
assert.equal(b.me.name, 'bob');
assert.equal(b.opponent.name, 'alice');
assert.equal(b.opponent.notability, 12);
assert.deepEqual(b.combat, [{ attackerId: '0:1', blockerId: undefined }]);
const att = b.opponent.battlefield.find(c => c.id === '0:1')!;
assert.equal(att.power, 4); assert.equal(att.basePower, 2); assert.equal(att.tapped, true);
assert.equal(b.opponent.battlefield.find(c => c.id === '0:2')!.power, undefined);
assert.equal(b.me.battlefield.find(c => c.id === '1:4')!.toughness, 3);
const mine = b.me.battlefield.find(c => c.id === '1:3')!;
assert.deepEqual(mine.attachments, ['1:5']);
assert.ok(mine.keywords.includes('Connected'));
assert.equal(mine.pending, true);
assert.equal(mine.connectedNote, 'Compatriot (Portugal): +1/+1');
assert.equal(b.hand[0].id, '1:7');
assert.equal(b.hand[0].flavour, 'A thing.');
});
test('legal actions → board legality, and board intents → atomic action sequences', () => {
const legal: DuelAction[] = [
{ type: 'block', blocker: '1:3', attacker: '0:1' }, { type: 'block', blocker: '1:4', attacker: '0:1' }, { type: 'confirmBlocks' },
];
const l = legalFromActions(legal);
assert.deepEqual(l.blockers, { '1:3': ['0:1'], '1:4': ['0:1'] });
assert.deepEqual(expand({ type: 'block', blocks: [{ blockerId: '1:4', attackerId: '0:1' }] }, legal),
[{ type: 'block', blocker: '1:4', attacker: '0:1' }, { type: 'confirmBlocks' }]);
const main: DuelAction[] = [
{ type: 'play', uid: 'h1' },
{ type: 'play', uid: 'h2', targets: [{ kind: 'card', uid: 'a' }, { kind: 'card', uid: 'x' }] },
{ type: 'play', uid: 'h3', targets: [{ kind: 'player', seat: 0 }] },
{ type: 'endPhase' },
];
const m = legalFromActions(main);
assert.deepEqual(m.plays, { h1: [[]], h2: [['a', 'x']], h3: [['player:0']] });
assert.equal(m.canGoToCombat, true);
// The exact legal element comes back, so the host's deep-equal check passes (no `targets: []`).
assert.strictEqual(expand({ type: 'play', cardId: 'h1', targetIds: [] }, main)[0], main[0]);
assert.strictEqual(expand({ type: 'play', cardId: 'h3', targetIds: ['player:0'] }, main)[0], main[2]);
assert.deepEqual(expand({ type: 'endTurn' }, main), [{ type: 'endPhase' }, { type: 'confirmAttack' }]);
assert.deepEqual(expand({ type: 'attack', attackerIds: ['a', 'b'] }, [{ type: 'toggleAttacker', uid: 'a' }, { type: 'toggleAttacker', uid: 'b' }, { type: 'confirmAttack' }]),
[{ type: 'toggleAttacker', uid: 'a' }, { type: 'toggleAttacker', uid: 'b' }, { type: 'confirmAttack' }]);
assert.deepEqual(expand({ type: 'mulligan', keep: true }, [{ type: 'keep' }, { type: 'mulligan' }]), [{ type: 'keep' }]);
assert.equal(legalFromActions([]).canEndTurn, false);
});
test('fallback log: real names and titles only, no adjectives', () => {
const ref = (title: string) => ({ uid: title, cardId: title, title, pageId: 1, type: 'Figure' as const, power: 3, toughness: 2 });
const events: LogEvent[] = [
{ seq: 1, turn: 3, kind: 'turnStart', seat: 0, citations: 3, life: [20, 20] },
{ seq: 2, turn: 3, kind: 'deploy', seat: 0, card: ref('Cho Yang-ho') },
{ seq: 3, turn: 3, kind: 'attack', seat: 0, attackers: [ref('Cho Yang-ho')] },
{ seq: 4, turn: 3, kind: 'playerDamage', source: ref('Cho Yang-ho'), seat: 1, amount: 3, life: 17, combat: true },
{ seq: 5, turn: 3, kind: 'destroyed', card: ref('Dichromorpha viridis'), owner: 1 },
{ seq: 6, turn: 9, kind: 'gameOver', winner: 0, reason: 'life', life: [12, 0] },
];
assert.deepEqual(plainLog(events, ['Eric', 'Bot (Normal)']), [
'Turn 3.', 'Eric deployed Cho Yang-ho.', 'Cho Yang-ho (3/2) attacked.', 'Bot (Normal) lost 3 Notability (17 remaining).',
'Dichromorpha viridis was moved to Deleted.', 'Bot (Normal) was nominated for deletion. The result was delete.',
]);
});
test('bot match decks: exactly deckSize owned, profiled cards; the bot deck is its own and deterministic', async () => {
const { botDeck, playerDeck } = await import('../src/game/duel/decks.ts');
const cards = Array.from({ length: 41 }, (_, i) => ({ tokenId: `t${i}`, title: `Card ${i}`, duel: card(`d${i}`, { pageId: i }) }));
const ids = cards.slice(0, 40).map(c => c.tokenId);
const ok = playerDeck(ids, cards, 40);
assert.equal(ok.cards.length, 40);
assert.equal(ok.cards[0].cardId, 't0'); // the NFT tokenId, not the profile id
assert.equal(playerDeck(ids.slice(0, 39), cards, 40).cards.length, 0); // no partial decks, no filler
assert.deepEqual(playerDeck([...ids.slice(0, 39), 'nope'], cards, 40).missing, ['nope']);
const noProfile = cards.map((c, i) => (i === 3 ? { tokenId: c.tokenId, title: c.title } : c));
assert.deepEqual(playerDeck(ids, noProfile, 40).pending, ['Card 3']);
const pool = Array.from({ length: 236 }, (_, i) => card(`s${i}`, { pageId: i }));
const a = botDeck(pool, 40, 'seed'), b = botDeck(pool, 40, 'seed');
assert.deepEqual(a, b);
assert.equal(new Set(a.map(c => c.cardId)).size, 40);
assert.ok(a.every(c => c.cardId.startsWith('bot:')));
assert.notDeepEqual(botDeck(pool, 40, 'other').map(c => c.cardId), a.map(c => c.cardId));
});
test('bot match: untyped profiles from the wire are shape-checked', async () => {
const { playerDeck, isDuelCard } = await import('../src/game/duel/decks.ts');
assert.equal(isDuelCard(card('x')), true);
assert.equal(isDuelCard({ title: 'x' }), false);
assert.equal(isDuelCard(null), false);
const cards = Array.from({ length: 40 }, (_, i) => ({ tokenId: `t${i}`, title: `C${i}`, duel: i === 5 ? { junk: true } : card(`d${i}`) }));
assert.deepEqual(playerDeck(cards.map(c => c.tokenId), cards, 40).pending, ['C5']);
});
+53
View File
@@ -0,0 +1,53 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { EASY_BOT, NORMAL_BOT } from '../src/game/duel/bots.ts';
import type { DuelAction, DuelCard, PermanentView, PlayerView } from '../src/game/duel/contract.ts';
const card = (id: string, extra: Partial<DuelCard> = {}): DuelCard => ({
cardId: id, pageId: 1, title: id, type: 'Figure', portal: 'Society', cost: 2, power: 2, toughness: 2, keywords: [], effects: [], rulesText: '', flavor: '', ...extra,
});
const perm = (uid: string, controller: 0 | 1, power: number, toughness: number, extra: Partial<PermanentView> = {}): PermanentView => ({
uid, owner: controller, controller, card: card(uid, { power, toughness }), tapped: false, sick: false, damage: 0, counters: 0, power, toughness, keywords: [], ...extra,
});
const side = (seat: 0 | 1, life = 20) => ({ seat, life, citations: 3, maxCitations: 3, handSize: 0, librarySize: 30, graveyard: [], bankSeconds: 300, ready: true, mulligansTaken: 0 });
const view = (p: Partial<PlayerView>): PlayerView => ({
engine: 'duel', seat: 1, turn: 4, active: 1, phase: 'main', toAct: 1, you: { ...side(1), hand: [] }, opponent: side(0),
battlefield: [], combat: { attackers: [], blocks: {} }, result: null, version: 1, rules: {}, ...p,
});
const rng = () => 0.5;
test('normal bot: plays the priciest card, harmful effects at the opponent', () => {
const hand = [{ uid: '1:1', owner: 1 as const, card: card('cheap', { cost: 1 }) },
{ uid: '1:2', owner: 1 as const, card: card('bolt', { type: 'Event', cost: 3, power: null, toughness: null, effects: [{ op: 'damage', amount: 3 }] }) }];
const v = view({ you: { ...side(1), hand }, battlefield: [perm('0:9', 0, 3, 3), perm('1:8', 1, 2, 2)] });
const legal: DuelAction[] = [{ type: 'play', uid: '1:1' },
{ type: 'play', uid: '1:2', targets: [{ kind: 'card', uid: '1:8' }] }, { type: 'play', uid: '1:2', targets: [{ kind: 'card', uid: '0:9' }] }, { type: 'endPhase' }];
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[2]);
});
test('normal bot: attacks unless a blocker eats it, all-in on lethal, then confirms', () => {
const bf = [perm('1:1', 1, 3, 3), perm('1:2', 1, 1, 1), perm('0:1', 0, 2, 4)];
const legal: DuelAction[] = [{ type: 'toggleAttacker', uid: '1:1' }, { type: 'toggleAttacker', uid: '1:2' }, { type: 'confirmAttack' }];
// 1:1 (3/3) faces a 2/4 that survives but doesn't kill: attack. 1:2 (1/1) would die to it for nothing.
const v = view({ phase: 'attack', battlefield: bf });
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[0]);
const after = view({ phase: 'attack', battlefield: bf, combat: { attackers: ['1:1'], blocks: {} } });
assert.deepEqual(NORMAL_BOT.choose(after, legal.slice(1), rng), { type: 'confirmAttack' });
const lethal = view({ phase: 'attack', battlefield: bf, opponent: side(0, 1), combat: { attackers: ['1:1'], blocks: {} } });
assert.deepEqual(NORMAL_BOT.choose(lethal, legal.slice(1), rng), legal[1]);
});
test('normal bot: takes the kill-and-survive block, otherwise no block', () => {
const bf = [perm('0:1', 0, 2, 2), perm('1:1', 1, 3, 3), perm('1:2', 1, 1, 1)];
const v = view({ phase: 'block', active: 0, battlefield: bf, combat: { attackers: ['0:1'], blocks: {} } });
const legal: DuelAction[] = [{ type: 'block', blocker: '1:1', attacker: '0:1' }, { type: 'block', blocker: '1:2', attacker: '0:1' }, { type: 'confirmBlocks' }];
assert.deepEqual(NORMAL_BOT.choose(v, legal, rng), legal[0]);
assert.deepEqual(NORMAL_BOT.choose(v, legal.slice(1), rng), { type: 'confirmBlocks' });
});
test('bots always return a listed action and keep their opening hand', () => {
const legal: DuelAction[] = [{ type: 'keep' }, { type: 'mulligan' }];
assert.deepEqual(NORMAL_BOT.choose(view({ phase: 'mulligan' }), legal, rng), { type: 'keep' });
let x = 1; const r = () => ((x = (x * 48271) % 2147483647) / 2147483647);
for (let i = 0; i < 50; i++) assert.ok(legal.includes(EASY_BOT.choose(view({ phase: 'mulligan' }), legal, r)));
});
+120
View File
@@ -0,0 +1,120 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
EMPTY_DECL, NO_LEGAL, blockList, cardSummary, eligibility, firstSentence, previewCombat, tapAttacker, tapBlocker, toggleAttacker, typeLine,
type BoardCard, type Legal,
} from '../src/game/duel/model.ts';
import { PREVIEW_POOL, previewView } from '../src/game/duel/mock.ts';
const fig = (id: string, power: number, toughness: number, extra: Partial<BoardCard> = {}): BoardCard =>
({ id, title: id, type: 'Figure', portal: 'Society', cost: 2, power, toughness, keywords: [], rulesText: '', ...extra });
test('attack declaration: one tap toggles a legal attacker, illegal ones are ignored', () => {
const legal: Legal = { ...NO_LEGAL, attackers: ['a', 'b'] };
let d = toggleAttacker(EMPTY_DECL, 'a', legal);
assert.deepEqual(d.attackers, ['a']);
d = toggleAttacker(d, 'z', legal);
assert.deepEqual(d.attackers, ['a']);
d = toggleAttacker(d, 'b', legal);
d = toggleAttacker(d, 'a', legal);
assert.deepEqual(d.attackers, ['b']);
});
test('block declaration: two taps per blocker, single blocks, re-tap clears', () => {
const legal: Legal = { ...NO_LEGAL, blockers: { x: ['A', 'B'], y: ['A'], z: [] } };
let d = tapBlocker(EMPTY_DECL, 'x', legal);
assert.equal(d.picked, 'x');
d = tapAttacker(d, 'A', legal);
assert.deepEqual(blockList(d), [{ blockerId: 'x', attackerId: 'A' }]);
assert.equal(d.picked, undefined);
// y takes over A; x is freed (at most one blocker per attacker).
d = tapAttacker(tapBlocker(d, 'y', legal), 'A', legal);
assert.deepEqual(blockList(d), [{ blockerId: 'y', attackerId: 'A' }]);
// y can't block B: the tap is ignored and y stays picked.
d = tapAttacker(tapBlocker(EMPTY_DECL, 'y', legal), 'B', legal);
assert.deepEqual(blockList(d), []);
// A blocker with no legal attacker can't be picked.
assert.equal(tapBlocker(EMPTY_DECL, 'z', legal).picked, undefined);
// Re-tapping an assigned blocker removes the block; so does tapping its attacker with nothing picked.
d = tapAttacker(tapBlocker(EMPTY_DECL, 'x', legal), 'B', legal);
assert.deepEqual(blockList(tapBlocker(d, 'x', legal)), []);
assert.deepEqual(blockList(tapAttacker(d, 'B', legal)), []);
// One blocker per attacker, and one attacker per blocker.
d = tapAttacker(tapBlocker(d, 'x', legal), 'A', legal);
assert.equal(blockList(d).length <= 1, true);
});
test('combat preview: simultaneous damage, single blocks, Well-sourced, marked damage', () => {
const cards = new Map([fig('a', 3, 3), fig('b', 2, 2), fig('c', 4, 1), fig('w', 1, 3, { keywords: ['Well-sourced'] }), fig('d', 2, 3, { damage: 1 })].map(c => [c.id, c]));
const out = previewCombat([{ attackerId: 'a', blockerId: 'b' }, { attackerId: 'c' }], cards);
assert.equal(out.toPlayer, 4);
assert.deepEqual(out.destroyed.sort(), ['b']);
// Well-sourced prevents the first 1: a 3-power attacker deals 2 to a 1/3, which survives.
assert.deepEqual(previewCombat([{ attackerId: 'a', blockerId: 'w' }], cards).destroyed, []);
// Damage already marked counts: 2 more kills a 2/3 with 1 damage.
assert.deepEqual(previewCombat([{ attackerId: 'b', blockerId: 'd' }], cards).destroyed.sort(), ['b', 'd']);
});
test('eligibility: exactly the deck size, no borrowed cards, progress label', () => {
assert.deepEqual(eligibility(23), { eligible: false, owned: 23, needed: 17, label: '23 / 40 cards' });
assert.equal(eligibility(40).eligible, true);
assert.equal(eligibility(57).label, '40 / 40 cards');
assert.equal(eligibility(12, 12).eligible, true); // testnet mode file may lower deckSize
});
test('flavour: first sentence of the extract, not split on initials or abbreviations', () => {
assert.equal(firstSentence('J. R. R. Tolkien was an English writer. He wrote books.'), 'J. R. R. Tolkien was an English writer.');
assert.equal(firstSentence('St. Georgen am Längsee is a town. It is in Austria.'), 'St. Georgen am Längsee is a town.');
assert.equal(firstSentence('Pi is about 3.14 in value. More.'), 'Pi is about 3.14 in value.');
assert.equal(firstSentence('No full stop here'), 'No full stop here');
assert.equal(firstSentence(''), undefined);
assert.ok((firstSentence('word '.repeat(100)) ?? '').length <= 220);
});
test('type line and accessible summary', () => {
const c = fig('Barack Obama', 3, 4, { subtype: 'People · 1961–', keywords: ['Protected'], tapped: true });
assert.equal(typeLine(c), 'Figure — People · 1961–');
assert.equal(cardSummary(c), 'Barack Obama, Figure — People · 1961–, cost 2, 3/4, Protected, tapped');
});
test('preview scenes: a full 5 + 5 board with every card from the real sample', () => {
assert.equal(PREVIEW_POOL.length, 236);
for (const scene of ['main', 'attack', 'block', 'over'] as const) {
const { view } = previewView(scene);
assert.equal(view.me.battlefield.length, 5);
assert.equal(view.opponent.battlefield.length, 5);
}
for (const c of PREVIEW_POOL) {
assert.ok(c.keywords.length <= 2, c.title);
assert.ok(c.cost >= 1 && c.cost <= 6, c.title);
}
});
test('DuelCard → board card: type line from real data only, flavour is one sentence', async () => {
const { boardCard, lifespan } = await import('../src/game/duel/cards.ts');
assert.equal(lifespan('Sultan of Aceh (1530–1537/9)'), '1530–1537');
assert.equal(lifespan('American voice actor and singer (born 1963)'), '1963–');
assert.equal(lifespan('American botanist (c.1872–1919)'), '1872–1919');
assert.equal(lifespan('Species of grasshopper'), undefined);
const c = boardCard({ cardId: 't', pageId: 1, revisionId: 9, title: 'Salahuddin of Aceh', type: 'Figure', subtype: null, portal: 'History',
cost: 4, power: 4, toughness: 3, keywords: ['Legacy'], rulesText: 'Legacy.', flavor: 'Sultan of Aceh (1530–1537/9). Second sentence.' });
assert.equal(typeLine(c), 'Figure — History · 1530–1537');
assert.equal(c.flavour, 'Sultan of Aceh (1530–1537/9).');
assert.equal(c.url, 'https://en.wikipedia.org/wiki/Salahuddin_of_Aceh');
const e = boardCard({ cardId: 'e', pageId: 2, revisionId: 9, title: '1954 Gold Coast general election', type: 'Event', subtype: 'election', portal: 'Society',
cost: 4, power: null, toughness: null, keywords: [], rulesText: 'x', flavor: '' });
assert.equal(typeLine(e), 'Event — Society · Election');
assert.equal(e.power, undefined);
});
test('targeting: multi-step sequences (own Figure, then theirs), players as targets', async () => {
const { nextTargets, targetsComplete, playerTarget } = await import('../src/game/duel/model.ts');
const seqs = [['a', 'x'], ['a', 'y'], ['b', 'x']];
assert.deepEqual([...nextTargets(seqs, [])].sort(), ['a', 'b']);
assert.deepEqual([...nextTargets(seqs, ['a'])].sort(), ['x', 'y']);
assert.deepEqual([...nextTargets(seqs, ['b'])], ['x']);
assert.equal(targetsComplete(seqs, ['a']), false);
assert.equal(targetsComplete(seqs, ['a', 'y']), true);
assert.equal(targetsComplete([[]], []), true);
assert.equal(nextTargets([[playerTarget(1)], ['c']], []).has('player:1'), true);
});
+99
View File
@@ -0,0 +1,99 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { collectionFromBlocks, deckProblem, eligibility, fillDeck, parseCollection, playableCount, progressLabel, type Collection } from '../src/game/collection/collection.ts';
import { CLASSIC, parseDuelModes } from '../src/game/collection/duelModes.ts';
import { inviteCode, inviteFromPath, parseDuelStatus, parseLadder, parseSeat } from '../src/game/online.ts';
import type { TestnetBlock } from '../shared/testnet.ts';
const card = (i: number, pageId = 1000 + i) => ({ tokenId: `t${i}`, pageId, title: `Article ${pageId}` });
const coll = (n: number, pages?: (i: number) => number, deckSize = 40): Collection =>
({ deckSize, copyLimit: 4, source: 'server', cards: Array.from({ length: n }, (_, i) => card(i, pages?.(i))) });
test('23 owned cards: not eligible, shows "23 / 40 cards" and needs 17 more', () => {
const e = eligibility(coll(23));
assert.equal(e.eligible, false);
assert.equal(e.needed, 17);
assert.equal(progressLabel(e), '23 / 40 cards');
});
test('40 owned distinct cards are eligible; the copy limit caps playable cards per article', () => {
assert.equal(eligibility(coll(40)).eligible, true);
// 44 cards over 10 articles: at most 4 copies each → 40 playable.
assert.equal(playableCount(coll(44, i => i % 10)), 40);
// 50 cards of 5 articles: only 20 playable, so not eligible despite owning 50.
const e = eligibility(coll(50, i => i % 5));
assert.equal(e.owned, 50);
assert.equal(e.playable, 20);
assert.equal(e.eligible, false);
});
test('deckProblem: exactly deckSize owned cards, no repeats, copy limit enforced', () => {
const c = coll(60, i => (i < 8 ? 1 : 1000 + i));
const legal = fillDeck([], c);
assert.equal(legal.length, 40);
assert.equal(deckProblem(legal, c), '');
assert.match(deckProblem(legal.slice(1), c), /exactly 40/);
assert.match(deckProblem([...legal.slice(1), 'not-mine'], c), /no longer own/);
assert.match(deckProblem([...legal.slice(1), legal[2]], c), /twice/);
const fiveCopies = [...c.cards.slice(0, 5).map(x => x.tokenId), ...c.cards.slice(8, 43).map(x => x.tokenId)];
assert.match(deckProblem(fiveCopies, c), /At most 4 copies/);
});
test('fillDeck keeps still-owned saved cards first and drops sold ones', () => {
const c = coll(45);
const deck = fillDeck(['t44', 'gone', 't43'], c);
assert.deepEqual(deck.slice(0, 2), ['t44', 't43']);
assert.equal(deck.length, 40);
assert.ok(!deck.includes('gone'));
});
test('a testnet mode may lower deckSize; production default stays 40', () => {
assert.equal(parseCollection({}).deckSize, 40);
assert.equal(eligibility(coll(12, undefined, 10)).eligible, true);
});
test('parseCollection drops malformed cards, duplicate tokenIds and non-https urls', () => {
const c = parseCollection({ deckSize: 40, copyLimit: 4, cards: [
{ tokenId: 'a', pageId: 5, title: 'Five', url: 'javascript:alert(1)', imageUrl: 'https://upload.wikimedia.org/x.jpg' },
{ tokenId: 'a', pageId: 6, title: 'Dup' }, { tokenId: 'b' }, null, 'x', { tokenId: 'c', pageId: -1 },
] });
assert.equal(c.cards.length, 1);
assert.equal(c.cards[0].url, undefined);
assert.equal(c.cards[0].imageUrl, 'https://upload.wikimedia.org/x.jpg');
});
test('the local fallback reads real owned blocks only', () => {
const block = { tokenId: 'tok', height: 7, article: { pageId: 9, title: 'Nine', revisionId: 3, url: 'https://en.wikipedia.org/wiki/Nine', extract: 'x', category: 'Places', source: 'live' } } as unknown as TestnetBlock;
const c = collectionFromBlocks([block]);
assert.equal(c.source, 'local');
assert.deepEqual(c.cards.map(x => [x.tokenId, x.pageId, x.height]), [['tok', 9, 7]]);
});
test('invite links: parse a pasted URL, a bare code, and the deep link path', () => {
assert.equal(inviteCode('https://wikideck.eom.dev/play/invite/AbC_123'), 'AbC_123');
assert.equal(inviteCode(' AbC_123 '), 'AbC_123');
assert.equal(inviteCode('https://evil.example/<script>'), '');
assert.equal(inviteFromPath('/play/invite/xyz9'), 'xyz9');
assert.equal(inviteFromPath('/play/join/lob_1'), 'lob_1');
assert.equal(inviteFromPath('/battle/abc'), '');
});
test('host responses are validated: seats, statuses and the ladder', () => {
assert.deepEqual(parseSeat({ lobbyId: 'L1', seat: 1, token: 'tok', invite: 'inv1' }), { lobbyId: 'L1', seat: 1, token: 'tok', invite: 'inv1' });
assert.throws(() => parseSeat({ lobbyId: 'L1', seat: 2, token: 'tok' }), /invalid seat/);
const s = parseDuelStatus({ lobbyId: 'L1', version: 4, phase: 'bogus', players: [{ name: 'x'.repeat(99), rating: 1211.6 }], matchId: '../etc' });
assert.equal(s.phase, 'waiting');
assert.equal(s.players[0].name.length, 24);
assert.equal(s.players[0].rating, 1212);
assert.equal(s.matchId, undefined);
const l = parseLadder({ entries: [{ name: 'alice', rating: 1224, wins: 3, losses: 1 }, { name: '', wins: -2 }, 7] });
assert.deepEqual(l, [{ name: 'alice', rating: 1224, wins: 3, losses: 1, draws: 0 }, { name: 'Anonymous', rating: null, wins: 0, losses: 0, draws: 0 }]);
});
test('only duel-engine modes are offered; Classic is the default', () => {
assert.equal(CLASSIC.id, 'classic');
const m = parseDuelModes({ modes: [{ mode: { id: 'standard', name: 'Edit War', engine: 'editwar' } },
{ mode: { id: 'classic', name: 'Classic', engine: 'duel', limits: { rated: true } } },
{ mode: { id: 'e2e', name: 'Testnet E2E', engine: 'duel', rules: { deckSize: 20 } } }] });
assert.deepEqual(m.map(x => [x.id, x.ranked, x.deckSize]), [['classic', true, undefined], ['e2e', false, 20]]);
});
+105
View File
@@ -0,0 +1,105 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { renderToStaticMarkup } from 'react-dom/server';
import { createElement } from 'react';
import { RecapArticle, loadRecap, matchIdFromPath } from '../src/game/recap/BattleRecap.tsx';
import { fallbackRecap, parseMatchRecord, runs } from '../src/game/recap/model.ts';
// Real cards from the sample pool (no network).
const sample = JSON.parse(readFileSync(new URL('../docs/game/card-sample.json', import.meta.url), 'utf8'));
const pool: { pageId: number; title: string; revisionId?: number }[] = (Array.isArray(sample) ? sample : sample.cards ?? []).map((c: Record<string, unknown>) => {
const a = (c.article ?? c) as Record<string, unknown>;
return { pageId: a.pageId as number, title: a.title as string, revisionId: a.revisionId as number | undefined };
}).filter((c: { pageId: unknown; title: unknown }) => typeof c.pageId === 'number' && typeof c.title === 'string');
const record = {
matchId: 'm_7f3a', modeName: 'Classic', players: [{ name: 'alice' }, { name: 'bob' }],
startedAt: Date.UTC(2026, 10, 17, 23, 40), endedAt: Date.UTC(2026, 10, 18, 0, 2), turns: 9,
result: { winner: 0, reason: 'notability' }, strength: [40, 40],
played: [pool.slice(0, 4).map(c => ({ ...c, type: 'Figure' })).concat([{ ...pool[4], type: 'Doctrine' }]), pool.slice(5, 8).map(c => ({ ...c, type: 'Figure' }))],
lost: [[pool[1]], [pool[5], pool[6]]],
};
test('recap: deterministic, named after the winner’s decisive non-Figure card, with an infobox', () => {
assert.ok(pool.length >= 8, 'card-sample.json has cards');
const a = fallbackRecap(parseMatchRecord(record));
const b = fallbackRecap(parseMatchRecord(structuredClone(record)));
assert.deepEqual(a, b);
assert.equal(a.title, `Battle of ${pool[4].title} (2026)`);
assert.equal(a.infobox.date, '18 November 2026');
assert.deepEqual(a.infobox.belligerents, ['alice', 'bob']);
assert.deepEqual(a.infobox.casualties, [`1 card destroyed: ${pool[1].title}`, `2 cards destroyed: ${pool[5].title}, ${pool[6].title}`]);
assert.deepEqual(a.infobox.commanders, [pool[0].title, pool[5].title]);
assert.equal(a.masthead, 'WikiDeck');
assert.match(a.footer, /game events/);
assert.equal(a.infobox.result, 'Victory for alice');
assert.equal(a.url, '/recap/m_7f3a');
});
test('recap: References cite every card played, once each, with revision ids', () => {
const doc = fallbackRecap(parseMatchRecord(record));
const played = [...record.played[0], ...record.played[1]];
assert.equal(doc.references.length, new Set(played.map(c => `${c.pageId}:${c.revisionId ?? ''}`)).size);
for (const c of played) assert.ok(doc.references.some(r => r.title === c.title));
const html = renderToStaticMarkup(createElement(RecapArticle, { doc }));
assert.match(html, /WikiDeck/);
assert.match(html, /Casualties/);
assert.match(html, /Course of the battle/);
assert.doesNotMatch(html, /\*\*/, 'markup is rendered, not shown');
assert.match(html, /href="#ref-1"/);
if (pool[0].revisionId) assert.match(html, new RegExp(`oldid=${pool[0].revisionId}`));
});
test('recap text: fixed templates only, no adjectives about the outcome or winks', () => {
const doc = fallbackRecap(parseMatchRecord(record));
const text = [doc.lead, ...doc.sections.flatMap(s => s.paragraphs)].join(' ');
assert.doesNotMatch(text, /!|lol|brutal|humiliat|heroic|surprising|twist|killed|decisive|pyrrhic/i);
assert.match(text, /\*\*Battle of [^*]+\*\* was a WikiDeck engagement fought on 18 November 2026 between the forces of alice and bob/);
assert.match(text, /nine turns/);
assert.match(text, /bob was reduced to zero Notability\./);
});
test('recap falls back to "Match of <date>" when nothing was played, and tolerates junk', () => {
const doc = fallbackRecap(parseMatchRecord({ matchId: 'x', endedAt: Date.UTC(2026, 10, 17), players: ['a', 'b'], result: { winner: null } }));
assert.equal(doc.title, 'Match of 17 November 2026');
assert.equal(doc.infobox.result, 'Draw');
const junk = fallbackRecap(parseMatchRecord({ players: 7, played: [[{ title: 3 }], 'x'], url: 'javascript:1' }));
assert.equal(junk.references.length, 0);
});
test('only https Wikipedia links reach the References', () => {
const doc = fallbackRecap(parseMatchRecord({ ...record, played: [[{ pageId: 1, title: 'A', url: 'https://evil.example/a' }], []] }));
assert.match(doc.references[0].url, /^https:\/\/en\.wikipedia\.org\/wiki\/A$/);
});
test('/battle/<id> routing and loading from GET /api/game/matches/:id (stubbed fetch)', async () => {
assert.equal(matchIdFromPath('/battle/m_7f3a'), 'm_7f3a');
assert.equal(matchIdFromPath('/battle/../x'), '');
assert.equal(matchIdFromPath('/recap/m_7f3a'), 'm_7f3a');
let asked = '';
const fake = (async (url: string) => { asked = url; return new Response(JSON.stringify(record), { headers: { 'content-type': 'application/json' } }); }) as typeof fetch;
const doc = await loadRecap('m_7f3a', fake);
assert.equal(asked, '/api/game/matches/m_7f3a');
assert.match(doc.title, /^Battle of /);
const missing = (async () => new Response('{}', { status: 404 })) as unknown as typeof fetch;
await assert.rejects(loadRecap('nope', missing), /No battle/);
});
test('story markup becomes text runs; card titles cannot inject markup', () => {
assert.deepEqual(runs('The **Battle of X** saw *Moon*[2].'), [{ text: 'The ' }, { text: 'Battle of X', bold: true }, { text: ' saw ' },
{ text: 'Moon', italic: true }, { text: '[2]', cite: 2 }, { text: '.' }]);
const doc = fallbackRecap(parseMatchRecord({ matchId: 'z', players: ['a', 'b'], result: { winner: 0 }, played: [[{ pageId: 1, title: '**Evil** [9]', type: 'Event' }], []] }));
assert.equal(doc.title, 'Battle of Evil 9');
const seen = [doc.lead, ...doc.sections.flatMap(s => s.paragraphs)].flatMap(runs);
assert.ok(!seen.some(r => r.cite === 9));
});
test('a host-pvp match record (winner/reason at top level, decks, no replay yet) still yields a plain recap', () => {
const doc = fallbackRecap(parseMatchRecord({ matchId: 'a'.repeat(32), modeId: 'classic', seed: 's', rules: {}, players: [{ id: 'x', name: 'alice' }, { id: 'y', name: 'bob' }],
winner: 1, reason: 'concede', startedAt: Date.UTC(2026, 10, 18, 1), endedAt: Date.UTC(2026, 10, 18, 1, 20), decks: [new Array(40).fill({}), new Array(40).fill({})], actions: [] }));
assert.equal(doc.title, 'Match of 18 November 2026');
assert.equal(doc.infobox.result, 'Victory for bob');
assert.deepEqual(doc.infobox.strength, ['40 cards', '40 cards']);
assert.match(doc.sections.flatMap(s => s.paragraphs).join(' '), /alice withdrew from the engagement\./);
});
+4 -1
View File
@@ -56,13 +56,16 @@ test('random article fetch rejects unsafe response types, redirects, and oversiz
() => new Response('{}', { headers: { 'Content-Type': 'text/html' } }),
() => new Response(null, { status: 302, headers: { Location: 'https://evil.example' } }),
() => new Response(' '.repeat(512 * 1024 + 1), { headers: { 'Content-Type': 'application/json' } }),
() => { throw new Error('offline'); },
];
for (const fail of failures) {
const { fetcher, calls } = mockFetch(() => fail());
await assert.rejects(new WikipediaArticleSource(fetcher).random());
assert.equal(calls.length, 3);
}
// A network failure (or throttling) stops at once instead of retrying against an unreachable upstream.
const { fetcher, calls } = mockFetch(() => { throw new Error('offline'); });
await assert.rejects(new WikipediaArticleSource(fetcher).random(), /Wikimedia unavailable/);
assert.equal(calls.length, 1);
});
test('bad page records are skipped while later valid candidates are considered', async () => {
+236
View File
@@ -0,0 +1,236 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { WikimediaClient, WikimediaUnavailable, configFromEnv, type ClientConfig } from '../server/wikimedia/client.ts';
import { WikimediaCache, cacheKey } from '../server/wikimedia/cache.ts';
import { warnIfNoContact } from '../server/wikimedia-user-agent.ts';
import { FakeClock, flush, json, recorder } from './wikimedia-helpers.ts';
const API = 'https://en.wikipedia.org/w/api.php?action=query&format=json&pageids=1';
const REST = 'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/x';
function setup(handler: Parameters<typeof recorder>[1] = () => json({ ok: true }), config: Partial<ClientConfig> = {},
cache?: WikimediaCache) {
const clock = new FakeClock();
const rec = recorder(clock, handler);
const client = new WikimediaClient({ fetch: rec.fetcher, clock, config, cache, userAgent: () => 'Test/1 (+x; y)' });
return { clock, client, ...rec };
}
test('token bucket: burst of 3, then 1 request per second, one in flight per host', async () => {
const { clock, client, calls } = setup();
const jobs = Array.from({ length: 6 }, () => client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 })
.then(r => r.response.body?.cancel()));
await clock.advance(0);
assert.equal(calls.length, 3);
await clock.advance(999);
assert.equal(calls.length, 3);
await clock.advance(1);
assert.equal(calls.length, 4);
await clock.advance(2000);
await Promise.all(jobs);
assert.deepEqual(calls.map(c => c.at - calls[0].at), [0, 0, 0, 1000, 2000, 3000]);
// Different hosts have separate buckets.
await client.request(new URL(REST), { lane: 'interactive', timeoutMs: 1000 });
assert.equal(calls.at(-1)!.url.hostname, 'wikimedia.org');
});
test('only one request is in flight per host, even with tokens to spare', async () => {
const releases: (() => void)[] = [];
const { clock, client, calls } = setup(() => new Promise(resolve => releases.push(() => resolve(json({})))));
const a = client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 });
const b = client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 });
await clock.advance(0);
assert.equal(calls.length, 1);
releases.shift()!();
await a;
await clock.advance(0);
assert.equal(calls.length, 2);
releases.shift()!();
await b;
});
test('priority lanes: mint, then interactive, then background', async () => {
const { clock, client, calls } = setup(url => json({ lane: url.searchParams.get('n') }), { burst: 1 });
await client.request(new URL(`${API}&n=warm`), { lane: 'background', timeoutMs: 1000 }); // Uses the only token.
const order: string[] = [];
const go = (lane: 'mint' | 'interactive' | 'background', n: string) =>
client.request(new URL(`${API}&n=${n}`), { lane, timeoutMs: 1000 }).then(() => order.push(n));
const jobs = [go('background', 'b1'), go('interactive', 'i1'), go('background', 'b2'), go('mint', 'm1'), go('interactive', 'i2')];
await clock.advance(5000);
await Promise.all(jobs);
assert.deepEqual(order, ['m1', 'i1', 'i2', 'b1', 'b2']);
assert.equal(calls.length, 6);
});
test('maxlag=5 is added to Action API requests only, and a maxlag reply waits for Retry-After', async () => {
let lagged = 1;
const { clock, client, calls } = setup(url => url.pathname === '/w/api.php' && lagged-- > 0
? json({ error: { code: 'maxlag' } }, { 'MediaWiki-API-Error': 'maxlag', 'Retry-After': '5' })
: json({ ok: true }));
const job = client.request(new URL(API), { lane: 'background', timeoutMs: 1000 });
await clock.advance(0);
assert.equal(calls.length, 1);
assert.equal(calls[0].url.searchParams.get('maxlag'), '5');
await clock.advance(4999);
assert.equal(calls.length, 1);
await clock.advance(1);
const { response } = await job;
assert.deepEqual(await response.json(), { ok: true });
assert.equal(calls.length, 2);
await client.request(new URL(REST), { lane: 'background', timeoutMs: 1000 });
assert.equal(calls[2].url.searchParams.has('maxlag'), false);
assert.equal(calls[0].headers.get('user-agent'), 'Test/1 (+x; y)');
});
test('429 honours Retry-After by pausing the host; three in a row open the circuit for 10 minutes', async () => {
let status = 429;
const { clock, client, calls } = setup(() => status === 200 ? json({}) : new Response('slow down',
{ status, headers: { 'Retry-After': '2' } }));
const req = (lane: 'mint' | 'background' = 'background') => client.request(new URL(API), { lane, timeoutMs: 1000 });
await assert.rejects(req(), (e: unknown) => e instanceof WikimediaUnavailable && e.status === 429);
// The next request waits out Retry-After (2 s) instead of going straight back.
const second = req().catch(e => e);
await clock.advance(1999);
assert.equal(calls.length, 1);
await clock.advance(1);
assert.equal(((await second) as WikimediaUnavailable).status, 429);
const third = req().catch(e => e);
await clock.advance(10_000);
assert.equal(((await third) as WikimediaUnavailable).status, 429);
assert.equal(calls.length, 3);
assert.equal(client.status().hosts['en.wikipedia.org'].circuitOpen, true);
// Open circuit: refused at once without touching Wikimedia, even on the mint lane.
status = 200;
await assert.rejects(req('mint'), /circuit open/);
assert.equal(calls.length, 3);
await clock.advance(10 * 60_000);
await req('mint');
assert.equal(calls.length, 4);
assert.equal(client.status().counters['breaker.open'], 1);
});
test('a success resets the consecutive-429 count', async () => {
const replies = [429, 200, 429, 200, 429];
const { clock, client } = setup(() => {
const status = replies.shift()!;
return status === 200 ? json({}) : new Response('', { status });
});
for (let i = 0; i < 5; i++) {
const job = client.request(new URL(API), { lane: 'background', timeoutMs: 1000 }).catch(() => {});
await clock.advance(60_000);
await job;
}
assert.equal(client.status().hosts['en.wikipedia.org'].circuitOpen, false);
});
test('daily cap: background stops at 80 %, interactive at 100 %, mint keeps a 10 % reserve; resets at UTC midnight', async () => {
const { clock, client } = setup(() => json({}), { dailyCap: 10, requestsPerSecond: 1000, burst: 1000 });
const req = (lane: 'mint' | 'interactive' | 'background') => client.request(new URL(API), { lane, timeoutMs: 1000 });
for (let i = 0; i < 8; i++) await req('background');
await assert.rejects(req('background'), /daily cap/);
await req('interactive'); await req('interactive');
await assert.rejects(req('interactive'), /daily cap/);
await req('mint');
await assert.rejects(req('mint'), /daily cap/);
await clock.advance(24 * 3600_000);
await req('background');
});
test('nodes sharing one egress IP split the rate and the daily cap', () => {
const config = configFromEnv({ WIKIDECK_WIKIMEDIA_RPS: '0.9', WIKIDECK_WIKIMEDIA_NODES_PER_IP: '3',
WIKIDECK_WIKIMEDIA_DAILY_CAP: '3000' });
const client = new WikimediaClient({ fetch: async () => json({}), config });
assert.ok(Math.abs(client.status().requestsPerSecond - 0.3) < 1e-9);
assert.equal(client.status().dailyCap, 1000);
assert.equal(configFromEnv({ WIKIDECK_WIKIMEDIA_RPS: 'abc' }).requestsPerSecond, 1);
});
test('a full queue sheds background work first and a mint request evicts a background waiter', async () => {
const { clock, client } = setup(() => json({}), { queueLimit: 2, burst: 1 });
await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 });
const b1 = client.request(new URL(API), { lane: 'background', timeoutMs: 1000 }).then(() => 'ok', e => e.message);
const b2 = client.request(new URL(API), { lane: 'background', timeoutMs: 1000 }).then(() => 'ok', e => e.message);
await assert.rejects(client.request(new URL(API), { lane: 'background', timeoutMs: 1000 }), /queue full/);
const mint = client.request(new URL(API), { lane: 'mint', timeoutMs: 1000 });
await clock.advance(5000);
await mint;
assert.deepEqual([await b1, await b2], ['ok', 'Wikimedia unavailable: queue full']);
});
test('waiting longer than the lane allows fails instead of queueing forever', async () => {
const { clock, client } = setup(() => json({}), { burst: 1, requestsPerSecond: 0.01, maxWaitMs: { interactive: 3000 } as ClientConfig['maxWaitMs'] });
await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 });
const late = client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000 }).catch(e => e);
await clock.advance(3000);
assert.match(String(await late), /queue wait/);
});
test('disk cache: ETag revalidation with If-None-Match, 304 refresh, stale-while-revalidate on the background lane', async () => {
const cache = new WikimediaCache(':memory:');
let body = { v: 1 };
const { clock, client, calls } = setup((_url, headers) => headers.get('if-none-match') === '"v1"' && body.v === 1
? new Response(null, { status: 304 }) : json(body, { ETag: `"v${body.v}"` }), {}, cache);
const policy = { ttlMs: 1000, staleWhileRevalidate: false };
const read = async (lane: 'interactive' | 'background' = 'interactive', cachePolicy = policy) =>
(await (await client.request(new URL(API), { lane, timeoutMs: 1000, cache: cachePolicy })).response.json());
assert.deepEqual(await read(), { v: 1 });
assert.deepEqual(await read(), { v: 1 });
assert.equal(calls.length, 1); // Fresh hit.
await clock.advance(1000);
assert.deepEqual(await read(), { v: 1 });
assert.equal(calls.length, 2);
assert.equal(calls[1].headers.get('if-none-match'), '"v1"'); // Conditional request, answered 304.
assert.equal(client.status().counters['cache.revalidated'], 1);
// Stale-while-revalidate: the stale copy is served at once; the refresh happens on the background lane.
await clock.advance(1000);
body = { v: 2 };
assert.deepEqual(await read('interactive', { ttlMs: 1000, staleWhileRevalidate: true }), { v: 1 });
await clock.advance(0); await flush();
assert.equal(calls.length, 3);
assert.equal(client.status().counters['lane.background'], 1);
assert.deepEqual(await read(), { v: 2 });
assert.equal(calls.length, 3);
// The key ignores maxlag and parameter order.
assert.equal(cacheKey(new URL('https://h.org/p?b=2&a=1&maxlag=5')), cacheKey(new URL('https://h.org/p?a=1&b=2')));
});
test('requests without a cache policy (mint) neither read nor write the cache', async () => {
const cache = new WikimediaCache(':memory:');
const { client, calls } = setup(() => json({ n: calls.length }), {}, cache);
await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000, cache: { ttlMs: 60_000 } });
const minted = await client.request(new URL(API), { lane: 'mint', timeoutMs: 1000 });
assert.equal(minted.fromCache, false);
assert.equal(calls.length, 2);
assert.equal(cache.size(), 1);
});
test('a stale copy is served when the upstream refuses, and non-JSON replies are never cached', async () => {
const cache = new WikimediaCache(':memory:');
let fail = false, html = false;
const { clock, client } = setup(() => fail ? new Response('', { status: 429 })
: html ? new Response('<html>', { headers: { 'Content-Type': 'text/html' } }) : json({ v: 1 }), {}, cache);
const policy = { ttlMs: 1000 };
await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000, cache: policy });
await clock.advance(2000);
fail = true;
const stale = await client.request(new URL(API), { lane: 'interactive', timeoutMs: 1000, cache: policy });
assert.equal(stale.fromCache, true);
fail = false; html = true;
await clock.advance(60_000);
await client.request(new URL(`${API}&other=1`), { lane: 'interactive', timeoutMs: 1000, cache: policy });
assert.equal(cache.size(), 1);
});
test('start-up warns when there is no operator contact', () => {
const messages: string[] = [];
assert.equal(warnIfNoContact({}, m => messages.push(m)), true);
assert.match(messages[0], /WIKIDECK_OPERATOR_CONTACT/);
assert.equal(warnIfNoContact({ WIKIDECK_OPERATOR_CONTACT: 'ops@example.org' }, m => messages.push(m)), false);
assert.equal(warnIfNoContact({ WIKIDECK_USER_AGENT: 'X/1 (+https://x; y)' }, m => messages.push(m)), false);
assert.equal(messages.length, 1);
});
test('only HTTPS is allowed', async () => {
const { client } = setup();
await assert.rejects(client.request(new URL('http://en.wikipedia.org/w/api.php'), { lane: 'mint', timeoutMs: 1 }), RangeError);
});
+52
View File
@@ -0,0 +1,52 @@
// Shared fakes for tests/wikimedia-*.test.ts: a manual clock and a recording fetch. Zero network.
import type { Clock } from '../server/wikimedia/client.ts';
export class FakeClock implements Clock {
time: number;
private timers: { at: number; fn: () => void; id: number }[] = [];
private nextId = 1;
constructor(start = Date.parse('2026-11-17T12:00:00Z')) { this.time = start; }
now(): number { return this.time; }
setTimeout(fn: () => void, ms: number): unknown {
const id = this.nextId++;
this.timers.push({ at: this.time + Math.max(0, ms), fn, id });
return id;
}
clearTimeout(handle: unknown): void { this.timers = this.timers.filter(t => t.id !== handle); }
/** Advance time, firing due timers in order and letting promise chains settle between them. */
async advance(ms: number): Promise<void> {
const target = this.time + ms;
await flush();
for (;;) {
this.timers.sort((a, b) => a.at - b.at || a.id - b.id);
const next = this.timers[0];
if (!next || next.at > target) break;
this.timers.shift();
this.time = Math.max(this.time, next.at);
next.fn();
await flush();
}
this.time = target;
await flush();
}
}
export async function flush(): Promise<void> {
for (let i = 0; i < 10; i++) await new Promise(resolve => setImmediate(resolve));
}
export function json(value: unknown, headers: Record<string, string> = {}, status = 200): Response {
return new Response(JSON.stringify(value), { status, headers: { 'Content-Type': 'application/json; charset=utf-8', ...headers } });
}
export type Call = { url: URL; headers: Headers; at: number };
export function recorder(clock: { now(): number }, handler: (url: URL, headers: Headers) => Response | Promise<Response>) {
const calls: Call[] = [];
const fetcher: typeof fetch = async (input, init) => {
const url = new URL(String(input));
const headers = new Headers(init?.headers);
calls.push({ url, headers, at: clock.now() });
return handler(url, headers);
};
return { calls, fetcher };
}
+104
View File
@@ -0,0 +1,104 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { WikipediaEnrichment } from '../server/enrichment.ts';
import { WikipediaArticleSource, randomArticlesUrl } from '../server/wiki.ts';
import { WikimediaClient } from '../server/wikimedia/client.ts';
import { WikimediaCache } from '../server/wikimedia/cache.ts';
import { UNTHROTTLED } from '../server/wikimedia/client.ts';
import { json } from './wikimedia-helpers.ts';
const JANUARY = new Date('2025-01-15T23:59:59Z');
const MONTHS = ['2024-07', '2024-08', '2024-09', '2024-10', '2024-11', '2024-12'];
const metadata = (pageId = 736) => ({ query: { pages: [{ pageid: pageId, ns: 0, title: 'Albert Einstein', lastrevid: 1234,
length: 100_000, pageprops: { wikibase_item: 'Q937' }, categories: [], langlinks: [{ lang: 'de' }] }] } });
const views = (counts = [10, 20, 30, 40, 50, 100]) => ({ items: MONTHS.map((month, i) => ({ timestamp: `${month.replace('-', '')}0100`,
views: counts[i], project: 'en.wikipedia', access: 'all-access', agent: 'user', granularity: 'monthly' })) });
function service(viewsReply: () => Response | Promise<Response>, cache?: WikimediaCache) {
const urls: URL[] = [];
const fetcher: typeof fetch = async input => {
const url = new URL(String(input));
urls.push(url);
return url.hostname === 'en.wikipedia.org' ? json(metadata(Number(url.searchParams.get('pageids')))) : viewsReply();
};
const client = new WikimediaClient({ fetch: fetcher, config: UNTHROTTLED, cache });
return { urls, client, enrichment: new WikipediaEnrichment({ client, now: () => JANUARY }) };
}
test('mint fix: a 429, 5xx, timeout or network failure on pageviews fails the mint read instead of pinning attention: null', async () => {
const failures: (() => Response | Promise<Response>)[] = [
() => new Response('', { status: 429, headers: { 'Retry-After': '0' } }),
() => new Response('', { status: 503 }),
() => new Response('', { status: 500 }),
() => new Response('<html>busy</html>', { headers: { 'Content-Type': 'text/html' } }),
() => { throw new TypeError('fetch failed'); },
() => Promise.reject(new DOMException('The operation timed out.', 'TimeoutError')),
];
for (const failure of failures) {
const { enrichment } = service(failure);
await assert.rejects(enrichment.getFresh(736), /unavailable/);
// Display reads keep their old behaviour: metadata with unavailable views.
const shown = await enrichment.get(736);
assert.equal(shown.pageviews.status, 'unavailable');
assert.equal(shown.stats.attention, null);
}
});
test('mint records unavailable views only for a genuine 404 or missing data', async () => {
for (const reply of [() => json({ type: 'not found' }, {}, 404), () => json({ items: [] }), () => json({ items: views().items.slice(1) })]) {
const { enrichment } = service(reply);
const minted = await enrichment.getFresh(736);
assert.equal(minted.pageviews.status, 'unavailable');
assert.equal(minted.stats.attention, null);
}
const { enrichment } = service(() => json(views()));
assert.equal((await enrichment.getFresh(736)).stats.attention, 33);
});
test('mint reads never use the disk cache or join a display read', async () => {
const cache = new WikimediaCache(':memory:');
let count = 100;
const { enrichment, urls } = service(() => json(views([1, 1, 1, 1, 1, count++])), cache);
const shown = await enrichment.get(736);
assert.equal(cache.size(), 2);
const [display, minted] = await Promise.all([enrichment.get(736), enrichment.getFresh(736)]);
assert.equal(display.pageviews.months[5].views, shown.pageviews.months[5].views);
assert.equal(minted.pageviews.months[5].views, 101); // Fetched again, not the cached 100.
assert.equal(urls.length, 4);
// A later display read (memory cache cleared by a new service) is served from disk: no upstream call.
const second = new WikipediaEnrichment({ client: new WikimediaClient({ fetch: async () => { throw new Error('no network'); },
config: UNTHROTTLED, cache }), now: () => JANUARY });
assert.equal((await second.get(736)).pageviews.months[5].views, 100);
});
test('golden mint URLs: request parameters are byte-identical apart from the added maxlag', async () => {
assert.equal(randomArticlesUrl().toString(), 'https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2'
+ '&generator=random&grnnamespace=0&grnlimit=10&prop=extracts%7Cpageimages%7Cinfo%7Ccategories&exintro=1&explaintext=1'
+ '&exchars=900&piprop=thumbnail&pithumbsize=800&cllimit=20');
const urls: string[] = [];
const fetcher: typeof fetch = async input => {
const url = new URL(String(input));
urls.push(url.toString());
if (url.searchParams.get('generator') === 'random') return json({ query: { pages: [{ pageid: 9, ns: 0, title: 'T',
extract: 'An extract that is comfortably longer than forty characters.', lastrevid: 2,
thumbnail: { source: 'https://upload.wikimedia.org/a.jpg' } }] } });
return url.hostname === 'en.wikipedia.org' ? json(metadata(9)) : json(views());
};
const client = new WikimediaClient({ fetch: fetcher, config: UNTHROTTLED });
const article = await new WikipediaArticleSource(client).random();
await new WikipediaEnrichment({ client, now: () => JANUARY }).getFresh(article.pageId);
assert.deepEqual(urls, [
`${randomArticlesUrl()}&maxlag=5`,
'https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&pageids=9'
+ '&prop=info%7Ccategories%7Cpageprops%7Cdescription%7Clanglinks&clshow=%21hidden&cllimit=50&lllimit=500'
+ '&ppprop=wikibase_item&maxlag=5',
'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/user/Albert_Einstein/monthly/2024070100/2024120100',
]);
});
test('a throttled upstream stops random() at once instead of retrying three times', async () => {
let calls = 0;
const source = new WikipediaArticleSource(async () => { calls++; return new Response('', { status: 429 }); });
await assert.rejects(source.random(), /HTTP 429/);
assert.equal(calls, 1);
});
+74
View File
@@ -0,0 +1,74 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { MintTemplatePool } from '../server/wikimedia/pool.ts';
import type { Article } from '../shared/protocol.ts';
import type { PageEnrichment } from '../shared/enrichment.ts';
function article(pageId: number): Article {
return { pageId, title: `Page ${pageId}`, extract: 'An extract that is comfortably longer than forty characters.',
image: 'https://upload.wikimedia.org/a.jpg', url: `https://en.wikipedia.org/?curid=${pageId}`, revisionId: pageId + 1,
source: 'live', category: 'Culture' };
}
function enrichment(pageId: number): PageEnrichment {
return { pageId, title: `Page ${pageId}`, description: null, wikidataId: null, revisionId: pageId + 1, pageBytes: 10,
languageCount: 1, languagesTruncated: false, categories: [], categoriesTruncated: false, fetchedAt: '2026-11-17T00:00:00Z',
pageviews: { status: 'available', months: [], latestMonth: '2026-10', total: 1, dailyAverage: 1, trendPercent: null },
stats: { attention: 1, depth: 1, reach: 1 } };
}
function fixture(options: { size?: number; maxAgeMs?: number } = {}) {
let next = 1, now = 0, fail = false;
const log: string[] = [];
const sources = {
articles: { random: async () => { log.push('random'); if (fail) throw new Error('Wikimedia unavailable: HTTP 429'); return article(next++); } },
enrichment: { getFresh: async (id: number) => { log.push(`fresh:${id}`); return enrichment(id); } },
};
const pool = new MintTemplatePool(sources, { now: () => now, ...options });
return { pool, log, advance: (ms: number) => { now += ms; }, setFail: (value: boolean) => { fail = value; } };
}
test('every template on one tip shares one article; a new tip gets a different one', async () => {
const { pool, log } = fixture({ size: 1 });
const first = await Promise.all(Array.from({ length: 20 }, () => pool.take('tip-a')));
assert.ok(first.every(pair => pair.article.pageId === first[0].article.pageId));
await pool.refill();
const requestsForTwentyMiners = log.length;
assert.equal(requestsForTwentyMiners, 4); // One direct pair, one prefetched pair: 2 calls each.
const second = await pool.take('tip-b');
assert.notEqual(second.article.pageId, first[0].article.pageId);
assert.equal(second.article.pageId, 2); // Served from the prefetched pair, no wait.
await pool.refill();
assert.equal(log.length, 6); // ...and that use alone triggers the next prefetch.
// The stats snapshot comes from a mint-path read of the same page.
assert.equal(second.statsSnapshot.revisionId, second.article.pageId + 1);
});
test('pairs older than maxAge are dropped, never served', async () => {
const { pool, advance } = fixture({ size: 1, maxAgeMs: 1000 });
const a = await pool.take('t1');
await pool.refill();
advance(1000);
const b = await pool.take('t1'); // Same tip, but its pair expired; the ready pair expired too.
assert.notEqual(b.article.pageId, a.article.pageId);
assert.equal(pool.status().expired, 1);
});
test('an idle pool makes no requests, and a failure rejects the template without a retry loop', async () => {
const { pool, log, setFail } = fixture({ size: 2 });
assert.equal(log.length, 0);
setFail(true);
await assert.rejects(pool.take('t1'), /429/);
await pool.refill();
assert.equal(log.filter(entry => entry === 'random').length, 2); // The direct attempt and one refill attempt.
setFail(false);
assert.ok((await pool.take('t1')).article.pageId > 0);
});
test('callers get copies they cannot mutate', async () => {
const { pool } = fixture();
const a = await pool.take('t');
a.article.title = 'changed';
assert.equal((await pool.take('t')).article.title.startsWith('Page'), true);
assert.throws(() => new MintTemplatePool({ articles: { random: async () => article(1) },
enrichment: { getFresh: async () => enrichment(1) } }, { size: 99 }), RangeError);
});