[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>
This commit is contained in:
+60
-2
@@ -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<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'>): Classification {
|
||||
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 }; }
|
||||
@@ -121,5 +168,16 @@ export function classify(profile: Pick<CardProfile, 'instanceOf' | 'subclassOf'
|
||||
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: '' };
|
||||
}
|
||||
|
||||
@@ -26,7 +26,8 @@ export type Rarity = 'Common' | 'Rare' | 'Epic' | 'Legendary';
|
||||
/** What derive() reads from the chain: a minted block's article and stats snapshot. */
|
||||
export interface CardOnChain {
|
||||
tokenId: string;
|
||||
article: Pick<Article, 'pageId' | 'title' | 'extract' | 'revisionId'>;
|
||||
/** `category` is the mint-time bucket (server/wiki.ts); only used when the profile is empty. */
|
||||
article: Pick<Article, 'pageId' | 'title' | 'extract' | 'revisionId'> & { category?: string };
|
||||
statsSnapshot: Pick<MintStatsSnapshot, 'pageBytes' | 'languageCount' | 'stats'>;
|
||||
}
|
||||
|
||||
@@ -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') {
|
||||
|
||||
@@ -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<Record<CardType, string | null>> = {
|
||||
Figure: null, Location: null, Event: 'other', Institution: 'other', Doctrine: 'adopt',
|
||||
};
|
||||
|
||||
export function subtypeFor(type: CardType, profile: Pick<CardProfile, 'instanceOf' | 'subclassOf' | 'description' | 'categories'>): string | null {
|
||||
export function subtypeFor(type: CardType, profile: Pick<CardProfile, 'instanceOf' | 'subclassOf' | 'description' | 'categories'>,
|
||||
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];
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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:
|
||||
// "<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));
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user