forked from WikiDeck/wikideck
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>
322 lines
18 KiB
TypeScript
322 lines
18 KiB
TypeScript
/**
|
||
* Duel card derivation: an on-chain card plus its frozen off-chain profile becomes a DuelCard
|
||
* (BRIEF "Stats", "Keywords", "Factions", "Connected"; data review §2 and §4; designer review §3).
|
||
* Pure and deterministic: no fetches, no clocks, no randomness. Every number is data in DERIVE_RULES.
|
||
* Owner: duel-cards.
|
||
*/
|
||
import type { Article } from '../protocol.ts';
|
||
import type { MintStatsSnapshot } from '../enrichment.ts';
|
||
import { rarity as rarityOf } from '../protocol.ts';
|
||
import { CARD_SAMPLE_PERCENTILES } from '../game/card-data.ts';
|
||
import { percentile } from '../game/derive.ts';
|
||
import { classify, type CardProfile, type CardType, type ClassifySource } from './classify.ts';
|
||
import { effectsFor, subtypeFor, type EffectSpec } from './effects.ts';
|
||
import { rulesTextFor } from './text.ts';
|
||
|
||
export type { CardProfile, CardType } from './classify.ts';
|
||
export type { EffectSpec } from './effects.ts';
|
||
|
||
export const DERIVE_VERSION = 'duel-derive-1';
|
||
|
||
export type Portal = 'Arts' | 'Earth' | 'History' | 'Science' | 'Society' | 'Neutral';
|
||
export const PORTALS: readonly Portal[] = ['Arts', 'Earth', 'History', 'Science', 'Society', 'Neutral'];
|
||
export type Keyword = 'Protected' | 'Featured' | 'Translated' | 'Legacy' | 'Stub' | 'Well-sourced' | 'Multilingual' | 'Local';
|
||
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;
|
||
/** `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'>;
|
||
}
|
||
|
||
export interface ConnectKeys {
|
||
/** P17/P27 values, or normalised country names from text when Wikidata has none. */
|
||
countries: string[];
|
||
centuries: number[];
|
||
/** Outlink pageIds. */
|
||
links: number[];
|
||
/** P31 Q-ids, excluding human and taxon (the Kin tier). */
|
||
p31: string[];
|
||
/** This card's Wikidata item (omitted when it has none), and the item Q-ids its claims cite (Linked tier). */
|
||
qid?: string;
|
||
cites: string[];
|
||
}
|
||
|
||
export interface DuelCard {
|
||
cardId: string;
|
||
pageId: number;
|
||
revisionId: number;
|
||
title: string;
|
||
/** Wikidata short description, for log first mentions (omitted when absent). */
|
||
description?: string;
|
||
type: CardType;
|
||
/** Template family within the type, e.g. 'conflict', 'election', 'organisation', 'pathology'. */
|
||
subtype: string | null;
|
||
portal: Portal;
|
||
cost: number;
|
||
/** Figures: power/toughness. Locations: 0 / Garrison. Others: null. */
|
||
power: number | null;
|
||
toughness: number | null;
|
||
/** Locations: Citations income ramp (the engine caps the total). */
|
||
territory: number;
|
||
keywords: Keyword[];
|
||
effects: EffectSpec[];
|
||
rulesText: string;
|
||
flavor: string;
|
||
connect: ConnectKeys;
|
||
rarity: Rarity;
|
||
deriveVersion: string;
|
||
/** Why the card got its type (for audit and the card's info panel). */
|
||
typedBy: ClassifySource;
|
||
/** The numbers behind cost and body, for the info panel and the simulator. */
|
||
basis: { pctAttention: number | null; pctDepth: number; pctReach: number; fame: number; magnitude: number };
|
||
}
|
||
|
||
export interface DeriveRules {
|
||
percentiles: Record<'attention' | 'depth' | 'reach', readonly number[]>;
|
||
/** fame → cost 1..6: 1 + number of thresholds ≤ fame. */
|
||
costThresholds: readonly number[];
|
||
/** P+T budget by cost (index = cost). MTG vanilla curve. */
|
||
bodyBudget: readonly number[];
|
||
maxKeywords: number;
|
||
/** Keywords that cost 1 point of body (from the larger stat, min 1 each). */
|
||
taxedKeywords: readonly Keyword[];
|
||
keywordOrder: readonly Keyword[];
|
||
featuredPct: number;
|
||
wellSourcedPct: number;
|
||
/** Translated: translatedPct ≤ pct_reach < multilingualPct. Multilingual: pct_reach ≥ multilingualPct. */
|
||
translatedPct: number;
|
||
multilingualPct: number;
|
||
stubBytes: number;
|
||
/** Garrison toughness = 1 + floor(pct_depth / garrisonStep). */
|
||
garrisonStep: number;
|
||
}
|
||
|
||
export const DERIVE_RULES: DeriveRules = {
|
||
percentiles: CARD_SAMPLE_PERCENTILES,
|
||
costThresholds: [26, 39, 51, 63, 78],
|
||
bodyBudget: [0, 3, 4, 6, 8, 10, 12],
|
||
maxKeywords: 2,
|
||
taxedKeywords: ['Protected', 'Featured', 'Legacy', 'Multilingual', 'Well-sourced'],
|
||
keywordOrder: ['Protected', 'Featured', 'Legacy', 'Multilingual', 'Translated', 'Well-sourced', 'Stub', 'Local'],
|
||
featuredPct: 85,
|
||
wellSourcedPct: 85,
|
||
translatedPct: 75,
|
||
multilingualPct: 90,
|
||
stubBytes: 3000,
|
||
garrisonStep: 25,
|
||
};
|
||
|
||
// ---------------------------------------------------------------- Portals (designer §3.2)
|
||
|
||
export const PORTAL_RULES: Readonly<Record<Exclude<Portal, 'Neutral'>, RegExp>> = {
|
||
Arts: /\b(actor|actress|singer|musician|rapper|band|album|song|single|film|novel|novelist|writer|poet|painter|artist|composer|television|tv series|music|theatre|theater|dance|dancer|video game|studio|animation|anime|fiction|character|literature|book|magazine|typeface|sculpt\w*|architect\w*|comedian|opera|orchestra)\b/g,
|
||
Earth: /\b(species|genus|genera|taxon|plant|plants|animal|bird|birds|fish|insect|moth|beetle|grasshopper|orchid|river|rivers|lake|mountain|island|islands|village|villages|commune|communes|geography|forest|park|ecology|breed|weather|storm|nor.easter|cyclone|earthquake|climate|flora|fauna|populated places|municipality|municipalities|county|township|parish|reef|valley|locality|oblast|freguesia|hamlet)\b/g,
|
||
History: /(\b\d+(st|nd|rd|th)-century\b|\b\d+ deaths\b|\b(sultan\w*|empire|castle|castles|medieval|ancient|dynasty|war|battle|battles|monarch|monarchs|king|queen|historic|archaeolog\w*|former|disestablish\w*|colonial|kingdom|museum|nobility|pharaoh)\b)/g,
|
||
Science: /\b(mathemat\w*|algebra\w*|programming|software|gene|genes|protein|chemi\w*|disease|diseases|scientist|physic\w*|astronom\w*|biolog\w*|medic\w*|engineer\w*|computer|computing|theorem|planet|galaxy|spacecraft|satellite|aircraft|technology|clinical|structure|structures|category theory|syndrome|virus|bacteri\w*)\b/g,
|
||
Society: /\b(politic\w*|politician|election|elections|party|government|law|court|sport|sports|football|cricket|basketball|baseball|olympic\w*|team|club|league|church|religio\w*|diocese|mosque|temple|school|university|company|companies|business|corporation|protest|protests|scandal|corruption|people from|living people|police|crime|cuisine|association|council)\b/g,
|
||
};
|
||
const PORTAL_TIE_ORDER: readonly Exclude<Portal, 'Neutral'>[] = ['History', 'Science', 'Arts', 'Society', 'Earth'];
|
||
export const TYPE_DEFAULT_PORTAL: Readonly<Record<CardType, Exclude<Portal, 'Neutral'>>> = {
|
||
Figure: 'Society', Location: 'Earth', Event: 'History', Institution: 'Arts', Doctrine: 'Science',
|
||
};
|
||
|
||
/** Count keyword hits over description + categories + P31 labels; ties go to the type default; no hits → Neutral. */
|
||
export function portalFor(profile: CardProfile, type: CardType): Portal {
|
||
const text = [profile.description ?? '', ...profile.categories, ...profile.instanceOf.map(c => c.label)]
|
||
.join(' | ').toLowerCase();
|
||
let best = 0; let tied: Exclude<Portal, 'Neutral'>[] = [];
|
||
for (const portal of PORTAL_TIE_ORDER) {
|
||
const hits = text.match(PORTAL_RULES[portal])?.length ?? 0;
|
||
if (hits > best) { best = hits; tied = [portal]; } else if (hits === best && hits > 0) tied.push(portal);
|
||
}
|
||
if (best === 0) return 'Neutral';
|
||
const fallback = TYPE_DEFAULT_PORTAL[type];
|
||
return tied.includes(fallback) ? fallback : tied[0];
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Connected keys (data §4)
|
||
|
||
const COUNTRY_WORDS: readonly (readonly [RegExp, string])[] = ([
|
||
['United States|American', 'United States'], ['United Kingdom|British|England|English|Scotland|Scottish|Wales|Welsh', 'United Kingdom'],
|
||
['France|French', 'France'], ['Germany|German', 'Germany'], ['Japan|Japanese', 'Japan'], ['China|Chinese', 'China'],
|
||
['India|Indian', 'India'], ['Brazil|Brazilian', 'Brazil'], ['Poland|Polish', 'Poland'], ['Italy|Italian', 'Italy'],
|
||
['Spain|Spanish', 'Spain'], ['Austria|Austrian', 'Austria'], ['Canada|Canadian', 'Canada'], ['Australia|Australian', 'Australia'],
|
||
['Russia|Russian', 'Russia'], ['Mexico|Mexican', 'Mexico'], ['Iran|Iranian', 'Iran'], ['Pakistan|Pakistani', 'Pakistan'],
|
||
['Bangladesh|Bangladeshi', 'Bangladesh'], ['Sweden|Swedish', 'Sweden'], ['Norway|Norwegian', 'Norway'], ['Estonia|Estonian', 'Estonia'],
|
||
['Ukraine|Ukrainian', 'Ukraine'], ['Croatia|Croatian', 'Croatia'], ['Philippines|Filipino', 'Philippines'], ['Cuba|Cuban', 'Cuba'],
|
||
['Israel|Israeli', 'Israel'], ['Portugal|Portuguese', 'Portugal'], ['Ireland|Irish', 'Ireland'], ['Kazakhstan|Kazakh', 'Kazakhstan'],
|
||
['Malaysia|Malaysian', 'Malaysia'], ['Argentina|Argentine', 'Argentina'], ['Belgium|Belgian', 'Belgium'], ['Iceland|Icelandic', 'Iceland'],
|
||
['Thailand|Thai', 'Thailand'], ['Singapore', 'Singapore'], ['Sri Lanka|Sri Lankan', 'Sri Lanka'], ['Slovenia|Slovene|Slovenian', 'Slovenia'],
|
||
['Moldova', 'Moldova'], ['Cyprus|Cypriot', 'Cyprus'], ['North Macedonia|Macedonian', 'North Macedonia'], ['Mauritania', 'Mauritania'],
|
||
['Congo', 'Congo'], ['New Zealand', 'New Zealand'], ['Korea|Korean', 'Korea'], ['Indonesia|Indonesian|Aceh', 'Indonesia'],
|
||
['Czech', 'Czechia'], ['Netherlands|Dutch', 'Netherlands'], ['Greece|Greek', 'Greece'], ['Turkey|Turkish', 'Turkey'],
|
||
['Egypt|Egyptian', 'Egypt'], ['Nigeria|Nigerian', 'Nigeria'], ['Kenya|Kenyan', 'Kenya'], ['Ghana|Gold Coast', 'Ghana'],
|
||
['Finland|Finnish', 'Finland'], ['Denmark|Danish', 'Denmark'], ['Switzerland|Swiss', 'Switzerland'], ['Hungary|Hungarian', 'Hungary'],
|
||
['Romania|Romanian', 'Romania'], ['Serbia|Serbian', 'Serbia'], ['Bulgaria|Bulgarian', 'Bulgaria'], ['Vietnam|Vietnamese', 'Vietnam'],
|
||
['Sri Lanka', 'Sri Lanka'], ['Chile|Chilean', 'Chile'], ['Colombia|Colombian', 'Colombia'], ['Peru|Peruvian', 'Peru'],
|
||
] as const).map(([rx, name]) => [new RegExp(`\\b(${rx})\\b`), name] as const);
|
||
|
||
const YEAR = /\b(1[0-9]{3}|20[0-2][0-9])\b/g;
|
||
const CENTURY = /\b(\d{1,2})(st|nd|rd|th)[- ]century\b/gi;
|
||
|
||
export function connectKeysFor(title: string, profile: CardProfile): ConnectKeys {
|
||
const text = [profile.description ?? '', ...profile.categories].join(' | ');
|
||
const countries = profile.countries?.length
|
||
? [...new Set(profile.countries)]
|
||
: [...new Set(COUNTRY_WORDS.filter(([rx]) => rx.test(text)).map(([, name]) => name))];
|
||
const centuries = new Set<number>();
|
||
if (profile.years?.length) for (const y of profile.years) centuries.add(y > 0 ? Math.floor((y - 1) / 100) + 1 : -(Math.floor(-y / 100) + 1));
|
||
else {
|
||
for (const m of `${title} | ${text}`.matchAll(YEAR)) centuries.add(Math.floor((Number(m[1]) - 1) / 100) + 1);
|
||
for (const m of text.matchAll(CENTURY)) centuries.add(Number(m[1]));
|
||
}
|
||
return {
|
||
countries: countries.sort(),
|
||
centuries: [...centuries].sort((a, b) => a - b),
|
||
links: [...new Set(profile.links ?? [])].sort((a, b) => a - b),
|
||
p31: [...new Set(profile.instanceOf.map(c => c.id).filter(id => id !== 'Q5' && id !== 'Q16521'))].sort(),
|
||
...(profile.wikidataId ? { qid: profile.wikidataId } : {}),
|
||
cites: [...new Set(profile.cites ?? [])].sort(),
|
||
};
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Flavour
|
||
|
||
/** First sentence of the on-chain extract (BRIEF "Flavour text"); the description if there is no extract. */
|
||
export function flavorFor(extract: string, description: string | null): string {
|
||
const text = extract.replace(/\s+/g, ' ').trim();
|
||
if (!text) return (description ?? '').trim();
|
||
// A sentence ends at . ! ? followed by a space and an uppercase letter or a quote, skipping
|
||
// common abbreviations and initials ("U.S.", "St.", "J. R. R.") so names are not cut.
|
||
const re = /[.!?](?=\s+["'“(\[]?[A-Z0-9])/g;
|
||
let m: RegExpExecArray | null;
|
||
while ((m = re.exec(text))) {
|
||
const before = text.slice(0, m.index);
|
||
const word = before.split(/\s/).pop() ?? '';
|
||
if (/^([A-Z]|[A-Z][a-z]{0,2}|[A-Z]\.[A-Z]|U\.S|U\.K|c|ca|St|Dr|Mr|Mrs|Ms|Jr|Sr|No|vs|etc|Inc|Ltd|Co|Mt|Ft|Gen|Col|Lt|Sgt|Rev|Prof)$/.test(word.replace(/\.$/, ''))) continue;
|
||
return text.slice(0, m.index + 1);
|
||
}
|
||
return text;
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Stats and keywords (data §2, designer §3.3–3.4)
|
||
|
||
export interface Percentiles { attention: number | null; depth: number; reach: number }
|
||
|
||
export function percentilesFor(stats: MintStatsSnapshot['stats'], rules: DeriveRules = DERIVE_RULES): Percentiles {
|
||
return {
|
||
attention: stats.attention === null ? null : percentile(stats.attention, rules.percentiles.attention),
|
||
depth: percentile(stats.depth, rules.percentiles.depth),
|
||
reach: percentile(stats.reach, rules.percentiles.reach),
|
||
};
|
||
}
|
||
|
||
export function fameOf(p: Percentiles): number {
|
||
const values = [p.attention, p.depth, p.reach].filter((v): v is number => v !== null);
|
||
return Math.floor(values.reduce((a, b) => a + b, 0) / values.length + 0.5);
|
||
}
|
||
|
||
export function costForFame(fame: number, rules: DeriveRules = DERIVE_RULES): number {
|
||
return 1 + rules.costThresholds.filter(t => t <= fame).length;
|
||
}
|
||
|
||
/** Every keyword the data triggers, in priority order (before the cap). */
|
||
export function triggeredKeywords(chain: CardOnChain, profile: CardProfile, p: Percentiles, rules: DeriveRules = DERIVE_RULES): Keyword[] {
|
||
const cats = profile.categories;
|
||
const on: Record<Keyword, boolean> = {
|
||
Protected: cats.includes('Living people'),
|
||
Featured: p.attention !== null && p.attention >= rules.featuredPct,
|
||
Legacy: profile.died === true || cats.some(c => /^\d+s? (BC )?deaths$/.test(c)),
|
||
'Well-sourced': p.depth >= rules.wellSourcedPct,
|
||
// Two bands of the same reach axis: a card never has both (DUEL_DESIGN §4).
|
||
Multilingual: p.reach >= rules.multilingualPct,
|
||
Translated: p.reach >= rules.translatedPct && p.reach < rules.multilingualPct,
|
||
Stub: cats.some(c => c.toLowerCase().includes('stubs')) || chain.statsSnapshot.pageBytes < rules.stubBytes,
|
||
Local: chain.statsSnapshot.stats.reach === 0,
|
||
};
|
||
return rules.keywordOrder.filter(k => on[k]);
|
||
}
|
||
|
||
export interface Body { power: number; toughness: number; keywords: Keyword[] }
|
||
|
||
/**
|
||
* Figure body (DUEL_DESIGN §3): take the first ≤2 triggered keywords in priority order, subtract 1
|
||
* from the cost's P+T budget per taxed keyword, then split by attention vs depth, each stat ≥ 1.
|
||
* A taxed keyword that would leave less than 2 points is skipped for the next one.
|
||
*/
|
||
export function figureBody(cost: number, p: Percentiles, keywords: readonly Keyword[], rules: DeriveRules = DERIVE_RULES): Body {
|
||
let budget = rules.bodyBudget[cost];
|
||
if (budget === undefined) throw new RangeError(`bodyBudget has no entry for cost ${cost}`);
|
||
const kept: Keyword[] = [];
|
||
for (const k of keywords) {
|
||
if (kept.length >= rules.maxKeywords) break;
|
||
if (rules.taxedKeywords.includes(k)) {
|
||
if (budget <= 2) continue;
|
||
budget--;
|
||
}
|
||
kept.push(k);
|
||
}
|
||
const a = p.attention ?? 50;
|
||
const power = Math.min(budget - 1, Math.max(1, Math.round(budget * a / Math.max(1, a + p.depth))));
|
||
return { power, toughness: budget - power, keywords: kept };
|
||
}
|
||
|
||
// ---------------------------------------------------------------- derive
|
||
|
||
export function derive(chain: CardOnChain, profile: CardProfile, rules: DeriveRules = DERIVE_RULES): DuelCard {
|
||
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, chain.article);
|
||
let cost = baseCost, power: number | null = null, toughness: number | null = null, territory = 0;
|
||
let keywords: Keyword[] = [];
|
||
if (type === 'Figure') {
|
||
const body = figureBody(baseCost, p, triggeredKeywords(chain, profile, p, rules), rules);
|
||
({ power, toughness, keywords } = body);
|
||
} else if (type === 'Location') {
|
||
cost = magnitude;
|
||
power = 0;
|
||
toughness = 1 + Math.floor(p.depth / rules.garrisonStep);
|
||
territory = 1;
|
||
}
|
||
const effects = effectsFor(type, subtype, baseCost);
|
||
const card: DuelCard = {
|
||
cardId: chain.tokenId, pageId: chain.article.pageId, revisionId: chain.article.revisionId, title: chain.article.title,
|
||
type, subtype, portal, cost, power, toughness, territory, keywords, effects, rulesText: '',
|
||
flavor: flavorFor(chain.article.extract, profile.description),
|
||
connect: connectKeysFor(chain.article.title, profile),
|
||
rarity: rarityOf(chain.tokenId), deriveVersion: DERIVE_VERSION, typedBy: source,
|
||
basis: { pctAttention: p.attention, pctDepth: p.depth, pctReach: p.reach, fame, magnitude },
|
||
};
|
||
if (profile.description) card.description = profile.description;
|
||
card.rulesText = rulesTextFor(card);
|
||
return card;
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Connected (data §4)
|
||
|
||
/** DUEL_DESIGN §6: Contemporary counts only between different types. */
|
||
export type ConnectedTier = 'Linked' | 'Compatriot' | 'Contemporary' | 'Kin';
|
||
|
||
/** The strongest Connected tier between two cards, or null. Linked gives +2/+2, the others +1/+1 (BRIEF). */
|
||
export function connectedTier(a: DuelCard, b: DuelCard,
|
||
tiers: readonly ConnectedTier[] = ['Linked', 'Compatriot', 'Contemporary', 'Kin']): ConnectedTier | null {
|
||
if (a.cardId === b.cardId) return null;
|
||
const meets = (x: readonly (string | number)[], y: readonly (string | number)[]) => x.some(v => y.includes(v));
|
||
for (const tier of tiers) {
|
||
if (tier === 'Linked' && (a.connect.links.includes(b.pageId) || b.connect.links.includes(a.pageId)
|
||
|| (b.connect.qid !== undefined && a.connect.cites.includes(b.connect.qid))
|
||
|| (a.connect.qid !== undefined && b.connect.cites.includes(a.connect.qid)))) return tier;
|
||
if (tier === 'Compatriot' && meets(a.connect.countries, b.connect.countries)) return tier;
|
||
if (tier === 'Contemporary' && a.type !== b.type && meets(a.connect.centuries, b.connect.centuries)) return tier;
|
||
if (tier === 'Kin' && meets(a.connect.p31, b.connect.p31)) return tier;
|
||
}
|
||
return null;
|
||
}
|