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

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

PR numbers refer to `claude/wikideck`.

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

This PR is for Eric to merge.

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

Co-authored-by: Claude <claude@eom.dev>
2026-11-18 18:12:24 +00:00

256 lines
16 KiB
TypeScript
Raw Permalink 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.
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { classify } from '../shared/duel/classify.ts';
import {
derive, connectedTier, figureBody, flavorFor, portalFor, DERIVE_RULES, DERIVE_VERSION,
type DuelCard, type CardProfile,
} from '../shared/duel/derive.ts';
import { deriveSample, sampleInputs, type SampleCard } from '../shared/duel/sample.ts';
import { rulesTextFor, rulesTextWithReminders, typeLine } from '../shared/duel/text.ts';
const root = new URL('../', import.meta.url);
const SAMPLE = (JSON.parse(readFileSync(new URL('docs/game/card-sample.json', root), 'utf8')) as { cards: SampleCard[] }).cards;
const FIXTURE = JSON.parse(readFileSync(new URL('docs/game/duel-card-sample.json', root), 'utf8')) as { deriveVersion: string; cards: DuelCard[] };
const CARDS = deriveSample(SAMPLE);
const byTitle = (title: string) => {
const card = CARDS.find(c => c.title === title);
assert.ok(card, `missing sample card ${title}`);
return card;
};
const profile = (overrides: Partial<CardProfile>): CardProfile =>
({ wikidataId: null, description: null, categories: [], instanceOf: [], ...overrides });
test('every sample card gets a type, and nothing falls through to the Doctrine residual', () => {
assert.equal(CARDS.length, 236);
const fallback = CARDS.filter(c => c.typedBy === 'fallback');
assert.deepEqual(fallback.map(c => c.title), []);
const share = (t: string) => CARDS.filter(c => c.type === t).length / CARDS.length;
// data §1 distribution, ±4 points
assert.ok(Math.abs(share('Figure') - 0.364) < 0.04);
assert.ok(Math.abs(share('Location') - 0.331) < 0.04);
assert.ok(share('Event') > 0.05 && share('Doctrine') > 0.05 && share('Institution') > 0.1);
});
test('"human settlement" villages are Locations, not Figures (the \\bhuman\\b bug)', () => {
for (const title of ['Buky', 'Lunugala', 'Žižki', 'Laukhella']) assert.equal(byTitle(title).type, 'Location', title);
assert.equal(classify(profile({ instanceOf: [{ id: 'Q999', label: 'human settlement' }] })).type, 'Location');
assert.equal(classify(profile({ instanceOf: [{ id: 'Q999', label: 'human' }] })).type, 'Figure');
});
test('rule order: elections beat "municipal", aspects beat "region", governing bodies are Institutions', () => {
assert.equal(byTitle('2023 Seville municipal election').type, 'Event');
assert.equal(byTitle('Corruption in Kazakhstan').type, 'Doctrine');
assert.equal(byTitle('Diocese of Mindelo').type, 'Institution');
assert.equal(byTitle('Region Östergötland').type, 'Institution');
assert.equal(byTitle('Lewis and Elizabeth Bolton House').type, 'Location');
});
test('P279 anchors and labels classify items without P31; categories then description are fallbacks', () => {
assert.deepEqual(classify(profile({ subclassOf: [{ id: 'Q1', label: 'algebraic structure' }] })),
{ type: 'Doctrine', source: 'p279', matched: 'algebraic structure' });
assert.equal(classify(profile({ subclassOf: [{ id: 'Q43229', label: 'x' }] })).source, 'p279-qid');
assert.equal(classify(profile({ categories: ['Villages in Somewhere', 'Somewhere geography stubs'] })).type, 'Location');
assert.equal(classify(profile({ description: 'Species of beetle' })).type, 'Figure');
assert.deepEqual(classify(profile({})), { type: 'Doctrine', source: 'fallback', matched: '' });
});
test('derive is deterministic and the committed fixture is current', () => {
assert.deepEqual(deriveSample(SAMPLE), CARDS);
assert.equal(FIXTURE.deriveVersion, DERIVE_VERSION);
assert.deepEqual(FIXTURE.cards, CARDS, 'run: node --experimental-strip-types scripts/duel-card-sample.ts');
const { chain, profile: p } = sampleInputs(SAMPLE[0]);
const frozen = structuredClone(p);
derive(chain, p);
assert.deepEqual(p, frozen, 'derive must not mutate the profile');
});
test('costs, bodies and keyword caps stay in range', () => {
for (const c of CARDS) {
assert.ok(c.keywords.length <= 2, c.title);
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 === 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') {
assert.ok(c.cost >= 1 && c.cost <= 3, c.title);
assert.equal(c.power, 0);
assert.ok(c.toughness! >= 1 && c.toughness! <= 4);
assert.deepEqual(c.keywords, []);
} else {
assert.equal(c.power, null);
assert.ok(c.effects.length > 0, c.title);
}
}
});
test('no famous Figure is strictly better than another Figure of no lower cost with the same keywords (data §2)', () => {
const figures = CARDS.filter(c => c.type === 'Figure');
const dominated: string[] = [];
for (const x of figures) for (const y of figures) {
if (x === y || x.keywords.join() !== y.keywords.join()) continue;
if (x.cost <= y.cost && x.power! >= y.power! && x.toughness! >= y.toughness!
&& (x.cost < y.cost || x.power! > y.power! || x.toughness! > y.toughness!)) dominated.push(`${x.title} > ${y.title}`);
}
assert.deepEqual(dominated, []);
// Fame buys size, not efficiency: (P+T)/cost does not rise with cost.
const eff = (cost: number) => { const g = figures.filter(c => c.cost === cost); return g.reduce((s, c) => s + (c.power! + c.toughness!) / cost, 0) / g.length; };
for (let cost = 2; cost <= 6; cost++) assert.ok(eff(cost) < eff(1) && eff(cost) <= 2, `cost ${cost}: ${eff(cost)}`);
});
test('figureBody: keyword tax comes off the budget first, then attention vs depth splits it', () => {
assert.deepEqual(figureBody(4, { attention: 90, depth: 10, reach: 0 }, []), { power: 7, toughness: 1, keywords: [] });
assert.deepEqual(figureBody(4, { attention: 10, depth: 90, reach: 0 }, ['Featured']), { power: 1, toughness: 6, keywords: ['Featured'] });
assert.deepEqual(figureBody(1, { attention: 50, depth: 50, reach: 0 }, ['Legacy', 'Stub', 'Local']),
{ power: 1, toughness: 1, keywords: ['Legacy', 'Stub'] });
assert.deepEqual(figureBody(1, { attention: 50, depth: 50, reach: 0 }, ['Protected', 'Legacy', 'Stub']),
{ power: 1, toughness: 1, keywords: ['Protected', 'Stub'] });
assert.deepEqual(figureBody(3, { attention: null, depth: 50, reach: 0 }, ['Translated', 'Stub', 'Local']),
{ power: 3, toughness: 3, keywords: ['Translated', 'Stub'] });
});
test('keyword bands: Multilingual and Translated never both; Figures only', () => {
for (const c of CARDS) {
assert.ok(!(c.keywords.includes('Multilingual') && c.keywords.includes('Translated')), c.title);
if (c.type !== 'Figure') assert.deepEqual(c.keywords, [], c.title);
}
});
test('DUEL_DESIGN §9 worked examples (golden)', () => {
const show = (title: string) => {
const c = byTitle(title);
const body = c.type === 'Figure' || c.type === 'Location' ? ` · ${c.power}/${c.toughness}` : '';
return `${c.cost} · ${typeLine(c)}${body} · ${c.rulesText.replace(/\n/g, ' ')} · ${c.flavor}`;
};
const golden: Record<string, string> = {
'Marc Fesneau': '5 · Figure — Society · 5/4 · Protected. · French politician (born 1971)',
'Tom Ewell': '6 · Figure — Arts · 5/5 · Featured, Legacy. · American actor (1909–1994)',
'Zbyszek Godlewski': '5 · Figure — History · 6/3 · Legacy, Translated. · Polish protester (1952–1970)',
"Pallas's cat": '6 · Figure — Earth · 5/5 · Featured, Multilingual. · Species of small wild cat',
'Dichromorpha viridis': '2 · Figure — Earth · 3/1 · Stub. · Species of grasshopper',
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',
'Heart rot': '5 · Doctrine — Science · Attach to target Figure. It gets −3/−3. · Fungal disease of trees',
"April 2021 nor'easter": "3 · Event — Earth · Deal 1 damage to each Figure and each Location. · Slow-moving nor'easter in April 2021",
// §9 says History; the Portal score is Society (protest/riot categories outnumber "war").
'2025 Tehreek-e-Labbaik Pakistan protests': '5 · Event — Society · Deal 4 damage to target Figure or Location. · Gaza war protests in Pakistan',
'1954 Gold Coast general election': '3 · Event — Society · Create two 1/1 Society Figure tokens named Elected Member. · ',
// §9 says History; "mosque" hits (P31, description, 2 categories) outscore 15th-century + Sultanate.
'Pathrail Mosque': '2 · Location — Society · 0/3 · Territory. Garrison 0/3. · Mosque in Faridpur, Bangladesh',
'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',
'Agda (programming language)': '6 · Doctrine — Science · Attach to target Figure you control. It gets +3/+3. '
+ 'Whenever it deals combat damage to a player, draw a card. · Functional programming language',
};
for (const [title, want] of Object.entries(golden)) assert.equal(show(title), want, title);
assert.equal(rulesTextWithReminders(byTitle('Tom Ewell')),
'Featured. (Can\'t be blocked except by Featured, Translated or Multilingual Figures.)\nLegacy. (When this is destroyed, draw a card.)');
assert.equal(rulesTextWithReminders(byTitle('Pathrail Mosque')),
'Territory. (Your Citation maximum is 1 higher while you control this, to at most +2 from Territory.)\n'
+ 'Garrison 0/3. (This can block like a Figure with power 0. It can\'t attack.)');
});
test('rules text uses only card numbers and fixed words: no title, description or category text leaks in', () => {
for (const c of CARDS) {
const stripped = c.rulesText.replace(/Protected|Featured|Translated|Legacy|Stub|Well-sourced|Multilingual|Local/g, '');
assert.ok(!stripped.includes(c.title), c.title);
assert.match(c.rulesText, /^[A-Za-z0-9 ,.;:'()+−/\n—-]*$/, c.title);
assert.equal(rulesTextFor(c), c.rulesText);
}
});
test('flavour is the first sentence of the extract, else the description', () => {
assert.equal(flavorFor('Tom Ewell (born Samuel Yewell Tompkins; April 29, 1909 – September 12, 1994) was an American actor. He won a Tony.', null),
'Tom Ewell (born Samuel Yewell Tompkins; April 29, 1909 – September 12, 1994) was an American actor.');
assert.equal(flavorFor('J. R. R. Tolkien was an English writer. He wrote.', null), 'J. R. R. Tolkien was an English writer.');
assert.equal(flavorFor('The U.S. Route 66 is a road in the U.S. state of Arizona. More.', null), 'The U.S. Route 66 is a road in the U.S. state of Arizona.');
assert.equal(flavorFor('No terminal punctuation', 'desc'), 'No terminal punctuation');
assert.equal(flavorFor(' ', 'Species of grasshopper'), 'Species of grasshopper');
assert.equal(byTitle('Dichromorpha viridis').flavor, 'Species of grasshopper');
});
test('Portals: keyword hits decide, ties go to the type default, no hits is Neutral', () => {
assert.equal(portalFor(profile({ description: 'Sultan of Aceh', categories: ['16th-century monarchs in Asia'] }), 'Figure'), 'History');
assert.equal(portalFor(profile({ description: 'mathematician and politician' }), 'Figure'), 'Society');
assert.equal(portalFor(profile({ description: 'zzz' }), 'Figure'), 'Neutral');
const portals = new Set(CARDS.map(c => c.portal));
for (const p of ['Arts', 'Earth', 'History', 'Science', 'Society']) assert.ok(portals.has(p as DuelCard['portal']), p);
});
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: [], 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');
assert.equal(connectedTier(a, base('b', 2, { countries: ['France'] })), 'Linked');
assert.equal(connectedTier(base('b', 2, { links: [1] }), a), 'Linked');
assert.equal(connectedTier(a, base('c', 3, { countries: ['France'], centuries: [20] })), 'Compatriot');
assert.equal(connectedTier(a, base('d', 4, { centuries: [20] })), 'Contemporary');
assert.equal(connectedTier(a, base('e', 5, { p31: ['Q1'] })), 'Kin');
assert.equal(connectedTier(a, base('f', 6, {})), null);
assert.equal(connectedTier(a, a), null);
assert.equal(connectedTier(a, base('c', 3, { centuries: [20] }), ['Linked', 'Compatriot']), null);
});
test('Connected fires in a plausible share of sample pairs (BRIEF target 15–30%, tuned in the sim)', () => {
let hits = 0, pairs = 0;
for (let i = 0; i < CARDS.length; i++) for (let j = i + 1; j < CARDS.length; j++) {
pairs++; if (connectedTier(CARDS[i], CARDS[j])) hits++;
}
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));
});