Files
wikideck/shared/game/derive.ts
T
claudeanderic 4f7a8a7c74 Night 1: Edit War card game, eom.dev accounts, peer-hosted modes, Android and iOS apps (#22)
Overnight build by 17 Claude agents (2026-11-16 22:45 → 01:30 EST), coordinated in [claude/wikideck milestone 63](https://gitea.eom.dev/claude/wikideck/milestone/63). **For Eric's review. Do not merge without it.** The full write-up is in `docs/night/REPORT.md`.

**What's in it** (38 reviewed PRs, squash-merged into `night/2026-11-16`):
- **Edit War:**
  - a 3-lane, 6-turn card game built on what WikiDeck cards actually hold
  - a pure, deterministic, off-chain rules engine (`shared/game/`, with the API in `docs/game/ENGINE_API.md`); rules are data and v1.1 is the default
  - a mobile-first Play UI with a lobby, deck builder, four loaner starter decks, a match against the AI, results and a tutorial
  - a landing page (fixes #3)
- **Design and balance:** `docs/game/DESIGN.md`, `CARD_DATA.md` (236 sampled articles) and `BALANCE.md` (bot simulations). Starter pairings went from 23–77% on v1 to roughly even on v1.1.
- **eom.dev accounts:** Dex OIDC with PKCE, plus off-chain wallet linking, where the client builds the message it signs (`server/account/`, `src/auth/`).
- **Peer-hosted game modes:** modes are JSON data, never code. Node API at `/api/game/*`, with host credit and leaderboards. Three example modes (`shared/game/modes.ts`, `server/game/`, `docs/game/HOSTING.md`).
- **Mobile:** Capacitor 7 Android app (a debug APK played a full match against the AI in the emulator), and an iOS project waiting on Xcode (`docs/night/ANDROID.md`, `docs/night/IOS.md`).
- **Testnet tooling:** `deploy/night/` (LAN-only, 3 nodes) and an optional `WIKIDECK_USER_AGENT` (the default is unchanged).

**Not touched:** consensus and protocol (`server/chain.ts`, `shared/protocol.ts`, `server/testnet/{consensus,ledger,…}.ts`, `native/`), the live deployment and mainnet. Matches run off-chain and never move or burn NFTs.

**Checks:** the final integration gate passed in `node:24-alpine`: `npm test` 241/242 with 0 fail (1 skipped), and `npm run build` passes. The repo needs Node 24, because Node 20 fails 12 tests falsely.

**Decisions for Eric** (see REPORT.md, Known issues and Next steps):
1. whether the live node should set `WIKIDECK_USER_AGENT`
2. the Xcode licence, which you should accept yourself
3. #49 in the fork, a bot change held after the freeze
4. on-chain host rewards (proposal only, in HOSTING.md)

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

Co-authored-by: Claude <claude@eom.dev>
2026-11-17 17:40:58 +00:00

144 lines
7.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Card derivation (DESIGN §1 and §10.1): a host-frozen CardInput becomes a GameCard.
* Pure and deterministic. The engine itself never reads raw 0–100 stats; hosts call
* deriveCard() before createMatch. Owner: engine-b.
*/
import { FACTION_KEYWORD } from './keywords.ts';
import { DEFAULT_RULESET } from './ruleset.ts';
import { STATS, type Faction, type GameCard, type Rarity, type Stat } from './types.ts';
/** §1.4 tie-break order: depth and reach are the hardest to inflate. */
export const HOME_TIE_ORDER: readonly Stat[] = ['depth', 'reach', 'attention'];
export interface CardInput {
cardId: string;
/** null for loaners without a known article (§2.1). */
pageId: number | null;
title: string;
category: Faction;
rarity: Rarity;
/** Only the derived scores are read (MintStatsSnapshot.stats). */
snapshot: { stats: { attention: number | null; depth: number; reach: number } };
/** Frozen by the host at match start. */
live: { trendPercent: number | null; dailyAverage: number | null };
/** §1.10, set by the host. Only 'unchecked' changes derivation (cost cap). */
check: 'verified' | 'unverified' | 'unchecked' | 'loaner';
/** Loaners only (§2.1): replaces §1.1–1.5. Ignored unless check === 'loaner'. */
pinned?: { cost: number; home: Stat; faction: Faction };
}
/** 99 ascending cut points per stat (§1.1). */
export type PercentileTable = Record<Stat, readonly number[]>;
/** The rules config keys derivation reads (§9). */
export interface DerivationRules {
costThresholds: readonly number[];
powerByCost: readonly number[];
vanillaBonus: number;
keywordsEnabled: readonly string[];
/** v1.1 hook: 'home' gives Culture cards a home-stat keyword instead of viral (§10.1). Default 'faction' (v1). */
cultureKeyword?: 'faction' | 'home';
keywordParams: Record<string, Record<string, number>>;
trendUp: number;
trendDown: number;
trendMinDaily: number;
uncheckedCostCap: number;
}
/** Derivation defaults are the engine's DEFAULT_RULESET (a Ruleset is a DerivationRules). */
export const DEFAULT_DERIVATION: DerivationRules = DEFAULT_RULESET;
/** §1.1: cut points strictly below, plus half of those equal, rounded down. */
export function percentile(score: number, cuts: readonly number[]): number {
let below = 0, equal = 0;
for (const cut of cuts) {
if (cut < score) below++;
else if (cut === score) equal++;
}
return Math.floor(below + equal / 2);
}
export function percentiles(stats: CardInput['snapshot']['stats'], table: PercentileTable): Record<Stat, number | null> {
return {
attention: stats.attention === null ? null : percentile(stats.attention, table.attention),
depth: percentile(stats.depth, table.depth),
reach: percentile(stats.reach, table.reach),
};
}
/** §1.2: integer mean of the non-null percentiles, rounded half up. */
export function fame(pct: Record<Stat, number | null>): number {
const values = STATS.map(stat => pct[stat]).filter((value): value is number => value !== null);
if (!values.length) return 0;
return Math.floor(values.reduce((total, value) => total + value, 0) / values.length + 0.5);
}
/** §1.2: 1 + the number of thresholds ≤ fame. */
export function costFor(fameValue: number, thresholds: readonly number[]): number {
return 1 + thresholds.filter(threshold => threshold <= fameValue).length;
}
/** §1.4: highest percentile, ties by depth > reach > attention; null never wins. */
export function homeStat(pct: Record<Stat, number | null>): Stat {
let best: Stat = HOME_TIE_ORDER[0];
for (const stat of HOME_TIE_ORDER) {
const value = pct[stat], current = pct[best];
if (value !== null && (current === null || value > current)) best = stat;
}
return best;
}
/** §1.6: ±1 past the thresholds; 0 for null or for articles under trendMinDaily views a day. */
export function trendFor(live: CardInput['live'], rules: Pick<DerivationRules, 'trendUp' | 'trendDown' | 'trendMinDaily'>): -1 | 0 | 1 {
const { trendPercent, dailyAverage } = live;
if (trendPercent === null || !Number.isFinite(trendPercent)) return 0;
if (dailyAverage === null || !(dailyAverage >= rules.trendMinDaily)) return 0;
if (trendPercent >= rules.trendUp) return 1;
if (trendPercent <= rules.trendDown) return -1;
return 0;
}
/**
* §10.1: cost 1 → vanilla (+vanillaBonus); edition if enabled and the deck has another
* copy; else the faction keyword if enabled; else vanilla without the bonus.
*/
/** v1.1 option (critic, #3): Culture keyword by home stat when `cultureKeyword: 'home'`. */
export const CULTURE_HOME_KEYWORD: Record<Stat, string> = { attention: 'viral', depth: 'encyclopedic', reach: 'translated' };
export function keywordFor(faction: Faction, cost: number, hasCopyInDeck: boolean,
rules: Pick<DerivationRules, 'keywordsEnabled' | 'cultureKeyword'>, home: Stat = 'attention'):
{ keyword: string | null; vanilla: boolean } {
if (cost === 1) return { keyword: null, vanilla: true };
if (hasCopyInDeck && rules.keywordsEnabled.includes('edition')) return { keyword: 'edition', vanilla: false };
const keyword = faction === 'Culture' && rules.cultureKeyword === 'home' ? CULTURE_HOME_KEYWORD[home] : FACTION_KEYWORD[faction];
return rules.keywordsEnabled.includes(keyword) ? { keyword, vanilla: false } : { keyword: null, vanilla: false };
}
export function deriveCard(input: CardInput, table: PercentileTable, rules: DerivationRules = DEFAULT_DERIVATION,
hasCopyInDeck = false): GameCard {
const pinned = input.check === 'loaner' ? input.pinned : undefined;
const pct = percentiles(input.snapshot.stats, table);
let cost = pinned ? pinned.cost : costFor(fame(pct), rules.costThresholds);
if (input.check === 'unchecked') cost = Math.min(cost, rules.uncheckedCostCap);
const faction = pinned ? pinned.faction : input.category;
const base = rules.powerByCost[cost];
if (base === undefined) throw new RangeError(`powerByCost has no entry for cost ${cost}`);
const home = pinned ? pinned.home : homeStat(pct);
const { keyword, vanilla } = keywordFor(faction, cost, hasCopyInDeck, rules, home);
const delta = keyword ? Math.max(-3, Math.min(0, rules.keywordParams[keyword]?.powerDelta ?? 0)) : 0;
return {
cardId: input.cardId, pageId: input.pageId, title: input.title, faction, rarity: pinned ? 'Common' : input.rarity,
cost, power: Math.max(0, base + (vanilla ? rules.vanillaBonus : 0) + delta),
home, trend: pinned ? 0 : trendFor(input.live, rules), keyword,
source: input.check === 'loaner' ? 'loaner' : 'owned', check: input.check,
};
}
/** Derive a whole deck; Edition (if enabled) needs to know about copies of the same pageId. */
export function deriveDeck(inputs: readonly CardInput[], table: PercentileTable, rules: DerivationRules = DEFAULT_DERIVATION): GameCard[] {
const key = (input: CardInput) => input.pageId ?? `card:${input.cardId}`;
const counts = new Map<number | string, number>();
for (const input of inputs) counts.set(key(input), (counts.get(key(input)) ?? 0) + 1);
return inputs.map(input => deriveCard(input, table, rules, (counts.get(key(input)) ?? 0) > 1));
}