Files
wikideck/shared/duel/classify.ts
claudeandClaude Opus 5.5 3c70f643f2 [duel-cards] Card profiles: classify, derive, effects, rules text from real data
shared/duel/classify.ts: Q-id anchors -> P31 label regex (^human$) -> P279 -> categories -> description -> Doctrine.
shared/duel/derive.ts: pure derive(chain, profile) -> DuelCard: fame cost 1-6, P+T budget per cost,
DUEL_DESIGN §4 keywords (<=2, Figures only, taxed), Portals, Connected keys and tiers, flavour.
shared/duel/effects.ts + text.ts: T1-T12 templates as EffectSpec data, MTG-register rules text.
shared/duel/sample.ts + docs/game/duel-card-sample.json: 236-card DuelCard fixture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 21:43:59 -05:00

126 lines
8.3 KiB
TypeScript

/**
* Card type classification (BRIEF "Card types", data review §1, designer review §3.1).
* Pure and deterministic: everything comes from the frozen CardProfile, nothing is fetched here.
* Order: exact Q-id anchors on P31, then P279 anchors, then P31 label regex (rule order is the
* priority), then P279 label regex, then non-stub categories, then the description, then Doctrine.
* Owner: duel-cards.
*/
export type CardType = 'Figure' | 'Location' | 'Event' | 'Institution' | 'Doctrine';
export const CARD_TYPES: readonly CardType[] = ['Figure', 'Location', 'Event', 'Institution', 'Doctrine'];
export interface WikidataClass { id: string; label: string }
/**
* The off-chain card profile, frozen the first time a host sees the card (data §3) and logged
* with the match so replays and recaps stay deterministic. Only what derivation reads.
*/
export interface CardProfile {
wikidataId: string | null;
/** Wikipedia short description. */
description: string | null;
/** Non-hidden category titles without the "Category:" prefix. */
categories: readonly string[];
/** P31 (instance of). */
instanceOf: readonly WikidataClass[];
/** P279 (subclass of) of the item itself, or the P31 classes' superclasses up to 4 hops, nearest first. */
subclassOf?: readonly WikidataClass[];
/** P17 / P27 country Q-ids (or labels when only text is known). */
countries?: readonly string[];
/** Years from P569/P570/P571/P580/P585 (negative = BCE). */
years?: readonly number[];
/** P570 (date of death) present. */
died?: boolean;
/** ns0 outlinks as pageIds (data §4), for the Linked tier of Connected. */
links?: readonly number[];
/** Item Q-ids cited by the frozen claims (P17, P27, P131, P361, P106, …), for the Linked tier. */
cites?: readonly string[];
/** The live revision the profile was fetched from (data §3). */
fetchedRevisionId?: number;
}
export type ClassifySource = 'qid' | 'p279-qid' | 'p31' | 'p279' | 'category' | 'description' | 'fallback';
export interface Classification { type: CardType; source: ClassifySource; matched: string }
/** Exact anchors (designer §3.1 step 1, data §1 production table). Checked against P31, then P279. */
export const QID_ANCHORS: Readonly<Record<string, CardType>> = {
Q5: 'Figure', Q95074: 'Figure', Q16521: 'Figure', Q23038290: 'Figure', Q8436: 'Figure', Q178885: 'Figure',
Q486972: 'Location', Q515: 'Location', Q532: 'Location', Q3957: 'Location', Q4022: 'Location', Q23397: 'Location',
Q8502: 'Location', Q23442: 'Location', Q41176: 'Location',
Q1656682: 'Event', Q40231: 'Event', Q178561: 'Event', Q198: 'Event', Q8065: 'Event',
Q43229: 'Institution', Q4830453: 'Institution', Q783794: 'Institution', Q7278: 'Institution', Q215380: 'Institution',
Q17537576: 'Institution', Q11424: 'Institution', Q482994: 'Institution', Q7366: 'Institution', Q571: 'Institution',
Q12136: 'Doctrine', Q151885: 'Doctrine', Q7187: 'Doctrine', Q9143: 'Doctrine', Q315: 'Doctrine',
};
type Rules = readonly (readonly [CardType, RegExp])[];
/** P31/P279 label rules (data §1 types.py, with `^human$` and the governing-body fix). Order is load-bearing. */
export const LABEL_RULES: Rules = [
['Doctrine', /aspect of|aspect in|disease|clinical sign|list article|chemical entity/],
['Event', new RegExp('election|protest|battle|war\\b|storm|nor.easter|cyclone|tornado|earthquake|disaster|event|match|final\\b|'
+ 'season|championship|tournament|\\brace\\b|grand prix|scandal|annexation|treaty|incident|festival|referendum|'
+ 'conference|ceremony|time period|delegation|spaceflight|siege|riot|massacre|flood|pandemic|epidemic|straw poll')],
['Institution', /artificial satellite|space station|space telescope|spacecraft|space probe|diocese|ecclesiastical|council\b|governing body|stele/],
['Location', new RegExp('planet|natural satellite|\\bstar\\b|galaxy|nebula|planetary system|astronomical object|rainforest|reef|'
+ 'civili[sz]ation|empire|historical country|archaeological site|'
+ 'human settlement|settlement|village|town|city|commune|municipal|parish|county|district|region|province|'
+ 'township|hamlet|townland|census area|local government|community of|island|river|lake|mountain|plateau|'
+ 'waterfall|valley|bay|peak|geographical feature|historic district|park|state park|square|road|highway|'
+ 'building|castle|mosque|church|temple|cathedral|house|home|museum|station|bridge|monument|historic site|'
+ 'military base|battery|refinery|shopping|stadium|arch|tower|fort|palace|columbari|freguesia|country\\b|sovereign state')],
['Figure', /^human$|fictional character|stock character|person|deity|orisha|loa\b|taxon|species|genus|breed|^family$|organism/],
['Institution', new RegExp('company|business|organi[sz]ation|association|society|party|agency|studio|band|musical group|team|club|'
+ 'university|college|school|institute|manufacturer|newspaper|magazine|film|album|'
+ 'song|single|musical work|composition|television|series|book|novel|video game|painting|award|position|'
+ 'aircraft|ship|steamship|vehicle|automobile|tram|railway line|route|typeface|software|product|brand|artifact|artefact')],
['Doctrine', new RegExp('concept|theory|theorem|mathematical|programming language|language|gene|protein|chemical|compound|'
+ 'ideology|religion|discipline|field|cuisine|food|dish|drink|aspect|'
+ 'particle|process|genre|form\\b|game\\b|branch of|class of|type of|tabular|structure')],
];
/** Category fallback (stub categories are skipped). */
export const CATEGORY_RULES: Rules = [
['Figure', /\bbirth|\bdeaths\b|living people|people from|\bspecies\b|described in \d|\bgenera\b|deities|characters/],
['Event', /\belections\b|protests|\bbattles\b|disasters|\braces\b|\bseasons\b|\bevents\b|scandals|annexations|competitions/],
['Location', new RegExp('villages|communes|parishes|local government|populated places|geography|rivers|islands|buildings and structures|bridges|'
+ 'stations|parks|districts|townships|cities and towns|historic places|freguesias')],
['Institution', new RegExp('companies|organi[sz]ations|\\bfilms\\b|albums|songs|novels|newspapers|television series|musical groups|'
+ 'aircraft|ships|typefaces|software|awards|teams|clubs|establishments')],
['Doctrine', new RegExp('theory|structures$|algebra|terminology|cuisine|drinks|desserts|ecology|languages|diseases|conditions|'
+ 'concepts|ranks|etymology|maps|atlases')],
];
/** Description fallback (present on ~90% of the sample). */
export const DESCRIPTION_RULES: Rules = [
['Figure', /^(species|genus) of|\b(painter|politician|actor|actress|writer|player|singer|born|species|genus)\b/],
['Event', /\b(race|election|battle|match|protest|storm|war|competition)\b/],
['Location', /^(commune|village|town|municipality|river) in|\b(village|town|city|river|island|building|church|columbarium|station|park)\b/],
['Institution', /\b(company|band|film|album|organi[sz]ation|team|aircraft|ship|newspaper)\b/],
['Doctrine', /\b(concept|theory|structure|dessert|drink|dish|technique|class of)\b/],
];
function firstRule(rules: Rules, texts: readonly string[]): [CardType, string] | null {
for (const [type, rx] of rules) for (const text of texts) if (rx.test(text)) return [type, text];
return null;
}
export function classify(profile: Pick<CardProfile, 'instanceOf' | 'subclassOf' | 'categories' | 'description'>): Classification {
const p31 = profile.instanceOf ?? [];
const p279 = profile.subclassOf ?? [];
for (const c of p31) { const t = QID_ANCHORS[c.id]; if (t) return { type: t, source: 'qid', matched: c.id }; }
const p31Labels = p31.map(c => c.label.toLowerCase());
let hit = firstRule(LABEL_RULES, p31Labels);
if (hit) return { type: hit[0], source: 'p31', matched: hit[1] };
for (const c of p279) { const t = QID_ANCHORS[c.id]; if (t) return { type: t, source: 'p279-qid', matched: c.id }; }
hit = firstRule(LABEL_RULES, p279.map(c => c.label.toLowerCase()));
if (hit) return { type: hit[0], source: 'p279', matched: hit[1] };
const cats = (profile.categories ?? []).map(c => c.toLowerCase()).filter(c => !c.includes('stubs'));
hit = firstRule(CATEGORY_RULES, cats);
if (hit) return { type: hit[0], source: 'category', matched: hit[1] };
const desc = (profile.description ?? '').toLowerCase();
hit = firstRule(DESCRIPTION_RULES, desc ? [desc] : []);
if (hit) return { type: hit[0], source: 'description', matched: hit[1] };
return { type: 'Doctrine', source: 'fallback', matched: '' };
}