host-pvp: toDuelCard fallback types cards from on-chain data (extract sentence, mint category hint), not all Doctrine (night-review P1)

This commit is contained in:
2026-11-18 00:45:50 -05:00
parent 56f1446d8f
commit dfb8abe0e2
2 changed files with 73 additions and 4 deletions
+37 -4
View File
@@ -10,6 +10,7 @@
*/ */
import { derive, type DuelCard } from '../../shared/duel/derive.ts'; import { derive, type DuelCard } from '../../shared/duel/derive.ts';
import { profileFromSources } from '../../shared/duel/profile.ts'; import { profileFromSources } from '../../shared/duel/profile.ts';
import { classify } from '../../shared/duel/classify.ts';
import { toProfile, type IdentityStore } from './identity.ts'; import { toProfile, type IdentityStore } from './identity.ts';
import type { ChainCard, EnginePort } from './engine-port.ts'; import type { ChainCard, EnginePort } from './engine-port.ts';
@@ -20,15 +21,47 @@ export type DuelCardSources = {
type AnyPort = EnginePort<any, any, any, any>; type AnyPort = EnginePort<any, any, any, any>;
/** The single ChainCard → DuelCard conversion. Deterministic for a given block and identity. */ /**
* Generic type hints from the mint-time `article.category` (server/wiki.ts `category()`), used
* only when neither a frozen identity nor the extract's first sentence types the card. They are
* class words, not facts about the subject, and never reach the Connected keys.
*/
const CATEGORY_HINTS: Readonly<Record<string, string>> = {
People: 'person', Nature: 'organism', Space: 'astronomical object', History: 'event', Science: 'concept', Culture: 'organization',
};
/** First sentence of the on-chain extract, as a description-like signal for the classifier. */
function firstSentence(extract: string): string {
const text = extract.replace(/\s+/g, ' ').trim();
return (/^.*?[.!?](?=\s|$)/.exec(text)?.[0] ?? text).slice(0, 300);
}
/**
* The single ChainCard → DuelCard conversion. Deterministic for a given block and identity.
* Miss path (no frozen identity yet): classify from what the block itself carries, the extract's
* first sentence, then the mint-time category hint. No fetch; card faces stay real data only.
*/
export function toDuelCard(card: ChainCard, sources: DuelCardSources = {}): DuelCard { export function toDuelCard(card: ChainCard, sources: DuelCardSources = {}): DuelCard {
const article = card.article as { pageId: number; title: string; extract: string; revisionId: number } | undefined; const article = card.article as { pageId: number; title: string; extract: string; revisionId: number; category?: string } | undefined;
const statsSnapshot = card.statsSnapshot as { pageBytes: number; languageCount: number; stats: any } | undefined; const statsSnapshot = card.statsSnapshot as { pageBytes: number; languageCount: number; stats: any } | undefined;
if (!article || !statsSnapshot) throw new Error(`Card ${card.tokenId} has no on-chain article or stats snapshot`); if (!article || !statsSnapshot) throw new Error(`Card ${card.tokenId} has no on-chain article or stats snapshot`);
const chain = { tokenId: card.tokenId, article, statsSnapshot };
const frozen = sources.identity?.get(card.tokenId); const frozen = sources.identity?.get(card.tokenId);
const profile = frozen ? toProfile(frozen) : profileFromSources({ enrichment: { if (frozen) return derive(chain, toProfile(frozen) as any);
const base = profileFromSources({ enrichment: {
description: null, wikidataId: null, categories: [], revisionId: article.revisionId ?? null } as any }); description: null, wikidataId: null, categories: [], revisionId: article.revisionId ?? null } as any });
return derive({ tokenId: card.tokenId, article, statsSnapshot }, profile as any); const sentence = firstSentence(article.extract ?? '');
let profile = { ...base, description: sentence || null };
if (classify(profile).source === 'fallback') {
const hint = CATEGORY_HINTS[article.category ?? ''];
if (hint) profile = { ...profile, instanceOf: [{ id: '', label: hint }] };
}
const out = derive(chain, profile as any);
// The sentence is the flavour text already; it is not a Wikidata short description.
delete (out as { description?: string }).description;
out.connect = { ...out.connect, p31: out.connect.p31.filter(id => id !== '') };
(out as { typedBy?: string }).typedBy = 'fallback';
return out;
} }
/** Wrap duel-core's `duelEnginePort` with what the host adds: owned-card building and the copy limit. */ /** Wrap duel-core's `duelEnginePort` with what the host adds: owned-card building and the copy limit. */
+36
View File
@@ -147,3 +147,39 @@ test('host-pvp binding: gameRouter mounts GET /collection when ownership deps ar
assert.equal((await fetch(`${base}/modes`)).status, 200, 'the game routes still answer'); assert.equal((await fetch(`${base}/modes`)).status, 200, 'the game routes still answer');
} finally { server.close(); } } finally { server.close(); }
}); });
/** server/wiki.ts's mint-time category(), reproduced for the sample (it is not exported). */
function mintCategory(title: string, categories: string[]): string {
const text = `${title} ${categories.join(' ')}`.toLowerCase();
if (/astronom|planet|space|galax|moon|star\b/.test(text)) return 'Space';
if (/animal|plant|species|ocean|biolog|mollusc/.test(text)) return 'Nature';
if (/births|deaths|people|scientist/.test(text)) return 'People';
if (/physic|chem|math|science|technolog/.test(text)) return 'Science';
if (/histor|ancient|archaeolog|empire/.test(text)) return 'History';
return 'Culture';
}
test('host-pvp binding: without a frozen identity, cards are typed from on-chain data, not all Doctrine (night-review P1)', () => {
const types: Record<string, number> = {};
for (const s of SAMPLE) {
const c = chainCard(s);
(c.article as any).category = mintCategory(s.title, s.categories);
const d = toDuelCard(c, {});
types[d.type] = (types[d.type] ?? 0) + 1;
assert.equal(d.typedBy, 'fallback');
assert.equal(d.description, undefined, 'no fabricated short description');
assert.ok(!d.connect.p31.includes(''), 'hints never become Connected keys');
}
assert.ok((types.Doctrine ?? 0) < SAMPLE.length / 2, JSON.stringify(types));
assert.ok((types.Figure ?? 0) >= 40, JSON.stringify(types));
// The extract's first sentence wins over the category hint.
const s = SAMPLE[0]!;
const battle = chainCard(s);
(battle.article as any).extract = 'The Battle of Somewhere was a battle fought in 1548. It was long.';
(battle.article as any).category = 'People';
assert.equal(toDuelCard(battle, {}).type, 'Event');
const pol = chainCard(s);
(pol.article as any).extract = 'Jane Doe is an American politician.';
(pol.article as any).category = 'Culture';
assert.equal(toDuelCard(pol, {}).type, 'Figure');
});