Files
wikideck/tests/wikimedia-mint.test.ts
claudeanderic dbb89ce9c5 Night 2: 40-card Magic-style duel, PvP with owned decks, polite Wikimedia client, Android mining (#23)
Night 2 (2026-11-17), from the `claude/wikideck` fork's `night/2026-11-17` branch. It follows Night 1 (#22).

## What's in it
- **Duel engine** (fork #72, #80): 40-card decks of cards you own, Notability/Citations, keywords, effects T1–T12, Connected, a hidden-information-safe `viewFor`/`logFor`, and replay. Balance v1 tuning (#84) gives the first player about 51%.
- **Card profiles** (#70, #82): Figure, Location, Event, Institution or Doctrine, plus stats, keywords and rules text, all derived from real article data. Templates only.
- **Design and story** (#66, #69, #83): DUEL_DESIGN.md, plus the match log and the encyclopedic "Battle of X (2026)" recap.
- **PvP** (#74, #77, #81, #76, #85):
  - The server checks ownership, and 40-card eligibility is enforced.
  - Modes: Classic (ranked), Draft and Trending.
  - Invites, quick match, Elo, a ladder and recap pages. Online matches render on the duel board.
- **Duel board UI** (#79): MTG-style card faces and combat declaration, built for 360 px first.
- **Polite Wikimedia client** (#73, #75): throttled, cached and identified requests, the mint-path fix, and a prefetch pool.
- **Android mining** (#78): native RandomX, as a sideload build. The emulator mined a testnet block.
- **Testnet ops** (#67, #68).

PR numbers refer to `claude/wikideck`.

## Status
- **Tests:** 423, of which 422 pass, 0 fail and 1 is skipped. The build is OK (`node:24-alpine`, `--network none`).
- **Testnet:** running this commit (036489c) on r350.
- **Untouched:** no changes to `server/testnet/consensus.ts`, `randomx.ts`, `native/` or the mainnet compose.
- **Review:** night-review reviewed fork #66–#79. #80–#85 came from the agents' unfinished branches and were not reviewed.
- **Known gaps:**
  - The PvP end-to-end test hasn't been run (it needs two eom.dev accounts).
  - Bot matches aren't reachable from Play.
  - Card identity pre-bake hasn't been done.
  - The RandomX verifier latch (`server/testnet/randomx.ts:140`) is still open.

This PR is for Eric to merge.

🤖 Generated with [Claude Code](https://claude.com/claude-code)Reviewed-on: WikiDeck/wikideck#23

Co-authored-by: Claude <claude@eom.dev>
2026-11-18 18:12:24 +00:00

105 lines
6.0 KiB
TypeScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { WikipediaEnrichment } from '../server/enrichment.ts';
import { WikipediaArticleSource, randomArticlesUrl } from '../server/wiki.ts';
import { WikimediaClient } from '../server/wikimedia/client.ts';
import { WikimediaCache } from '../server/wikimedia/cache.ts';
import { UNTHROTTLED } from '../server/wikimedia/client.ts';
import { json } from './wikimedia-helpers.ts';
const JANUARY = new Date('2025-01-15T23:59:59Z');
const MONTHS = ['2024-07', '2024-08', '2024-09', '2024-10', '2024-11', '2024-12'];
const metadata = (pageId = 736) => ({ query: { pages: [{ pageid: pageId, ns: 0, title: 'Albert Einstein', lastrevid: 1234,
length: 100_000, pageprops: { wikibase_item: 'Q937' }, categories: [], langlinks: [{ lang: 'de' }] }] } });
const views = (counts = [10, 20, 30, 40, 50, 100]) => ({ items: MONTHS.map((month, i) => ({ timestamp: `${month.replace('-', '')}0100`,
views: counts[i], project: 'en.wikipedia', access: 'all-access', agent: 'user', granularity: 'monthly' })) });
function service(viewsReply: () => Response | Promise<Response>, cache?: WikimediaCache) {
const urls: URL[] = [];
const fetcher: typeof fetch = async input => {
const url = new URL(String(input));
urls.push(url);
return url.hostname === 'en.wikipedia.org' ? json(metadata(Number(url.searchParams.get('pageids')))) : viewsReply();
};
const client = new WikimediaClient({ fetch: fetcher, config: UNTHROTTLED, cache });
return { urls, client, enrichment: new WikipediaEnrichment({ client, now: () => JANUARY }) };
}
test('mint fix: a 429, 5xx, timeout or network failure on pageviews fails the mint read instead of pinning attention: null', async () => {
const failures: (() => Response | Promise<Response>)[] = [
() => new Response('', { status: 429, headers: { 'Retry-After': '0' } }),
() => new Response('', { status: 503 }),
() => new Response('', { status: 500 }),
() => new Response('<html>busy</html>', { headers: { 'Content-Type': 'text/html' } }),
() => { throw new TypeError('fetch failed'); },
() => Promise.reject(new DOMException('The operation timed out.', 'TimeoutError')),
];
for (const failure of failures) {
const { enrichment } = service(failure);
await assert.rejects(enrichment.getFresh(736), /unavailable/);
// Display reads keep their old behaviour: metadata with unavailable views.
const shown = await enrichment.get(736);
assert.equal(shown.pageviews.status, 'unavailable');
assert.equal(shown.stats.attention, null);
}
});
test('mint records unavailable views only for a genuine 404 or missing data', async () => {
for (const reply of [() => json({ type: 'not found' }, {}, 404), () => json({ items: [] }), () => json({ items: views().items.slice(1) })]) {
const { enrichment } = service(reply);
const minted = await enrichment.getFresh(736);
assert.equal(minted.pageviews.status, 'unavailable');
assert.equal(minted.stats.attention, null);
}
const { enrichment } = service(() => json(views()));
assert.equal((await enrichment.getFresh(736)).stats.attention, 33);
});
test('mint reads never use the disk cache or join a display read', async () => {
const cache = new WikimediaCache(':memory:');
let count = 100;
const { enrichment, urls } = service(() => json(views([1, 1, 1, 1, 1, count++])), cache);
const shown = await enrichment.get(736);
assert.equal(cache.size(), 2);
const [display, minted] = await Promise.all([enrichment.get(736), enrichment.getFresh(736)]);
assert.equal(display.pageviews.months[5].views, shown.pageviews.months[5].views);
assert.equal(minted.pageviews.months[5].views, 101); // Fetched again, not the cached 100.
assert.equal(urls.length, 4);
// A later display read (memory cache cleared by a new service) is served from disk: no upstream call.
const second = new WikipediaEnrichment({ client: new WikimediaClient({ fetch: async () => { throw new Error('no network'); },
config: UNTHROTTLED, cache }), now: () => JANUARY });
assert.equal((await second.get(736)).pageviews.months[5].views, 100);
});
test('golden mint URLs: request parameters are byte-identical apart from the added maxlag', async () => {
assert.equal(randomArticlesUrl().toString(), 'https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2'
+ '&generator=random&grnnamespace=0&grnlimit=10&prop=extracts%7Cpageimages%7Cinfo%7Ccategories&exintro=1&explaintext=1'
+ '&exchars=900&piprop=thumbnail&pithumbsize=800&cllimit=20');
const urls: string[] = [];
const fetcher: typeof fetch = async input => {
const url = new URL(String(input));
urls.push(url.toString());
if (url.searchParams.get('generator') === 'random') return json({ query: { pages: [{ pageid: 9, ns: 0, title: 'T',
extract: 'An extract that is comfortably longer than forty characters.', lastrevid: 2,
thumbnail: { source: 'https://upload.wikimedia.org/a.jpg' } }] } });
return url.hostname === 'en.wikipedia.org' ? json(metadata(9)) : json(views());
};
const client = new WikimediaClient({ fetch: fetcher, config: UNTHROTTLED });
const article = await new WikipediaArticleSource(client).random();
await new WikipediaEnrichment({ client, now: () => JANUARY }).getFresh(article.pageId);
assert.deepEqual(urls, [
`${randomArticlesUrl()}&maxlag=5`,
'https://en.wikipedia.org/w/api.php?action=query&format=json&formatversion=2&pageids=9'
+ '&prop=info%7Ccategories%7Cpageprops%7Cdescription%7Clanglinks&clshow=%21hidden&cllimit=50&lllimit=500'
+ '&ppprop=wikibase_item&maxlag=5',
'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/user/Albert_Einstein/monthly/2024070100/2024120100',
]);
});
test('a throttled upstream stops random() at once instead of retrying three times', async () => {
let calls = 0;
const source = new WikipediaArticleSource(async () => { calls++; return new Response('', { status: 429 }); });
await assert.rejects(source.random(), /HTTP 429/);
assert.equal(calls, 1);
});