From 5076299e7cf3021cc4cc6e898865757644501f2b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 00:50:13 -0500 Subject: [PATCH] [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 --- shared/duel/classify.ts | 62 +++++++++++++++++++++++++++++++-- shared/duel/derive.ts | 7 ++-- shared/duel/effects.ts | 7 ++-- shared/duel/sample.ts | 5 ++- tests/duel-cards-derive.test.ts | 34 ++++++++++++++++++ 5 files changed, 107 insertions(+), 8 deletions(-) diff --git a/shared/duel/classify.ts b/shared/duel/classify.ts index 2f59bb7..bf1b305 100644 --- a/shared/duel/classify.ts +++ b/shared/duel/classify.ts @@ -39,7 +39,8 @@ export interface CardProfile { fetchedRevisionId?: number; } -export type ClassifySource = 'qid' | 'p279-qid' | 'p31' | 'p279' | 'category' | 'description' | 'fallback'; +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. */ @@ -100,12 +101,58 @@ export const DESCRIPTION_RULES: Rules = [ ['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> = { + 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): Classification { +export function classify(profile: Pick, + 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 }; } @@ -121,5 +168,16 @@ export function classify(profile: Pick; + /** `category` is the mint-time bucket (server/wiki.ts); only used when the profile is empty. */ + article: Pick & { category?: string }; statsSnapshot: Pick; } @@ -266,13 +267,13 @@ export function figureBody(cost: number, p: Percentiles, keywords: readonly Keyw // ---------------------------------------------------------------- derive export function derive(chain: CardOnChain, profile: CardProfile, rules: DeriveRules = DERIVE_RULES): DuelCard { - const { type, source } = classify(profile); + const { type, source } = classify(profile, chain.article); const p = percentilesFor(chain.statsSnapshot.stats, rules); const fame = fameOf(p); const baseCost = costForFame(fame, rules); const magnitude = Math.ceil(baseCost / 2); const portal = portalFor(profile, type); - const subtype = subtypeFor(type, profile); + const subtype = subtypeFor(type, profile, chain.article); let cost = baseCost, power: number | null = null, toughness: number | null = null, territory = 0; let keywords: Keyword[] = []; if (type === 'Figure') { diff --git a/shared/duel/effects.ts b/shared/duel/effects.ts index 285b0c9..1769dfe 100644 --- a/shared/duel/effects.ts +++ b/shared/duel/effects.ts @@ -3,7 +3,7 @@ * Effects are plain data for duel-core's interpreter. k = ceil(cost / 2), 1–3, from the derived (fame) cost. * Owner: duel-cards. */ -import type { CardProfile, CardType } from './classify.ts'; +import { definitionOf, type CardProfile, type CardType, type ChainHints } from './classify.ts'; import type { Keyword, Portal } from './derive.ts'; export type EffectTrigger = 'onPlay' | 'onEnter' | 'startOfTurn' | 'onDestroyed' | 'static' | 'onCombatDamageToPlayer'; @@ -59,11 +59,14 @@ export const DEFAULT_SUBTYPE: Readonly> = { Figure: null, Location: null, Event: 'other', Institution: 'other', Doctrine: 'adopt', }; -export function subtypeFor(type: CardType, profile: Pick): string | null { +export function subtypeFor(type: CardType, profile: Pick, + chain?: ChainHints): string | null { const groups = [ [...profile.instanceOf.map(c => c.label), ...(profile.subclassOf ?? []).map(c => c.label)], [profile.description ?? ''], [...(profile.categories ?? []).filter(c => !/stubs$/i.test(c))], + // On-chain fallbacks, last: the extract's definitional phrase, then the title. + [definitionOf(chain?.extract), chain?.title ?? ''], ].map(g => g.map(t => t.toLowerCase()).filter(Boolean)); for (const texts of groups) for (const [name, rx] of SUBTYPE_RULES[type]) if (texts.some(t => rx.test(t))) return name; return DEFAULT_SUBTYPE[type]; diff --git a/shared/duel/sample.ts b/shared/duel/sample.ts index 05df0a9..dcb22d7 100644 --- a/shared/duel/sample.ts +++ b/shared/duel/sample.ts @@ -13,6 +13,8 @@ export interface SampleCard { stats: { attention: number | null; depth: number; reach: number }; instanceOf: { id: string; label: string }[]; extract?: string; + /** The on-chain mint-time category (server/wiki.ts bucket). */ + legacyCategory?: string; } export function sampleTokenId(pageId: number): string { @@ -23,7 +25,8 @@ export function sampleInputs(card: SampleCard): { chain: CardOnChain; profile: C return { chain: { tokenId: sampleTokenId(card.pageId), - article: { pageId: card.pageId, title: card.title, extract: card.extract ?? '', revisionId: card.revisionId }, + article: { pageId: card.pageId, title: card.title, extract: card.extract ?? '', revisionId: card.revisionId, + ...(card.legacyCategory ? { category: card.legacyCategory } : {}) }, statsSnapshot: { pageBytes: card.pageBytes, languageCount: card.languageCount, stats: card.stats }, }, profile: { diff --git a/tests/duel-cards-derive.test.ts b/tests/duel-cards-derive.test.ts index efe41f5..62142f8 100644 --- a/tests/duel-cards-derive.test.ts +++ b/tests/duel-cards-derive.test.ts @@ -219,3 +219,37 @@ test('Doctrines use the engine encoding: attach picks the Figure, a static pump 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: + // " 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)); +});