diff --git a/.gitignore b/.gitignore index a34d4d9..d6d4a52 100644 --- a/.gitignore +++ b/.gitignore @@ -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/ diff --git a/android/app/build.gradle b/android/app/build.gradle index 58a9e88..093389e 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -16,6 +16,13 @@ android { ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~' } } + packagingOptions { + jniLibs { + // The RandomX engine (jniLibs//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 diff --git a/android/app/src/main/java/dev/eom/wikideck/MainActivity.java b/android/app/src/main/java/dev/eom/wikideck/MainActivity.java index 94c31d3..f6d5dbd 100644 --- a/android/app/src/main/java/dev/eom/wikideck/MainActivity.java +++ b/android/app/src/main/java/dev/eom/wikideck/MainActivity.java @@ -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); + } +} diff --git a/android/app/src/main/java/dev/eom/wikideck/MinerPlugin.java b/android/app/src/main/java/dev/eom/wikideck/MinerPlugin.java new file mode 100644 index 0000000..07732dc --- /dev/null +++ b/android/app/src/main/java/dev/eom/wikideck/MinerPlugin.java @@ -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//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 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 `. + * 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"); + } + } +} diff --git a/android/build-debug.sh b/android/build-debug.sh index a114749..e3a5cfb 100755 --- a/android/build-debug.sh +++ b/android/build-debug.sh @@ -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//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 diff --git a/deploy/night/README.md b/deploy/night/README.md index fa737ca..c9e2565 100644 --- a/deploy/night/README.md +++ b/deploy/night/README.md @@ -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. diff --git a/deploy/night/autodeploy.sh b/deploy/night/autodeploy.sh index 3d994ea..fc1e6e8 100755 --- a/deploy/night/autodeploy.sh +++ b/deploy/night/autodeploy.sh @@ -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} diff --git a/deploy/night/compose.lan.yaml b/deploy/night/compose.lan.yaml index a4e3a8d..c0f3790 100644 --- a/deploy/night/compose.lan.yaml +++ b/deploy/night/compose.lan.yaml @@ -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 diff --git a/docs/game/DUEL_DESIGN.md b/docs/game/DUEL_DESIGN.md new file mode 100644 index 0000000..fe4d5f3 --- /dev/null +++ b/docs/game/DUEL_DESIGN.md @@ -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 ` 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. diff --git a/docs/game/duel-card-sample.json b/docs/game/duel-card-sample.json index ef983ed..a82bd43 100644 --- a/docs/game/duel-card-sample.json +++ b/docs/game/duel-card-sample.json @@ -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" } ], diff --git a/docs/night2/MOBILE_MINING.md b/docs/night2/MOBILE_MINING.md new file mode 100644 index 0000000..9c2ac66 --- /dev/null +++ b/docs/night2/MOBILE_MINING.md @@ -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//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. diff --git a/docs/night2/WIKIMEDIA.md b/docs/night2/WIKIMEDIA.md new file mode 100644 index 0000000..3979092 --- /dev/null +++ b/docs/night2/WIKIMEDIA.md @@ -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/ (+https://gitea.eom.dev/WikiDeck/wikideck; ) node/` | + +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. diff --git a/docs/night2/mobile-mining-accepted.jpg b/docs/night2/mobile-mining-accepted.jpg new file mode 100644 index 0000000..c05457a Binary files /dev/null and b/docs/night2/mobile-mining-accepted.jpg differ diff --git a/scripts/build-randomx-android.sh b/scripts/build-randomx-android.sh new file mode 100755 index 0000000..37cd70b --- /dev/null +++ b/scripts/build-randomx-android.sh @@ -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//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;) and CMake 3.24+ (cmake;, 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 diff --git a/scripts/sim/duel-decks.ts b/scripts/sim/duel-decks.ts new file mode 100644 index 0000000..388bd49 --- /dev/null +++ b/scripts/sim/duel-decks.ts @@ -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 { 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(pool: C[], arch: Archetype, seed: number, size = 40): SimDeck { + 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 = {}; for (const c of cards) m[f(c)] = (m[f(c)] ?? 0) + 1; return m; }; + const top = (m: Record) => 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(pool: C[], n: number, seed: number, size = 40): SimDeck[] { + const out: SimDeck[] = []; + 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; +} diff --git a/scripts/sim/duel-run.ts b/scripts/sim/duel-run.ts new file mode 100644 index 0000000..8d1f8a2 --- /dev/null +++ b/scripts/sim/duel-run.ts @@ -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 /