Files
wikideck/shared/duel/classify.ts
T
claudeandClaude Opus 5.5 5076299e7c [duel-cards] classify: on-chain fallback (extract definition, title, mint category) before Doctrine
An empty profile typed every card as Doctrine (night-review on #61). derive() now passes
chain.article to classify/subtypeFor; full-profile results are unchanged (fixture identical).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 00:50:13 -05:00

184 lines
13 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 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'
| 'extract' | 'title' | 'chain-category' | 'fallback';
export interface Classification { type: CardType; source: ClassifySource; matched: string }
/** Exact anchors (designer §3.1 step 1, data §1 production table). Checked against P31, then P279. */
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/],
];
/**
* On-chain data every block carries (protocol Article), used when the frozen profile is empty or
* missing: the mint-time `category` (server/wiki.ts buckets), the title and the extract.
*/
export interface ChainHints { title: string; extract?: string; category?: string }
/**
* Rules for an extract's definitional phrase ("is a village in …"). Broader than the short-description
* rules because lead sentences use more varied nouns. Order: Doctrine overrides, then as for labels.
*/
export const EXTRACT_RULES: Rules = [
['Doctrine', /\b(gene|protein|enzyme|disease|syndrome|disorder|theorem|conjecture|concept|theory|language|cuisine|dish|algebraic|mathematical|list of)\b/],
['Event', /\b(election|referendum|battle|war|siege|protest|riot|massacre|annexation|storm|hurricane|cyclone|tornado|tornadoes|earthquake|flood|season|tournament|championship|race|grand prix|match|festival|ceremony)\b/],
['Figure', /\b(actor|actress|politician|writer|author|poet|painter|artist|singer|musician|composer|director|producer|player|footballer|cricketer|athlete|boxer|scientist|engineer|bishop|priest|monarch|king|queen|sultan|businessman|businesswoman|family|dynasty|species|genus|breed|character|deity|god|goddess)\b/],
['Institution', /\b(company|corporation|business|manufacturer|organi[sz]ation|association|society|party|coalition|band|team|club|university|college|school|studio|newspaper|magazine|film|album|song|single|novel|book|series|video game|aircraft|airliner|ship|automobile|car|locomotive|tramway|railway line|bus route|typeface|software|position|office|award|diocese|council)\b/],
['Location', /\b(village|town|city|municipality|commune|parish|county|district|region|province|state|locality|hamlet|suburb|neighbourhood|neighborhood|settlement|community|census area|river|lake|island|mountain|plateau|valley|bay|peak|building|house|church|cathedral|mosque|temple|castle|ch[aâ]teau|palace|museum|pavilion|stadium|bridge|station|park|mall|shopping (centre|center)|road|street|square|monument)\b/],
];
/** Title patterns (checked after the extract's definitional phrase). */
export const TITLE_RULES: Rules = [
['Event', /\b(election|elections|referendum|straw poll|battle of|siege of|war|protests?|riots?|massacre|earthquake|hurricane|cyclone|typhoon|nor'easter|storm|flood|season|championship|tournament|grand prix|olympics|world cup|final)\b/i],
['Institution', /\((film|album|song|single|novel|book|band|tv series|television series|video game|magazine|newspaper|company|ship|aircraft|typeface|software)\)|\b(f\.?c\.?|company|corporation|university|college|school|party|club|association|society|records|airlines?)\b/i],
['Doctrine', /\((programming language|mathematics|disease|gene|chemistry|philosophy|religion)\)|\b(disease|syndrome|theorem|conjecture|cuisine)\b/i],
['Figure', /\((actor|actress|politician|footballer|cricketer|singer|musician|writer|author|painter|artist|boxer|wrestler|bishop|priest|judge|businessman|athlete|rugby union|rugby league|baseball|basketball)\)|\((plant|animal|bird|fish|moth|beetle|spider|fungus|genus)\)/i],
['Location', /\b(river|lake|mount|mountain|island|islands|county|village|township|parish|district|province|church|cathedral|chapel|castle|mosque|temple|abbey|bridge|station|house|park|street|road|square|tower|palace|fort|airport|dam|valley|bay)\b/i],
];
/** Mint-time category buckets that carry a type signal (History and Culture don't). */
export const CHAIN_CATEGORY_TYPE: Readonly<Record<string, CardType>> = {
People: 'Figure', Nature: 'Figure', Space: 'Location', Science: 'Doctrine',
};
/**
* The definitional phrase of an extract's first sentence: what follows "is a / was an / are the …",
* up to the next clause break. "Tom Ewell (1909–1994) was an American actor." → "american actor".
*/
export function definitionOf(extract: string | undefined): string {
const text = (extract ?? '').replace(/\s+/g, ' ').trim();
const m = /\b(?:is|was|are|were)\s+(?:an?|the|one of the)\s+([^.;:]{1,120})/i.exec(text);
return m ? m[1].toLowerCase() : '';
}
/** Lead-sentence life dates: "Name (born 1971)", "Name (1909–1994)", "Name (c. 1530 – 1548)". */
const LIFE_DATES = /^[^.(]{1,80}\((?:[^)]*;\s*)?(?:born\s+(?:[A-Z][a-z]+\s+)?(?:\d{1,2}\s+)?(?:[A-Z][a-z]+\s+)?\d{3,4}|(?:c\.\s*)?\d{3,4}\s*[–-]\s*(?:c\.\s*)?\d{3,4})/;
function firstRule(rules: Rules, texts: readonly string[]): [CardType, string] | null {
for (const [type, rx] of rules) for (const text of texts) if (rx.test(text)) return [type, text];
return null;
}
export function classify(profile: Pick<CardProfile, 'instanceOf' | 'subclassOf' | 'categories' | 'description'>,
chain?: ChainHints): Classification {
const p31 = profile.instanceOf ?? [];
const p279 = profile.subclassOf ?? [];
for (const c of p31) { const t = QID_ANCHORS[c.id]; if (t) return { type: t, source: 'qid', matched: c.id }; }
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] };
if (chain) {
const extract = (chain.extract ?? '').replace(/\s+/g, ' ').trim();
const definition = definitionOf(extract);
hit = firstRule(EXTRACT_RULES, definition ? [definition] : []);
if (hit) return { type: hit[0], source: 'extract', matched: hit[1] };
if (LIFE_DATES.test(extract)) return { type: 'Figure', source: 'extract', matched: 'life dates' };
hit = firstRule(TITLE_RULES, chain.title ? [chain.title] : []);
if (hit) return { type: hit[0], source: 'title', matched: chain.title };
const t = chain.category ? CHAIN_CATEGORY_TYPE[chain.category] : undefined;
if (t) return { type: t, source: 'chain-category', matched: chain.category! };
}
return { type: 'Doctrine', source: 'fallback', matched: '' };
}