diff --git a/deploy/night/compose.lan.yaml b/deploy/night/compose.lan.yaml index 973bd1d..a4e3a8d 100644 --- a/deploy/night/compose.lan.yaml +++ b/deploy/night/compose.lan.yaml @@ -1,10 +1,12 @@ # sim-testnet override: publish the fixture on r350's LAN address only (not 0.0.0.0). +# WIKIDECK_USER_AGENT identifies the testnet to Wikimedia (UA policy; no personal contact info). # Game-mode env (modes team, #6) is inert until night/modes/hosting merges. services: node-a: ports: !override ["192.168.1.32:3101:3001"] environment: PUBLIC_ORIGIN: http://192.168.1.32:3101 + WIKIDECK_USER_AGENT: &ua WikiDeck-testnet/0.1 (https://gitea.eom.dev/claude/wikideck; private testnet) WIKIDECK_MODES: classic,trending WIKIDECK_GAME_OPERATOR: Testnet A WIKIDECK_GAME_PEERS: http://192.168.1.32:3102,http://192.168.1.32:3103 @@ -12,6 +14,7 @@ services: ports: !override ["192.168.1.32:3102:3001"] environment: PUBLIC_ORIGIN: http://192.168.1.32:3102 + WIKIDECK_USER_AGENT: *ua WIKIDECK_MODES: draft WIKIDECK_GAME_OPERATOR: Testnet B WIKIDECK_GAME_PEERS: http://192.168.1.32:3101,http://192.168.1.32:3103 @@ -19,6 +22,7 @@ services: ports: !override ["192.168.1.32:3103:3001"] environment: PUBLIC_ORIGIN: http://192.168.1.32:3103 + WIKIDECK_USER_AGENT: *ua WIKIDECK_MODES: classic,trending,draft WIKIDECK_GAME_OPERATOR: Testnet C WIKIDECK_GAME_PEERS: http://192.168.1.32:3101,http://192.168.1.32:3102 diff --git a/deploy/night/mine.ts b/deploy/night/mine.ts index 96f9e4e..9e39fb6 100644 --- a/deploy/night/mine.ts +++ b/deploy/night/mine.ts @@ -13,7 +13,8 @@ const blocks = Number(process.argv[2] ?? 45), workers = Number(process.argv[3] ? if (!(workers >= 1 && workers <= 8)) throw new Error('1..8 workers'); const NODES = ['http://node-a:3001', 'http://node-b:3001', 'http://node-c:3001']; const WALLET_NAMES = ['alice', 'bob', 'carol', 'dave']; -const PASSWORD = 'wikideck-night-testnet'; +// PUBLIC, TESTNET-ONLY password for the disposable wallets' browser backups (posted on #4). Never reuse. +const PASSWORD = process.env.TESTNET_WALLET_PASSWORD ?? 'wikideck-night-testnet'; const STATE = process.env.STATE_DIR ?? '/state'; const dir = `${STATE}/wallets`; mkdirSync(dir, { recursive: true }); diff --git a/docs/game/CARD_DATA.md b/docs/game/CARD_DATA.md new file mode 100644 index 0000000..949e90f --- /dev/null +++ b/docs/game/CARD_DATA.md @@ -0,0 +1,98 @@ +# Card data: real stat distributions (council-data) + +Status: **interim**, generated 2026-11-16 23:06 EST. The full 330-card run is still fetching pageviews politely; this file and `card-sample.json` will be regenerated. + +Method: `scripts/night/card_sample.py` draws random ns0 articles in batches of 20 and keeps those passing the `server/wiki.ts` filter (thumbnail from upload/thumb.wikimedia.org, intro extract of at least 40 characters). It enriches them with the same API parameters as `server/enrichment.ts`: six completed months Jun–Oct 2026; attention uses October. It adds Wikidata P31 and 30-day drift (views 10-17..11-15 vs 09-17..10-16). `scripts/night/card_analyze.py` produces the tables below. + +## Headline findings (INTERIM: 100 fully enriched random illustrated cards; 330 sampled, rest still fetching under Wikimedia 429 rate limits) + +1. **Raw stats are compressed and skewed.** Median card: attention 33, depth 63, reach 24 (p10–p90: attention 23–53, depth 54–71, reach 9–48). No card above 81 on anything; 100 is unreachable honestly. **Use the 1–10 tier tables below (sample deciles), not 0–100.** +2. **Correlation is weaker than feared, except attention↔depth (Spearman 0.59).** Reach is nearly independent of both (0.10 / 0.02): stub villages get many bot-made language editions. So reach is a real separate axis; attention+depth partly double-count fame. +3. **Underlying raw values are very long-tailed:** monthly views median 94 (p90 1,438, max 14k); pageBytes median 6 KB; languageCount median 4, and **10% have 0 other languages** (reach 0). +4. **Trend is mostly negative:** 69% of cards have trendPercent < 0 (median −10%), 31% positive, 14% swing by more than 50%. Null is rare (1%). A "Trending" keyword fires for about a third of cards: fine as a small ±1. +5. **Live values are fairly stable in score terms:** 30-day pageview drift median |18%| (p90 55%), but that moves the attention score by only a median of **1.4 points** (p90 5.6). So "live vs. mint" differences are small for random cards; big swings only come from deliberate inflation (see the critic's point A4). +6. **The legacy `category()` buckets are unusable as factions:** Culture 53%, People 30%, Nature 9%, History 5%, Science 3%, **Space 0%**. +7. **Candidate factions from Wikidata P31 (instance of), clean and readable:** People 31%, Places 25%, Nature 10%, Structures 6%, Works 5%, Events 5%, Sport 3%, Ideas & Tech 3%, Organisations 2%, unclassified 10%. Suggest **6 factions**: People, Places, Nature, Works & Culture (Works + Organisations + Sport), Structures, Events & Ideas (Events + Ideas & Tech), plus a neutral fallback. People and Places are big, so faction bonuses should scale with *share in deck*, not raw count, or the small factions need their own perks. +8. **Starter/loaner list:** frozen stats for up to 4 cards per legacy category, spread across tiers, in `docs/game/starter-cards.json` (Space has no sample cards: hand-pick e.g. the Moon from `shared/catalog.ts`). + +## Full tables + +Sample: **100 cards**; ~44% (149/340 logged during sampling) of random pages pass the illustrated filter. Pageviews available for 100. + +| stat | n | min | p10 | p25 | median | p75 | p90 | max | mean | skew | +|---|---|---|---|---|---|---|---|---|---|---| +| attention | 100 | 13 | 23 | 27 | 33 | 41 | 53 | 69 | 35 | 0.75 | +| depth | 100 | 50 | 54 | 59 | 63 | 68 | 71 | 81 | 63 | 0.24 | +| reach | 100 | 0 | 9 | 16 | 24 | 36 | 48 | 59 | 26 | 0.11 | +| pageBytes | 100 | 998 | 1804 | 3407 | 6018 | 12512 | 19161 | 74169 | 9885 | 3.20 | +| languageCount | 100 | 0 | 1 | 2 | 4 | 11 | 27 | 56 | 9 | 1.83 | +| monthlyViews | 100 | 5 | 22 | 43 | 94 | 277 | 1438 | 14374 | 611 | 5.76 | +| dailyAverage | 100 | 0.2 | 0.7 | 1.4 | 3.0 | 8.9 | 46.4 | 463.7 | 19.7 | 5.76 | +| trendPercent | 99 | -86.6 | -45.1 | -26.4 | -10.4 | 4.5 | 21.1 | 187.1 | -9.5 | 1.83 | +| drift30Percent | 99 | -94.7 | -45.9 | -30.7 | -12.7 | -1.7 | 14.8 | 72.1 | -16.1 | -0.20 | + +**Spearman rank correlations** (cards with pageviews): + +| | attention | depth | reach | trendPercent | drift30Percent | +|---|---|---|---|---|---| +| attention | 1.00 | 0.59 | 0.10 | 0.24 | 0.25 | +| depth | 0.59 | 1.00 | 0.02 | 0.07 | 0.05 | +| reach | 0.10 | 0.02 | 1.00 | -0.10 | 0.24 | +| trendPercent | 0.24 | 0.07 | -0.10 | 1.00 | 0.53 | +| drift30Percent | 0.25 | 0.05 | 0.24 | 0.53 | 1.00 | + +(n=99; attention~monthlyViews, depth~pageBytes, reach~languageCount are monotonic so their rank correlations are identical.) + +**trendPercent sign:** positive 31 (31%), negative 68 (69%), zero 0; null (prior month 0 or no views) 1. |trend| > 50%: 14; > 100%: 1. + +**30-day drift** (views 10-17..11-15 vs 09-17..10-16): median |drift| 18%, p90 |drift| 55%. Attention score change implied: median 1.4 points, p90 5.6 points. + +**attention histogram (deciles 0-9,10-19..90-100):** 0 4 30 39 12 11 4 0 0 0 +**depth histogram (deciles 0-9,10-19..90-100):** 0 0 0 0 0 30 53 15 2 0 +**reach histogram (deciles 0-9,10-19..90-100):** 10 25 23 23 10 9 0 0 0 0 + +Reach = 0 (no other languages): 10; reach 100 (>=999 langs) impossible in practice, max langs 56. Attention null: 0; attention 0: 0. + +**Sum of three stats:** min 84, p10 97, p25 107, median 120, p75 140, p90 155, max 193 + +**Legacy `category()` (server/wiki.ts):** Culture 53, People 30, Nature 9, History 5, Science 3 + +**Top Wikidata P31 classes:** human 30, taxon 8, river 4, village 4, commune of France 3, musical group 2, building 2, castle 2, rural municipality of Austria 1, municipality of Austria 1, municipality of Brazil 1, television film 1, nor'easter 1, rail company (Japan) 1, village of Poland 1, municipality 1, civil parish 1, association football match 1, final 1, local government area of Victoria 1, plant disease 1, basketball team season 1, mosque 1, functional programming language 1, purely functional programming language 1, dependently typed programming language 1, programming language 1, free software 1, proof assistant 1, municipality of Croatia 1, municipality of Bangladesh 1, town 1, town in the United States 1, municipality of Georgia 1, epiphyte 1, protest 1, region of Mauritania 1, legislative election 1, musical work/composition 1, plateau 1 + +No Wikidata item: 0; no P31: 6 + +**Most frequent category words (cards containing):** stubs 35, births 27, people 26, from 24, century 22, living 16, geography 15, deaths 14, american 13, county 9, university 8, male 7, united 7, film 7, players 7, district 6, states 6, sports 6, biography 6, television 5, alumni 5, genera 5, established 5, villages 5, football 5, city 5, buildings 5, expatriate 5, sportspeople 5, sportsmen 5, towns 4, municipalities 4, writers 4, women 4, faculty 4, communes 4, rivers 4, places 4, establishments 4, actors 4, california 4, russian 4, association 4, structures 4, described 3, british 3, french 3, ohio 3, academics 3, based 3, japanese 3, pennsylvania 3, argentine 3, australia 3, populated 3, directors 3, rock 3, musical 3, conference 3, division 3 + + +## Rank-normalised tiers (1–10) + +Tier = 1 + number of breakpoints the score is **>=**. Breakpoints are the sample deciles p10..p90 of the 0–100 score. Ties make some tiers thin (scores are integers). + +| stat | p10 | p20 | p30 | p40 | p50 | p60 | p70 | p80 | p90 | +|---|---|---|---|---|---|---|---|---|---| +| attention | 23 | 25 | 28 | 31 | 33 | 36 | 38 | 45 | 53 | +| depth | 54 | 57 | 60 | 61 | 63 | 65 | 67 | 69 | 72 | +| reach | 10 | 10 | 16 | 20 | 26 | 30 | 36 | 39 | 49 | + +Resulting tier counts — attention: None:0 1:10 2:9 3:7 4:14 5:8 6:12 7:7 8:12 9:10 10:11 +; depth: 1:7 2:11 3:12 4:6 5:11 6:11 7:9 8:9 9:14 10:10 +; reach: 1:10 2:0 3:13 4:12 5:15 6:8 7:11 8:10 9:11 10:10 + +Starter candidates: 19 written to /tmp/claude-1000/-home-eric-worker-jobs-night-council-data/d4e31987-ce7f-4f28-8262-8f0225215102/scratchpad/starter.json: Counter({'Nature': 4, 'People': 4, 'History': 4, 'Culture': 4, 'Science': 3}) + +## Candidate factions (Wikidata P31 rules) + +| faction | n | share | median attention | median depth | median reach | example | +|---|---|---|---|---|---|---| +| People | 31 | 31% | 33 | 65 | 26 | Salahuddin of Aceh | +| Places | 25 | 25% | 28 | 61 | 36 | St. Georgen am Längsee | +| Nature | 10 | 10% | 30 | 56 | 31 | Dichromorpha viridis | +| Other | 10 | 10% | 52 | 64 | 22 | Village (Pennsylvania) | +| Structures | 6 | 6% | 32 | 58 | 16 | Pathrail Mosque | +| Works | 5 | 5% | 40 | 64 | 16 | The Best of Men | +| Events | 5 | 5% | 38 | 72 | 10 | April 2021 nor'easter | +| Sport | 3 | 3% | 25 | 71 | 0 | 1912 Argentine Primera División final | +| Ideas & Tech | 3 | 3% | 37 | 62 | 20 | Agda (programming language) | +| Organisations | 2 | 2% | 50 | 62 | 24 | Hiroshima Electric Railway | + +Unclassified P31 labels: typeface 1, annexation 1, position 1, family 1 diff --git a/docs/game/DESIGN.md b/docs/game/DESIGN.md index 090b52b..8a11676 100644 --- a/docs/game/DESIGN.md +++ b/docs/game/DESIGN.md @@ -92,12 +92,11 @@ big cards are flexible. mono-faction deck gains no consistency edge (§10: no v1 keyword scales with faction count). ### 1.6 Trend (live, small, capped) -`trend` = +1 if `live.trendPercent ≥ trendUp` (default 25), −1 if `≤ trendDown` (default **−200**, i.e. off: there is no down arrow in v1), -otherwise 0. A `null` value gives 0. Trend also needs `live.dailyAverage ≥ trendMinDaily` (default +`trend` = +1 if `live.trendPercent ≥ trendUp` (default 25), −1 if `≤ trendDown` (default **−200**, +which means there is **no down arrow in v1**: 69% of cards trend negative, so a ▼ would mostly land as +a quiet penalty on famous owned cards; modes can turn it back on), otherwise 0. A `null` value gives 0. Trend also needs `live.dailyAverage ≥ trendMinDaily` (default **20**), because percentages on tiny articles are noise; otherwise trend is 0. The host computes it **once at match start**, and it is frozen for -the match. It shows as an arrow (▲), not a number. It adds to power in every Topic. *Why no ▼ in v1:* 69% of the sample has a -negative `trendPercent`, and only busy (mostly owned, famous) cards pass `trendMinDaily`, so a ▼ would quietly penalise collectors. -Modes may turn it back on with e.g. `trendDown: -25`. +the match. It shows as an arrow (▲/▼), not a number. It adds to power in every Topic. ### 1.7 Rarity The hash-derived `rarity` (`shared/protocol.ts:38`) is **cosmetic in v1** (frame colour only). Mining luck must not @@ -361,7 +360,7 @@ the last turn's, and every "at scoring" Portal resolves **before** Topics are ju | Line | Why it isn't dominant | |---|---| -| All-famous (all max-stat) deck | It becomes an all-cost-5/6 deck with dead early turns. Cheap cards are more efficient **per energy**, expensive cards **per card**. Only 9 cards are seen per match (3 + 6 draws), so both matter. The 1-energy carry-over lets a heavy deck bank energy for a turn-5 six-drop. **sim-balance target: heavy vs curve ≥ 40%.** | +| All-famous (all max-stat) deck | It becomes an all-cost-5/6 deck with dead early turns. Cheap cards are more efficient **per energy**, expensive cards **per card**. Only 9 cards are seen per match (3 + 6 draws), so both matter. An all-cost-5/6 deck is **weak by design**: it has four dead turns (sim-balance interim: 0–15%). There is no hard deck rule in v1; the deck builder warns when a deck has fewer than 4 cards of cost ≤ 2, and every starter deck is curve-shaped (§2.1). **sim-balance target: a **top-heavy curve** (half the deck at cost 4 or more) vs curve ≥ 40%.** `energyByTurn [2..7]` is a v1.1 candidate. | | All-cheap flood (cost 1–2) | Weak by design: only 9 slots and 9 cards seen. Critic's sim under these rules: swarm vs curve about 7–11%. Its home is Culture's wide-turn keyword (§10). | | All one faction | No v1 keyword scales with faction count. `factionSynergyCap` is reserved for modes. Culture, the largest pool, has the weakest keyword (viral). | | "Always play the highest-power card" | It ignores the on-topic bonus, lane capacity and the hidden Portals. Critic's sim: 18–21% against a smart bot (target < 55%). | diff --git a/docs/game/ENGINE_API.md b/docs/game/ENGINE_API.md new file mode 100644 index 0000000..e4aedd7 --- /dev/null +++ b/docs/game/ENGINE_API.md @@ -0,0 +1,223 @@ +# WikiDeck game engine API (v1) + +**Owner:** engine-a (core and API) and engine-b (keywords, card derivation, tests). Issue: claude/wikideck#3. +**Rules:** `docs/game/DESIGN.md` v1 ("Edit War", as frozen in PR #17 @ cf2fceb). Where this file and DESIGN.md disagree, raise it on #3. +**Stability:** UI, simulation and modes build against this file. Any change to a name or shape below is +announced on #3 before it merges. + +The engine is a pure TypeScript library in `shared/game/`: +- It does no I/O and has no clocks: no `Date.now()`, no `Math.random()`. +- It imports nothing from `server/` or `src/`. +- It runs entirely **off-chain**. A match never reads, moves, locks or burns an NFT. +- It is deterministic: the same `(ruleset, decks, seed, actions)` always gives the same state, byte for byte. + +**Import only from `shared/game/index.ts`.** + +```ts +import { createMatch, legalActions, applyAction, isOver, result, viewFor, + serialize, deserialize, replay, DEFAULT_RULESET, parseRuleset, validateDeck, + starterDeck, previewPool, type MatchState, type Action, type GameCard } from '../shared/game/index.ts'; +``` + +## 1. Lifecycle + +```ts +let state = createMatch(DEFAULT_RULESET, [deck0, deck1], seed); // turn 1, planning +while (!isOver(state)) { + // Each seat (in any order, any interleaving) queues plays, then commits. + const actions = legalActions(state, seat); // play / undo / commit + state = applyAction(state, chosen); // returns a NEW state + // When both seats have committed, the turn resolves inside applyAction. +} +const r = result(state); // { winner: 0 | 1 | null, reason, topicsLed, lanePower, totalPower, turns } +``` + +| Function | Description | +|---|---| +| `createMatch(ruleset, [deck0, deck1], seed: number \| string): MatchState` | Validates the ruleset (`parseRuleset`) and both decks (`validateDeck`), then performs DESIGN §4 setup and turn-1 start. A `seed` is a uint32. A string is hashed with FNV-1a (`seedFromString`). Throws `ZodError` for a bad ruleset and `IllegalActionError` for a bad deck. | +| `legalActions(state, seat): Action[]` | Lists every `play` (each card × each lane it can legally go into), every `undo`, and `commit`. Returns `[]` once the seat has committed or the match is over. It never lists `concede` (always legal while the match is running) or `timeout` (host only). | +| `applyAction(state, action): MatchState` | Pure: the input is never mutated. Throws `IllegalActionError` if the action is illegal. | +| `actionProblem(state, action): string \| null` | Explains why an action is illegal, without throwing. Use it for UI hints and for validating client input on a host. | +| `isOver(state)` / `result(state)` | `result` is `null` while the match is running. | +| `viewFor(state, seat): PlayerView` | The **hidden-information view**. Send only this to clients and AIs, never `MatchState`, because a `MatchState` contains both deck orders and the RNG state. | +| `serialize(state): string` / `deserialize(json): MatchState` | Lossless JSON. `MatchState` is plain data. | +| `replay(ruleset, decks, seed, actions): MatchState` | Rebuilds a match from its inputs. `state.actions` records every action applied, so a host can store `(ruleset, decks, seed, actions)` and verify a result later. | +| `validateDeck(ruleset, cards): string[]` | Returns the list of problems; empty means the deck is legal. | +| `cardPower(state, cardInPlay)`, `lanePower(state, lane)`, `laneLeader(state, lane)`, `topicsLed(state)` | Power queries (DESIGN §6). `laneLeader` and `topicsLed` apply the consensus tie-break. | +| `scoringPower(state, lane)` | Lane power plus revealed "at scoring" Portals (§7). `result().lanePower` uses this. | +| `laneCapacity(state, lane)` | Per-seat capacity of a lane. A Portal such as Stub may override it. | +| `isOnTopic(state, cardInPlay)` | §1.4/§6 on-topic test, including Disambiguation. | +| `starterDeck(seed): GameCard[]` | A 12-card loaner deck (DESIGN §2). **Placeholder** cards until starter-cards.json lands. | +| `previewPool(): GameCard[]` | Every loaner card once. For draft modes. | +| `placeCard(state, seat, lane, card)`, `revealPortal(state, lane)` | Test helpers for building boards by hand. | + +## 2. Actions + +```ts +type Action = + | { type: 'play'; player: 0 | 1; cardId: string; lane: number } // queue a card from hand (hidden) + | { type: 'undo'; player: 0 | 1; cardId: string } // un-queue it (refunds energy) + | { type: 'commit'; player: 0 | 1 } // lock in this turn (empty = pass) + | { type: 'timeout'; player: 0 | 1 } // HOST ONLY: turn timer expired + | { type: 'concede'; player: 0 | 1 }; +``` + +**Queuing a play** +- `play` reserves the card's cost from this turn's energy. It checks the energy, the lane's room (cards already in the lane plus queued plays must stay under `laneCapacity(state, lane)`), and, once the Portal is revealed, whether it accepts the card (`canPlay`). +- Your plays reveal in **your queue order**, interleaved with the opponent's (see below). +- `undo` and new plays are allowed until the seat sends `commit`. + +**Resolving a turn** +- When both seats have committed, `applyAction` resolves the turn (DESIGN §5.4–5.5): + 1. Carry is set: min(`energyCarryMax`, energy not reserved by queued plays). Energy spent on a play that later fizzles is still spent. + 2. **Interleaved reveal:** the initiative seat's 1st play, then the other seat's 1st, then the initiative seat's 2nd, and so on. When one seat runs out, the other's remaining plays reveal in order. Each card gets the next global `seq` number, and its on-reveal effects (keyword, then Portal) run at once. + 3. End-of-turn effects run: the initiative seat's cards first, then lanes left→right, then `seq` order. + 4. On the last turn, scoring follows (§7). Otherwise the next turn starts: + - initiative **alternates** + - any Portal scheduled by `portalReveal` is revealed + - energy = `energyByTurn[t-1]` + carry + `bonusEnergy` + - each seat draws + - the underdog bonus applies (only if `underdog` is on) +- **A play that is illegal at reveal** (the lane filled up, or a Portal rejects the card) fizzles. The card stays in hand and its energy is lost. A `fizzle` log event records it. + +**Timeouts.** `timeout` is how a host enforces `turnSeconds`. It commits whatever is queued. A timeout with an empty queue counts toward `afkTurns`. When that count is reached, the seat concedes and the result has `reason: 'afk'`. An ordinary `commit` resets the count. + +**Seat ownership.** The engine does not authenticate anyone. The host must check that the seat in `action.player` is the caller's. + +## 3. Cards + +```ts +interface GameCard { + cardId: string; // unique within a deck: the NFT card hash, or `loaner::` + pageId: number | null; // at most maxCopiesPerPage cards share a pageId; null (unpinned loaners) → counted per cardId + title: string; + faction: 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture'; + rarity: 'Common' | 'Rare' | 'Epic' | 'Legendary'; // cosmetic in v1 + cost: number; // 0–6 (uncheckedCostCap already applied by derivation) + power: number; // 0–30, base power + home: 'attention' | 'depth' | 'reach'; + trend: -1 | 0 | 1; // frozen at match start + keyword: string | null; // an id in KEYWORDS + source: 'owned' | 'loaner'; + check?: 'verified' | 'unverified' | 'unchecked' | 'loaner'; // host plausibility result (§1.10), for logs +} +``` + +- **The engine takes already-derived cards and never reads raw stats.** The council asked for this, because snapshot stats are self-reported (#1, critic brief A.1). +- Derivation (DESIGN §1 and §10.1: percentile → fame → cost → power, home, trend, keyword and vanillaBonus) lives in `shared/game/derive.ts`, which engine-b owns. Hosts run it on host-frozen, plausibility-checked inputs before calling `createMatch`. +- Modes may adjust `GameCard` fields such as `power` before `createMatch`. The engine does not re-derive them. +- A keyword that isn't in `ruleset.keywordsEnabled` never runs. Derivation is responsible for not giving that card `vanillaBonus`. +- Lane power = `power` + `bonus` + `trend` + `onTopicBonus[cost]` if on-topic + ongoing keyword and Portal effects, floored at 0. + +## 4. Ruleset + +`Ruleset` holds the DESIGN §9 keys, **flat** (nothing deeper than one level, apart from `topicPool` entries and the param tables). +- `parseRuleset(unknown)` is a **strict** zod parse: unknown keys are rejected and every number is bounded, so any ruleset that passes terminates within `turns` turns. +- Modes merge overrides onto `DEFAULT_RULESET` and then call `parseRuleset`. + +Notes on the §9 keys: +- `topicPool` is inline `TopicDef[] = { id, name, stat, portal: PortalId | null }[]`. `DEFAULT_TOPIC_POOL` is the 9 Topics of §10.3. A Portal id is one of `PORTAL_IDS` (`main-page, trending, featured-article, stub, interwiki, disambiguation`). +- `keywordParams[keywordId]` holds keyword numbers; keys must be in `KEYWORD_IDS`. `portalParams[topicId]` holds Portal numbers, and falls back to `portalParams[portalId]`, so a mode can add a Topic that reuses a Portal kind with new numbers. +- `keywordsEnabled` ⊆ `KEYWORD_IDS` (the 6 v1 ids plus `edition`, `obscure` and `wildcard`). +- `mulligan` must be `false`. Mulligans are not implemented in v1. +- `percentiles`, `starterDecks`, `trendUp/Down`, `trendMinDaily`, `uncheckedCostCap`, `vanillaBonus`, `costThresholds`, `powerByCost`, `verifyStats` and `factionSynergyCap` are for derivation and the host. The core loop doesn't read them. + +Validation also enforces: +- `turns × turnSeconds ≤ 240` +- `energyByTurn.length ≥ turns` +- `portalReveal.length = topicCount` +- `openingHand ≤ handLimit` +- `costThresholds` in ascending order +- with `distinctStats`, `topicCount == 3` and the pool has all 3 stats +- the ranges in DESIGN §11 are **stricter** and are enforced by modes (`shared/game/modes.ts`). The engine's bounds only guarantee safety and termination. + +## 5. Determinism and the RNG + +- The RNG is **mulberry32(seed: uint32)**, as in DESIGN §4. Its state is a single uint32 in `state.rng`. +- Draw order: + 1. p0's deck is shuffled. + 2. p1's deck is shuffled. + 3. **The Topics are drawn.** With `distinctStats`: for each stat in the order `attention, depth, reach`, take `group[floor(next() × group.length)]`, where `group` is that stat's Topics in `topicPool` order. Then the picks are shuffled, and that is the lane order. Without `distinctStats`: the whole pool is shuffled and the first `topicCount` are taken. + 4. The initiative coin is flipped: p0 has initiative on turn 1 (and every odd turn) if `next() < 0.5`; otherwise p1 does. After that, initiative strictly alternates. + 5. Keyword and Portal hooks draw in resolution order. +- Shuffles are Fisher–Yates with `i` from n−1 down to 1 and `j = floor(next() × (i+1))`. +- `ongoing` power hooks get a throwaway RNG copy, so computing power never changes the match RNG. + +## 6. State and views + +The full `MatchState` (plain JSON) is for the **host only**: + +```ts +interface MatchState { + schema: 'wikideck-match/1'; engineVersion: number; ruleset: Ruleset; seed: number; rng: number; + turn: number /* 1-based */; phase: 'planning' | 'over'; initiative: 0 | 1; + players: [PlayerState, PlayerState]; // deck, hand, energy, queue, committed, afk + lanes: { topic: TopicDef; portalRevealed: boolean; cards: [CardInPlay[], CardInPlay[]] }[]; + revealSeq: number; log: LogEvent[]; actions: Action[]; result: MatchResult | null; +} +interface PlayerState { deck; hand; energy; queue: { cardId; lane }[]; committed; afk; carry } +interface CardInPlay { card: GameCard; owner: 0 | 1; lane: number; turn: number; seq: number; bonus: number } +``` + +`PlayerView`, returned by `viewFor(state, seat)`, is what a seat may see. In it, "you" is always index 0 and the opponent is index 1: + +```ts +interface PlayerView { + you: 0 | 1; ruleset; turn; phase; initiative; + energy: number; energyLeft: number; hand: GameCard[]; queue: { cardId; lane }[]; committed; deckCount; + opponent: { handCount; deckCount; queuedCount; committed }; // never their cards or queue + lanes: { topic: TopicDef /* stat always; id/name/portal masked until portalRevealed */, portalRevealed, cards: [mine, theirs], + cardPower: [number[], number[]], power: [mine, theirs], leader: 'you' | 'opponent' | null }[]; + result: MatchResult | null; +} +``` + +`state.log` is an append-only event list for animation and replays. Event types: `turnStart`, `portalRevealed`, `underdog`, `draw`, `reveal`, `fizzle`, `effect`, `concede` and `matchOver`. It contains both seats' draws, so a host must filter it per seat before sending it. + +## 7. Results + +```ts +interface MatchResult { + winner: 0 | 1 | null; // null = draw + reason: 'topics' | 'totalPower' | 'draw' | 'concede' | 'afk'; + topicsLed: [number, number]; lanePower: [number, number][]; totalPower: [number, number]; turns: number; +} +``` + +Scoring runs after the last turn's End phase. Lane powers include revealed "at scoring" Portals, and each lane's leader uses the consensus tie-break (§6). Winner, per DESIGN §7: +1. The seat that leads more Topics. +2. If tied on Topics, the seat with more total power. +3. If that is also tied, a draw. + +## 8. Keywords and Portals (extension contract) + +`KEYWORDS` and `PORTALS` in `shared/game/keywords.ts` (engine-b) are registries of hook objects. The header of that file is normative. Every hook gets `ctx = { state, rng, params, lane, log, power(card) }`. + +**Keywords** +- `onReveal(ctx, self)` and `endOfTurn(ctx, self)` may change `bonus` on cards in `ctx.state`. +- `ongoing(ctx, self, target) → number` must be **pure**, and must not call `ctx.power`. +- Keyword hooks run only if the keyword is in `keywordsEnabled`. + +**Portals** have the same hooks, plus: +- `onPortalReveal(ctx)` +- `canPlay(ctx, card, seat) → boolean`, checked when a play is queued and again at reveal +- `capacity(ctx) → number` +- `allOnTopic: true` +- `atScoring(ctx) → [delta0, delta1]` + +Portal hooks act only once the Portal is revealed. + +**Rules for all hooks** +- Hooks must not move or remove cards (DESIGN §10). +- Any randomness must come from `ctx.rng`. No v1 keyword uses it. + +## 9. Testing + +- `tests/game-core.test.ts` (engine-a) covers the core loop: + - the RNG reference value, ruleset bounds and setup + - hidden information and hidden Portals + - energy carry, interleaved reveal and alternating initiative + - on-topic power, the consensus tie-break, and Portal capacity, fizzle and at-scoring hooks + - disabled keywords, AFK and concede, and draws + - the random-play property: matches terminate, replay exactly, and serialise after every action +- `tests/game-*.test.ts` (engine-b): keywords, card derivation, property tests and the DESIGN §12 golden match. diff --git a/docs/game/card-sample.json b/docs/game/card-sample.json new file mode 100644 index 0000000..c66c833 --- /dev/null +++ b/docs/game/card-sample.json @@ -0,0 +1,7103 @@ +{ + "generatedAt": "2026-11-17T04:05:04.081324+00:00", + "method": "random ns0 batches of 20, filter as server/wiki.ts (thumbnail + extract>=40); enrichment as server/enrichment.ts; monthly views summed from daily REST pageviews; P31 from Wikidata", + "randomBatches": 0, + "rawPagesSeen": 0, + "cards": [ + { + "pageId": 8723556, + "title": "Salahuddin of Aceh", + "description": "Sultan of Aceh (1530–1537/9)", + "wikidataId": "Q4264920", + "revisionId": 1358732737, + "pageBytes": 5773, + "languageCount": 6, + "languagesTruncated": false, + "categories": [ + "1548 deaths", + "16th-century Indonesian people", + "16th-century monarchs in Asia", + "Sultans of Aceh" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 151 + }, + { + "month": "2026-06", + "views": 129 + }, + { + "month": "2026-07", + "views": 155 + }, + { + "month": "2026-08", + "views": 155 + }, + { + "month": "2026-09", + "views": 159 + }, + { + "month": "2026-10", + "views": 142 + } + ], + "latestMonth": "2026-10", + "total": 891, + "dailyAverage": 4.580645161290323, + "trendPercent": -10.69182389937107 + }, + "stats": { + "attention": 36, + "depth": 63, + "reach": 28 + }, + "legacyCategory": "People", + "drift30": { + "last30": 140, + "prev30": 152, + "pct": -7.894736842105263 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 10800205, + "title": "St. Georgen am Längsee", + "description": "Municipality in Carinthia, Austria", + "wikidataId": "Q664135", + "revisionId": 1376918522, + "pageBytes": 5004, + "languageCount": 30, + "languagesTruncated": false, + "categories": [ + "Carinthia geography stubs", + "Cities and towns in Sankt Veit an der Glan District" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 46 + }, + { + "month": "2026-06", + "views": 33 + }, + { + "month": "2026-07", + "views": 43 + }, + { + "month": "2026-08", + "views": 53 + }, + { + "month": "2026-09", + "views": 56 + }, + { + "month": "2026-10", + "views": 45 + } + ], + "latestMonth": "2026-10", + "total": 276, + "dailyAverage": 1.4516129032258065, + "trendPercent": -19.642857142857142 + }, + "stats": { + "attention": 28, + "depth": 62, + "reach": 50 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 36, + "prev30": 46, + "pct": -21.73913043478261 + }, + "instanceOf": [ + { + "id": "Q1802801", + "label": "rural municipality of Austria" + }, + { + "id": "Q667509", + "label": "municipality of Austria" + } + ] + }, + { + "pageId": 25468405, + "title": "Maracás", + "description": "Municipality of Bahia, Brazil", + "wikidataId": "Q1795100", + "revisionId": 1378546622, + "pageBytes": 5063, + "languageCount": 27, + "languagesTruncated": false, + "categories": [ + "Bahia geography stubs", + "Municipalities in Bahia" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 105 + }, + { + "month": "2026-06", + "views": 81 + }, + { + "month": "2026-07", + "views": 68 + }, + { + "month": "2026-08", + "views": 67 + }, + { + "month": "2026-09", + "views": 79 + }, + { + "month": "2026-10", + "views": 58 + } + ], + "latestMonth": "2026-10", + "total": 458, + "dailyAverage": 1.8709677419354838, + "trendPercent": -26.582278481012654 + }, + "stats": { + "attention": 30, + "depth": 62, + "reach": 48 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 55, + "prev30": 62, + "pct": -11.29032258064516 + }, + "instanceOf": [ + { + "id": "Q3184121", + "label": "municipality of Brazil" + } + ] + }, + { + "pageId": 25856905, + "title": "Dichromorpha viridis", + "description": "Species of grasshopper", + "wikidataId": "Q5272562", + "revisionId": 1367363150, + "pageBytes": 1347, + "languageCount": 4, + "languagesTruncated": false, + "categories": [ + "Gomphocerinae", + "Insects described in 1863" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 182 + }, + { + "month": "2026-06", + "views": 242 + }, + { + "month": "2026-07", + "views": 326 + }, + { + "month": "2026-08", + "views": 296 + }, + { + "month": "2026-09", + "views": 236 + }, + { + "month": "2026-10", + "views": 133 + } + ], + "latestMonth": "2026-10", + "total": 1415, + "dailyAverage": 4.290322580645161, + "trendPercent": -43.64406779661017 + }, + "stats": { + "attention": 35, + "depth": 52, + "reach": 23 + }, + "legacyCategory": "Nature", + "drift30": { + "last30": 121, + "prev30": 197, + "pct": -38.578680203045685 + }, + "instanceOf": [ + { + "id": "Q16521", + "label": "taxon" + } + ] + }, + { + "pageId": 36740675, + "title": "The Best of Men", + "description": "2012 British television film", + "wikidataId": "Q7717125", + "revisionId": 1372732350, + "pageBytes": 6002, + "languageCount": 4, + "languagesTruncated": false, + "categories": [ + "2010s docudrama films", + "2012 British films", + "2012 films", + "2012 television films", + "BBC television dramas", + "British docudrama films", + "Science docudramas" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 521 + }, + { + "month": "2026-06", + "views": 656 + }, + { + "month": "2026-07", + "views": 644 + }, + { + "month": "2026-08", + "views": 518 + }, + { + "month": "2026-09", + "views": 493 + }, + { + "month": "2026-10", + "views": 476 + } + ], + "latestMonth": "2026-10", + "total": 3308, + "dailyAverage": 15.35483870967742, + "trendPercent": -3.4482758620689653 + }, + "stats": { + "attention": 45, + "depth": 63, + "reach": 23 + }, + "legacyCategory": "Science", + "drift30": { + "last30": 436, + "prev30": 455, + "pct": -4.175824175824175 + }, + "instanceOf": [ + { + "id": "Q506240", + "label": "television film" + } + ] + }, + { + "pageId": 41530188, + "title": "Hervé Fischer", + "description": null, + "wikidataId": "Q3134490", + "revisionId": 1383948367, + "pageBytes": 10429, + "languageCount": 6, + "languagesTruncated": false, + "categories": [ + "1941 births", + "French male writers", + "French sociologists", + "Living people" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 68 + }, + { + "month": "2026-06", + "views": 32 + }, + { + "month": "2026-07", + "views": 49 + }, + { + "month": "2026-08", + "views": 62 + }, + { + "month": "2026-09", + "views": 81 + }, + { + "month": "2026-10", + "views": 47 + } + ], + "latestMonth": "2026-10", + "total": 339, + "dailyAverage": 1.5161290322580645, + "trendPercent": -41.9753086419753 + }, + "stats": { + "attention": 28, + "depth": 67, + "reach": 28 + }, + "legacyCategory": "People", + "drift30": { + "last30": 47, + "prev30": 68, + "pct": -30.88235294117647 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 41676480, + "title": "Mary Sophie Young", + "description": "American botanist (c.1872–1919)", + "wikidataId": "Q16043849", + "revisionId": 1187069209, + "pageBytes": 4654, + "languageCount": 3, + "languagesTruncated": false, + "categories": [ + "1870s births", + "1919 deaths", + "American botanists", + "American women academics", + "American women botanists", + "Botanists active in North America", + "People from Glendale, Ohio", + "University of Chicago alumni", + "University of Texas at Austin faculty", + "Wellesley College alumni" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 20 + }, + { + "month": "2026-06", + "views": 25 + }, + { + "month": "2026-07", + "views": 15 + }, + { + "month": "2026-08", + "views": 11 + }, + { + "month": "2026-09", + "views": 16 + }, + { + "month": "2026-10", + "views": 18 + } + ], + "latestMonth": "2026-10", + "total": 105, + "dailyAverage": 0.5806451612903226, + "trendPercent": 12.5 + }, + "stats": { + "attention": 21, + "depth": 61, + "reach": 20 + }, + "legacyCategory": "People", + "drift30": { + "last30": 20, + "prev30": 20, + "pct": 0.0 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 60187566, + "title": "Oncopagurus", + "description": "Genus of crustaceans", + "wikidataId": "Q4471563", + "revisionId": 1353977816, + "pageBytes": 2123, + "languageCount": 6, + "languagesTruncated": false, + "categories": [ + "Anomura stubs", + "Decapod genera", + "Hermit crabs" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 90 + }, + { + "month": "2026-06", + "views": 66 + }, + { + "month": "2026-07", + "views": 72 + }, + { + "month": "2026-08", + "views": 82 + }, + { + "month": "2026-09", + "views": 39 + }, + { + "month": "2026-10", + "views": 63 + } + ], + "latestMonth": "2026-10", + "total": 412, + "dailyAverage": 2.032258064516129, + "trendPercent": 61.53846153846154 + }, + "stats": { + "attention": 30, + "depth": 55, + "reach": 28 + }, + "legacyCategory": "Nature", + "drift30": { + "last30": 51, + "prev30": 47, + "pct": 8.51063829787234 + }, + "instanceOf": [ + { + "id": "Q16521", + "label": "taxon" + } + ] + }, + { + "pageId": 67426902, + "title": "April 2021 nor'easter", + "description": "Slow-moving nor'easter in April 2021", + "wikidataId": "Q106542029", + "revisionId": 1355258366, + "pageBytes": 24519, + "languageCount": 0, + "languagesTruncated": false, + "categories": [ + "2020–21 North American winter", + "2021 in Maine", + "2021 in Massachusetts", + "2021 in New Hampshire", + "2021 in Vermont", + "April 2021 in the United States", + "Nor'easters" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 127 + }, + { + "month": "2026-06", + "views": 86 + }, + { + "month": "2026-07", + "views": 78 + }, + { + "month": "2026-08", + "views": 108 + }, + { + "month": "2026-09", + "views": 302 + }, + { + "month": "2026-10", + "views": 89 + } + ], + "latestMonth": "2026-10", + "total": 790, + "dailyAverage": 2.870967741935484, + "trendPercent": -70.52980132450331 + }, + "stats": { + "attention": 33, + "depth": 73, + "reach": 0 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 80, + "prev30": 277, + "pct": -71.11913357400722 + }, + "instanceOf": [ + { + "id": "Q2001587", + "label": "nor'easter" + } + ] + }, + { + "pageId": 8330236, + "title": "Hiroshima Electric Railway", + "description": "Japanese transportation company", + "wikidataId": "Q16595959", + "revisionId": 1383654640, + "pageBytes": 8796, + "languageCount": 14, + "languagesTruncated": false, + "categories": [ + "Bus companies of Japan", + "Companies based in Hiroshima Prefecture", + "Companies listed on the Tokyo Stock Exchange", + "Hiroshima Electric Railway", + "Japanese companies established in 1910", + "Railway companies established in 1910", + "Railway companies of Japan" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 1387 + }, + { + "month": "2026-06", + "views": 1086 + }, + { + "month": "2026-07", + "views": 1092 + }, + { + "month": "2026-08", + "views": 1483 + }, + { + "month": "2026-09", + "views": 1232 + }, + { + "month": "2026-10", + "views": 1059 + } + ], + "latestMonth": "2026-10", + "total": 7339, + "dailyAverage": 34.16129032258065, + "trendPercent": -14.042207792207792 + }, + "stats": { + "attention": 50, + "depth": 66, + "reach": 39 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 1048, + "prev30": 1102, + "pct": -4.900181488203267 + }, + "instanceOf": [ + { + "id": "Q85907346", + "label": "rail company (Japan)" + } + ] + }, + { + "pageId": 15810707, + "title": "Charmont-en-Beauce", + "description": "Commune in Centre-Val de Loire, France", + "wikidataId": "Q667131", + "revisionId": 1381828954, + "pageBytes": 1811, + "languageCount": 32, + "languagesTruncated": false, + "categories": [ + "Communes of Loiret", + "Loiret geography stubs" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 26 + }, + { + "month": "2026-06", + "views": 14 + }, + { + "month": "2026-07", + "views": 9 + }, + { + "month": "2026-08", + "views": 7 + }, + { + "month": "2026-09", + "views": 18 + }, + { + "month": "2026-10", + "views": 23 + } + ], + "latestMonth": "2026-10", + "total": 97, + "dailyAverage": 0.7419354838709677, + "trendPercent": 27.77777777777778 + }, + "stats": { + "attention": 23, + "depth": 54, + "reach": 51 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 14, + "prev30": 21, + "pct": -33.33333333333333 + }, + "instanceOf": [ + { + "id": "Q484170", + "label": "commune of France" + } + ] + }, + { + "pageId": 15884863, + "title": "Freshwater River", + "description": "River on Stewart Island / Rakiura, New Zealand", + "wikidataId": "Q5503122", + "revisionId": 1358001871, + "pageBytes": 4058, + "languageCount": 5, + "languagesTruncated": false, + "categories": [ + "Rivers of Stewart Island" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 21 + }, + { + "month": "2026-06", + "views": 39 + }, + { + "month": "2026-07", + "views": 31 + }, + { + "month": "2026-08", + "views": 28 + }, + { + "month": "2026-09", + "views": 32 + }, + { + "month": "2026-10", + "views": 29 + } + ], + "latestMonth": "2026-10", + "total": 180, + "dailyAverage": 0.9354838709677419, + "trendPercent": -9.375 + }, + "stats": { + "attention": 25, + "depth": 60, + "reach": 26 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 26, + "prev30": 41, + "pct": -36.58536585365854 + }, + "instanceOf": [ + { + "id": "Q4022", + "label": "river" + } + ] + }, + { + "pageId": 18775530, + "title": "Złaków Kościelny", + "description": "Village in Łódź Voivodeship, Poland", + "wikidataId": "Q321622", + "revisionId": 1378518207, + "pageBytes": 1153, + "languageCount": 7, + "languagesTruncated": false, + "categories": [ + "Villages in Łowicz County", + "Łowicz County geography stubs" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 19 + }, + { + "month": "2026-06", + "views": 10 + }, + { + "month": "2026-07", + "views": 7 + }, + { + "month": "2026-08", + "views": 27 + }, + { + "month": "2026-09", + "views": 13 + }, + { + "month": "2026-10", + "views": 11 + } + ], + "latestMonth": "2026-10", + "total": 87, + "dailyAverage": 0.3548387096774194, + "trendPercent": -15.384615384615385 + }, + "stats": { + "attention": 18, + "depth": 51, + "reach": 30 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 7, + "prev30": 10, + "pct": -30.0 + }, + "instanceOf": [ + { + "id": "Q3558970", + "label": "village of Poland" + } + ] + }, + { + "pageId": 24509551, + "title": "Village (Pennsylvania)", + "description": null, + "wikidataId": "Q16936588", + "revisionId": 1367096869, + "pageBytes": 4229, + "languageCount": 0, + "languagesTruncated": false, + "categories": [ + "Local government in Pennsylvania" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 88 + }, + { + "month": "2026-06", + "views": 80 + }, + { + "month": "2026-07", + "views": 74 + }, + { + "month": "2026-08", + "views": 70 + }, + { + "month": "2026-09", + "views": 67 + }, + { + "month": "2026-10", + "views": 51 + } + ], + "latestMonth": "2026-10", + "total": 430, + "dailyAverage": 1.6451612903225807, + "trendPercent": -23.88059701492537 + }, + "stats": { + "attention": 29, + "depth": 60, + "reach": 0 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 40, + "prev30": 60, + "pct": -33.33333333333333 + }, + "instanceOf": [] + }, + { + "pageId": 25207440, + "title": "Sainte-Félicité, Chaudière-Appalaches", + "description": "Municipality in Quebec, Canada", + "wikidataId": "Q3464275", + "revisionId": 1376759357, + "pageBytes": 4402, + "languageCount": 7, + "languagesTruncated": false, + "categories": [ + "Chaudière-Appalaches geography stubs", + "Incorporated places in Chaudière-Appalaches", + "Municipalities in Quebec" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 18 + }, + { + "month": "2026-06", + "views": 24 + }, + { + "month": "2026-07", + "views": 12 + }, + { + "month": "2026-08", + "views": 23 + }, + { + "month": "2026-09", + "views": 27 + }, + { + "month": "2026-10", + "views": 18 + } + ], + "latestMonth": "2026-10", + "total": 122, + "dailyAverage": 0.5806451612903226, + "trendPercent": -33.33333333333333 + }, + "stats": { + "attention": 21, + "depth": 61, + "reach": 30 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 6, + "prev30": 26, + "pct": -76.92307692307693 + }, + "instanceOf": [ + { + "id": "Q27676428", + "label": "municipality" + } + ] + }, + { + "pageId": 29902322, + "title": "Llanveynoe", + "description": "Village in Herefordshire, England", + "wikidataId": "Q6661845", + "revisionId": 1325745411, + "pageBytes": 4047, + "languageCount": 7, + "languagesTruncated": false, + "categories": [ + "Civil parishes in Herefordshire", + "Villages in Herefordshire" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 55 + }, + { + "month": "2026-06", + "views": 36 + }, + { + "month": "2026-07", + "views": 59 + }, + { + "month": "2026-08", + "views": 84 + }, + { + "month": "2026-09", + "views": 54 + }, + { + "month": "2026-10", + "views": 43 + } + ], + "latestMonth": "2026-10", + "total": 331, + "dailyAverage": 1.3870967741935485, + "trendPercent": -20.37037037037037 + }, + "stats": { + "attention": 27, + "depth": 60, + "reach": 30 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 29, + "prev30": 40, + "pct": -27.500000000000004 + }, + "instanceOf": [ + { + "id": "Q532", + "label": "village" + }, + { + "id": "Q1115575", + "label": "civil parish" + } + ] + }, + { + "pageId": 66508497, + "title": "Amanita mairei", + "description": "Species of fungus", + "wikidataId": "Q15651951", + "revisionId": 1323515500, + "pageBytes": 998, + "languageCount": 8, + "languagesTruncated": false, + "categories": [ + "Amanita", + "Fungi described in 1949", + "Fungus species" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 24 + }, + { + "month": "2026-06", + "views": 30 + }, + { + "month": "2026-07", + "views": 19 + }, + { + "month": "2026-08", + "views": 54 + }, + { + "month": "2026-09", + "views": 78 + }, + { + "month": "2026-10", + "views": 61 + } + ], + "latestMonth": "2026-10", + "total": 266, + "dailyAverage": 1.967741935483871, + "trendPercent": -21.794871794871796 + }, + "stats": { + "attention": 30, + "depth": 50, + "reach": 32 + }, + "legacyCategory": "Nature", + "drift30": { + "last30": 49, + "prev30": 67, + "pct": -26.865671641791046 + }, + "instanceOf": [ + { + "id": "Q16521", + "label": "taxon" + } + ] + }, + { + "pageId": 80560274, + "title": "1912 Argentine Primera División final", + "description": "Football match", + "wikidataId": "Q135493693", + "revisionId": 1351705367, + "pageBytes": 11909, + "languageCount": 0, + "languagesTruncated": false, + "categories": [ + "1910s in Buenos Aires", + "1912 in Argentine football", + "Argentine Primera División", + "Club Atlético Independiente matches", + "Club Atlético Porteño matches", + "December 1912 in sports", + "Football competitions in Buenos Aires" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 41 + }, + { + "month": "2026-06", + "views": 24 + }, + { + "month": "2026-07", + "views": 21 + }, + { + "month": "2026-08", + "views": 23 + }, + { + "month": "2026-09", + "views": 23 + }, + { + "month": "2026-10", + "views": 19 + } + ], + "latestMonth": "2026-10", + "total": 151, + "dailyAverage": 0.6129032258064516, + "trendPercent": -17.391304347826086 + }, + "stats": { + "attention": 22, + "depth": 68, + "reach": 0 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 6, + "prev30": 27, + "pct": -77.77777777777779 + }, + "instanceOf": [ + { + "id": "Q12166442", + "label": "association football match" + }, + { + "id": "Q1366722", + "label": "final" + } + ] + }, + { + "pageId": 466891, + "title": "City of Wyndham", + "description": "Local government area in Victoria, Australia", + "wikidataId": "Q1502429", + "revisionId": 1386046344, + "pageBytes": 13630, + "languageCount": 9, + "languagesTruncated": false, + "categories": [ + "1862 establishments in Australia", + "City of Wyndham", + "Local government areas in Melbourne", + "Populated places established in 1862" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 1464 + }, + { + "month": "2026-06", + "views": 1160 + }, + { + "month": "2026-07", + "views": 1194 + }, + { + "month": "2026-08", + "views": 1260 + }, + { + "month": "2026-09", + "views": 1034 + }, + { + "month": "2026-10", + "views": 954 + } + ], + "latestMonth": "2026-10", + "total": 7066, + "dailyAverage": 30.774193548387096, + "trendPercent": -7.7369439071566735 + }, + "stats": { + "attention": 50, + "depth": 69, + "reach": 33 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 841, + "prev30": 991, + "pct": -15.136226034308779 + }, + "instanceOf": [ + { + "id": "Q1426035", + "label": "local government area of Victoria" + } + ] + }, + { + "pageId": 2453788, + "title": "Heart rot", + "description": "Fungal disease of trees", + "wikidataId": "Q5692479", + "revisionId": 1374732887, + "pageBytes": 10880, + "languageCount": 4, + "languagesTruncated": false, + "categories": [ + "Fungal tree pathogens and diseases" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 854 + }, + { + "month": "2026-06", + "views": 691 + }, + { + "month": "2026-07", + "views": 567 + }, + { + "month": "2026-08", + "views": 670 + }, + { + "month": "2026-09", + "views": 799 + }, + { + "month": "2026-10", + "views": 762 + } + ], + "latestMonth": "2026-10", + "total": 4343, + "dailyAverage": 24.580645161290324, + "trendPercent": -4.630788485607009 + }, + "stats": { + "attention": 48, + "depth": 67, + "reach": 23 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 665, + "prev30": 765, + "pct": -13.071895424836603 + }, + "instanceOf": [ + { + "id": "Q2662845", + "label": "plant disease" + } + ] + }, + { + "pageId": 2806760, + "title": "Jess Harnell", + "description": "American voice actor and singer (born 1963)", + "wikidataId": "Q258503", + "revisionId": 1385958400, + "pageBytes": 53307, + "languageCount": 22, + "languagesTruncated": false, + "categories": [ + "1963 births", + "20th-century American male actors", + "20th-century American male singers", + "21st-century American male actors", + "21st-century American male singers", + "American announcers", + "American casting directors", + "American impressionists (entertainers)", + "American male film actors", + "American male radio actors", + "American male television actors", + "American male video game actors", + "American male voice actors", + "American rock singers", + "American voice directors", + "Audiobook narrators", + "Disney people", + "Living people", + "Male actors from Englewood, New Jersey", + "Male actors from Teaneck, New Jersey", + "Musicians from Englewood, New Jersey", + "Musicians from Teaneck, New Jersey" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 13061 + }, + { + "month": "2026-06", + "views": 12627 + }, + { + "month": "2026-07", + "views": 14539 + }, + { + "month": "2026-08", + "views": 14585 + }, + { + "month": "2026-09", + "views": 14785 + }, + { + "month": "2026-10", + "views": 14374 + } + ], + "latestMonth": "2026-10", + "total": 83971, + "dailyAverage": 463.6774193548387, + "trendPercent": -2.77984443692932 + }, + "stats": { + "attention": 69, + "depth": 79, + "reach": 45 + }, + "legacyCategory": "People", + "drift30": { + "last30": 14621, + "prev30": 13492, + "pct": 8.367921731396383 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 9026000, + "title": "Names of Poland", + "description": "", + "wikidataId": "Q6961536", + "revisionId": 1351068420, + "pageBytes": 18966, + "languageCount": 4, + "languagesTruncated": false, + "categories": [ + "Country name etymology", + "History of Poland", + "Polish language" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 2197 + }, + { + "month": "2026-06", + "views": 1797 + }, + { + "month": "2026-07", + "views": 1657 + }, + { + "month": "2026-08", + "views": 1500 + }, + { + "month": "2026-09", + "views": 1444 + }, + { + "month": "2026-10", + "views": 1431 + } + ], + "latestMonth": "2026-10", + "total": 10026, + "dailyAverage": 46.16129032258065, + "trendPercent": -0.9002770083102494 + }, + "stats": { + "attention": 53, + "depth": 71, + "reach": 23 + }, + "legacyCategory": "History", + "drift30": { + "last30": 1295, + "prev30": 1458, + "pct": -11.179698216735254 + }, + "instanceOf": [] + }, + { + "pageId": 15768716, + "title": "Ungersheim", + "description": "Commune in Grand Est, France", + "wikidataId": "Q122940", + "revisionId": 1382030873, + "pageBytes": 3450, + "languageCount": 39, + "languagesTruncated": false, + "categories": [ + "Communes of Haut-Rhin", + "Mulhouse arrondissement geography stubs" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 69 + }, + { + "month": "2026-06", + "views": 62 + }, + { + "month": "2026-07", + "views": 113 + }, + { + "month": "2026-08", + "views": 96 + }, + { + "month": "2026-09", + "views": 73 + }, + { + "month": "2026-10", + "views": 66 + } + ], + "latestMonth": "2026-10", + "total": 479, + "dailyAverage": 2.129032258064516, + "trendPercent": -9.58904109589041 + }, + "stats": { + "attention": 30, + "depth": 59, + "reach": 53 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 62, + "prev30": 64, + "pct": -3.125 + }, + "instanceOf": [ + { + "id": "Q484170", + "label": "commune of France" + } + ] + }, + { + "pageId": 38195538, + "title": "Joe Gideon & the Shark", + "description": "English blues/indie rock band", + "wikidataId": "Q3012108", + "revisionId": 1354427246, + "pageBytes": 2489, + "languageCount": 1, + "languagesTruncated": false, + "categories": [ + "British musical group stubs", + "English blues rock musical groups", + "Rock music groups from London" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 102 + }, + { + "month": "2026-06", + "views": 71 + }, + { + "month": "2026-07", + "views": 75 + }, + { + "month": "2026-08", + "views": 91 + }, + { + "month": "2026-09", + "views": 85 + }, + { + "month": "2026-10", + "views": 96 + } + ], + "latestMonth": "2026-10", + "total": 520, + "dailyAverage": 3.096774193548387, + "trendPercent": 12.941176470588237 + }, + "stats": { + "attention": 33, + "depth": 57, + "reach": 10 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 87, + "prev30": 88, + "pct": -1.1363636363636365 + }, + "instanceOf": [ + { + "id": "Q215380", + "label": "musical group" + } + ] + }, + { + "pageId": 39770094, + "title": "2013–14 California Golden Bears men's basketball team", + "description": "American college basketball season", + "wikidataId": "Q16245089", + "revisionId": 1376919282, + "pageBytes": 31778, + "languageCount": 0, + "languagesTruncated": false, + "categories": [ + "2013 in sports in California", + "2013–14 Pac-12 Conference men's basketball season", + "2014 National Invitation Tournament participants", + "2014 in sports in California", + "California Golden Bears men's basketball seasons" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 68 + }, + { + "month": "2026-06", + "views": 66 + }, + { + "month": "2026-07", + "views": 39 + }, + { + "month": "2026-08", + "views": 27 + }, + { + "month": "2026-09", + "views": 36 + }, + { + "month": "2026-10", + "views": 29 + } + ], + "latestMonth": "2026-10", + "total": 265, + "dailyAverage": 0.9354838709677419, + "trendPercent": -19.444444444444446 + }, + "stats": { + "attention": 25, + "depth": 75, + "reach": 0 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 29, + "prev30": 41, + "pct": -29.268292682926827 + }, + "instanceOf": [ + { + "id": "Q26894053", + "label": "basketball team season" + } + ] + }, + { + "pageId": 49830722, + "title": "Dicroidium odontopteroides", + "description": "Species of ancient plant", + "wikidataId": "Q25095289", + "revisionId": 1116073630, + "pageBytes": 1943, + "languageCount": 0, + "languagesTruncated": false, + "categories": [ + "Mesozoic plant stubs", + "Pteridospermatophyta", + "Triassic plants" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 41 + }, + { + "month": "2026-06", + "views": 82 + }, + { + "month": "2026-07", + "views": 52 + }, + { + "month": "2026-08", + "views": 69 + }, + { + "month": "2026-09", + "views": 56 + }, + { + "month": "2026-10", + "views": 59 + } + ], + "latestMonth": "2026-10", + "total": 359, + "dailyAverage": 1.903225806451613, + "trendPercent": 5.357142857142857 + }, + "stats": { + "attention": 30, + "depth": 55, + "reach": 0 + }, + "legacyCategory": "Nature", + "drift30": { + "last30": 42, + "prev30": 64, + "pct": -34.375 + }, + "instanceOf": [ + { + "id": "Q16521", + "label": "taxon" + } + ] + }, + { + "pageId": 52302489, + "title": "Pathrail Mosque", + "description": "Mosque in Faridpur, Bangladesh", + "wikidataId": "Q28173356", + "revisionId": 1380325251, + "pageBytes": 6701, + "languageCount": 3, + "languagesTruncated": false, + "categories": [ + "15th-century mosques in Bangladesh", + "Bengal Sultanate mosques", + "Faridpur District", + "Mosque buildings with domes in Bangladesh", + "Mosque buildings with minarets in Bangladesh", + "Mosques in Dhaka Division" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 117 + }, + { + "month": "2026-06", + "views": 100 + }, + { + "month": "2026-07", + "views": 100 + }, + { + "month": "2026-08", + "views": 98 + }, + { + "month": "2026-09", + "views": 81 + }, + { + "month": "2026-10", + "views": 71 + } + ], + "latestMonth": "2026-10", + "total": 567, + "dailyAverage": 2.2903225806451615, + "trendPercent": -12.345679012345679 + }, + "stats": { + "attention": 31, + "depth": 64, + "reach": 20 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 70, + "prev30": 69, + "pct": 1.4492753623188406 + }, + "instanceOf": [ + { + "id": "Q32815", + "label": "mosque" + } + ] + }, + { + "pageId": 1979500, + "title": "Zbyszek Godlewski", + "description": "Polish protester (1952–1970)", + "wikidataId": "Q3497070", + "revisionId": 1382599906, + "pageBytes": 6049, + "languageCount": 11, + "languagesTruncated": false, + "categories": [ + "1952 births", + "1970 deaths", + "Anti-communism in Poland", + "Deaths by firearm in Poland", + "Fictional characters based on real people", + "Legendary Polish people", + "Polish murder victims", + "Polish poems", + "Polish songs", + "Victims of human rights abuses" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 507 + }, + { + "month": "2026-06", + "views": 397 + }, + { + "month": "2026-07", + "views": 452 + }, + { + "month": "2026-08", + "views": 427 + }, + { + "month": "2026-09", + "views": 385 + }, + { + "month": "2026-10", + "views": 402 + } + ], + "latestMonth": "2026-10", + "total": 2570, + "dailyAverage": 12.96774193548387, + "trendPercent": 4.415584415584416 + }, + "stats": { + "attention": 43, + "depth": 63, + "reach": 36 + }, + "legacyCategory": "People", + "drift30": { + "last30": 451, + "prev30": 352, + "pct": 28.125 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 4426773, + "title": "Agda (programming language)", + "description": "Functional programming language", + "wikidataId": "Q20479", + "revisionId": 1384528612, + "pageBytes": 14254, + "languageCount": 11, + "languagesTruncated": false, + "categories": [ + "2007 software", + "Academic programming languages", + "Chalmers University of Technology", + "Cross-platform free software", + "Dependently typed languages", + "Extensible syntax programming languages", + "Free and open source compilers", + "Free software programmed in Haskell", + "Functional languages", + "Haskell programming language family", + "Pattern matching programming languages", + "Programming languages", + "Programming languages created in 2007", + "Proof assistants", + "Statically typed programming languages" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 2783 + }, + { + "month": "2026-06", + "views": 2318 + }, + { + "month": "2026-07", + "views": 2230 + }, + { + "month": "2026-08", + "views": 2257 + }, + { + "month": "2026-09", + "views": 2262 + }, + { + "month": "2026-10", + "views": 2439 + } + ], + "latestMonth": "2026-10", + "total": 14289, + "dailyAverage": 78.6774193548387, + "trendPercent": 7.824933687002653 + }, + "stats": { + "attention": 56, + "depth": 69, + "reach": 36 + }, + "legacyCategory": "Science", + "drift30": { + "last30": 2310, + "prev30": 2299, + "pct": 0.4784688995215311 + }, + "instanceOf": [ + { + "id": "Q3839507", + "label": "functional programming language" + }, + { + "id": "Q28920201", + "label": "purely functional programming language" + }, + { + "id": "Q56223375", + "label": "dependently typed programming language" + }, + { + "id": "Q9143", + "label": "programming language" + }, + { + "id": "Q341", + "label": "free software" + }, + { + "id": "Q11387554", + "label": "proof assistant" + } + ] + }, + { + "pageId": 4674437, + "title": "Topusko", + "description": "Commune in Sisak-Moslavina County, Croatia", + "wikidataId": "Q2457438", + "revisionId": 1384106265, + "pageBytes": 13847, + "languageCount": 23, + "languagesTruncated": false, + "categories": [ + "Hot springs of Croatia", + "Municipalities of Croatia", + "Populated places in Sisak-Moslavina County", + "Spa towns in Croatia", + "Zagreb County (former)" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 649 + }, + { + "month": "2026-06", + "views": 331 + }, + { + "month": "2026-07", + "views": 303 + }, + { + "month": "2026-08", + "views": 372 + }, + { + "month": "2026-09", + "views": 289 + }, + { + "month": "2026-10", + "views": 302 + } + ], + "latestMonth": "2026-10", + "total": 2246, + "dailyAverage": 9.741935483870968, + "trendPercent": 4.498269896193772 + }, + "stats": { + "attention": 41, + "depth": 69, + "reach": 46 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 297, + "prev30": 257, + "pct": 15.56420233463035 + }, + "instanceOf": [ + { + "id": "Q57058", + "label": "municipality of Croatia" + } + ] + }, + { + "pageId": 5096391, + "title": "Isabella of Aragon, Queen of Portugal", + "description": "Queen of Portugal from 1497 to 1498", + "wikidataId": "Q466305", + "revisionId": 1376332037, + "pageBytes": 14306, + "languageCount": 43, + "languagesTruncated": false, + "categories": [ + "1470 births", + "1498 deaths", + "15th-century Portuguese people", + "15th-century Portuguese women", + "15th-century Spanish people", + "15th-century Spanish women", + "Aragonese infantas", + "Castilian infantas", + "Children of Ferdinand II of Aragon", + "Children of Isabella I of Castile", + "Daughters of counts", + "Daughters of kings", + "Daughters of queens regnant", + "Deaths in childbirth", + "Heirs presumptive", + "House of Aviz", + "House of Trastámara", + "Princes of Asturias", + "Princesses of Portugal", + "Queens consort of Portugal", + "Spanish Roman Catholics", + "Spanish expatriate royalty", + "Spanish people of English descent", + "Spanish people of French descent", + "Spanish people of Italian descent", + "Spanish people of Portuguese descent" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 7082 + }, + { + "month": "2026-06", + "views": 6550 + }, + { + "month": "2026-07", + "views": 7514 + }, + { + "month": "2026-08", + "views": 7636 + }, + { + "month": "2026-09", + "views": 6506 + }, + { + "month": "2026-10", + "views": 6358 + } + ], + "latestMonth": "2026-10", + "total": 41646, + "dailyAverage": 205.09677419354838, + "trendPercent": -2.2748232400860746 + }, + "stats": { + "attention": 63, + "depth": 69, + "reach": 55 + }, + "legacyCategory": "People", + "drift30": { + "last30": 5553, + "prev30": 6384, + "pct": -13.016917293233082 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 15915366, + "title": "Montjavoult", + "description": "Commune in Hauts-de-France, France", + "wikidataId": "Q1336846", + "revisionId": 1381946137, + "pageBytes": 1584, + "languageCount": 36, + "languagesTruncated": false, + "categories": [ + "Beauvais arrondissement geography stubs", + "Communes of Oise" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 33 + }, + { + "month": "2026-06", + "views": 20 + }, + { + "month": "2026-07", + "views": 29 + }, + { + "month": "2026-08", + "views": 57 + }, + { + "month": "2026-09", + "views": 44 + }, + { + "month": "2026-10", + "views": 10 + } + ], + "latestMonth": "2026-10", + "total": 193, + "dailyAverage": 0.3225806451612903, + "trendPercent": -77.27272727272727 + }, + "stats": { + "attention": 17, + "depth": 53, + "reach": 52 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 12, + "prev30": 17, + "pct": -29.411764705882355 + }, + "instanceOf": [ + { + "id": "Q484170", + "label": "commune of France" + } + ] + }, + { + "pageId": 15963682, + "title": "Viktor Genev", + "description": "Bulgarian footballer", + "wikidataId": "Q2604995", + "revisionId": 1384826851, + "pageBytes": 13767, + "languageCount": 13, + "languagesTruncated": false, + "categories": [ + "1988 births", + "21st-century Bulgarian sportsmen", + "Botev Plovdiv players", + "Bulgarian expatriate men's footballers", + "Bulgarian expatriate sportspeople in Israel", + "Bulgarian expatriate sportspeople in Kazakhstan", + "Bulgarian expatriate sportspeople in Romania", + "Bulgarian expatriate sportspeople in Russia", + "Bulgarian expatriate sportspeople in Scotland", + "Bulgarian expatriate sportspeople in Ukraine", + "Bulgarian men's footballers", + "Expatriate men's footballers in Belarus", + "Expatriate men's footballers in Israel", + "Expatriate men's footballers in Kazakhstan", + "Expatriate men's footballers in Russia", + "Expatriate men's footballers in Scotland", + "Expatriate men's footballers in Ukraine", + "F.C. Ashdod players", + "FC Dinamo Minsk players", + "FC Montana players", + "FC Oleksandriya players", + "FC Petrolul Ploiești players", + "FC Rilski Sportist Samokov players", + "FC Yelimay players", + "First Professional Football League (Bulgaria) players", + "Footballers from Sofia", + "Israeli Premier League players", + "Kazakhstan Premier League players", + "Liga I players", + "Living people", + "Men's association football defenders", + "PFC Beroe Stara Zagora players", + "PFC Cherno More Varna players", + "PFC Krylia Sovetov Samara players", + "PFC Levski Sofia players", + "PFC Slavia Sofia players", + "Russian Premier League players", + "St Mirren F.C. players", + "Ukrainian Premier League players" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 123 + }, + { + "month": "2026-06", + "views": 65 + }, + { + "month": "2026-07", + "views": 61 + }, + { + "month": "2026-08", + "views": 80 + }, + { + "month": "2026-09", + "views": 74 + }, + { + "month": "2026-10", + "views": 93 + } + ], + "latestMonth": "2026-10", + "total": 496, + "dailyAverage": 3.0, + "trendPercent": 25.675675675675674 + }, + "stats": { + "attention": 33, + "depth": 69, + "reach": 38 + }, + "legacyCategory": "People", + "drift30": { + "last30": 98, + "prev30": 69, + "pct": 42.028985507246375 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 28025187, + "title": "Pühajõe", + "description": "Village in Estonia", + "wikidataId": "Q179358", + "revisionId": 1377386321, + "pageBytes": 1880, + "languageCount": 11, + "languagesTruncated": false, + "categories": [ + "Ida-Viru County geography stubs", + "Toila Parish", + "Villages in Ida-Viru County", + "Wierland County" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 31 + }, + { + "month": "2026-06", + "views": 24 + }, + { + "month": "2026-07", + "views": 30 + }, + { + "month": "2026-08", + "views": 58 + }, + { + "month": "2026-09", + "views": 41 + }, + { + "month": "2026-10", + "views": 16 + } + ], + "latestMonth": "2026-10", + "total": 200, + "dailyAverage": 0.5161290322580645, + "trendPercent": -60.97560975609756 + }, + "stats": { + "attention": 21, + "depth": 55, + "reach": 36 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 22, + "prev30": 23, + "pct": -4.3478260869565215 + }, + "instanceOf": [ + { + "id": "Q51049922", + "label": "village" + } + ] + }, + { + "pageId": 49116132, + "title": "Kalihati", + "description": "Town in Dhaka Division, Bangladesh", + "wikidataId": "Q22348003", + "revisionId": 1376271314, + "pageBytes": 4406, + "languageCount": 3, + "languagesTruncated": false, + "categories": [ + "Dhaka Division geography stubs", + "Populated places in Tangail District", + "Towns in Bangladesh" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 72 + }, + { + "month": "2026-06", + "views": 53 + }, + { + "month": "2026-07", + "views": 59 + }, + { + "month": "2026-08", + "views": 79 + }, + { + "month": "2026-09", + "views": 78 + }, + { + "month": "2026-10", + "views": 37 + } + ], + "latestMonth": "2026-10", + "total": 378, + "dailyAverage": 1.1935483870967742, + "trendPercent": -52.56410256410257 + }, + "stats": { + "attention": 26, + "depth": 61, + "reach": 20 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 42, + "prev30": 45, + "pct": -6.666666666666667 + }, + "instanceOf": [ + { + "id": "Q23759397", + "label": "municipality of Bangladesh" + }, + { + "id": "Q3957", + "label": "town" + } + ] + }, + { + "pageId": 49444193, + "title": "Miloje Vasić", + "description": "Serbian archaeologist (1869–1956)", + "wikidataId": "Q3314419", + "revisionId": 1371976132, + "pageBytes": 22470, + "languageCount": 11, + "languagesTruncated": false, + "categories": [ + "1869 births", + "1956 deaths", + "20th-century Serbian people", + "Members of the Serbian Academy of Sciences and Arts", + "People from Veliko Gradište", + "People from the Kingdom of Serbia", + "Serbian archaeologists", + "University of Belgrade people", + "Yugoslav archaeologists" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 208 + }, + { + "month": "2026-06", + "views": 145 + }, + { + "month": "2026-07", + "views": 162 + }, + { + "month": "2026-08", + "views": 191 + }, + { + "month": "2026-09", + "views": 197 + }, + { + "month": "2026-10", + "views": 128 + } + ], + "latestMonth": "2026-10", + "total": 1031, + "dailyAverage": 4.129032258064516, + "trendPercent": -35.025380710659896 + }, + "stats": { + "attention": 35, + "depth": 73, + "reach": 36 + }, + "legacyCategory": "People", + "drift30": { + "last30": 104, + "prev30": 180, + "pct": -42.22222222222222 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 110015, + "title": "Haralson, Georgia", + "description": "Town in Georgia, United States", + "wikidataId": "Q2520618", + "revisionId": 1377786275, + "pageBytes": 8736, + "languageCount": 26, + "languagesTruncated": false, + "categories": [ + "Towns in Coweta County, Georgia", + "Towns in Georgia (U.S. state)", + "Towns in Meriwether County, Georgia" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 182 + }, + { + "month": "2026-06", + "views": 145 + }, + { + "month": "2026-07", + "views": 142 + }, + { + "month": "2026-08", + "views": 214 + }, + { + "month": "2026-09", + "views": 168 + }, + { + "month": "2026-10", + "views": 137 + } + ], + "latestMonth": "2026-10", + "total": 988, + "dailyAverage": 4.419354838709677, + "trendPercent": -18.452380952380953 + }, + "stats": { + "attention": 36, + "depth": 66, + "reach": 48 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 138, + "prev30": 152, + "pct": -9.210526315789473 + }, + "instanceOf": [ + { + "id": "Q15127012", + "label": "town in the United States" + }, + { + "id": "Q76514543", + "label": "municipality of Georgia" + } + ] + }, + { + "pageId": 11240525, + "title": "Joseph Ujlaki", + "description": "French-Hungarian footballer (1929-2006)", + "wikidataId": "Q905343", + "revisionId": 1382620781, + "pageBytes": 3449, + "languageCount": 14, + "languagesTruncated": false, + "categories": [ + "1929 births", + "2006 deaths", + "20th-century French sportsmen", + "20th-century Hungarian sportsmen", + "AS Aix-en-Provence players", + "FC Metz players", + "Footballers from Budapest", + "France men's international footballers", + "French football forward stubs", + "French men's footballers", + "French people of Hungarian descent", + "Hungarian men's footballers", + "Ligue 1 players", + "Men's association football forwards", + "Naturalized citizens of France", + "Nîmes Olympique players", + "OGC Nice players", + "Racing Club de France Football players", + "SC Sète players", + "Stade Français (association football) players" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 188 + }, + { + "month": "2026-06", + "views": 242 + }, + { + "month": "2026-07", + "views": 327 + }, + { + "month": "2026-08", + "views": 211 + }, + { + "month": "2026-09", + "views": 148 + }, + { + "month": "2026-10", + "views": 163 + } + ], + "latestMonth": "2026-10", + "total": 1279, + "dailyAverage": 5.258064516129032, + "trendPercent": 10.135135135135135 + }, + "stats": { + "attention": 37, + "depth": 59, + "reach": 39 + }, + "legacyCategory": "People", + "drift30": { + "last30": 159, + "prev30": 118, + "pct": 34.74576271186441 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 23256692, + "title": "Coelogyne trinervis", + "description": "Species of orchid", + "wikidataId": "Q1601035", + "revisionId": 1176682009, + "pageBytes": 1580, + "languageCount": 7, + "languagesTruncated": false, + "categories": [ + "Coelogyne", + "Epidendroideae stubs" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 30 + }, + { + "month": "2026-06", + "views": 18 + }, + { + "month": "2026-07", + "views": 27 + }, + { + "month": "2026-08", + "views": 36 + }, + { + "month": "2026-09", + "views": 42 + }, + { + "month": "2026-10", + "views": 24 + } + ], + "latestMonth": "2026-10", + "total": 177, + "dailyAverage": 0.7741935483870968, + "trendPercent": -42.857142857142854 + }, + "stats": { + "attention": 23, + "depth": 53, + "reach": 30 + }, + "legacyCategory": "Nature", + "drift30": { + "last30": 28, + "prev30": 34, + "pct": -17.647058823529413 + }, + "instanceOf": [ + { + "id": "Q16521", + "label": "taxon" + }, + { + "id": "Q188238", + "label": "epiphyte" + } + ] + }, + { + "pageId": 30886907, + "title": "Pine River (Manistee River tributary)", + "description": "River in Michigan, United States", + "wikidataId": "Q7195337", + "revisionId": 1367824379, + "pageBytes": 4768, + "languageCount": 1, + "languagesTruncated": false, + "categories": [ + "Manistee River", + "Michigan river stubs", + "Rivers of Lake County, Michigan", + "Rivers of Manistee County, Michigan", + "Rivers of Michigan", + "Rivers of Osceola County, Michigan", + "Rivers of Wexford County, Michigan", + "Wild and Scenic Rivers of the United States" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 208 + }, + { + "month": "2026-06", + "views": 218 + }, + { + "month": "2026-07", + "views": 301 + }, + { + "month": "2026-08", + "views": 277 + }, + { + "month": "2026-09", + "views": 151 + }, + { + "month": "2026-10", + "views": 115 + } + ], + "latestMonth": "2026-10", + "total": 1270, + "dailyAverage": 3.7096774193548385, + "trendPercent": -23.841059602649008 + }, + "stats": { + "attention": 34, + "depth": 61, + "reach": 10 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 91, + "prev30": 131, + "pct": -30.53435114503817 + }, + "instanceOf": [ + { + "id": "Q4022", + "label": "river" + } + ] + }, + { + "pageId": 62190512, + "title": "Nguyễn Văn Huy", + "description": "Vietnamese chess grandmaster (born 1985)", + "wikidataId": "Q20026028", + "revisionId": 1377313379, + "pageBytes": 3624, + "languageCount": 3, + "languagesTruncated": false, + "categories": [ + "1985 births", + "21st-century Vietnamese chess players", + "21st-century Vietnamese sportsmen", + "Asian chess biography stubs", + "Chess Grandmasters", + "Chess Olympiad competitors", + "Living people", + "People from Bắc Ninh", + "Vietnamese chess players", + "Vietnamese sportspeople stubs" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 50 + }, + { + "month": "2026-06", + "views": 42 + }, + { + "month": "2026-07", + "views": 30 + }, + { + "month": "2026-08", + "views": 36 + }, + { + "month": "2026-09", + "views": 62 + }, + { + "month": "2026-10", + "views": 71 + } + ], + "latestMonth": "2026-10", + "total": 291, + "dailyAverage": 2.2903225806451615, + "trendPercent": 14.516129032258066 + }, + "stats": { + "attention": 31, + "depth": 59, + "reach": 20 + }, + "legacyCategory": "People", + "drift30": { + "last30": 56, + "prev30": 68, + "pct": -17.647058823529413 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 64406081, + "title": "San Wai (San Tin)", + "description": null, + "wikidataId": "Q96739151", + "revisionId": 1280859035, + "pageBytes": 6034, + "languageCount": 1, + "languagesTruncated": false, + "categories": [ + "San Tin", + "Villages in Yuen Long District, Hong Kong", + "Yuen Long District geography stubs" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 24 + }, + { + "month": "2026-06", + "views": 17 + }, + { + "month": "2026-07", + "views": 14 + }, + { + "month": "2026-08", + "views": 17 + }, + { + "month": "2026-09", + "views": 21 + }, + { + "month": "2026-10", + "views": 27 + } + ], + "latestMonth": "2026-10", + "total": 120, + "dailyAverage": 0.8709677419354839, + "trendPercent": 28.57142857142857 + }, + "stats": { + "attention": 24, + "depth": 63, + "reach": 10 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 28, + "prev30": 21, + "pct": 33.33333333333333 + }, + "instanceOf": [ + { + "id": "Q532", + "label": "village" + } + ] + }, + { + "pageId": 65287105, + "title": "Kishore Tirumala", + "description": "Indian film director", + "wikidataId": "Q93762585", + "revisionId": 1376673468, + "pageBytes": 6604, + "languageCount": 2, + "languagesTruncated": false, + "categories": [ + "Film directors from Andhra Pradesh", + "Film people from Andhra Pradesh", + "Indian film director stubs", + "Indian film directors", + "Indian screenwriters", + "Living people", + "People from Andhra Pradesh", + "People from Chittoor district", + "People from Tirupati", + "Screenwriters from Andhra Pradesh", + "Telugu film directors" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 2548 + }, + { + "month": "2026-06", + "views": 2543 + }, + { + "month": "2026-07", + "views": 2500 + }, + { + "month": "2026-08", + "views": 4416 + }, + { + "month": "2026-09", + "views": 3484 + }, + { + "month": "2026-10", + "views": 2283 + } + ], + "latestMonth": "2026-10", + "total": 17774, + "dailyAverage": 73.64516129032258, + "trendPercent": -34.47187141216992 + }, + "stats": { + "attention": 56, + "depth": 64, + "reach": 16 + }, + "legacyCategory": "People", + "drift30": { + "last30": 1793, + "prev30": 2984, + "pct": -39.91286863270778 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 81307395, + "title": "2025 Tehreek-e-Labbaik Pakistan protests", + "description": "Gaza war protests in Pakistan", + "wikidataId": "Q136649814", + "revisionId": 1378554406, + "pageBytes": 20919, + "languageCount": 1, + "languagesTruncated": false, + "categories": [ + "2020s in Islamabad", + "2020s in Lahore", + "2025 in Punjab, Pakistan", + "2025 protests", + "21st century in Faisalabad", + "Anti-Israeli sentiment in Pakistan", + "Gaza war protests", + "October 2025 in Pakistan", + "Protest marches in Pakistan", + "Protests in Pakistan", + "Riots and civil disorder in Pakistan", + "Tehreek-e-Labbaik Pakistan" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 686 + }, + { + "month": "2026-06", + "views": 986 + }, + { + "month": "2026-07", + "views": 782 + }, + { + "month": "2026-08", + "views": 629 + }, + { + "month": "2026-09", + "views": 735 + }, + { + "month": "2026-10", + "views": 618 + } + ], + "latestMonth": "2026-10", + "total": 4436, + "dailyAverage": 19.93548387096774, + "trendPercent": -15.918367346938775 + }, + "stats": { + "attention": 47, + "depth": 72, + "reach": 10 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 318, + "prev30": 771, + "pct": -58.754863813229576 + }, + "instanceOf": [ + { + "id": "Q273120", + "label": "protest" + } + ] + }, + { + "pageId": 902446, + "title": "Guidimaka region", + "description": "Region of Mauritania", + "wikidataId": "Q768119", + "revisionId": 1378970556, + "pageBytes": 13210, + "languageCount": 32, + "languagesTruncated": false, + "categories": [ + "Guidimaka region", + "Regions of Mauritania" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 207 + }, + { + "month": "2026-06", + "views": 140 + }, + { + "month": "2026-07", + "views": 124 + }, + { + "month": "2026-08", + "views": 154 + }, + { + "month": "2026-09", + "views": 149 + }, + { + "month": "2026-10", + "views": 123 + } + ], + "latestMonth": "2026-10", + "total": 897, + "dailyAverage": 3.967741935483871, + "trendPercent": -17.449664429530202 + }, + "stats": { + "attention": 35, + "depth": 69, + "reach": 51 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 123, + "prev30": 143, + "pct": -13.986013986013987 + }, + "instanceOf": [ + { + "id": "Q846327", + "label": "region of Mauritania" + } + ] + }, + { + "pageId": 1374812, + "title": "Tom Ewell", + "description": "American actor (1909–1994)", + "wikidataId": "Q427388", + "revisionId": 1381663979, + "pageBytes": 17965, + "languageCount": 30, + "languagesTruncated": false, + "categories": [ + "1909 births", + "1994 deaths", + "20th-century American male actors", + "American male film actors", + "American male stage actors", + "American male television actors", + "Best Musical or Comedy Actor Golden Globe (film) winners", + "Clarence Derwent Award winners", + "Donaldson Award winners", + "Male actors from Kentucky", + "People from Owensboro, Kentucky", + "Tony Award winners", + "United States Navy personnel of World War II", + "United States Navy sailors" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 5239 + }, + { + "month": "2026-06", + "views": 13927 + }, + { + "month": "2026-07", + "views": 5978 + }, + { + "month": "2026-08", + "views": 5693 + }, + { + "month": "2026-09", + "views": 5668 + }, + { + "month": "2026-10", + "views": 4548 + } + ], + "latestMonth": "2026-10", + "total": 41053, + "dailyAverage": 146.70967741935485, + "trendPercent": -19.760056457304167 + }, + "stats": { + "attention": 61, + "depth": 71, + "reach": 50 + }, + "legacyCategory": "People", + "drift30": { + "last30": 4027, + "prev30": 4518, + "pct": -10.86764054891545 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 15362336, + "title": "1954 Gold Coast general election", + "description": "", + "wikidataId": "Q2539674", + "revisionId": 1351181171, + "pageBytes": 4141, + "languageCount": 2, + "languagesTruncated": false, + "categories": [ + "1954 elections in Africa", + "1954 elections in the British Empire", + "1954 in the Gold Coast (British colony)", + "Parliamentary elections in Ghana" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 592 + }, + { + "month": "2026-06", + "views": 512 + }, + { + "month": "2026-07", + "views": 407 + }, + { + "month": "2026-08", + "views": 219 + }, + { + "month": "2026-09", + "views": 202 + }, + { + "month": "2026-10", + "views": 181 + } + ], + "latestMonth": "2026-10", + "total": 2113, + "dailyAverage": 5.838709677419355, + "trendPercent": -10.396039603960396 + }, + "stats": { + "attention": 38, + "depth": 60, + "reach": 16 + }, + "legacyCategory": "History", + "drift30": { + "last30": 196, + "prev30": 167, + "pct": 17.365269461077844 + }, + "instanceOf": [ + { + "id": "Q2618461", + "label": "legislative election" + } + ] + }, + { + "pageId": 23242983, + "title": "Larry Weber", + "description": "American entrepreneur", + "wikidataId": "Q6491266", + "revisionId": 1351414373, + "pageBytes": 12852, + "languageCount": 2, + "languagesTruncated": false, + "categories": [ + "1955 births", + "American business writers", + "Living people", + "Writers from Ohio" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 230 + }, + { + "month": "2026-06", + "views": 184 + }, + { + "month": "2026-07", + "views": 160 + }, + { + "month": "2026-08", + "views": 167 + }, + { + "month": "2026-09", + "views": 158 + }, + { + "month": "2026-10", + "views": 188 + } + ], + "latestMonth": "2026-10", + "total": 1087, + "dailyAverage": 6.064516129032258, + "trendPercent": 18.9873417721519 + }, + "stats": { + "attention": 38, + "depth": 68, + "reach": 16 + }, + "legacyCategory": "People", + "drift30": { + "last30": 161, + "prev30": 186, + "pct": -13.440860215053762 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 49648409, + "title": "Ulla! min Ulla! Säj får jag dig bjuda", + "description": "Song by the 18th century Swedish bard Carl Michael Bellman", + "wikidataId": "Q19528685", + "revisionId": 1344963259, + "pageBytes": 17244, + "languageCount": 1, + "languagesTruncated": false, + "categories": [ + "1790 compositions", + "Fredmans epistlar", + "Swedish songs" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 79 + }, + { + "month": "2026-06", + "views": 48 + }, + { + "month": "2026-07", + "views": 17 + }, + { + "month": "2026-08", + "views": 47 + }, + { + "month": "2026-09", + "views": 53 + }, + { + "month": "2026-10", + "views": 34 + } + ], + "latestMonth": "2026-10", + "total": 278, + "dailyAverage": 1.096774193548387, + "trendPercent": -35.84905660377358 + }, + "stats": { + "attention": 26, + "depth": 71, + "reach": 10 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 33, + "prev30": 43, + "pct": -23.25581395348837 + }, + "instanceOf": [ + { + "id": "Q105543609", + "label": "musical work/composition" + } + ] + }, + { + "pageId": 84332185, + "title": "Oscar González Oro", + "description": "Argentine journalist and radio host (1951–2026)", + "wikidataId": "Q6053873", + "revisionId": 1378056768, + "pageBytes": 3281, + "languageCount": 1, + "languagesTruncated": false, + "categories": [ + "1951 births", + "2026 deaths", + "20th-century Argentine journalists", + "21st-century Argentine journalists", + "Argentine LGBTQ broadcasters" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 0 + }, + { + "month": "2026-06", + "views": 0 + }, + { + "month": "2026-07", + "views": 0 + }, + { + "month": "2026-08", + "views": 0 + }, + { + "month": "2026-09", + "views": 1401 + }, + { + "month": "2026-10", + "views": 188 + } + ], + "latestMonth": "2026-10", + "total": 1589, + "dailyAverage": 6.064516129032258, + "trendPercent": -86.58101356174161 + }, + "stats": { + "attention": 38, + "depth": 59, + "reach": 10 + }, + "legacyCategory": "People", + "drift30": { + "last30": 81, + "prev30": 1520, + "pct": -94.67105263157895 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 2385264, + "title": "Ofanto", + "description": "River in Italy", + "wikidataId": "Q841550", + "revisionId": 1334637363, + "pageBytes": 5049, + "languageCount": 29, + "languagesTruncated": false, + "categories": [ + "Adriatic Italian coast basins", + "Apulia geography stubs", + "Basilicata geography stubs", + "Italy river stubs", + "Province of Avellino geography stubs", + "Rivers of Italy", + "Rivers of the Province of Avellino", + "Rivers of the Province of Barletta-Andria-Trani", + "Rivers of the Province of Foggia", + "Rivers of the Province of Potenza" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 291 + }, + { + "month": "2026-06", + "views": 238 + }, + { + "month": "2026-07", + "views": 220 + }, + { + "month": "2026-08", + "views": 256 + }, + { + "month": "2026-09", + "views": 210 + }, + { + "month": "2026-10", + "views": 223 + } + ], + "latestMonth": "2026-10", + "total": 1438, + "dailyAverage": 7.193548387096774, + "trendPercent": 6.190476190476191 + }, + "stats": { + "attention": 39, + "depth": 62, + "reach": 49 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 213, + "prev30": 194, + "pct": 9.793814432989691 + }, + "instanceOf": [ + { + "id": "Q4022", + "label": "river" + } + ] + }, + { + "pageId": 7674700, + "title": "Shipley Plateau", + "description": "Place in the Blue Mountains, Australia", + "wikidataId": "Q7498025", + "revisionId": 1384061257, + "pageBytes": 1745, + "languageCount": 1, + "languagesTruncated": false, + "categories": [ + "Geography of the Blue Mountains (New South Wales)", + "New South Wales geography stubs", + "Plateaus of Australia" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 48 + }, + { + "month": "2026-06", + "views": 24 + }, + { + "month": "2026-07", + "views": 33 + }, + { + "month": "2026-08", + "views": 54 + }, + { + "month": "2026-09", + "views": 49 + }, + { + "month": "2026-10", + "views": 22 + } + ], + "latestMonth": "2026-10", + "total": 230, + "dailyAverage": 0.7096774193548387, + "trendPercent": -55.10204081632652 + }, + "stats": { + "attention": 23, + "depth": 54, + "reach": 10 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 18, + "prev30": 40, + "pct": -55.00000000000001 + }, + "instanceOf": [ + { + "id": "Q75520", + "label": "plateau" + } + ] + }, + { + "pageId": 21016492, + "title": "Xiancantan", + "description": null, + "wikidataId": "Q434483", + "revisionId": 1363646521, + "pageBytes": 1731, + "languageCount": 7, + "languagesTruncated": false, + "categories": [ + "1740s establishments in China", + "1742 establishments in Asia", + "Religious buildings and structures in Beijing" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 155 + }, + { + "month": "2026-06", + "views": 87 + }, + { + "month": "2026-07", + "views": 67 + }, + { + "month": "2026-08", + "views": 88 + }, + { + "month": "2026-09", + "views": 86 + }, + { + "month": "2026-10", + "views": 85 + } + ], + "latestMonth": "2026-10", + "total": 568, + "dailyAverage": 2.7419354838709675, + "trendPercent": -1.1627906976744187 + }, + "stats": { + "attention": 32, + "depth": 54, + "reach": 30 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 83, + "prev30": 86, + "pct": -3.488372093023256 + }, + "instanceOf": [ + { + "id": "Q41176", + "label": "building" + } + ] + }, + { + "pageId": 51796741, + "title": "Alex Piquero", + "description": "Cuban-American criminologist (born 1970)", + "wikidataId": "Q27058048", + "revisionId": 1356084913, + "pageBytes": 7837, + "languageCount": 0, + "languagesTruncated": false, + "categories": [ + "1970 births", + "American academic journal editors", + "American criminologists", + "American sociologist stubs", + "Criminologist stubs", + "Cuban emigrants to the United States", + "Living people", + "University of Maryland, College Park alumni", + "University of Miami faculty", + "University of Texas at Dallas faculty" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 239 + }, + { + "month": "2026-06", + "views": 152 + }, + { + "month": "2026-07", + "views": 150 + }, + { + "month": "2026-08", + "views": 154 + }, + { + "month": "2026-09", + "views": 308 + }, + { + "month": "2026-10", + "views": 151 + } + ], + "latestMonth": "2026-10", + "total": 1154, + "dailyAverage": 4.870967741935484, + "trendPercent": -50.97402597402597 + }, + "stats": { + "attention": 36, + "depth": 65, + "reach": 0 + }, + "legacyCategory": "People", + "drift30": { + "last30": 117, + "prev30": 269, + "pct": -56.50557620817844 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 1587861, + "title": "Vélez-Málaga", + "description": "Place in Málaga, Spain", + "wikidataId": "Q492741", + "revisionId": 1382422731, + "pageBytes": 30172, + "languageCount": 56, + "languagesTruncated": false, + "categories": [ + "Municipalities in the Province of Málaga" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 1271 + }, + { + "month": "2026-06", + "views": 1491 + }, + { + "month": "2026-07", + "views": 1606 + }, + { + "month": "2026-08", + "views": 1442 + }, + { + "month": "2026-09", + "views": 1586 + }, + { + "month": "2026-10", + "views": 1033 + } + ], + "latestMonth": "2026-10", + "total": 8429, + "dailyAverage": 33.32258064516129, + "trendPercent": -34.867591424968474 + }, + "stats": { + "attention": 50, + "depth": 75, + "reach": 59 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 989, + "prev30": 1051, + "pct": -5.899143672692674 + }, + "instanceOf": [ + { + "id": "Q2074737", + "label": "municipality of Spain" + } + ] + }, + { + "pageId": 4289899, + "title": "Anthodon (reptile)", + "description": "Extinct genus of reptiles", + "wikidataId": "Q2505064", + "revisionId": 1384682008, + "pageBytes": 9037, + "languageCount": 12, + "languagesTruncated": false, + "categories": [ + "Changhsingian life", + "Fossil taxa described in 1876", + "Lopingian reptiles of Africa", + "Pareiasauria", + "Prehistoric reptile genera", + "Taxa named by Richard Owen" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 244 + }, + { + "month": "2026-06", + "views": 244 + }, + { + "month": "2026-07", + "views": 229 + }, + { + "month": "2026-08", + "views": 270 + }, + { + "month": "2026-09", + "views": 254 + }, + { + "month": "2026-10", + "views": 233 + } + ], + "latestMonth": "2026-10", + "total": 1474, + "dailyAverage": 7.516129032258065, + "trendPercent": -8.267716535433072 + }, + "stats": { + "attention": 39, + "depth": 66, + "reach": 37 + }, + "legacyCategory": "Nature", + "drift30": { + "last30": 198, + "prev30": 243, + "pct": -18.51851851851852 + }, + "instanceOf": [ + { + "id": "Q47487597", + "label": "monotypic fossil taxon" + } + ] + }, + { + "pageId": 17506241, + "title": "Marion Thees", + "description": "German skeleton racer", + "wikidataId": "Q72724", + "revisionId": 1361257647, + "pageBytes": 3061, + "languageCount": 11, + "languagesTruncated": false, + "categories": [ + "1984 births", + "21st-century German sportswomen", + "German female skeleton racers", + "German winter sports biography stubs", + "Living people", + "Olympic skeleton racers for Germany", + "Skeleton racers at the 2010 Winter Olympics", + "Skeleton racers at the 2014 Winter Olympics", + "Skeleton racing biography stubs", + "Sportspeople from Eisenach" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 58 + }, + { + "month": "2026-06", + "views": 57 + }, + { + "month": "2026-07", + "views": 63 + }, + { + "month": "2026-08", + "views": 63 + }, + { + "month": "2026-09", + "views": 52 + }, + { + "month": "2026-10", + "views": 53 + } + ], + "latestMonth": "2026-10", + "total": 346, + "dailyAverage": 1.7096774193548387, + "trendPercent": 1.9230769230769231 + }, + "stats": { + "attention": 29, + "depth": 58, + "reach": 36 + }, + "legacyCategory": "People", + "drift30": { + "last30": 49, + "prev30": 55, + "pct": -10.909090909090908 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 20701320, + "title": "Horse Feathers (band)", + "description": "American indie folk band", + "wikidataId": "Q5905442", + "revisionId": 1385997032, + "pageBytes": 6636, + "languageCount": 2, + "languagesTruncated": false, + "categories": [ + "2004 establishments in Oregon", + "American folk rock groups", + "American indie folk groups", + "Indie rock musical groups from Oregon", + "Kill Rock Stars artists", + "Musical groups established in 2004", + "Musical groups from Portland, Oregon" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 287 + }, + { + "month": "2026-06", + "views": 365 + }, + { + "month": "2026-07", + "views": 416 + }, + { + "month": "2026-08", + "views": 753 + }, + { + "month": "2026-09", + "views": 648 + }, + { + "month": "2026-10", + "views": 263 + } + ], + "latestMonth": "2026-10", + "total": 2732, + "dailyAverage": 8.483870967741936, + "trendPercent": -59.413580246913575 + }, + "stats": { + "attention": 40, + "depth": 64, + "reach": 16 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 264, + "prev30": 461, + "pct": -42.73318872017354 + }, + "instanceOf": [ + { + "id": "Q215380", + "label": "musical group" + } + ] + }, + { + "pageId": 47784502, + "title": "Christian Zübert", + "description": "German film director and screenwriter (born 1973)", + "wikidataId": "Q1082448", + "revisionId": 1375411209, + "pageBytes": 8086, + "languageCount": 5, + "languagesTruncated": false, + "categories": [ + "1973 births", + "Film directors from Würzburg", + "German male television writers", + "German screenwriters", + "German television writers", + "Living people" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 152 + }, + { + "month": "2026-06", + "views": 211 + }, + { + "month": "2026-07", + "views": 99 + }, + { + "month": "2026-08", + "views": 134 + }, + { + "month": "2026-09", + "views": 104 + }, + { + "month": "2026-10", + "views": 76 + } + ], + "latestMonth": "2026-10", + "total": 776, + "dailyAverage": 2.4516129032258065, + "trendPercent": -26.923076923076923 + }, + "stats": { + "attention": 31, + "depth": 65, + "reach": 26 + }, + "legacyCategory": "People", + "drift30": { + "last30": 75, + "prev30": 82, + "pct": -8.536585365853659 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 64423476, + "title": "2023 Seville municipal election", + "description": "Election in the Spanish municipality of Seville", + "wikidataId": "Q97188845", + "revisionId": 1377264425, + "pageBytes": 62894, + "languageCount": 2, + "languagesTruncated": false, + "categories": [ + "2023 in Seville", + "2023 municipal elections in Spain", + "Elections in Seville", + "May 2023 in Spain" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 126 + }, + { + "month": "2026-06", + "views": 58 + }, + { + "month": "2026-07", + "views": 86 + }, + { + "month": "2026-08", + "views": 79 + }, + { + "month": "2026-09", + "views": 85 + }, + { + "month": "2026-10", + "views": 100 + } + ], + "latestMonth": "2026-10", + "total": 534, + "dailyAverage": 3.225806451612903, + "trendPercent": 17.647058823529413 + }, + "stats": { + "attention": 33, + "depth": 80, + "reach": 16 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 78, + "prev30": 89, + "pct": -12.359550561797752 + }, + "instanceOf": [ + { + "id": "Q152450", + "label": "municipal election" + } + ] + }, + { + "pageId": 77371520, + "title": "Coalición Vamos", + "description": "Political party in Panama", + "wikidataId": "Q127386808", + "revisionId": 1372235441, + "pageBytes": 3605, + "languageCount": 1, + "languagesTruncated": false, + "categories": [ + "Politics of Panama" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 495 + }, + { + "month": "2026-06", + "views": 736 + }, + { + "month": "2026-07", + "views": 561 + }, + { + "month": "2026-08", + "views": 671 + }, + { + "month": "2026-09", + "views": 507 + }, + { + "month": "2026-10", + "views": 852 + } + ], + "latestMonth": "2026-10", + "total": 3822, + "dailyAverage": 27.483870967741936, + "trendPercent": 68.04733727810651 + }, + "stats": { + "attention": 49, + "depth": 59, + "reach": 10 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 852, + "prev30": 495, + "pct": 72.12121212121212 + }, + "instanceOf": [ + { + "id": "Q7278", + "label": "political party" + } + ] + }, + { + "pageId": 115448, + "title": "Mackville, Kentucky", + "description": "City in Kentucky, United States", + "wikidataId": "Q2246158", + "revisionId": 1374535006, + "pageBytes": 6984, + "languageCount": 33, + "languagesTruncated": false, + "categories": [ + "Cities in Kentucky", + "Cities in Washington County, Kentucky" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 130 + }, + { + "month": "2026-06", + "views": 110 + }, + { + "month": "2026-07", + "views": 129 + }, + { + "month": "2026-08", + "views": 141 + }, + { + "month": "2026-09", + "views": 118 + }, + { + "month": "2026-10", + "views": 87 + } + ], + "latestMonth": "2026-10", + "total": 715, + "dailyAverage": 2.806451612903226, + "trendPercent": -26.27118644067797 + }, + "stats": { + "attention": 32, + "depth": 64, + "reach": 51 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 74, + "prev30": 93, + "pct": -20.43010752688172 + }, + "instanceOf": [ + { + "id": "Q1093829", + "label": "city in the United States" + } + ] + }, + { + "pageId": 4324457, + "title": "Juha Suoranta", + "description": "Finnish social scientist", + "wikidataId": "Q6305056", + "revisionId": 1372952688, + "pageBytes": 10693, + "languageCount": 3, + "languagesTruncated": false, + "categories": [ + "1966 births", + "Finnish bloggers", + "Finnish educational theorists", + "Finnish sociologists", + "Living people", + "People from Tampere" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 36 + }, + { + "month": "2026-06", + "views": 39 + }, + { + "month": "2026-07", + "views": 30 + }, + { + "month": "2026-08", + "views": 38 + }, + { + "month": "2026-09", + "views": 54 + }, + { + "month": "2026-10", + "views": 46 + } + ], + "latestMonth": "2026-10", + "total": 243, + "dailyAverage": 1.4838709677419355, + "trendPercent": -14.814814814814813 + }, + "stats": { + "attention": 28, + "depth": 67, + "reach": 20 + }, + "legacyCategory": "People", + "drift30": { + "last30": 35, + "prev30": 56, + "pct": -37.5 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 9472671, + "title": "Fletcher (typeface)", + "description": "Serif typeface", + "wikidataId": "Q2539914", + "revisionId": 1280127322, + "pageBytes": 1133, + "languageCount": 1, + "languagesTruncated": false, + "categories": [ + "Blackletter typefaces" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 72 + }, + { + "month": "2026-06", + "views": 66 + }, + { + "month": "2026-07", + "views": 100 + }, + { + "month": "2026-08", + "views": 101 + }, + { + "month": "2026-09", + "views": 90 + }, + { + "month": "2026-10", + "views": 108 + } + ], + "latestMonth": "2026-10", + "total": 537, + "dailyAverage": 3.4838709677419355, + "trendPercent": 20.0 + }, + "stats": { + "attention": 34, + "depth": 51, + "reach": 10 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 98, + "prev30": 100, + "pct": -2.0 + }, + "instanceOf": [ + { + "id": "Q17451", + "label": "typeface" + } + ] + }, + { + "pageId": 12516367, + "title": "Frogham, Kent", + "description": "Hamlet in Kent, England", + "wikidataId": "Q5505274", + "revisionId": 1320927031, + "pageBytes": 1530, + "languageCount": 3, + "languagesTruncated": false, + "categories": [ + "Dover District", + "Hamlets in Kent", + "Kent geography stubs" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 42 + }, + { + "month": "2026-06", + "views": 34 + }, + { + "month": "2026-07", + "views": 32 + }, + { + "month": "2026-08", + "views": 77 + }, + { + "month": "2026-09", + "views": 45 + }, + { + "month": "2026-10", + "views": 27 + } + ], + "latestMonth": "2026-10", + "total": 257, + "dailyAverage": 0.8709677419354839, + "trendPercent": -40.0 + }, + "stats": { + "attention": 24, + "depth": 53, + "reach": 20 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 13, + "prev30": 32, + "pct": -59.375 + }, + "instanceOf": [ + { + "id": "Q5084", + "label": "hamlet" + } + ] + }, + { + "pageId": 25275009, + "title": "Amur Annexation", + "description": "Russian annexation of Outer Manchuria", + "wikidataId": "Q4379152", + "revisionId": 1381503728, + "pageBytes": 15490, + "languageCount": 9, + "languagesTruncated": false, + "categories": [ + "19th century in Manchuria", + "Annexations by Russia", + "China–Russian Empire relations", + "History of Siberia", + "Russian Far East" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 3812 + }, + { + "month": "2026-06", + "views": 3492 + }, + { + "month": "2026-07", + "views": 3723 + }, + { + "month": "2026-08", + "views": 3681 + }, + { + "month": "2026-09", + "views": 3469 + }, + { + "month": "2026-10", + "views": 3238 + } + ], + "latestMonth": "2026-10", + "total": 21415, + "dailyAverage": 104.45161290322581, + "trendPercent": -6.65897953300663 + }, + "stats": { + "attention": 59, + "depth": 70, + "reach": 33 + }, + "legacyCategory": "History", + "drift30": { + "last30": 3203, + "prev30": 3248, + "pct": -1.3854679802955665 + }, + "instanceOf": [ + { + "id": "Q194465", + "label": "annexation" + } + ] + }, + { + "pageId": 33276983, + "title": "Buky", + "description": "Rural locality in Cherkasy Oblast, Ukraine", + "wikidataId": "Q2473493", + "revisionId": 1375320562, + "pageBytes": 4244, + "languageCount": 15, + "languagesTruncated": false, + "categories": [ + "Rural settlements in Uman Raion", + "Umansky uezd" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 73 + }, + { + "month": "2026-06", + "views": 73 + }, + { + "month": "2026-07", + "views": 63 + }, + { + "month": "2026-08", + "views": 68 + }, + { + "month": "2026-09", + "views": 69 + }, + { + "month": "2026-10", + "views": 51 + } + ], + "latestMonth": "2026-10", + "total": 397, + "dailyAverage": 1.6451612903225807, + "trendPercent": -26.08695652173913 + }, + "stats": { + "attention": 29, + "depth": 60, + "reach": 40 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 46, + "prev30": 49, + "pct": -6.122448979591836 + }, + "instanceOf": [ + { + "id": "Q4100864", + "label": "urban-type settlement in Ukraine" + }, + { + "id": "Q486972", + "label": "human settlement" + } + ] + }, + { + "pageId": 39238370, + "title": "2013 San Jose State Spartans football team", + "description": "American college football season", + "wikidataId": "Q16972991", + "revisionId": 1330396969, + "pageBytes": 18442, + "languageCount": 0, + "languagesTruncated": false, + "categories": [ + "2013 Mountain West Conference football season", + "2013 in sports in California", + "San Jose State Spartans football seasons" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 156 + }, + { + "month": "2026-06", + "views": 83 + }, + { + "month": "2026-07", + "views": 143 + }, + { + "month": "2026-08", + "views": 160 + }, + { + "month": "2026-09", + "views": 185 + }, + { + "month": "2026-10", + "views": 143 + } + ], + "latestMonth": "2026-10", + "total": 870, + "dailyAverage": 4.612903225806452, + "trendPercent": -22.702702702702705 + }, + "stats": { + "attention": 36, + "depth": 71, + "reach": 0 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 114, + "prev30": 187, + "pct": -39.037433155080215 + }, + "instanceOf": [ + { + "id": "Q26895936", + "label": "American football team season" + } + ] + }, + { + "pageId": 46263191, + "title": "Max Touloute", + "description": "Haitian footballer (born 1990)", + "wikidataId": "Q20641573", + "revisionId": 1384441370, + "pageBytes": 10140, + "languageCount": 2, + "languagesTruncated": false, + "categories": [ + "1990 births", + "21st-century Haitian sportsmen", + "Expatriate men's soccer players in the United States", + "Flint City Bucks players", + "Florida Tropics SC players", + "Haitian expatriate men's footballers", + "Haitian men's footballers", + "Kansas City Comets (2010–) players", + "Living people", + "Major Arena Soccer League players", + "Men's association football forwards", + "People from Les Cayes", + "Pittsburgh Riverhounds SC players", + "Purdue Fort Wayne Mastodons men's soccer players", + "Reading United AC players", + "Tindastóll men's football players", + "USL Championship players", + "USL League Two players", + "Vermont Voltage players" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 53 + }, + { + "month": "2026-06", + "views": 37 + }, + { + "month": "2026-07", + "views": 19 + }, + { + "month": "2026-08", + "views": 27 + }, + { + "month": "2026-09", + "views": 24 + }, + { + "month": "2026-10", + "views": 47 + } + ], + "latestMonth": "2026-10", + "total": 207, + "dailyAverage": 1.5161290322580645, + "trendPercent": 95.83333333333334 + }, + "stats": { + "attention": 28, + "depth": 67, + "reach": 16 + }, + "legacyCategory": "People", + "drift30": { + "last30": 30, + "prev30": 40, + "pct": -25.0 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 50185825, + "title": "Majid Qodiri", + "description": "Uzbek literary scholar and educator (1886–1938)", + "wikidataId": "Q23823703", + "revisionId": 1371365886, + "pageBytes": 9420, + "languageCount": 6, + "languagesTruncated": false, + "categories": [ + "1886 births", + "1938 deaths", + "20th-century Uzbekistani writers", + "People from Syr-Darya Oblast", + "Soviet writers", + "Uzbekistani academics", + "Uzbekistani male writers", + "Writers from Tashkent" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 25 + }, + { + "month": "2026-06", + "views": 22 + }, + { + "month": "2026-07", + "views": 53 + }, + { + "month": "2026-08", + "views": 65 + }, + { + "month": "2026-09", + "views": 65 + }, + { + "month": "2026-10", + "views": 43 + } + ], + "latestMonth": "2026-10", + "total": 273, + "dailyAverage": 1.3870967741935485, + "trendPercent": -33.84615384615385 + }, + "stats": { + "attention": 27, + "depth": 66, + "reach": 28 + }, + "legacyCategory": "People", + "drift30": { + "last30": 37, + "prev30": 51, + "pct": -27.450980392156865 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 52540452, + "title": "Olga Gorshenina", + "description": "Russian handball player", + "wikidataId": "Q2019617", + "revisionId": 1381108921, + "pageBytes": 2811, + "languageCount": 11, + "languagesTruncated": false, + "categories": [ + "1990 births", + "21st-century Russian sportswomen", + "Expatriate handball players in Hungary", + "Expatriate handball players in Romania", + "Handball players from Tolyatti", + "Living people", + "Russian expatriate handball players in Germany", + "Russian expatriate sportspeople in Hungary", + "Russian expatriate sportspeople in Romania", + "Russian handball biography stubs", + "Russian women's handball players" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 26 + }, + { + "month": "2026-06", + "views": 26 + }, + { + "month": "2026-07", + "views": 19 + }, + { + "month": "2026-08", + "views": 13 + }, + { + "month": "2026-09", + "views": 22 + }, + { + "month": "2026-10", + "views": 21 + } + ], + "latestMonth": "2026-10", + "total": 127, + "dailyAverage": 0.6774193548387096, + "trendPercent": -4.545454545454546 + }, + "stats": { + "attention": 22, + "depth": 57, + "reach": 36 + }, + "legacyCategory": "People", + "drift30": { + "last30": 21, + "prev30": 21, + "pct": 0.0 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 71038192, + "title": "1952 Avusrennen", + "description": "Motor car race", + "wikidataId": "Q112838670", + "revisionId": 1382877416, + "pageBytes": 4609, + "languageCount": 0, + "languagesTruncated": false, + "categories": [ + "1950s in West Berlin", + "1952 Formula Two races", + "1952 in West German motorsport", + "Motorsport in Berlin", + "September 1952 sports events in Europe", + "Sports competitions in Berlin" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 29 + }, + { + "month": "2026-06", + "views": 25 + }, + { + "month": "2026-07", + "views": 35 + }, + { + "month": "2026-08", + "views": 40 + }, + { + "month": "2026-09", + "views": 23 + }, + { + "month": "2026-10", + "views": 31 + } + ], + "latestMonth": "2026-10", + "total": 183, + "dailyAverage": 1.0, + "trendPercent": 34.78260869565217 + }, + "stats": { + "attention": 25, + "depth": 61, + "reach": 0 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 27, + "prev30": 23, + "pct": 17.391304347826086 + }, + "instanceOf": [] + }, + { + "pageId": 81318312, + "title": "Guido Iván Justo", + "description": "Argentine tennis player (born 1997)", + "wikidataId": "Q138414200", + "revisionId": 1382049023, + "pageBytes": 6501, + "languageCount": 1, + "languagesTruncated": false, + "categories": [ + "1997 births", + "Argentine male tennis players", + "Argentine tennis biography stubs", + "Living people", + "Sportspeople from Buenos Aires" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 360 + }, + { + "month": "2026-06", + "views": 309 + }, + { + "month": "2026-07", + "views": 535 + }, + { + "month": "2026-08", + "views": 402 + }, + { + "month": "2026-09", + "views": 287 + }, + { + "month": "2026-10", + "views": 824 + } + ], + "latestMonth": "2026-10", + "total": 2717, + "dailyAverage": 26.580645161290324, + "trendPercent": 187.10801393728224 + }, + "stats": { + "attention": 49, + "depth": 64, + "reach": 10 + }, + "legacyCategory": "People", + "drift30": { + "last30": 155, + "prev30": 1003, + "pct": -84.54636091724825 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 2218990, + "title": "Deputy Prime Minister of Malaysia", + "description": "Political office in Malaysia", + "wikidataId": "Q5261073", + "revisionId": 1386025479, + "pageBytes": 21259, + "languageCount": 10, + "languagesTruncated": false, + "categories": [ + "Deputy prime ministers of Malaysia", + "Lists of deputy prime ministers", + "Lists of political office-holders in Malaysia", + "Malaysia politics-related lists" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 1374 + }, + { + "month": "2026-06", + "views": 1126 + }, + { + "month": "2026-07", + "views": 1532 + }, + { + "month": "2026-08", + "views": 1494 + }, + { + "month": "2026-09", + "views": 1837 + }, + { + "month": "2026-10", + "views": 1504 + } + ], + "latestMonth": "2026-10", + "total": 8867, + "dailyAverage": 48.516129032258064, + "trendPercent": -18.127381600435495 + }, + "stats": { + "attention": 53, + "depth": 72, + "reach": 35 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 1304, + "prev30": 1919, + "pct": -32.04794163626889 + }, + "instanceOf": [ + { + "id": "Q4164871", + "label": "position" + } + ] + }, + { + "pageId": 8275276, + "title": "Thomas Wharton Jr.", + "description": "American politician (1735–1778)", + "wikidataId": "Q883460", + "revisionId": 1350443233, + "pageBytes": 12218, + "languageCount": 2, + "languagesTruncated": false, + "categories": [ + "1735 births", + "1778 deaths", + "18th-century American Episcopalians", + "Governors of Pennsylvania", + "Merchants from colonial Pennsylvania", + "Patriots in the American Revolution", + "People disowned by the Quakers", + "People of Pennsylvania in the American Revolution", + "Politicians from Chester County, Pennsylvania", + "Politicians from Philadelphia", + "Wharton family" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 536 + }, + { + "month": "2026-06", + "views": 462 + }, + { + "month": "2026-07", + "views": 656 + }, + { + "month": "2026-08", + "views": 503 + }, + { + "month": "2026-09", + "views": 419 + }, + { + "month": "2026-10", + "views": 420 + } + ], + "latestMonth": "2026-10", + "total": 2996, + "dailyAverage": 13.548387096774194, + "trendPercent": 0.23866348448687352 + }, + "stats": { + "attention": 44, + "depth": 68, + "reach": 16 + }, + "legacyCategory": "People", + "drift30": { + "last30": 511, + "prev30": 446, + "pct": 14.573991031390134 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 21376831, + "title": "Bez (Drôme)", + "description": "River in France", + "wikidataId": "Q1019347", + "revisionId": 1374494957, + "pageBytes": 1685, + "languageCount": 2, + "languagesTruncated": false, + "categories": [ + "Auvergne-Rhône-Alpes river stubs", + "Drôme geography stubs", + "Rivers of Auvergne-Rhône-Alpes", + "Rivers of Drôme", + "Rivers of France", + "Tributaries of the Rhône" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 19 + }, + { + "month": "2026-06", + "views": 9 + }, + { + "month": "2026-07", + "views": 36 + }, + { + "month": "2026-08", + "views": 41 + }, + { + "month": "2026-09", + "views": 22 + }, + { + "month": "2026-10", + "views": 23 + } + ], + "latestMonth": "2026-10", + "total": 150, + "dailyAverage": 0.7419354838709677, + "trendPercent": 4.545454545454546 + }, + "stats": { + "attention": 23, + "depth": 54, + "reach": 16 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 8, + "prev30": 21, + "pct": -61.904761904761905 + }, + "instanceOf": [ + { + "id": "Q4022", + "label": "river" + } + ] + }, + { + "pageId": 22403198, + "title": "Cioc-Maidan", + "description": "Commune in Gagauzia, Moldova", + "wikidataId": "Q2639022", + "revisionId": 1375646501, + "pageBytes": 3479, + "languageCount": 12, + "languagesTruncated": false, + "categories": [ + "Communes of Gagauzia", + "Southern Moldova geography stubs" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 44 + }, + { + "month": "2026-06", + "views": 39 + }, + { + "month": "2026-07", + "views": 38 + }, + { + "month": "2026-08", + "views": 80 + }, + { + "month": "2026-09", + "views": 52 + }, + { + "month": "2026-10", + "views": 44 + } + ], + "latestMonth": "2026-10", + "total": 297, + "dailyAverage": 1.4193548387096775, + "trendPercent": -15.384615384615385 + }, + "stats": { + "attention": 28, + "depth": 59, + "reach": 37 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 31, + "prev30": 55, + "pct": -43.63636363636363 + }, + "instanceOf": [ + { + "id": "Q4229812", + "label": "commune of Moldova" + }, + { + "id": "Q532", + "label": "village" + } + ] + }, + { + "pageId": 22517668, + "title": "Kwong Wai Siew Peck San Theng", + "description": "Columbarium in Singapore", + "wikidataId": "Q6450554", + "revisionId": 1244289559, + "pageBytes": 6673, + "languageCount": 1, + "languagesTruncated": false, + "categories": [ + "Buildings and structures in Bishan, Singapore", + "Columbaria in Singapore", + "Hakka culture in Singapore" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 504 + }, + { + "month": "2026-06", + "views": 308 + }, + { + "month": "2026-07", + "views": 393 + }, + { + "month": "2026-08", + "views": 438 + }, + { + "month": "2026-09", + "views": 412 + }, + { + "month": "2026-10", + "views": 304 + } + ], + "latestMonth": "2026-10", + "total": 2359, + "dailyAverage": 9.806451612903226, + "trendPercent": -26.21359223300971 + }, + "stats": { + "attention": 41, + "depth": 64, + "reach": 10 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 279, + "prev30": 347, + "pct": -19.596541786743515 + }, + "instanceOf": [] + }, + { + "pageId": 47519878, + "title": "Jeanne Madden", + "description": "American singer and actress (1917–1989)", + "wikidataId": "Q20974011", + "revisionId": 1382761423, + "pageBytes": 1817, + "languageCount": 4, + "languagesTruncated": false, + "categories": [ + "1917 births", + "1989 deaths", + "20th-century American actresses", + "20th-century American singers", + "Actors from Scranton, Pennsylvania", + "Actresses from Lackawanna County, Pennsylvania", + "American film actor, 1910s birth stubs", + "American film actresses", + "American singer stubs", + "American stage actresses", + "American theatre actor, 20th-century birth stubs", + "Musicians from Scranton, Pennsylvania" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 39 + }, + { + "month": "2026-06", + "views": 44 + }, + { + "month": "2026-07", + "views": 48 + }, + { + "month": "2026-08", + "views": 46 + }, + { + "month": "2026-09", + "views": 44 + }, + { + "month": "2026-10", + "views": 26 + } + ], + "latestMonth": "2026-10", + "total": 247, + "dailyAverage": 0.8387096774193549, + "trendPercent": -40.909090909090914 + }, + "stats": { + "attention": 24, + "depth": 54, + "reach": 23 + }, + "legacyCategory": "People", + "drift30": { + "last30": 35, + "prev30": 35, + "pct": 0.0 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 48714450, + "title": "Payam Heydari", + "description": "Iranian-American Professor", + "wikidataId": "Q22097382", + "revisionId": 1383721847, + "pageBytes": 12398, + "languageCount": 2, + "languagesTruncated": false, + "categories": [ + "American electrical engineers", + "Engineers from California", + "Fellows of the IEEE", + "Iranian electrical engineers", + "Iranian engineers", + "Iranian expatriate academics", + "Living people", + "Sharif University of Technology alumni", + "USC Viterbi School of Engineering alumni", + "University of California, Irvine faculty" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 225 + }, + { + "month": "2026-06", + "views": 145 + }, + { + "month": "2026-07", + "views": 114 + }, + { + "month": "2026-08", + "views": 154 + }, + { + "month": "2026-09", + "views": 126 + }, + { + "month": "2026-10", + "views": 127 + } + ], + "latestMonth": "2026-10", + "total": 891, + "dailyAverage": 4.096774193548387, + "trendPercent": 0.7936507936507936 + }, + "stats": { + "attention": 35, + "depth": 68, + "reach": 16 + }, + "legacyCategory": "People", + "drift30": { + "last30": 122, + "prev30": 125, + "pct": -2.4 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 78868030, + "title": "Mercenasco Castle", + "description": "Building in Mercenasco, Italy", + "wikidataId": "Q131729377", + "revisionId": 1327239041, + "pageBytes": 2716, + "languageCount": 2, + "languagesTruncated": false, + "categories": [ + "Castles in the Metropolitan City of Turin", + "Mercenasco" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 12 + }, + { + "month": "2026-06", + "views": 22 + }, + { + "month": "2026-07", + "views": 17 + }, + { + "month": "2026-08", + "views": 10 + }, + { + "month": "2026-09", + "views": 11 + }, + { + "month": "2026-10", + "views": 5 + } + ], + "latestMonth": "2026-10", + "total": 77, + "dailyAverage": 0.16129032258064516, + "trendPercent": -54.54545454545454 + }, + "stats": { + "attention": 13, + "depth": 57, + "reach": 16 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 7, + "prev30": 10, + "pct": -30.0 + }, + "instanceOf": [ + { + "id": "Q23413", + "label": "castle" + } + ] + }, + { + "pageId": 84606242, + "title": "Edward Ellsworth Underwood", + "description": "American physician (1864–1942)", + "wikidataId": "Q141822855", + "revisionId": 1382829231, + "pageBytes": 7526, + "languageCount": 0, + "languagesTruncated": false, + "categories": [ + "1864 births", + "1942 deaths", + "19th-century African-American medical doctors", + "19th-century American medical doctors", + "20th-century African-American medical doctors", + "20th-century American medical doctors", + "African-American people in Kentucky politics", + "African Methodist Episcopal Church clergy", + "Burials at Frankfort Cemetery", + "Case Western Reserve University School of Medicine alumni", + "People from Dayton, Ohio", + "People from Frankfort, Kentucky", + "People from Jefferson County, Ohio" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 0 + }, + { + "month": "2026-06", + "views": 0 + }, + { + "month": "2026-07", + "views": 0 + }, + { + "month": "2026-08", + "views": 0 + }, + { + "month": "2026-09", + "views": 0 + }, + { + "month": "2026-10", + "views": 81 + } + ], + "latestMonth": "2026-10", + "total": 81, + "dailyAverage": 2.6129032258064515, + "trendPercent": null + }, + "stats": { + "attention": 32, + "depth": 65, + "reach": 0 + }, + "legacyCategory": "People", + "drift30": { + "last30": 97, + "prev30": 0, + "pct": null + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 981340, + "title": "Tatsunoko Production", + "description": "Japanese animation studio", + "wikidataId": "Q1323459", + "revisionId": 1384823392, + "pageBytes": 74169, + "languageCount": 19, + "languagesTruncated": false, + "categories": [ + "Animation studios in Tokyo", + "Companies based in Musashino, Tokyo", + "Film production companies of Japan", + "Japanese animation studios", + "Japanese companies established in 1962", + "Mass media companies established in 1962", + "Tatsunoko Production", + "Television production companies of Japan" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 5947 + }, + { + "month": "2026-06", + "views": 4922 + }, + { + "month": "2026-07", + "views": 5774 + }, + { + "month": "2026-08", + "views": 6054 + }, + { + "month": "2026-09", + "views": 5228 + }, + { + "month": "2026-10", + "views": 4738 + } + ], + "latestMonth": "2026-10", + "total": 32663, + "dailyAverage": 152.83870967741936, + "trendPercent": -9.372609028309105 + }, + "stats": { + "attention": 61, + "depth": 81, + "reach": 43 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 4819, + "prev30": 4525, + "pct": 6.497237569060774 + }, + "instanceOf": [ + { + "id": "Q1107679", + "label": "animation studio" + } + ] + }, + { + "pageId": 2020649, + "title": "Luxury box", + "description": "Class of seating in arena or stadium", + "wikidataId": "Q852359", + "revisionId": 1356568738, + "pageBytes": 17537, + "languageCount": 6, + "languagesTruncated": false, + "categories": [ + "Luxury", + "Rooms", + "Sports venues", + "Stadiums" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 1291 + }, + { + "month": "2026-06", + "views": 1503 + }, + { + "month": "2026-07", + "views": 1176 + }, + { + "month": "2026-08", + "views": 926 + }, + { + "month": "2026-09", + "views": 1083 + }, + { + "month": "2026-10", + "views": 1071 + } + ], + "latestMonth": "2026-10", + "total": 7050, + "dailyAverage": 34.54838709677419, + "trendPercent": -1.10803324099723 + }, + "stats": { + "attention": 51, + "depth": 71, + "reach": 28 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 1003, + "prev30": 1117, + "pct": -10.205908683974933 + }, + "instanceOf": [] + }, + { + "pageId": 2978129, + "title": "Saraca", + "description": "Genus of legumes", + "wikidataId": "Q2426272", + "revisionId": 1354827085, + "pageBytes": 3926, + "languageCount": 18, + "languagesTruncated": false, + "categories": [ + "Fabaceae genera", + "Saraca" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 161 + }, + { + "month": "2026-06", + "views": 119 + }, + { + "month": "2026-07", + "views": 159 + }, + { + "month": "2026-08", + "views": 188 + }, + { + "month": "2026-09", + "views": 153 + }, + { + "month": "2026-10", + "views": 130 + } + ], + "latestMonth": "2026-10", + "total": 910, + "dailyAverage": 4.193548387096774, + "trendPercent": -15.032679738562091 + }, + "stats": { + "attention": 35, + "depth": 60, + "reach": 43 + }, + "legacyCategory": "Nature", + "drift30": { + "last30": 116, + "prev30": 127, + "pct": -8.661417322834646 + }, + "instanceOf": [ + { + "id": "Q16521", + "label": "taxon" + } + ] + }, + { + "pageId": 14048250, + "title": "Frontier, Saskatchewan", + "description": "Village in Saskatchewan, Canada", + "wikidataId": "Q2003391", + "revisionId": 1377607311, + "pageBytes": 13275, + "languageCount": 3, + "languagesTruncated": false, + "categories": [ + "Division No. 4, Saskatchewan", + "Rural Municipality of Frontier No. 19", + "Villages in Saskatchewan" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 319 + }, + { + "month": "2026-06", + "views": 239 + }, + { + "month": "2026-07", + "views": 248 + }, + { + "month": "2026-08", + "views": 212 + }, + { + "month": "2026-09", + "views": 210 + }, + { + "month": "2026-10", + "views": 182 + } + ], + "latestMonth": "2026-10", + "total": 1410, + "dailyAverage": 5.870967741935484, + "trendPercent": -13.333333333333334 + }, + "stats": { + "attention": 38, + "depth": 69, + "reach": 20 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 145, + "prev30": 196, + "pct": -26.02040816326531 + }, + "instanceOf": [ + { + "id": "Q6644778", + "label": "village in Saskatchewan" + } + ] + }, + { + "pageId": 30524663, + "title": "Aichi AB-2", + "description": "Prototype reconnaissance floatplane", + "wikidataId": "Q4696551", + "revisionId": 1321144611, + "pageBytes": 5492, + "languageCount": 3, + "languagesTruncated": false, + "categories": [ + "1930s Japanese military reconnaissance aircraft", + "Aichi aircraft", + "Aircraft first flown in 1930", + "Biplanes", + "Floatplanes", + "Single-engined tractor aircraft" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 65 + }, + { + "month": "2026-06", + "views": 68 + }, + { + "month": "2026-07", + "views": 70 + }, + { + "month": "2026-08", + "views": 75 + }, + { + "month": "2026-09", + "views": 77 + }, + { + "month": "2026-10", + "views": 70 + } + ], + "latestMonth": "2026-10", + "total": 425, + "dailyAverage": 2.2580645161290325, + "trendPercent": -9.090909090909092 + }, + "stats": { + "attention": 31, + "depth": 62, + "reach": 20 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 53, + "prev30": 85, + "pct": -37.64705882352941 + }, + "instanceOf": [ + { + "id": "Q15056995", + "label": "aircraft model" + } + ] + }, + { + "pageId": 30852837, + "title": "Symphodus", + "description": "Genus of fishes", + "wikidataId": "Q2019861", + "revisionId": 1366643102, + "pageBytes": 5918, + "languageCount": 21, + "languagesTruncated": false, + "categories": [ + "Fauna of Morocco", + "Fauna of Spain", + "Fish of the East Atlantic", + "Fish of the Mediterranean Sea", + "Labridae", + "Labridae stubs", + "Marine fish genera", + "Symphodus", + "Taxa named by Constantine Samuel Rafinesque" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 96 + }, + { + "month": "2026-06", + "views": 84 + }, + { + "month": "2026-07", + "views": 82 + }, + { + "month": "2026-08", + "views": 111 + }, + { + "month": "2026-09", + "views": 98 + }, + { + "month": "2026-10", + "views": 67 + } + ], + "latestMonth": "2026-10", + "total": 538, + "dailyAverage": 2.161290322580645, + "trendPercent": -31.63265306122449 + }, + "stats": { + "attention": 31, + "depth": 63, + "reach": 45 + }, + "legacyCategory": "Nature", + "drift30": { + "last30": 72, + "prev30": 74, + "pct": -2.7027027027027026 + }, + "instanceOf": [ + { + "id": "Q16521", + "label": "taxon" + } + ] + }, + { + "pageId": 42770753, + "title": "Château de la Faye (Villexavier)", + "description": "Manor house in Charente-Maritime, France", + "wikidataId": "Q2971223", + "revisionId": 1375492681, + "pageBytes": 1851, + "languageCount": 1, + "languagesTruncated": false, + "categories": [ + "Châteaux in Charente-Maritime", + "Monuments historiques of Charente-Maritime" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 31 + }, + { + "month": "2026-06", + "views": 11 + }, + { + "month": "2026-07", + "views": 10 + }, + { + "month": "2026-08", + "views": 19 + }, + { + "month": "2026-09", + "views": 13 + }, + { + "month": "2026-10", + "views": 14 + } + ], + "latestMonth": "2026-10", + "total": 98, + "dailyAverage": 0.45161290322580644, + "trendPercent": 7.6923076923076925 + }, + "stats": { + "attention": 20, + "depth": 54, + "reach": 10 + }, + "legacyCategory": "History", + "drift30": { + "last30": 12, + "prev30": 14, + "pct": -14.285714285714285 + }, + "instanceOf": [ + { + "id": "Q23413", + "label": "castle" + } + ] + }, + { + "pageId": 48653101, + "title": "Tornadoes of 1978", + "description": "", + "wikidataId": "Q22093730", + "revisionId": 1381828221, + "pageBytes": 16373, + "languageCount": 0, + "languagesTruncated": false, + "categories": [ + "1978-related lists", + "Meteorological events in 1978", + "Tornado-related lists by year", + "Tornadoes of 1978" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 569 + }, + { + "month": "2026-06", + "views": 572 + }, + { + "month": "2026-07", + "views": 525 + }, + { + "month": "2026-08", + "views": 643 + }, + { + "month": "2026-09", + "views": 495 + }, + { + "month": "2026-10", + "views": 511 + } + ], + "latestMonth": "2026-10", + "total": 3315, + "dailyAverage": 16.483870967741936, + "trendPercent": 3.2323232323232323 + }, + "stats": { + "attention": 45, + "depth": 70, + "reach": 0 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 491, + "prev30": 536, + "pct": -8.395522388059701 + }, + "instanceOf": [ + { + "id": "Q18340514", + "label": "events in a specific year or time period" + } + ] + }, + { + "pageId": 55083500, + "title": "United Kingdom House", + "description": "Building on Oxford Street, London, England", + "wikidataId": "Q26319049", + "revisionId": 1383844197, + "pageBytes": 2837, + "languageCount": 1, + "languagesTruncated": false, + "categories": [ + "1906 establishments in England", + "Buildings and structures completed in 1906", + "Department store buildings in the United Kingdom", + "Grade II listed buildings in the City of Westminster", + "Grade II listed retail buildings", + "London building and structure stubs", + "Oxford Street" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 125 + }, + { + "month": "2026-06", + "views": 101 + }, + { + "month": "2026-07", + "views": 100 + }, + { + "month": "2026-08", + "views": 75 + }, + { + "month": "2026-09", + "views": 103 + }, + { + "month": "2026-10", + "views": 109 + } + ], + "latestMonth": "2026-10", + "total": 613, + "dailyAverage": 3.5161290322580645, + "trendPercent": 5.825242718446602 + }, + "stats": { + "attention": 34, + "depth": 58, + "reach": 10 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 111, + "prev30": 92, + "pct": 20.652173913043477 + }, + "instanceOf": [ + { + "id": "Q41176", + "label": "building" + } + ] + }, + { + "pageId": 3372934, + "title": "Hermes Ramírez", + "description": "Cuban sprinter (1948–2024)", + "wikidataId": "Q522855", + "revisionId": 1364063954, + "pageBytes": 8264, + "languageCount": 13, + "languagesTruncated": false, + "categories": [ + "1948 births", + "2024 deaths", + "20th-century Cuban sportsmen", + "Athletes (track and field) at the 1967 Pan American Games", + "Athletes (track and field) at the 1968 Summer Olympics", + "Athletes (track and field) at the 1971 Pan American Games", + "Athletes (track and field) at the 1972 Summer Olympics", + "Athletes (track and field) at the 1975 Pan American Games", + "Athletes (track and field) at the 1976 Summer Olympics", + "Central American and Caribbean Games gold medalists for Cuba", + "Central American and Caribbean Games medalists in athletics", + "Competitors at the 1965 Summer Universiade", + "Competitors at the 1966 Central American and Caribbean Games", + "Competitors at the 1970 Central American and Caribbean Games", + "Cuban Olympic medalist stubs", + "Cuban athletics biography stubs", + "Cuban men sprinters", + "Medalists at the 1967 Pan American Games", + "Medalists at the 1968 Summer Olympics", + "Medalists at the 1971 Pan American Games", + "Medalists at the 1975 Pan American Games", + "Olympic athletes for Cuba", + "Olympic men sprinters", + "Olympic silver medalists for Cuba", + "Olympic silver medalists in athletics", + "Pan American Games bronze medalists for Cuba", + "Pan American Games bronze medalists in athletics (track and field)", + "Pan American Games silver medalists for Cuba", + "Pan American Games silver medalists in athletics (track and field)" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 54 + }, + { + "month": "2026-06", + "views": 72 + }, + { + "month": "2026-07", + "views": 53 + }, + { + "month": "2026-08", + "views": 58 + }, + { + "month": "2026-09", + "views": 65 + }, + { + "month": "2026-10", + "views": 59 + } + ], + "latestMonth": "2026-10", + "total": 361, + "dailyAverage": 1.903225806451613, + "trendPercent": -9.230769230769232 + }, + "stats": { + "attention": 30, + "depth": 65, + "reach": 38 + }, + "legacyCategory": "People", + "drift30": { + "last30": 55, + "prev30": 52, + "pct": 5.769230769230769 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 8341140, + "title": "Ceaușescu family", + "description": "Family of Nicolae Ceaușescu", + "wikidataId": "Q5055770", + "revisionId": 1370304900, + "pageBytes": 8422, + "languageCount": 3, + "languagesTruncated": false, + "categories": [ + "Ceaușescu family", + "Nicolae Ceaușescu", + "Romanian revolution" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 2312 + }, + { + "month": "2026-06", + "views": 2282 + }, + { + "month": "2026-07", + "views": 2408 + }, + { + "month": "2026-08", + "views": 2665 + }, + { + "month": "2026-09", + "views": 2662 + }, + { + "month": "2026-10", + "views": 2560 + } + ], + "latestMonth": "2026-10", + "total": 14889, + "dailyAverage": 82.58064516129032, + "trendPercent": -3.831705484598046 + }, + "stats": { + "attention": 57, + "depth": 65, + "reach": 20 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 2274, + "prev30": 2605, + "pct": -12.7063339731286 + }, + "instanceOf": [ + { + "id": "Q8436", + "label": "family" + } + ] + }, + { + "pageId": 13799810, + "title": "Levophacetoperane", + "description": "Stimulant drug", + "wikidataId": "Q6535818", + "revisionId": 1374230485, + "pageBytes": 4639, + "languageCount": 2, + "languagesTruncated": false, + "categories": [ + "2-Benzylpiperidines", + "2-Piperidinyl compounds", + "Acetate esters", + "Amphetamine stubs", + "Anorectics", + "Antidepressants", + "Beta-Hydroxyamphetamines", + "Drugs not assigned an ATC code", + "Norepinephrine–dopamine reuptake inhibitors", + "Phenylethanolamine ethers", + "Stimulants", + "Wakefulness-promoting agents" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 193 + }, + { + "month": "2026-06", + "views": 170 + }, + { + "month": "2026-07", + "views": 166 + }, + { + "month": "2026-08", + "views": 185 + }, + { + "month": "2026-09", + "views": 168 + }, + { + "month": "2026-10", + "views": 165 + } + ], + "latestMonth": "2026-10", + "total": 1047, + "dailyAverage": 5.32258064516129, + "trendPercent": -1.7857142857142856 + }, + "stats": { + "attention": 37, + "depth": 61, + "reach": 16 + }, + "legacyCategory": "Science", + "drift30": { + "last30": 148, + "prev30": 160, + "pct": -7.5 + }, + "instanceOf": [ + { + "id": "Q113145171", + "label": "type of chemical entity" + } + ] + }, + { + "pageId": 17755916, + "title": "Xiaoliang Sunney Xie", + "description": "Chinese-American biochemist", + "wikidataId": "Q906616", + "revisionId": 1360992742, + "pageBytes": 35403, + "languageCount": 5, + "languagesTruncated": false, + "categories": [ + "1962 births", + "Chinese emigrants to the United States", + "Fellows of the American Academy of Arts and Sciences", + "Fellows of the American Association for the Advancement of Science", + "Foreign members of the Chinese Academy of Sciences", + "Harvard University faculty", + "Living people", + "Members of the National Academy of Medicine", + "Members of the Standing Committee of the 14th Chinese People's Political Consultative Conference", + "Members of the United States National Academy of Sciences", + "Peking University alumni", + "Scientists from Beijing", + "Spectroscopists", + "University of California, San Diego alumni", + "University of Chicago alumni" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 348 + }, + { + "month": "2026-06", + "views": 213 + }, + { + "month": "2026-07", + "views": 190 + }, + { + "month": "2026-08", + "views": 222 + }, + { + "month": "2026-09", + "views": 182 + }, + { + "month": "2026-10", + "views": 269 + } + ], + "latestMonth": "2026-10", + "total": 1424, + "dailyAverage": 8.67741935483871, + "trendPercent": 47.8021978021978 + }, + "stats": { + "attention": 41, + "depth": 76, + "reach": 26 + }, + "legacyCategory": "People", + "drift30": { + "last30": 241, + "prev30": 249, + "pct": -3.2128514056224895 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 19025970, + "title": "Marina Kuzina", + "description": "Russian basketball player", + "wikidataId": "Q2704942", + "revisionId": 1385734329, + "pageBytes": 2074, + "languageCount": 18, + "languagesTruncated": false, + "categories": [ + "1985 births", + "21st-century Russian sportswomen", + "Basketball players at the 2008 Summer Olympics", + "Basketball players at the 2012 Summer Olympics", + "Indiana Fever draft picks", + "Living people", + "Medalists at the 2008 Summer Olympics", + "Olympic basketball players for Russia", + "Olympic bronze medalists for Russia", + "Olympic medalists in basketball", + "Russian Olympic medalist stubs", + "Russian basketball biography stubs", + "Russian women's basketball players" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 59 + }, + { + "month": "2026-06", + "views": 37 + }, + { + "month": "2026-07", + "views": 144 + }, + { + "month": "2026-08", + "views": 49 + }, + { + "month": "2026-09", + "views": 47 + }, + { + "month": "2026-10", + "views": 27 + } + ], + "latestMonth": "2026-10", + "total": 363, + "dailyAverage": 0.8709677419354839, + "trendPercent": -42.5531914893617 + }, + "stats": { + "attention": 24, + "depth": 55, + "reach": 43 + }, + "legacyCategory": "People", + "drift30": { + "last30": 26, + "prev30": 44, + "pct": -40.909090909090914 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 24114222, + "title": "Rum cake", + "description": "Type of dessert", + "wikidataId": "Q7379109", + "revisionId": 1317119586, + "pageBytes": 4446, + "languageCount": 8, + "languagesTruncated": false, + "categories": [ + "Caribbean cuisine", + "Christmas cakes", + "Dessert stubs", + "Guyanese cuisine", + "Jamaican desserts", + "Puerto Rican cuisine", + "Rum desserts", + "Sponge cakes", + "Trinidad and Tobago cuisine" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 1340 + }, + { + "month": "2026-06", + "views": 1343 + }, + { + "month": "2026-07", + "views": 1536 + }, + { + "month": "2026-08", + "views": 1878 + }, + { + "month": "2026-09", + "views": 1808 + }, + { + "month": "2026-10", + "views": 1919 + } + ], + "latestMonth": "2026-10", + "total": 9824, + "dailyAverage": 61.903225806451616, + "trendPercent": 6.139380530973451 + }, + "stats": { + "attention": 55, + "depth": 61, + "reach": 32 + }, + "legacyCategory": "Culture", + "drift30": { + "last30": 2299, + "prev30": 1848, + "pct": 24.404761904761905 + }, + "instanceOf": [] + }, + { + "pageId": 31581668, + "title": "Ian Potter Museum of Art", + "description": "Art museum in Parkville, Victoria", + "wikidataId": "Q5982619", + "revisionId": 1377811586, + "pageBytes": 10524, + "languageCount": 2, + "languagesTruncated": false, + "categories": [ + "Archaeological museums in Australia", + "Art museums and galleries established in 1998", + "Art museums and galleries in Melbourne", + "Buildings and structures in the City of Melbourne (LGA)", + "Contemporary art galleries in Australia", + "University museums in Australia", + "University of Melbourne" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 136 + }, + { + "month": "2026-06", + "views": 117 + }, + { + "month": "2026-07", + "views": 138 + }, + { + "month": "2026-08", + "views": 156 + }, + { + "month": "2026-09", + "views": 128 + }, + { + "month": "2026-10", + "views": 148 + } + ], + "latestMonth": "2026-10", + "total": 823, + "dailyAverage": 4.774193548387097, + "trendPercent": 15.625 + }, + "stats": { + "attention": 36, + "depth": 67, + "reach": 16 + }, + "legacyCategory": "History", + "drift30": { + "last30": 125, + "prev30": 122, + "pct": 2.459016393442623 + }, + "instanceOf": [ + { + "id": "Q207694", + "label": "art museum" + } + ] + }, + { + "pageId": 33510186, + "title": "Piet Hesse", + "description": "Dutch actor and comedian (1872–1936)", + "wikidataId": "Q2513810", + "revisionId": 1371413731, + "pageBytes": 3044, + "languageCount": 4, + "languagesTruncated": false, + "categories": [ + "1872 births", + "1936 deaths", + "20th-century Dutch comedians", + "20th-century Dutch male actors", + "Comedians from Amsterdam", + "Dutch male comedians", + "Dutch male silent film actors", + "Dutch slapstick comedians", + "Male actors from Amsterdam" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 30 + }, + { + "month": "2026-06", + "views": 15 + }, + { + "month": "2026-07", + "views": 21 + }, + { + "month": "2026-08", + "views": 30 + }, + { + "month": "2026-09", + "views": 16 + }, + { + "month": "2026-10", + "views": 22 + } + ], + "latestMonth": "2026-10", + "total": 134, + "dailyAverage": 0.7096774193548387, + "trendPercent": 37.5 + }, + "stats": { + "attention": 23, + "depth": 58, + "reach": 23 + }, + "legacyCategory": "People", + "drift30": { + "last30": 17, + "prev30": 16, + "pct": 6.25 + }, + "instanceOf": [ + { + "id": "Q5", + "label": "human" + } + ] + }, + { + "pageId": 34748061, + "title": "Goneplax", + "description": "Genus of crabs", + "wikidataId": "Q5234395", + "revisionId": 1315380924, + "pageBytes": 2236, + "languageCount": 8, + "languagesTruncated": false, + "categories": [ + "Decapod genera", + "Extant Miocene first appearances", + "Goneplacoidea", + "Goneplacoidea stubs" + ], + "categoriesTruncated": false, + "fetchedAt": "2026-11-16T00:00:00+00:00", + "pageviews": { + "status": "available", + "months": [ + { + "month": "2026-05", + "views": 22 + }, + { + "month": "2026-06", + "views": 20 + }, + { + "month": "2026-07", + "views": 21 + }, + { + "month": "2026-08", + "views": 18 + }, + { + "month": "2026-09", + "views": 36 + }, + { + "month": "2026-10", + "views": 11 + } + ], + "latestMonth": "2026-10", + "total": 128, + "dailyAverage": 0.3548387096774194, + "trendPercent": -69.44444444444444 + }, + "stats": { + "attention": 18, + "depth": 56, + "reach": 32 + }, + "legacyCategory": "Nature", + "drift30": { + "last30": 18, + "prev30": 22, + "pct": -18.181818181818183 + }, + "instanceOf": [ + { + "id": "Q16521", + "label": "taxon" + } + ] + } + ] +} \ No newline at end of file diff --git a/docs/game/starter-cards.json b/docs/game/starter-cards.json new file mode 100644 index 0000000..93f1787 --- /dev/null +++ b/docs/game/starter-cards.json @@ -0,0 +1,424 @@ +{ + "frozenAt": "2026-11-17", + "note": "Frozen loaner/starter stats from the council-data random sample. Do not fetch live.", + "cards": [ + { + "pageId": 49830722, + "title": "Dicroidium odontopteroides", + "category": "Nature", + "wikidataId": "Q25095289", + "revisionId": 1116073630, + "pageBytes": 1943, + "languageCount": 0, + "monthlyViews": 59, + "latestMonth": "2026-10", + "trendPercent": 5.4, + "stats": { + "attention": 30, + "depth": 55, + "reach": 0 + }, + "tiers": { + "attention": 4, + "depth": 2, + "reach": 1 + } + }, + { + "pageId": 25856905, + "title": "Dichromorpha viridis", + "category": "Nature", + "wikidataId": "Q5272562", + "revisionId": 1367363150, + "pageBytes": 1347, + "languageCount": 4, + "monthlyViews": 133, + "latestMonth": "2026-10", + "trendPercent": -43.6, + "stats": { + "attention": 35, + "depth": 52, + "reach": 23 + }, + "tiers": { + "attention": 6, + "depth": 1, + "reach": 5 + } + }, + { + "pageId": 66508497, + "title": "Amanita mairei", + "category": "Nature", + "wikidataId": "Q15651951", + "revisionId": 1323515500, + "pageBytes": 998, + "languageCount": 8, + "monthlyViews": 61, + "latestMonth": "2026-10", + "trendPercent": -21.8, + "stats": { + "attention": 30, + "depth": 50, + "reach": 32 + }, + "tiers": { + "attention": 4, + "depth": 1, + "reach": 7 + } + }, + { + "pageId": 4289899, + "title": "Anthodon (reptile)", + "category": "Nature", + "wikidataId": "Q2505064", + "revisionId": 1384682008, + "pageBytes": 9037, + "languageCount": 12, + "monthlyViews": 233, + "latestMonth": "2026-10", + "trendPercent": -8.3, + "stats": { + "attention": 39, + "depth": 66, + "reach": 37 + }, + "tiers": { + "attention": 8, + "depth": 7, + "reach": 8 + } + }, + { + "pageId": 47519878, + "title": "Jeanne Madden", + "category": "People", + "wikidataId": "Q20974011", + "revisionId": 1382761423, + "pageBytes": 1817, + "languageCount": 4, + "monthlyViews": 26, + "latestMonth": "2026-10", + "trendPercent": -40.9, + "stats": { + "attention": 24, + "depth": 54, + "reach": 23 + }, + "tiers": { + "attention": 2, + "depth": 2, + "reach": 5 + } + }, + { + "pageId": 46263191, + "title": "Max Touloute", + "category": "People", + "wikidataId": "Q20641573", + "revisionId": 1384441370, + "pageBytes": 10140, + "languageCount": 2, + "monthlyViews": 47, + "latestMonth": "2026-10", + "trendPercent": 95.8, + "stats": { + "attention": 28, + "depth": 67, + "reach": 16 + }, + "tiers": { + "attention": 4, + "depth": 8, + "reach": 4 + } + }, + { + "pageId": 3372934, + "title": "Hermes Ramírez", + "category": "People", + "wikidataId": "Q522855", + "revisionId": 1364063954, + "pageBytes": 8264, + "languageCount": 13, + "monthlyViews": 59, + "latestMonth": "2026-10", + "trendPercent": -9.2, + "stats": { + "attention": 30, + "depth": 65, + "reach": 38 + }, + "tiers": { + "attention": 4, + "depth": 7, + "reach": 8 + } + }, + { + "pageId": 1374812, + "title": "Tom Ewell", + "category": "People", + "wikidataId": "Q427388", + "revisionId": 1381663979, + "pageBytes": 17965, + "languageCount": 30, + "monthlyViews": 4548, + "latestMonth": "2026-10", + "trendPercent": -19.8, + "stats": { + "attention": 61, + "depth": 71, + "reach": 50 + }, + "tiers": { + "attention": 10, + "depth": 9, + "reach": 10 + } + }, + { + "pageId": 13799810, + "title": "Levophacetoperane", + "category": "Science", + "wikidataId": "Q6535818", + "revisionId": 1374230485, + "pageBytes": 4639, + "languageCount": 2, + "monthlyViews": 165, + "latestMonth": "2026-10", + "trendPercent": -1.8, + "stats": { + "attention": 37, + "depth": 61, + "reach": 16 + }, + "tiers": { + "attention": 7, + "depth": 5, + "reach": 4 + } + }, + { + "pageId": 36740675, + "title": "The Best of Men", + "category": "Science", + "wikidataId": "Q7717125", + "revisionId": 1372732350, + "pageBytes": 6002, + "languageCount": 4, + "monthlyViews": 476, + "latestMonth": "2026-10", + "trendPercent": -3.4, + "stats": { + "attention": 45, + "depth": 63, + "reach": 23 + }, + "tiers": { + "attention": 9, + "depth": 6, + "reach": 5 + } + }, + { + "pageId": 4426773, + "title": "Agda (programming language)", + "category": "Science", + "wikidataId": "Q20479", + "revisionId": 1384528612, + "pageBytes": 14254, + "languageCount": 11, + "monthlyViews": 2439, + "latestMonth": "2026-10", + "trendPercent": 7.8, + "stats": { + "attention": 56, + "depth": 69, + "reach": 36 + }, + "tiers": { + "attention": 10, + "depth": 9, + "reach": 8 + } + }, + { + "pageId": 42770753, + "title": "Château de la Faye (Villexavier)", + "category": "History", + "wikidataId": "Q2971223", + "revisionId": 1375492681, + "pageBytes": 1851, + "languageCount": 1, + "monthlyViews": 14, + "latestMonth": "2026-10", + "trendPercent": 7.7, + "stats": { + "attention": 20, + "depth": 54, + "reach": 10 + }, + "tiers": { + "attention": 1, + "depth": 2, + "reach": 3 + } + }, + { + "pageId": 15362336, + "title": "1954 Gold Coast general election", + "category": "History", + "wikidataId": "Q2539674", + "revisionId": 1351181171, + "pageBytes": 4141, + "languageCount": 2, + "monthlyViews": 181, + "latestMonth": "2026-10", + "trendPercent": -10.4, + "stats": { + "attention": 38, + "depth": 60, + "reach": 16 + }, + "tiers": { + "attention": 8, + "depth": 4, + "reach": 4 + } + }, + { + "pageId": 9026000, + "title": "Names of Poland", + "category": "History", + "wikidataId": "Q6961536", + "revisionId": 1351068420, + "pageBytes": 18966, + "languageCount": 4, + "monthlyViews": 1431, + "latestMonth": "2026-10", + "trendPercent": -0.9, + "stats": { + "attention": 53, + "depth": 71, + "reach": 23 + }, + "tiers": { + "attention": 10, + "depth": 9, + "reach": 5 + } + }, + { + "pageId": 25275009, + "title": "Amur Annexation", + "category": "History", + "wikidataId": "Q4379152", + "revisionId": 1381503728, + "pageBytes": 15490, + "languageCount": 9, + "monthlyViews": 3238, + "latestMonth": "2026-10", + "trendPercent": -6.7, + "stats": { + "attention": 59, + "depth": 70, + "reach": 33 + }, + "tiers": { + "attention": 10, + "depth": 9, + "reach": 7 + } + }, + { + "pageId": 7674700, + "title": "Shipley Plateau", + "category": "Culture", + "wikidataId": "Q7498025", + "revisionId": 1384061257, + "pageBytes": 1745, + "languageCount": 1, + "monthlyViews": 22, + "latestMonth": "2026-10", + "trendPercent": -55.1, + "stats": { + "attention": 23, + "depth": 54, + "reach": 10 + }, + "tiers": { + "attention": 2, + "depth": 2, + "reach": 3 + } + }, + { + "pageId": 15810707, + "title": "Charmont-en-Beauce", + "category": "Culture", + "wikidataId": "Q667131", + "revisionId": 1381828954, + "pageBytes": 1811, + "languageCount": 32, + "monthlyViews": 23, + "latestMonth": "2026-10", + "trendPercent": 27.8, + "stats": { + "attention": 23, + "depth": 54, + "reach": 51 + }, + "tiers": { + "attention": 2, + "depth": 2, + "reach": 10 + } + }, + { + "pageId": 48653101, + "title": "Tornadoes of 1978", + "category": "Culture", + "wikidataId": "Q22093730", + "revisionId": 1381828221, + "pageBytes": 16373, + "languageCount": 0, + "monthlyViews": 511, + "latestMonth": "2026-10", + "trendPercent": 3.2, + "stats": { + "attention": 45, + "depth": 70, + "reach": 0 + }, + "tiers": { + "attention": 9, + "depth": 9, + "reach": 1 + } + }, + { + "pageId": 981340, + "title": "Tatsunoko Production", + "category": "Culture", + "wikidataId": "Q1323459", + "revisionId": 1384823392, + "pageBytes": 74169, + "languageCount": 19, + "monthlyViews": 4738, + "latestMonth": "2026-10", + "trendPercent": -9.4, + "stats": { + "attention": 61, + "depth": 81, + "reach": 43 + }, + "tiers": { + "attention": 10, + "depth": 10, + "reach": 9 + } + } + ] +} \ No newline at end of file diff --git a/scripts/night/card_analyze.py b/scripts/night/card_analyze.py new file mode 100644 index 0000000..6bbb30c --- /dev/null +++ b/scripts/night/card_analyze.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Summarise card-sample.json into markdown stats. Usage: python3 -I card_analyze.py sample.json > out.md""" +import json, sys, math, statistics as st, collections, re +d = json.load(open(sys.argv[1])); C = d['cards'] +def q(v): + v = sorted(v); n = len(v) + def p(x): + k = (n - 1) * x; f = math.floor(k); c = min(f + 1, n - 1); return v[f] + (v[c] - v[f]) * (k - f) + return [v[0], p(.1), p(.25), p(.5), p(.75), p(.9), v[-1]] +def skew(v): + m, s = st.mean(v), st.pstdev(v); return sum((x - m) ** 3 for x in v) / len(v) / s ** 3 if s else 0 +def rank(v): + o = sorted(range(len(v)), key=lambda i: v[i]); r = [0] * len(v); i = 0 + while i < len(o): + j = i + while j + 1 < len(o) and v[o[j + 1]] == v[o[i]]: j += 1 + for k in range(i, j + 1): r[o[k]] = (i + j) / 2 + i = j + 1 + return r +def pearson(a, b): + ma, mb = st.mean(a), st.mean(b); sa = math.sqrt(sum((x - ma) ** 2 for x in a)); sb = math.sqrt(sum((y - mb) ** 2 for y in b)) + return sum((x - ma) * (y - mb) for x, y in zip(a, b)) / (sa * sb) if sa and sb else float('nan') +pv = [c for c in C if c['pageviews']['status'] == 'available'] +F = {'attention': lambda c: c['stats']['attention'], 'depth': lambda c: c['stats']['depth'], 'reach': lambda c: c['stats']['reach'], + 'pageBytes': lambda c: c['pageBytes'], 'languageCount': lambda c: c['languageCount'], + 'monthlyViews': lambda c: c['pageviews']['months'][5]['views'] if c['pageviews']['status'] == 'available' else None, + 'dailyAverage': lambda c: c['pageviews']['dailyAverage'], 'trendPercent': lambda c: c['pageviews']['trendPercent'], + 'drift30Percent': lambda c: c['drift30']['pct']} +out = [] +P = out.append +rate = f"{len(C)/d['rawPagesSeen']*100:.0f}%" if d['rawPagesSeen'] else '~44% (149/340 logged during sampling)' +P(f"Sample: **{len(C)} cards**; {rate} of random pages pass the illustrated filter. Pageviews available for {len(pv)}.\n") +P('| stat | n | min | p10 | p25 | median | p75 | p90 | max | mean | skew |'); P('|---|---|---|---|---|---|---|---|---|---|---|') +for k, f in F.items(): + v = [f(c) for c in C if f(c) is not None] + qs = q(v); fmt = (lambda x: f'{x:.0f}') if k not in ('trendPercent', 'drift30Percent', 'dailyAverage') else (lambda x: f'{x:.1f}') + P(f"| {k} | {len(v)} | " + ' | '.join(fmt(x) for x in qs) + f" | {fmt(st.mean(v))} | {skew(v):.2f} |") +P('\n**Spearman rank correlations** (cards with pageviews):\n') +keys = ['attention', 'depth', 'reach', 'trendPercent', 'drift30Percent'] +rows = [c for c in pv if c['pageviews']['trendPercent'] is not None and c['drift30']['pct'] is not None] +R = {k: rank([F[k](c) for c in rows]) for k in keys} +P('| | ' + ' | '.join(keys) + ' |'); P('|---' * (len(keys) + 1) + '|') +for a in keys: P(f'| {a} | ' + ' | '.join(f'{pearson(R[a], R[b]):.2f}' for b in keys) + ' |') +P(f'\n(n={len(rows)}; attention~monthlyViews, depth~pageBytes, reach~languageCount are monotonic so their rank correlations are identical.)\n') +tp = [c['pageviews']['trendPercent'] for c in pv if c['pageviews']['trendPercent'] is not None] +P(f"**trendPercent sign:** positive {sum(t>0 for t in tp)} ({sum(t>0 for t in tp)/len(tp)*100:.0f}%), negative {sum(t<0 for t in tp)} ({sum(t<0 for t in tp)/len(tp)*100:.0f}%), zero {sum(t==0 for t in tp)}; null (prior month 0 or no views) {len(C)-len(tp)}. " + f"|trend| > 50%: {sum(abs(t)>50 for t in tp)}; > 100%: {sum(abs(t)>100 for t in tp)}.\n") +dr = [c['drift30']['pct'] for c in C if c['drift30']['pct'] is not None] +P(f"**30-day drift** (views 10-17..11-15 vs 09-17..10-16): median |drift| {st.median([abs(x) for x in dr]):.0f}%, " + f"p90 |drift| {q([abs(x) for x in dr])[5]:.0f}%. Attention score change implied: " + f"median {st.median([abs(100*math.log10((c['drift30']['last30']+1)/(c['drift30']['prev30']+1))/6) for c in C]):.1f} points, " + f"p90 {q([abs(100*math.log10((c['drift30']['last30']+1)/(c['drift30']['prev30']+1))/6) for c in C])[5]:.1f} points.\n") +for name, f in [('attention', F['attention']), ('depth', F['depth']), ('reach', F['reach'])]: + v = [f(c) for c in C if f(c) is not None]; h = collections.Counter(min(x // 10, 9) for x in v) + P(f"**{name} histogram (deciles 0-9,10-19..90-100):** " + ' '.join(str(h.get(i, 0)) for i in range(10))) +P(f"\nReach = 0 (no other languages): {sum(c['languageCount']==0 for c in C)}; reach 100 (>=999 langs) impossible in practice, max langs {max(c['languageCount'] for c in C)}. " + f"Attention null: {sum(c['stats']['attention'] is None for c in C)}; attention 0: {sum(c['stats']['attention']==0 for c in C)}.\n") +s3 = [sum(F[k](c) or 0 for k in ('attention', 'depth', 'reach')) for c in C] +P(f"**Sum of three stats:** " + ', '.join(f'{n} {x:.0f}' for n, x in zip(['min', 'p10', 'p25', 'median', 'p75', 'p90', 'max'], q(s3))) + '\n') +P('**Legacy `category()` (server/wiki.ts):** ' + ', '.join(f'{k} {v}' for k, v in collections.Counter(c['legacyCategory'] for c in C).most_common()) + '\n') +io = collections.Counter(x['label'] for c in C for x in c['instanceOf']) +P('**Top Wikidata P31 classes:** ' + ', '.join(f'{k} {v}' for k, v in io.most_common(40)) + '\n') +P(f"No Wikidata item: {sum(not c['wikidataId'] for c in C)}; no P31: {sum(not c['instanceOf'] for c in C)}\n") +words = collections.Counter() +for c in C: + for cat in set(w for t in c['categories'] for w in re.findall(r'[a-z]+', t.lower()) if len(w) > 3): words[cat] += 1 +P('**Most frequent category words (cards containing):** ' + ', '.join(f'{k} {v}' for k, v in words.most_common(60)) + '\n') +print('\n'.join(out)) + +# ---- rank normalisation table (critic request): score -> 1..10 tier by sample decile +def tiers(name): + v = sorted(F[name](c) for c in C if F[name](c) is not None) + return [v[min(len(v) - 1, int(len(v) * k / 10))] for k in range(1, 10)] +T = {k: tiers(k) for k in ('attention', 'depth', 'reach')} +print('\n## Rank-normalised tiers (1–10)\n') +print('Tier = 1 + number of breakpoints the score is **>=**. Breakpoints are the sample deciles p10..p90 of the 0–100 score. ' + 'Ties make some tiers thin (scores are integers).\n') +print('| stat | p10 | p20 | p30 | p40 | p50 | p60 | p70 | p80 | p90 |'); print('|---' * 10 + '|') +for k, b in T.items(): print(f'| {k} | ' + ' | '.join(str(x) for x in b) + ' |') +def tier(k, s): return None if s is None else 1 + sum(s >= x for x in T[k]) +for c in C: c['tiers'] = {k: tier(k, c['stats'][k]) for k in T} +tc = collections.Counter(c['tiers']['attention'] for c in C) +print('\nResulting tier counts — attention: ' + ' '.join(f'{t}:{tc.get(t,0)}' for t in [None] + list(range(1, 11)))) +for k in ('depth', 'reach'): + tc = collections.Counter(c['tiers'][k] for c in C); print(f'; {k}: ' + ' '.join(f'{t}:{tc.get(t,0)}' for t in range(1, 11))) +json.dump({'breakpoints': T, 'rule': 'tier = 1 + count(breakpoints <= score); attention null -> no tier'}, + open(sys.argv[2] if len(sys.argv) > 2 else '/dev/null', 'w'), indent=1) + +# ---- starter loaner candidates: 4 per legacy category, spread over combined tier +if len(sys.argv) > 3: + pick = [] + for cat in ['Space', 'Nature', 'People', 'Science', 'History', 'Culture']: + pool = sorted((c for c in C if c['legacyCategory'] == cat and c['stats']['attention'] is not None), + key=lambda c: sum(c['tiers'].values())) + if not pool: continue + n = min(4, len(pool)); idx = sorted({round(i * (len(pool) - 1) / max(1, n - 1)) for i in range(n)}) + for i in idx: + c = pool[i] + pick.append({'pageId': c['pageId'], 'title': c['title'], 'category': cat, 'wikidataId': c['wikidataId'], + 'revisionId': c['revisionId'], 'pageBytes': c['pageBytes'], 'languageCount': c['languageCount'], + 'monthlyViews': c['pageviews']['months'][5]['views'], 'latestMonth': c['pageviews']['latestMonth'], + 'trendPercent': None if c['pageviews']['trendPercent'] is None else round(c['pageviews']['trendPercent'], 1), + 'stats': c['stats'], 'tiers': c['tiers']}) + json.dump({'frozenAt': d['generatedAt'][:10], 'note': 'Frozen loaner/starter stats from the council-data random sample. Do not fetch live.', + 'cards': pick}, open(sys.argv[3], 'w'), indent=1, ensure_ascii=False) + print(f'\nStarter candidates: {len(pick)} written to {sys.argv[3]}: ' + collections.Counter(p['category'] for p in pick).__repr__()) + +# ---- candidate factions from Wikidata P31 (+ categories fallback) +FAC = [ + ('People', r'\bhuman\b|fictional character|person'), + ('Sport', r'season|sports team|football|match|tournament|championship|final\b|club|league|olympic|race\b'), + ('Nature', r'taxon|species|genus|plant|fungus|disease|epiphyte|mineral|bird|fish|insect'), + ('Places', r'village|town|city|commune|municipality|river|lake|mountain|county|district|parish|region|plateau|island|settlement|neighbo|locality|census|hamlet|valley|bay|area|province|state of|capital|suburb|stream|peak|unincorporated|human settlement|local government'), + ('Structures', r'building|castle|mosque|church|cathedral|temple|bridge|station|railway line|road|highway|museum|structure|stadium|dam|tower|house|school|hospital|airport|monument|fort|palace|lighthouse|park'), + ('Works', r'film|album|single|song|musical|television|book|novel|video game|painting|literary|composition|series|episode|magazine|newspaper|poem|opera|play\b|artwork|sculpture'), + ('Organisations', r'company|group|band|organi[sz]ation|university|college|party|business|enterprise|agency|institute|association|brand|union|ministry|military unit'), + ('Events', r'election|protest|battle|war\b|storm|nor.easter|cyclone|event|disaster|treaty|conflict|earthquake|incident|festival|referendum|conference|ceremony'), + ('Ideas & Tech', r'programming|software|language|chemical|compound|gene|protein|theorem|concept|technology|vehicle|aircraft|ship|weapon|class|model|device|algorithm|religion|discipline|theory|food|dish'), +] +def faction(c): + text = ' | '.join(x['label'].lower() for x in c['instanceOf']) + for name, rx in FAC: + if text and re.search(rx, text): return name + cats = ' | '.join(c['categories']).lower() + if re.search(r'births|deaths|people', cats): return 'People' + if re.search(r'populated|villages|towns|geography|rivers', cats): return 'Places' + if re.search(r'films|albums|songs|novels|television|video games', cats): return 'Works' + return 'Other' +for c in C: c['faction'] = faction(c) +print('\n## Candidate factions (Wikidata P31 rules)\n') +print('| faction | n | share | median attention | median depth | median reach | example |'); print('|---|---|---|---|---|---|---|') +by = collections.defaultdict(list) +for c in C: by[c['faction']].append(c) +for name, cs in sorted(by.items(), key=lambda kv: -len(kv[1])): + med = lambda k: st.median([x['stats'][k] for x in cs if x['stats'][k] is not None] or [0]) + print(f"| {name} | {len(cs)} | {len(cs)/len(C)*100:.0f}% | {med('attention'):.0f} | {med('depth'):.0f} | {med('reach'):.0f} | {cs[0]['title']} |") +other = collections.Counter(x['label'] for c in by.get('Other', []) for x in c['instanceOf']) +print('\nUnclassified P31 labels: ' + ', '.join(f'{k} {v}' for k, v in other.most_common(25))) +if len(sys.argv) > 4: json.dump({c['pageId']: c['faction'] for c in C}, open(sys.argv[4], 'w')) diff --git a/scripts/night/card_sample.py b/scripts/night/card_sample.py new file mode 100644 index 0000000..06f1fc6 --- /dev/null +++ b/scripts/night/card_sample.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Sample random illustrated en.wikipedia articles the way server/wiki.ts selects them and +enrich them the way server/enrichment.ts does. Polite: ~4 req/s, sequential, disk cache. +Usage: python3 -I card_sample.py [target=320]""" +import hashlib, json, os, re, sys, time, urllib.parse, urllib.request, calendar, datetime as dt + +UA = 'WikiDeckCardDataSampler/0.1 (experimental card-game stat research; python-urllib)' +CACHE, OUT = sys.argv[1], sys.argv[2] +TARGET = int(sys.argv[3]) if len(sys.argv) > 3 else 320 +os.makedirs(CACHE, exist_ok=True) +_last = [0.0] + +def get(url, cache=True): + key = os.path.join(CACHE, hashlib.sha1(url.encode()).hexdigest() + '.json') + if cache and os.path.exists(key): + return json.load(open(key)) + if os.environ.get('CACHE_ONLY') and 'wikidata.org' not in url: + return {'__missing': True} + for attempt in range(6): + wait = (1.0 if 'en.wikipedia.org' in url else 0.25) - (time.time() - _last[0]) + if wait > 0: time.sleep(wait) + _last[0] = time.time() + req = urllib.request.Request(url, headers={'User-Agent': UA, 'Accept': 'application/json'}) + try: + with urllib.request.urlopen(req, timeout=20) as r: + data = json.loads(r.read().decode()) + break + except urllib.error.HTTPError as e: + if e.code == 404: data = {'__404': True}; break + if e.code == 429 or e.code >= 500: + ra = e.headers.get('retry-after'); w = int(ra) + 1 if ra and ra.isdigit() else 5 * (attempt + 1) + print('http', e.code, 'sleep', w, file=sys.stderr); time.sleep(min(w, 60)); continue + raise + except Exception as e: + print('retry', attempt, type(e).__name__, e, file=sys.stderr); time.sleep(2 * (attempt + 1)) + else: + raise RuntimeError('failed ' + url) + if cache: json.dump(data, open(key, 'w')) + return data + +def api(params, cache=True): + return get('https://en.wikipedia.org/w/api.php?' + urllib.parse.urlencode({'format': 'json', 'formatversion': '2', **params}), cache) + +def legacy_category(title, cats): + t = (title + ' ' + ' '.join(cats)).lower() + if re.search(r'astronom|planet|space|galax|moon|star\b', t): return 'Space' + if re.search(r'animal|plant|species|ocean|biolog|mollusc', t): return 'Nature' + if re.search(r'births|deaths|people|scientist', t): return 'People' + if re.search(r'physic|chem|math|science|technolog', t): return 'Science' + if re.search(r'histor|ancient|archaeolog|empire', t): return 'History' + return 'Culture' + +def score(v, scale): + import math + return min(100, round(math.log10(v + 1) / scale * 100)) + +# 1. random illustrated articles (same filter as wiki.ts: thumbnail + extract >= 40 chars) +picked, seen, batches, raw_pages = [], set(), 0, 0 +state_file = os.path.join(CACHE, '_random_state.json') +if os.path.exists(state_file): + picked = json.load(open(state_file)); seen = {p['pageId'] for p in picked} +while len(picked) < TARGET: + try: d = api({'action': 'query', 'generator': 'random', 'grnnamespace': '0', 'grnlimit': '20', + 'prop': 'extracts|pageimages|info|categories', 'exintro': '1', 'explaintext': '1', 'exchars': '900', + 'exlimit': '20', 'piprop': 'thumbnail', 'pithumbsize': '800', 'cllimit': '500'}, cache=False) + except RuntimeError as e: print(e, file=sys.stderr); time.sleep(5); continue + batches += 1 + for p in d.get('query', {}).get('pages', []): + raw_pages += 1 + thumb = (p.get('thumbnail') or {}).get('source', '') + ext = (p.get('extract') or '').strip() + if not re.match(r'https://(upload|thumb)\.wikimedia\.org/', thumb) or len(ext) < 40 or p['pageid'] in seen: continue + seen.add(p['pageid']) + picked.append({'pageId': p['pageid'], 'title': p['title'], + 'legacyCategory': legacy_category(p['title'], [c['title'] for c in p.get('categories', [])])}) + json.dump(picked, open(state_file, 'w')) + print(f'random batch {batches}: {len(picked)} illustrated / {raw_pages} raw', file=sys.stderr) +picked = picked[:TARGET] + +# 2. enrichment per article (same params as enrichment.ts) + daily views for drift +now = dt.datetime(2026, 11, 16, tzinfo=dt.timezone.utc) +months = [] +for i in range(6): + m = now.month - 6 + i; y = now.year + (m - 1) // 12; m = (m - 1) % 12 + 1 + months.append(f'{y:04d}-{m:02d}') +# batched metadata (same props as enrichment.ts; per-page cllimit 50 is emulated by truncating) +meta = {} +ids = [p['pageId'] for p in picked] +for i in range(0, len(ids), 50): + chunk = ids[i:i + 50]; cont = {}; pages = {} + while True: + md = api({'action': 'query', 'pageids': '|'.join(map(str, chunk)), 'prop': 'info|categories|pageprops|description|langlinks', + 'clshow': '!hidden', 'cllimit': '500', 'lllimit': '500', 'ppprop': 'wikibase_item', **cont}) + for pg in md['query']['pages']: + cur = pages.setdefault(pg['pageid'], {**pg, 'categories': [], 'langlinks': []}) + cur['categories'] += pg.get('categories', []); cur['langlinks'] += pg.get('langlinks', []) + if 'continue' not in md: break + cont = md['continue'] + meta.update(pages) + print(f'metadata {len(meta)}/{len(ids)}', file=sys.stderr) +cards = [] +for n, pk in enumerate(picked): + page = meta[pk['pageId']] + cont = {'clcontinue': 1} if len(page['categories']) > 50 else {} + page['categories'] = page['categories'][:50] + langs = len(page.get('langlinks', [])) + t = urllib.parse.quote(page['title'].replace(' ', '_'), safe='') + daily = get(f'https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/user/{t}/daily/{months[0].replace("-", "")}01/20261115') + if daily.get('__missing'): continue + dmap = {it['timestamp'][:8]: it['views'] for it in daily.get('items', [])} + pv = {'status': 'unavailable', 'months': [], 'latestMonth': months[5], 'total': None, 'dailyAverage': None, 'trendPercent': None} + if dmap: + ordered = [] + for m in months: + y, mo = map(int, m.split('-')); nd = calendar.monthrange(y, mo)[1] + ordered.append({'month': m, 'views': sum(dmap.get(f'{y:04d}{mo:02d}{d:02d}', 0) for d in range(1, nd + 1))}) + latest, prior = ordered[5]['views'], ordered[4]['views'] + nd = calendar.monthrange(*map(int, months[5].split('-')))[1] + pv = {'status': 'available', 'months': ordered, 'latestMonth': months[5], 'total': sum(o['views'] for o in ordered), + 'dailyAverage': latest / nd, 'trendPercent': (latest - prior) / prior * 100 if prior > 0 else None} + # 30-day drift: views 2026-10-17..11-15 vs 2026-09-17..10-16 + def window(start, days): + s = dt.date.fromisoformat(start) + return sum(dmap.get((s + dt.timedelta(d)).strftime('%Y%m%d'), 0) for d in range(days)) + last30, prev30 = window('2026-10-17', 30), window('2026-09-17', 30) + pb = page['length'] + cards.append({'pageId': page['pageid'], 'title': page['title'], 'description': page.get('description'), + 'wikidataId': (page.get('pageprops') or {}).get('wikibase_item'), 'revisionId': page['lastrevid'], 'pageBytes': pb, + 'languageCount': langs, 'languagesTruncated': 'llcontinue' in cont, + 'categories': [c['title'].removeprefix('Category:') for c in page.get('categories', [])], + 'categoriesTruncated': 'clcontinue' in cont, 'fetchedAt': now.isoformat(), 'pageviews': pv, + 'stats': {'attention': score(pv['months'][5]['views'], 6) if pv['status'] == 'available' else None, + 'depth': score(pb, 6), 'reach': score(langs, 3)}, + 'legacyCategory': pk['legacyCategory'], + 'drift30': {'last30': last30, 'prev30': prev30, 'pct': (last30 - prev30) / prev30 * 100 if prev30 else None}}) + if n % 25 == 0: print(f'enriched {n + 1}/{len(picked)}', file=sys.stderr) + +# 3. Wikidata P31 (instance of) + labels +qids = [c['wikidataId'] for c in cards if c['wikidataId']] +p31 = {} +for i in range(0, len(qids), 50): + d = get('https://www.wikidata.org/w/api.php?' + urllib.parse.urlencode({'action': 'wbgetentities', 'format': 'json', + 'ids': '|'.join(qids[i:i + 50]), 'props': 'claims'})) + for q, ent in d.get('entities', {}).items(): + p31[q] = [c['mainsnak']['datavalue']['value']['id'] for c in ent.get('claims', {}).get('P31', []) + if c['mainsnak'].get('datavalue')] +classes = sorted({c for v in p31.values() for c in v}) +labels = {} +for i in range(0, len(classes), 50): + d = get('https://www.wikidata.org/w/api.php?' + urllib.parse.urlencode({'action': 'wbgetentities', 'format': 'json', + 'ids': '|'.join(classes[i:i + 50]), 'props': 'labels', 'languages': 'en'})) + for q, ent in d.get('entities', {}).items(): + labels[q] = ent.get('labels', {}).get('en', {}).get('value', q) +for c in cards: + c['instanceOf'] = [{'id': q, 'label': labels.get(q, q)} for q in p31.get(c['wikidataId'], [])] +json.dump({'generatedAt': dt.datetime.now(dt.timezone.utc).isoformat(), 'method': 'random ns0 batches of 20, filter as server/wiki.ts (thumbnail + extract>=40); enrichment as server/enrichment.ts; monthly views summed from daily REST pageviews; P31 from Wikidata', + 'randomBatches': batches, 'rawPagesSeen': raw_pages, 'cards': cards}, open(OUT, 'w'), indent=1, ensure_ascii=False) +print('done', len(cards), file=sys.stderr) diff --git a/server/account/README.md b/server/account/README.md new file mode 100644 index 0000000..de49bb7 --- /dev/null +++ b/server/account/README.md @@ -0,0 +1,60 @@ +# eom.dev accounts (Dex SSO) and wallet linking + +Off-chain only. Nothing here changes blocks, transfers, trades or validation. + +## Flow +1. **Browser** (`src/auth/session.ts`): + - `GET /api/account/config` + - build the PKCE S256 authorize URL (with `state` and `nonce`) + - navigate to `https://dex.eom.dev/auth` +2. Dex redirects to `/auth/callback`. On native, it uses `dev.eom.wikideck:/oauth/callback`. +3. **Browser** sends `POST /api/account/token {code, codeVerifier, redirectUri, nonce}`. The **node** then: + - exchanges the code as the public client `wikideck` (no secret) + - verifies the ID token against the JWKS + - returns `{idToken, expiresAt, account}` + + The exchange runs on the node because Dex sends no CORS headers. +4. The browser keeps the ID token in **sessionStorage** and sends it as `Authorization: Bearer`. +5. **Linking a wallet:** + - `POST challenge {address}` → `{nonce, message, expiresAt}` + - the **client builds the message itself** (`shared/account-link.ts` `clientLinkMessage`). It validates the nonce and expiry, refuses if the node's `message` differs, and signs locally with `src/wallet.ts` `sign`. The wallet never signs node-supplied text. + - `POST link {nonce, address, publicKey, signature}` + + Nonces are single use, expire after 5 minutes, and are bound to (sub, address). There are at most 5 pending per account. One wallet belongs to one account. + +## Endpoints (`/api/account/...`) +| Method | Path | Auth | Purpose | +|---|---|---|---| +| GET | `config` | none | issuer, clientId, scopes, authorization endpoint, allowed redirect URIs | +| POST | `token` | none | code exchange → ID token + account | +| GET | `me` | Bearer | account + linked wallets | +| POST | `challenge` | Bearer | one-time link challenge | +| POST | `link` | Bearer | prove wallet ownership, store mapping | +| DELETE | `link/:address` | Bearer | unlink | +| GET | `names?addresses=a,b` | none | leaderboard display names (`preferred_username`, else `name`; never email) | + +Signed link message (off-chain, domain-tagged): +`["wikideck:account-link:v1", NETWORK, issuer, sub, address, nonce, expiresAt]` + +## Node configuration +- **`PUBLIC_ORIGIN`** must be the node's UI origin, for example `http://192.168.1.32:3101`. Otherwise the existing POST origin check returns 403. +- **Outbound HTTPS** to `https://dex.eom.dev` is required. +- **Optional overrides:** + - `WIKIDECK_OIDC_ISSUER` (default `https://dex.eom.dev/`) + - `WIKIDECK_OIDC_CLIENT_ID` (default `wikideck`) + - `WIKIDECK_OIDC_REDIRECT_URIS` (comma-separated; must match the Dex registration) +- **Storage:** `$WIKIDECK_DATA_DIR/accounts.sqlite`. + +## Capacitor +- The UI is bundled locally, so set `globalThis.WIKIDECK_NODE_URL = 'http://192.168.1.32:3101'` before using `src/auth`. That node's POST origin check must allow the app's WebView origin. +- Register the URL scheme `dev.eom.wikideck`. +- Install `@capacitor/browser` and `@capacitor/app`. +- Add the listener: + ```ts + App.addListener('appUrlOpen', ({ url }) => { if (isCallback(url)) void completeLogin(url); }); + ``` + +## Known limits +- **Logout is local.** Dex publishes no `end_session_endpoint`, so its SSO cookie remains. +- **ID tokens aren't refreshed.** The default Dex lifetime is 24 h; after that, log in again. +- **Challenges live in memory.** A node restart drops pending challenges, so the client just asks again. diff --git a/server/account/oidc.ts b/server/account/oidc.ts new file mode 100644 index 0000000..a2df418 --- /dev/null +++ b/server/account/oidc.ts @@ -0,0 +1,141 @@ +import { createPublicKey, verify, type JsonWebKey, type KeyObject } from 'node:crypto'; + +// eom.dev accounts through Dex. WikiDeck is a *public* OIDC client (PKCE, no secret). +// The node performs the code exchange because Dex sends no CORS headers; it then +// verifies the ID token against Dex's JWKS. No Dex credentials live on the node. +export type OidcConfig = { + issuer: string; + clientId: string; + scopes: string; + /** Exact redirect URIs the node will pass to Dex (Dex enforces its own allowlist too). */ + redirectUris: string[]; + /** Allowed clock skew, seconds. */ + skew: number; +}; + +export function oidcConfig(env: NodeJS.ProcessEnv = process.env): OidcConfig { + const issuer = env.WIKIDECK_OIDC_ISSUER ?? 'https://dex.eom.dev/'; + const redirectUris = (env.WIKIDECK_OIDC_REDIRECT_URIS ?? + 'http://192.168.1.32:3101/auth/callback,http://192.168.1.32:3102/auth/callback,' + + 'http://192.168.1.32:3103/auth/callback,dev.eom.wikideck:/oauth/callback') + .split(',').map(s => s.trim()).filter(Boolean); + return { issuer, clientId: env.WIKIDECK_OIDC_CLIENT_ID ?? 'wikideck', + scopes: 'openid profile email groups', redirectUris, skew: 60 }; +} + +export type Discovery = { issuer: string; authorization_endpoint: string; token_endpoint: string; jwks_uri: string }; +export type IdClaims = { + iss: string; sub: string; aud: string | string[]; exp: number; iat: number; nbf?: number; + azp?: string; nonce?: string; name?: string; preferred_username?: string; email?: string; + email_verified?: boolean; groups?: string[]; +}; + +export class TokenError extends Error { readonly status = 401; } + +const b64url = (s: string) => Buffer.from(s, 'base64url'); +function decodeJson(part: string): Record { + if (!/^[A-Za-z0-9_-]+$/.test(part)) throw new TokenError('Malformed token'); + const value = JSON.parse(b64url(part).toString('utf8')); + if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TokenError('Malformed token'); + return value as Record; +} + +/** Fetches and caches the discovery document and JWKS; refreshes keys on an unknown kid (rotation). */ +export class DexKeys { + private discovery?: Promise; + private keys = new Map(); + private fetchedAt = 0; + readonly config: OidcConfig; + private readonly fetcher: typeof fetch; + private readonly now: () => number; + constructor(config: OidcConfig, fetcher: typeof fetch = fetch, now: () => number = Date.now) { + this.config = config; this.fetcher = fetcher; this.now = now; + } + + async meta(): Promise { + this.discovery ??= (async () => { + const url = new URL('.well-known/openid-configuration', this.config.issuer.endsWith('/') ? this.config.issuer : this.config.issuer + '/'); + const res = await this.fetcher(url, { signal: AbortSignal.timeout(8000) }); + if (!res.ok) throw new Error('OIDC discovery failed'); + const doc = await res.json() as Discovery; + // Issuer in discovery must match exactly (OIDC Discovery §4.3). + if (doc.issuer !== this.config.issuer) throw new Error('OIDC discovery issuer mismatch'); + return doc; + })().catch(e => { this.discovery = undefined; throw e; }); + return this.discovery; + } + + async key(kid: string): Promise { + const cached = this.keys.get(kid); + if (cached) return cached; + // Rate-limit refetches so random kids can't hammer Dex. + if (this.now() - this.fetchedAt < 30_000 && this.keys.size) return undefined; + await this.refresh(); + return this.keys.get(kid); + } + + async refresh(): Promise { + const { jwks_uri } = await this.meta(); + const res = await this.fetcher(jwks_uri, { signal: AbortSignal.timeout(8000) }); + if (!res.ok) throw new Error('JWKS fetch failed'); + const { keys } = await res.json() as { keys: (JsonWebKey & { kid?: string; use?: string; alg?: string })[] }; + const next = new Map(); + for (const jwk of keys ?? []) { + if (!jwk.kid || jwk.kty !== 'RSA' || (jwk.use && jwk.use !== 'sig') || (jwk.alg && jwk.alg !== 'RS256')) continue; + try { next.set(jwk.kid, createPublicKey({ key: jwk, format: 'jwk' })); } catch { /* skip bad key */ } + } + this.keys = next; this.fetchedAt = this.now(); + } +} + +/** + * Verifies a compact JWS ID token: RS256 only, signature against JWKS, exact issuer, + * audience contains our client (azp must be us when there are several), exp/nbf/iat with skew, + * and the nonce when one is expected. + */ +export async function verifyIdToken(token: string, keys: Pick, config: OidcConfig, + opts: { now?: number; nonce?: string } = {}): Promise { + if (typeof token !== 'string' || token.length > 8192) throw new TokenError('Malformed token'); + const parts = token.split('.'); + if (parts.length !== 3) throw new TokenError('Malformed token'); + let header: Record, claims: Record; + try { header = decodeJson(parts[0]); claims = decodeJson(parts[1]); } + catch (e) { throw e instanceof TokenError ? e : new TokenError('Malformed token'); } + if (header.alg !== 'RS256') throw new TokenError('Unsupported token algorithm'); + if (typeof header.kid !== 'string') throw new TokenError('Token key id missing'); + const key = await keys.key(header.kid); + if (!key) throw new TokenError('Unknown token signing key'); + if (!/^[A-Za-z0-9_-]+$/.test(parts[2]) || + !verify('sha256', Buffer.from(`${parts[0]}.${parts[1]}`), key, b64url(parts[2]))) + throw new TokenError('Invalid token signature'); + const now = Math.floor((opts.now ?? Date.now()) / 1000); + if (claims.iss !== config.issuer) throw new TokenError('Wrong token issuer'); + const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud]; + if (!aud.includes(config.clientId)) throw new TokenError('Wrong token audience'); + if (aud.length > 1 && claims.azp !== config.clientId) throw new TokenError('Wrong token authorized party'); + if (typeof claims.sub !== 'string' || !claims.sub || claims.sub.length > 512) throw new TokenError('Token subject missing'); + if (typeof claims.exp !== 'number' || now - config.skew >= claims.exp) throw new TokenError('Token expired'); + if (typeof claims.iat !== 'number' || claims.iat > now + config.skew) throw new TokenError('Token issued in the future'); + if (typeof claims.nbf === 'number' && claims.nbf > now + config.skew) throw new TokenError('Token not yet valid'); + if (opts.nonce !== undefined && claims.nonce !== opts.nonce) throw new TokenError('Token nonce mismatch'); + return claims as unknown as IdClaims; +} + +/** Authorization-code exchange as a public client (no secret), with the PKCE verifier. */ +export async function exchangeCode(keys: DexKeys, input: { code: string; codeVerifier: string; redirectUri: string }, + fetcher: typeof fetch = fetch): Promise<{ idToken: string }> { + const { token_endpoint } = await keys.meta(); + const res = await fetcher(token_endpoint, { method: 'POST', signal: AbortSignal.timeout(10000), + headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' }, + body: new URLSearchParams({ grant_type: 'authorization_code', client_id: keys.config.clientId, + code: input.code, code_verifier: input.codeVerifier, redirect_uri: input.redirectUri }) }); + const body = await res.json().catch(() => ({})) as { id_token?: string; error?: string }; + if (!res.ok || typeof body.id_token !== 'string') throw new TokenError(`Login failed${body.error ? `: ${String(body.error).slice(0, 60)}` : ''}`); + return { idToken: body.id_token }; +} + +/** Display name used on leaderboards: the eom.dev username, else name; never the email address. */ +export function displayName(claims: Pick): string { + const raw = (claims.preferred_username || claims.name || `player-${claims.sub.slice(0, 6)}`).normalize('NFKC'); + return raw.replace(/[\u0000-\u001f\u007f]/g, '').trim().slice(0, 48) || 'player'; +} diff --git a/server/account/router.ts b/server/account/router.ts new file mode 100644 index 0000000..9fe0530 --- /dev/null +++ b/server/account/router.ts @@ -0,0 +1,98 @@ +import { Router, type Request, type Response, type NextFunction } from 'express'; +import { resolve } from 'node:path'; +import { z } from 'zod'; +import { DexKeys, TokenError, displayName, exchangeCode, oidcConfig, verifyIdToken, type OidcConfig } from './oidc.ts'; +import { AccountStore, LinkError, type Account } from './store.ts'; + +// Mounted at /api/account by server/testnet/http.ts. Body parsing, the POST origin check, +// rate limits and no-store caching come from the /api middleware there. +export type AccountDeps = { config?: OidcConfig; keys?: DexKeys; store?: AccountStore; dataDir?: string; + fetcher?: typeof fetch; now?: () => number }; + +type Authed = Request & { account?: Account }; +const hex64 = z.string().regex(/^[a-f0-9]{64}$/); + +export function createAccountRouter(deps: AccountDeps = {}): Router { + const config = deps.config ?? oidcConfig(); + const now = deps.now ?? Date.now; + const keys = deps.keys ?? new DexKeys(config, deps.fetcher, now); + const store = deps.store ?? new AccountStore(resolve(deps.dataDir ?? 'data', 'accounts.sqlite'), now); + const router = Router(); + + const toAccount = (claims: Awaited>): Account => + ({ sub: claims.sub, issuer: claims.iss, name: displayName(claims), username: claims.preferred_username ?? '' }); + + const auth = async (req: Authed, _res: Response, next: NextFunction) => { + try { + const m = /^Bearer ([A-Za-z0-9_.-]+)$/.exec(req.get('authorization') ?? ''); + if (!m) throw new TokenError('Log in with your eom.dev account'); + req.account = toAccount(await verifyIdToken(m[1], keys, config, { now: now() })); + store.upsert(req.account); + next(); + } catch (e) { next(e); } + }; + + // Public, so the browser builds the authorize URL without fetching Dex (no CSP/CORS change). + router.get('/config', async (_req, res, next) => { + try { + const meta = await keys.meta(); + res.json({ issuer: config.issuer, clientId: config.clientId, scopes: config.scopes, + authorizationEndpoint: meta.authorization_endpoint, redirectUris: config.redirectUris }); + } catch (e) { next(e); } + }); + + router.post('/token', async (req, res, next) => { + try { + const body = z.object({ code: z.string().min(1).max(512), codeVerifier: z.string().regex(/^[A-Za-z0-9._~-]{43,128}$/), + redirectUri: z.string().max(256), nonce: z.string().min(16).max(128) }).strict().parse(req.body); + if (!config.redirectUris.includes(body.redirectUri)) throw new LinkError('Redirect URI not allowed'); + const { idToken } = await exchangeCode(keys, body, deps.fetcher); + const claims = await verifyIdToken(idToken, keys, config, { now: now(), nonce: body.nonce }); + const account = toAccount(claims); + store.upsert(account); + res.json({ idToken, expiresAt: claims.exp * 1000, account: { ...account, wallets: store.wallets(account.sub) } }); + } catch (e) { next(e); } + }); + + router.get('/me', auth, (req: Authed, res) => { + const a = req.account!; + res.json({ ...a, wallets: store.wallets(a.sub) }); + }); + + router.post('/challenge', auth, (req: Authed, res, next) => { + try { + const { address } = z.object({ address: hex64 }).strict().parse(req.body); + res.json(store.challenge(req.account!, address)); + } catch (e) { next(e); } + }); + + // Wallet keys never leave the client: only the public key and a signature arrive here. + router.post('/link', auth, (req: Authed, res, next) => { + try { + const body = z.object({ nonce: z.string().regex(/^[A-Za-z0-9_-]{16,64}$/), address: hex64, + publicKey: z.string().max(256), signature: z.string().max(256) }).strict().parse(req.body); + res.status(201).json(store.link(req.account!, body)); + } catch (e) { next(e); } + }); + + router.delete('/link/:address', auth, (req: Authed, res) => { + const address = String(req.params.address); + if (!/^[a-f0-9]{64}$/.test(address)) { res.status(400).json({ error: 'Invalid wallet address' }); return; } + res.json({ removed: store.unlink(req.account!.sub, address) }); + }); + + // Leaderboards: GET /api/account/names?addresses=a,b,c → { [address]: displayName } + router.get('/names', (req, res) => { + const list = String(req.query.addresses ?? '').split(',').filter(Boolean); + if (list.length > 100 || !list.every(a => /^[a-f0-9]{64}$/.test(a))) { res.status(400).json({ error: 'Invalid addresses' }); return; } + res.json({ names: store.names(list) }); + }); + + router.use((err: Error & { status?: number }, _req: Request, res: Response, _next: NextFunction) => { + if (err instanceof TokenError || err instanceof LinkError) { res.status(err.status).json({ error: err.message }); return; } + if (err instanceof z.ZodError) { res.status(400).json({ error: 'Invalid request' }); return; } + if (/OIDC|JWKS/.test(err.message) || err.name === 'TimeoutError' || err.message === 'fetch failed') { res.status(503).json({ error: 'eom.dev login is temporarily unavailable' }); return; } + res.status(err.status === 413 ? 413 : 400).json({ error: 'Account request failed' }); + }); + return router; +} diff --git a/server/account/store.ts b/server/account/store.ts new file mode 100644 index 0000000..3e91dcf --- /dev/null +++ b/server/account/store.ts @@ -0,0 +1,89 @@ +import { DatabaseSync } from 'node:sqlite'; +import { randomBytes } from 'node:crypto'; +import { address as walletAddress, verifySignature } from '../testnet/consensus.ts'; +import { linkMessage } from '../../shared/account-link.ts'; + +export { linkMessage }; + +// Off-chain account <-> wallet mapping. Nothing here touches the chain or consensus. +export type Account = { sub: string; issuer: string; name: string; username: string }; +export type LinkedWallet = { address: string; linkedAt: number }; + +export const CHALLENGE_TTL_MS = 5 * 60_000; +export const MAX_PENDING_PER_ACCOUNT = 5; + +export class LinkError extends Error { + readonly status: number; + constructor(message: string, status = 400) { super(message); this.status = status; } +} + +export class AccountStore { + private readonly db: DatabaseSync; + private readonly challenges = new Map(); + private readonly now: () => number; + constructor(file: string, now: () => number = Date.now) { + this.now = now; + this.db = new DatabaseSync(file); + this.db.exec(`PRAGMA journal_mode=WAL; + CREATE TABLE IF NOT EXISTS accounts(sub TEXT PRIMARY KEY, issuer TEXT NOT NULL, name TEXT NOT NULL, + username TEXT NOT NULL, updated_at INTEGER NOT NULL); + CREATE TABLE IF NOT EXISTS wallets(address TEXT PRIMARY KEY, sub TEXT NOT NULL REFERENCES accounts(sub), + public_key TEXT NOT NULL, linked_at INTEGER NOT NULL); + CREATE INDEX IF NOT EXISTS wallets_sub ON wallets(sub);`); + } + close() { this.db.close(); } + + upsert(a: Account): void { + this.db.prepare(`INSERT INTO accounts(sub,issuer,name,username,updated_at) VALUES(?,?,?,?,?) + ON CONFLICT(sub) DO UPDATE SET name=excluded.name, username=excluded.username, updated_at=excluded.updated_at`) + .run(a.sub, a.issuer, a.name, a.username, this.now()); + } + + wallets(sub: string): LinkedWallet[] { + return (this.db.prepare('SELECT address, linked_at FROM wallets WHERE sub=? ORDER BY linked_at').all(sub) as + { address: string; linked_at: number }[]).map(r => ({ address: r.address, linkedAt: r.linked_at })); + } + + /** Public leaderboard lookup: display names only, for linked wallets. */ + names(addresses: string[]): Record { + const out: Record = {}; + const q = this.db.prepare('SELECT a.name FROM wallets w JOIN accounts a ON a.sub=w.sub WHERE w.address=?'); + for (const addr of addresses) { const row = q.get(addr) as { name: string } | undefined; if (row) out[addr] = row.name; } + return out; + } + + challenge(account: Account, address: string): { nonce: string; expiresAt: number; message: string } { + if (!/^[a-f0-9]{64}$/.test(address)) throw new LinkError('Invalid wallet address'); + const now = this.now(); + for (const [k, v] of this.challenges) if (v.expiresAt <= now) this.challenges.delete(k); + if (this.challenges.size > 10_000) throw new LinkError('Too many pending link challenges', 503); + let mine = 0; for (const v of this.challenges.values()) if (v.sub === account.sub) mine++; + if (mine >= MAX_PENDING_PER_ACCOUNT) throw new LinkError('Too many pending link challenges for this account; wait a few minutes', 429); + const nonce = randomBytes(24).toString('base64url'); + const expiresAt = now + CHALLENGE_TTL_MS; + this.challenges.set(nonce, { sub: account.sub, address, expiresAt }); + return { nonce, expiresAt, message: linkMessage({ issuer: account.issuer, sub: account.sub, address, nonce, expiresAt }) }; + } + + /** Verifies the wallet signature over the challenge; each nonce is single use. */ + link(account: Account, input: { nonce: string; address: string; publicKey: string; signature: string }): LinkedWallet { + const pending = this.challenges.get(input.nonce); + // Consume before verifying: a failed attempt also burns the nonce (no oracle, no replay). + this.challenges.delete(input.nonce); + if (!pending || pending.expiresAt <= this.now()) throw new LinkError('Link challenge expired or already used', 409); + if (pending.sub !== account.sub || pending.address !== input.address) throw new LinkError('Link challenge does not match this account and wallet', 409); + if (walletAddress(input.publicKey) !== input.address) throw new LinkError('Public key does not match the wallet address'); + const message = linkMessage({ issuer: account.issuer, sub: account.sub, address: input.address, nonce: input.nonce, expiresAt: pending.expiresAt }); + if (!verifySignature(input.publicKey, input.address, message, input.signature)) throw new LinkError('Invalid wallet signature', 401); + const owner = this.db.prepare('SELECT sub FROM wallets WHERE address=?').get(input.address) as { sub: string } | undefined; + if (owner && owner.sub !== account.sub) throw new LinkError('This wallet is already linked to another account', 409); + const linkedAt = this.now(); + this.db.prepare('INSERT INTO wallets(address,sub,public_key,linked_at) VALUES(?,?,?,?) ON CONFLICT(address) DO NOTHING') + .run(input.address, account.sub, input.publicKey, linkedAt); + return this.wallets(account.sub).find(w => w.address === input.address)!; + } + + unlink(sub: string, address: string): boolean { + return Number(this.db.prepare('DELETE FROM wallets WHERE sub=? AND address=?').run(sub, address).changes) > 0; + } +} diff --git a/server/enrichment.ts b/server/enrichment.ts index 32dc775..fa7175a 100644 --- a/server/enrichment.ts +++ b/server/enrichment.ts @@ -1,4 +1,5 @@ import { z } from 'zod'; +import { ENRICHMENT_USER_AGENT, wikimediaUserAgent } from './wikimedia-user-agent.ts'; import { deriveStats, type PageEnrichment } from '../shared/enrichment.ts'; const MAX_BYTES = 1024 * 1024; @@ -101,7 +102,7 @@ export class WikipediaEnrichment { private async json(url: URL): Promise { const signal = AbortSignal.timeout(6000); const response = await this.fetcher(url, { signal, redirect: 'error', - headers: { Accept: 'application/json', 'User-Agent': 'Wikideck/0.1 (Wikipedia off-chain page enrichment)' } }); + headers: { Accept: 'application/json', 'User-Agent': wikimediaUserAgent(ENRICHMENT_USER_AGENT) } }); const length = response.headers.get('content-length'); if (!response.ok || response.redirected || !/^application\/json(?:\s*;|\s*$)/i.test(response.headers.get('content-type') ?? '') || diff --git a/server/testnet/http.ts b/server/testnet/http.ts index d0f2807..272bde9 100644 --- a/server/testnet/http.ts +++ b/server/testnet/http.ts @@ -17,6 +17,7 @@ import { IS_MAINNET, PROFILE } from '../../shared/network.ts'; import { assertLaunchAllowed, launchManifest } from '../launch.ts'; import { resourceConfig, RpcBudget, RpcError } from '../resources.ts'; import { trustedProxies, operationsPort, startOperations } from '../operations.ts'; +import { createAccountRouter } from '../account/router.ts'; const root = fileURLToPath(new URL('../../', import.meta.url)); assertLaunchAllowed(); @@ -149,6 +150,7 @@ app.post('/p2p/transaction',workLimit,async(req,res)=>{ const id=await ledger.submitTransaction(transaction); res.status(202).json({id,status:'pending'}); }); +app.use('/api/account',createAccountRouter({dataDir})); app.use(['/api','/p2p'],(_req,res)=>{res.status(404).json({error:'Unknown testnet endpoint'});}); app.use(express.static(resolve(root,'dist'))); app.get('/{*path}',(_req,res)=>res.sendFile(resolve(root,'dist/index.html'))); diff --git a/server/wiki.ts b/server/wiki.ts index 71d8405..4b5ccaf 100644 --- a/server/wiki.ts +++ b/server/wiki.ts @@ -1,5 +1,6 @@ import { z } from 'zod'; import type { Article } from '../shared/protocol.ts'; +import { ARTICLE_USER_AGENT, wikimediaUserAgent } from './wikimedia-user-agent.ts'; const pageSchema = z.object({ pageid: z.number().int().positive().max(Number.MAX_SAFE_INTEGER), ns: z.literal(0), @@ -74,7 +75,7 @@ export class WikipediaArticleSource { generator: 'random', grnnamespace: '0', grnlimit: '10', prop: 'extracts|pageimages|info|categories', exintro: '1', explaintext: '1', exchars: '900', piprop: 'thumbnail', pithumbsize: '800', cllimit: '20' }).toString(); const response = await this.fetcher(url, { signal: AbortSignal.timeout(3500), redirect: 'error', - headers: { 'User-Agent': 'Wikideck/0.1 (experimental Wikipedia article cards)', Accept: 'application/json' } }); + headers: { 'User-Agent': wikimediaUserAgent(ARTICLE_USER_AGENT), Accept: 'application/json' } }); const data = responseSchema.parse(await readJson(response)); for (const rawPage of data.query.pages) { const parsedPage = pageSchema.safeParse(rawPage); diff --git a/server/wikimedia-user-agent.ts b/server/wikimedia-user-agent.ts new file mode 100644 index 0000000..39eb229 --- /dev/null +++ b/server/wikimedia-user-agent.ts @@ -0,0 +1,13 @@ +// User-Agent for Wikimedia API requests. Wikimedia asks automated clients to identify +// themselves with contact information; operators can opt in with WIKIDECK_USER_AGENT. +// Unset (or blank), each caller keeps its historical default string unchanged. +export const ARTICLE_USER_AGENT = 'Wikideck/0.1 (experimental Wikipedia article cards)'; +export const ENRICHMENT_USER_AGENT = 'Wikideck/0.1 (Wikipedia off-chain page enrichment)'; +const MAX_LENGTH = 256; + +export function wikimediaUserAgent(fallback: string, env: Record = process.env): string { + const configured = env.WIKIDECK_USER_AGENT?.trim(); + // Reject header-injection/control characters and oversized values; fall back to the default. + if (!configured || configured.length > MAX_LENGTH || !/^[\x20-\x7e]+$/.test(configured)) return fallback; + return configured; +} diff --git a/shared/account-link.ts b/shared/account-link.ts new file mode 100644 index 0000000..b86bb02 --- /dev/null +++ b/shared/account-link.ts @@ -0,0 +1,25 @@ +import { NETWORK } from './testnet.ts'; + +// Off-chain wallet <-> eom.dev account proof. Pure, shared by node and client so the +// client builds the exact text it signs and never signs server-chosen text. +export type LinkChallenge = { nonce: string; expiresAt: number }; +export const LINK_NONCE = /^[A-Za-z0-9_-]{16,64}$/; +export const LINK_CHALLENGE_MAX_MS = 10 * 60_000; + +export function linkMessage(c: { issuer: string; sub: string; address: string; nonce: string; expiresAt: number }): string { + return JSON.stringify(['wikideck:account-link:v1', NETWORK, c.issuer, c.sub, c.address, c.nonce, c.expiresAt]); +} + +/** Client side: validate a node challenge and build the message locally. Throws on anything unexpected. */ +export function clientLinkMessage(account: { issuer: string; sub: string }, address: string, + challenge: { nonce?: unknown; expiresAt?: unknown; message?: unknown }, now = Date.now()): string { + const { nonce, expiresAt } = challenge; + if (typeof nonce !== 'string' || !LINK_NONCE.test(nonce)) throw new Error('The node sent an invalid link challenge.'); + if (typeof expiresAt !== 'number' || !Number.isSafeInteger(expiresAt) || expiresAt <= now || expiresAt > now + LINK_CHALLENGE_MAX_MS) + throw new Error('The node sent an invalid link challenge.'); + if (!/^[a-f0-9]{64}$/.test(address)) throw new Error('Invalid wallet address.'); + const message = linkMessage({ issuer: account.issuer, sub: account.sub, address, nonce, expiresAt }); + if (challenge.message !== undefined && challenge.message !== message) + throw new Error('The node asked the wallet to sign something other than an account link. Nothing was signed.'); + return message; +} diff --git a/shared/game/engine.ts b/shared/game/engine.ts new file mode 100644 index 0000000..67d8616 --- /dev/null +++ b/shared/game/engine.ts @@ -0,0 +1,454 @@ +/** + * WikiDeck game engine core ("Edit War", docs/game/DESIGN.md): pure, + * deterministic, off-chain. Exported functions never mutate their inputs. + * All randomness comes from the match seed via state.rng (mulberry32, §4). + * Contract: docs/game/ENGINE_API.md. + */ +import { KEYWORDS, KEYWORD_IDS, activePortal, isOnTopic, type EffectContext, type KeywordDef, type PortalDef } from './keywords.ts'; +import { Rng, normalizeSeed } from './rng.ts'; +import { parseRuleset } from './ruleset.ts'; +import { + IllegalActionError, PLAYERS, STATS, + type Action, type CardInPlay, type GameCard, type MatchResult, type MatchState, + type PlayerId, type PlayerState, type PlayerView, type Ruleset, type TopicDef, +} from './types.ts'; + +export const ENGINE_VERSION = 1; + +export const other = (player: PlayerId): PlayerId => (player === 0 ? 1 : 0); +const clone = (value: T): T => structuredClone(value); +const RARITIES = new Set(['Common', 'Rare', 'Epic', 'Legendary']); +const FACTION_SET = new Set(['Space', 'Nature', 'People', 'Science', 'History', 'Culture']); +const CHECKS = new Set(['verified', 'unverified', 'unchecked', 'loaner']); + +// ---------- validation ---------- + +/** Problems with a deck under `rules` (empty = legal). DESIGN §2. */ +export function validateDeck(rules: Ruleset, deck: readonly GameCard[]): string[] { + const problems: string[] = []; + if (!Array.isArray(deck)) return ['Deck must be an array']; + if (deck.length !== rules.deckSize) problems.push(`Deck must have exactly ${rules.deckSize} cards (has ${deck.length})`); + const ids = new Set(); + const copies = new Map(); + let loaners = 0; + for (const card of deck) { + if (typeof card?.cardId !== 'string' || !card.cardId || card.cardId.length > 128) { problems.push('cardId must be a non-empty string'); continue; } + const label = card.cardId; + if (ids.has(card.cardId)) problems.push(`Duplicate cardId ${label}`); + ids.add(card.cardId); + if (card.pageId !== null && !Number.isInteger(card.pageId)) problems.push(`${label}: bad pageId`); + if (card.pageId === null && card.source !== 'loaner') problems.push(`${label}: owned cards need a pageId`); + if (typeof card.title !== 'string' || card.title.length > 256) problems.push(`${label}: bad title`); + if (!FACTION_SET.has(card.faction)) problems.push(`${label}: bad faction`); + if (!RARITIES.has(card.rarity)) problems.push(`${label}: bad rarity`); + if (!Number.isInteger(card.cost) || card.cost < 0 || card.cost > 6) problems.push(`${label}: cost must be 0–6`); + if (!Number.isInteger(card.power) || card.power < 0 || card.power > 30) problems.push(`${label}: power must be 0–30`); + if (!STATS.includes(card.home)) problems.push(`${label}: bad home stat`); + if (card.trend !== -1 && card.trend !== 0 && card.trend !== 1) problems.push(`${label}: trend must be -1, 0 or 1`); + if (card.keyword !== null && !(KEYWORD_IDS as readonly string[]).includes(card.keyword)) problems.push(`${label}: unknown keyword ${card.keyword}`); + if (card.source !== 'owned' && card.source !== 'loaner') problems.push(`${label}: bad source`); + if (card.check !== undefined && !CHECKS.has(card.check)) problems.push(`${label}: bad check`); + if (card.source === 'loaner') loaners++; + if (card.source === 'owned' && !rules.ownedCards) problems.push(`${label}: owned cards are not allowed in this mode`); + // §2 / §2.1: owned and loaner copies count together by pageId; unpinned loaners (pageId null) by cardId. + const key = card.pageId !== null ? `page:${card.pageId}` : `card:${card.cardId}`; + const n = (copies.get(key) ?? 0) + 1; + copies.set(key, n); + if (n === rules.maxCopiesPerPage + 1) problems.push(`More than ${rules.maxCopiesPerPage} copies of ${card.pageId !== null ? `page ${card.pageId}` : card.cardId}`); + } + if (loaners > rules.maxLoaners) problems.push(`At most ${rules.maxLoaners} loaner cards`); + return problems; +} + +// ---------- match setup (§4) ---------- + +/** + * Draw the match's Topics (§4.2.3). distinctStats: for each stat in STATS order + * (attention, depth, reach) pick one Topic of that stat with rng.int(groupSize), + * then Fisher–Yates the picks, then keep the first topicCount. Otherwise + * Fisher–Yates the whole pool and keep the first topicCount. + */ +function drawTopics(rules: Ruleset, rng: Rng): TopicDef[] { + if (!rules.distinctStats) return rng.shuffle(rules.topicPool).slice(0, rules.topicCount); + const picked: TopicDef[] = []; + for (const stat of STATS) { + const group = rules.topicPool.filter(topic => topic.stat === stat); + if (group.length) picked.push(group[rng.int(group.length)]); + } + return rng.shuffle(picked).slice(0, rules.topicCount); +} + +/** + * Start a match. `decks[0]` belongs to seat 0. Seed is a uint32 (or a string, + * hashed with FNV-1a). Throws ZodError for a bad ruleset, IllegalActionError for a bad deck. + */ +export function createMatch(ruleset: Ruleset, decks: readonly [readonly GameCard[], readonly GameCard[]], seed: number | string): MatchState { + const rules = parseRuleset(clone(ruleset)); + const seedValue = normalizeSeed(seed); + for (const player of PLAYERS) { + const problems = validateDeck(rules, decks?.[player] as GameCard[]); + if (problems.length) throw new IllegalActionError(`Seat ${player} deck: ${problems.join('; ')}`); + } + const rng = new Rng(seedValue); + const newPlayer = (player: PlayerId): PlayerState => ({ + deck: rng.shuffle(clone(decks[player])), hand: [], energy: 0, queue: [], committed: false, afk: 0, carry: 0, + }); + const p0 = newPlayer(0); + const p1 = newPlayer(1); + const topics = drawTopics(rules, rng); + const initiative: PlayerId = rng.next() < 0.5 ? 0 : 1; + const state: MatchState = { + schema: 'wikideck-match/1', engineVersion: ENGINE_VERSION, ruleset: rules, seed: seedValue, rng: rng.state, + turn: 0, phase: 'planning', initiative, revealSeq: 0, players: [p0, p1], + lanes: topics.map(topic => ({ topic: clone(topic), portalRevealed: false, cards: [[], []] as [CardInPlay[], CardInPlay[]] })), + log: [], actions: [], result: null, + }; + for (const player of PLAYERS) for (let i = 0; i < rules.openingHand; i++) draw(state, player); + startTurn(state, rng); + state.rng = rng.state; + return state; +} + +function draw(state: MatchState, player: PlayerId): void { + const p = state.players[player]; + if (!p.deck.length || p.hand.length >= state.ruleset.handLimit) return; + const card = p.deck.shift()!; + p.hand.push(card); + state.log.push({ t: 'draw', player, cardId: card.cardId }); +} + +function context(state: MatchState, rng: Rng, params: Record | undefined, lane: number, source: string, player: PlayerId): EffectContext { + return { + state, rng, params: params ?? {}, lane, + log: text => state.log.push({ t: 'effect', source, player, text }), + power: card => cardPower(state, card), + }; +} + +/** Enabled keyword definition for a card, if any. */ +function keywordOf(state: MatchState, card: GameCard): KeywordDef | undefined { + return card.keyword && state.ruleset.keywordsEnabled.includes(card.keyword) ? KEYWORDS[card.keyword] : undefined; +} + +function keywordCtx(state: MatchState, rng: Rng, keyword: KeywordDef, card: CardInPlay): EffectContext { + return context(state, rng, state.ruleset.keywordParams[keyword.id], card.lane, keyword.id, card.owner); +} + +function portalCtx(state: MatchState, rng: Rng, lane: number, portal: PortalDef, player: PlayerId): EffectContext { + const topic = state.lanes[lane].topic; + const params = state.ruleset.portalParams[topic.id] ?? state.ruleset.portalParams[portal.id]; + return context(state, rng, params, lane, portal.id, player); +} + +/** Per-seat card capacity of a lane (a Portal may override it, e.g. Stub). */ +export function laneCapacity(state: MatchState, lane: number): number { + const portal = activePortal(state, lane); + return portal?.capacity ? portal.capacity(portalCtx(state, new Rng(state.rng), lane, portal, state.initiative)) : state.ruleset.laneCapacity; +} + +/** §5.1 Start (Portal reveal, energy, draw), then §5.2 Underdog. Initiative alternates (§5.5). */ +function startTurn(state: MatchState, rng: Rng): void { + state.turn += 1; + if (state.turn > 1) state.initiative = other(state.initiative); + const rules = state.ruleset; + state.lanes.forEach((lane, index) => { + if (lane.portalRevealed || (rules.portalReveal[index] ?? 1) > state.turn) return; + lane.portalRevealed = true; + state.log.push({ t: 'portalRevealed', lane: index, topic: clone(lane.topic) }); + const portal = activePortal(state, index); + portal?.onPortalReveal?.(portalCtx(state, rng, index, portal, state.initiative)); + }); + const base = (rules.energyByTurn[state.turn - 1] ?? rules.energyByTurn.at(-1)!) + rules.bonusEnergy; + for (const player of PLAYERS) { + const p = state.players[player]; + Object.assign(p, { energy: base + p.carry, queue: [], committed: false }); + } + for (const player of PLAYERS) draw(state, player); + if (rules.underdog && state.turn >= 2) { + const led = topicsLed(state); + for (const player of PLAYERS) if (led[player] === 0 && led[other(player)] >= 2) { + state.players[player].energy += 1; + state.log.push({ t: 'underdog', player }); + } + } + state.log.push({ t: 'turnStart', turn: state.turn, energy: [state.players[0].energy, state.players[1].energy], initiative: state.initiative }); +} + +// ---------- power (§6) ---------- + +/** A card's current lane power (§6, never below 0). */ +export function cardPower(state: MatchState, target: CardInPlay): number { + const rules = state.ruleset; + const scratch = new Rng(state.rng); // ongoing effects must not consume real randomness + let power = target.card.power + target.bonus + target.card.trend; + if (isOnTopic(state, target)) power += rules.onTopicBonus[target.card.cost] ?? 0; + for (const lane of state.lanes) for (const side of lane.cards) for (const source of side) { + const keyword = keywordOf(state, source.card); + if (keyword?.ongoing) power += keyword.ongoing(keywordCtx(state, scratch, keyword, source), source, target); + } + const portal = activePortal(state, target.lane); + if (portal?.ongoing) power += portal.ongoing(portalCtx(state, scratch, target.lane, portal, target.owner), target); + return Math.max(0, power); +} + +/** [seat 0 power, seat 1 power] in one lane (during play; excludes "at scoring" Portals). */ +export function lanePower(state: MatchState, lane: number): [number, number] { + return PLAYERS.map(player => state.lanes[lane].cards[player].reduce((sum, card) => sum + cardPower(state, card), 0)) as [number, number]; +} + +/** §6: who leads a lane given its powers. Equal and > 0 → more on-topic cards leads (consensus). */ +export function laneLeader(state: MatchState, lane: number, power: [number, number] = lanePower(state, lane)): PlayerId | null { + const [a, b] = power; + if (a !== b) return a > b ? 0 : 1; + if (a === 0) return null; + const onTopic = PLAYERS.map(player => state.lanes[lane].cards[player].filter(card => isOnTopic(state, card)).length); + return onTopic[0] === onTopic[1] ? null : onTopic[0] > onTopic[1] ? 0 : 1; +} + +/** Number of Topics each seat leads right now (with the consensus tie-break). */ +export function topicsLed(state: MatchState): [number, number] { + const led: [number, number] = [0, 0]; + state.lanes.forEach((_, lane) => { + const leader = laneLeader(state, lane); + if (leader !== null) led[leader]++; + }); + return led; +} + +/** Final lane powers: lanePower plus revealed "at scoring" Portals (§7, §10.3). */ +export function scoringPower(state: MatchState, lane: number): [number, number] { + const power = lanePower(state, lane); + const portal = activePortal(state, lane); + if (!portal?.atScoring) return power; + const [d0, d1] = portal.atScoring(portalCtx(state, new Rng(state.rng), lane, portal, state.initiative)); + return [power[0] + d0, power[1] + d1]; +} + +// ---------- actions (§5.3) ---------- + +const queuedCost = (p: PlayerState) => p.queue.reduce((sum, play) => sum + (p.hand.find(c => c.cardId === play.cardId)?.cost ?? 0), 0); +const queuedInLane = (p: PlayerState, lane: number) => p.queue.filter(play => play.lane === lane).length; + +function laneRejects(state: MatchState, lane: number, card: GameCard, player: PlayerId): string | null { + const portal = activePortal(state, lane); + if (!portal?.canPlay) return null; + return portal.canPlay(portalCtx(state, new Rng(state.rng), lane, portal, player), card, player) ? null : `${portal.name} rejects this card`; +} + +function playProblem(state: MatchState, action: Extract): string | null { + const p = state.players[action.player]; + if (p.committed) return 'Already committed this turn'; + const card = p.hand.find(c => c.cardId === action.cardId); + if (!card) return 'Card is not in your hand'; + if (p.queue.some(play => play.cardId === action.cardId)) return 'Card is already queued'; + if (!Number.isInteger(action.lane) || action.lane < 0 || action.lane >= state.lanes.length) return 'No such Topic'; + if (card.cost > p.energy - queuedCost(p)) return 'Not enough energy'; + if (state.lanes[action.lane].cards[action.player].length + queuedInLane(p, action.lane) >= laneCapacity(state, action.lane)) return 'Topic is full'; + return laneRejects(state, action.lane, card, action.player); +} + +/** Why `action` is illegal in `state`, or null if it is legal. */ +export function actionProblem(state: MatchState, action: Action): string | null { + if (state.phase === 'over') return 'Match is over'; + if (!action || (action.player !== 0 && action.player !== 1)) return 'Unknown player'; + const p = state.players[action.player]; + switch (action.type) { + case 'play': return playProblem(state, action); + case 'undo': + if (p.committed) return 'Already committed this turn'; + return p.queue.some(play => play.cardId === action.cardId) ? null : 'Card is not queued'; + case 'commit': + case 'timeout': + return p.committed ? 'Already committed this turn' : null; + case 'concede': return null; + default: return 'Unknown action'; + } +} + +/** + * Legal actions for `player`: every `play`, every `undo`, and `commit`. + * `concede` (always legal while running) and `timeout` (host-only) are not listed. + * Empty once the player has committed or the match is over. + */ +export function legalActions(state: MatchState, player: PlayerId): Action[] { + if (state.phase === 'over') return []; + const p = state.players[player]; + if (p.committed) return []; + const actions: Action[] = []; + for (const card of p.hand) { + if (p.queue.some(play => play.cardId === card.cardId)) continue; + for (let lane = 0; lane < state.lanes.length; lane++) { + const action: Action = { type: 'play', player, cardId: card.cardId, lane }; + if (!playProblem(state, action)) actions.push(action); + } + } + for (const play of p.queue) actions.push({ type: 'undo', player, cardId: play.cardId }); + actions.push({ type: 'commit', player }); + return actions; +} + +/** Apply one action and return the new state. Throws IllegalActionError if illegal. */ +export function applyAction(state: MatchState, action: Action): MatchState { + const problem = actionProblem(state, action); + if (problem) throw new IllegalActionError(problem); + const next = clone(state); + next.actions.push(clone(action)); + const p = next.players[action.player]; + const rng = new Rng(next.rng); + switch (action.type) { + case 'play': p.queue.push({ cardId: action.cardId, lane: action.lane }); break; + case 'undo': p.queue.splice(p.queue.findIndex(play => play.cardId === action.cardId), 1); break; + case 'commit': p.committed = true; p.afk = 0; break; + case 'timeout': + p.committed = true; + p.afk = p.queue.length ? 0 : p.afk + 1; + if (p.afk >= next.ruleset.afkTurns) { + next.log.push({ t: 'concede', player: action.player, afk: true }); + finish(next, other(action.player), 'afk'); + } + break; + case 'concede': + next.log.push({ t: 'concede', player: action.player, afk: false }); + finish(next, other(action.player), 'concede'); + break; + } + if (next.phase !== 'over' && next.players.every(player => player.committed)) resolveTurn(next, rng); + next.rng = rng.state; + return next; +} + +/** §5.4 Reveal (interleaved) and §5.5 End. */ +function resolveTurn(state: MatchState, rng: Rng): void { + const rules = state.ruleset; + const order: PlayerId[] = [state.initiative, other(state.initiative)]; + // Carry (§5.1): energy not reserved by a queued play. Fizzled plays still spent theirs. + for (const player of PLAYERS) { + const p = state.players[player]; + p.carry = Math.min(rules.energyCarryMax, Math.max(0, p.energy - queuedCost(p))); + } + const queues = order.map(player => state.players[player].queue.slice()); + for (let i = 0; i < Math.max(queues[0].length, queues[1].length); i++) { + for (const [k, player] of order.entries()) { + const play = queues[k][i]; + if (play) reveal(state, rng, player, play.cardId, play.lane); + } + } + for (const player of PLAYERS) state.players[player].queue = []; + for (const player of order) for (const lane of state.lanes) { + for (const card of lane.cards[player].slice().sort((x, y) => x.seq - y.seq)) { + const keyword = keywordOf(state, card.card); + keyword?.endOfTurn?.(keywordCtx(state, rng, keyword, card), card); + } + } + if (state.turn >= rules.turns) finish(state, null, 'topics'); + else startTurn(state, rng); +} + +function reveal(state: MatchState, rng: Rng, player: PlayerId, cardId: string, lane: number): void { + const p = state.players[player]; + const index = p.hand.findIndex(c => c.cardId === cardId); + const card = p.hand[index]; + if (index < 0 || state.lanes[lane].cards[player].length >= laneCapacity(state, lane) || laneRejects(state, lane, card, player)) { + state.log.push({ t: 'fizzle', player, cardId, lane }); // stays in hand, energy lost + return; + } + p.hand.splice(index, 1); + const inPlay: CardInPlay = { card, owner: player, lane, turn: state.turn, seq: ++state.revealSeq, bonus: 0 }; + state.lanes[lane].cards[player].push(inPlay); + state.log.push({ t: 'reveal', player, cardId, lane }); + const keyword = keywordOf(state, card); + keyword?.onReveal?.(keywordCtx(state, rng, keyword, inPlay), inPlay); + const portal = activePortal(state, lane); + portal?.onReveal?.(portalCtx(state, rng, lane, portal, player), inPlay); +} + +/** §7 scoring (after the last End phase, with "at scoring" Portals), or a concede. */ +function finish(state: MatchState, forcedWinner: PlayerId | null, reason: 'topics' | 'concede' | 'afk'): void { + const lanePowers = state.lanes.map((_, lane) => scoringPower(state, lane)); + const led: [number, number] = [0, 0]; + const totalPower: [number, number] = [0, 0]; + lanePowers.forEach((power, lane) => { + const leader = laneLeader(state, lane, power); + if (leader !== null) led[leader]++; + totalPower[0] += power[0]; totalPower[1] += power[1]; + }); + let winner: PlayerId | null = forcedWinner; + let why: MatchResult['reason'] = reason; + if (reason === 'topics') { + if (led[0] !== led[1]) winner = led[0] > led[1] ? 0 : 1; + else if (totalPower[0] !== totalPower[1]) { winner = totalPower[0] > totalPower[1] ? 0 : 1; why = 'totalPower'; } + else why = 'draw'; + } + state.result = { winner, reason: why, topicsLed: led, lanePower: lanePowers, totalPower, turns: state.turn }; + state.phase = 'over'; + state.log.push({ t: 'matchOver', result: clone(state.result) }); +} + +// ---------- queries ---------- + +export function isOver(state: MatchState): boolean { return state.phase === 'over'; } + +/** The final result, or null while the match is running. */ +export function result(state: MatchState): MatchResult | null { return state.result; } + +/** Hidden-information view for one seat. Send only this to clients and AIs. */ +export function viewFor(state: MatchState, you: PlayerId): PlayerView { + const them = other(you); + const me = state.players[you], opp = state.players[them]; + return clone({ + you, ruleset: state.ruleset, turn: state.turn, phase: state.phase, initiative: state.initiative, + energy: me.energy, energyLeft: me.energy - queuedCost(me), hand: me.hand, queue: me.queue, + committed: me.committed, deckCount: me.deck.length, + opponent: { handCount: opp.hand.length - opp.queue.length, deckCount: opp.deck.length, queuedCount: opp.queue.length, committed: opp.committed }, + lanes: state.lanes.map((lane, index) => { + const power = lanePower(state, index); + const mine = power[you], theirs = power[them]; + const leader = laneLeader(state, index, power); + return { + // Until its Portal is revealed only the stat is visible (the id/name would give the Portal away). + topic: lane.portalRevealed ? lane.topic : { id: `lane-${index + 1}`, name: '?', stat: lane.topic.stat, portal: null }, + portalRevealed: lane.portalRevealed, + cards: [lane.cards[you], lane.cards[them]] as [CardInPlay[], CardInPlay[]], + cardPower: [lane.cards[you].map(c => cardPower(state, c)), lane.cards[them].map(c => cardPower(state, c))] as [number[], number[]], + power: [mine, theirs] as [number, number], + leader: leader === null ? null : leader === you ? 'you' as const : 'opponent' as const, + }; + }), + result: state.result, + }); +} + +// ---------- serialisation, replay, test helpers ---------- + +export function serialize(state: MatchState): string { return JSON.stringify(state); } + +export function deserialize(json: string): MatchState { + const state = JSON.parse(json) as MatchState; + if (state?.schema !== 'wikideck-match/1') throw new Error('Not a wikideck-match/1 state'); + state.ruleset = parseRuleset(state.ruleset); + return state; +} + +/** Rebuild a match from its inputs; a host can verify a reported result this way. */ +export function replay(ruleset: Ruleset, decks: readonly [readonly GameCard[], readonly GameCard[]], seed: number | string, actions: readonly Action[]): MatchState { + let state = createMatch(ruleset, decks, seed); + for (const action of actions) state = applyAction(state, action); + return state; +} + +/** + * Test helper: put `card` straight into a lane (no on-reveal, no energy, no hand). + * Returns a new state. For unit-testing keywords against hand-built boards. + */ +export function placeCard(state: MatchState, player: PlayerId, lane: number, card: GameCard, bonus = 0): MatchState { + const next = clone(state); + next.lanes[lane].cards[player].push({ card: clone(card), owner: player, lane, turn: next.turn, seq: ++next.revealSeq, bonus }); + return next; +} + +/** Test helper: reveal a Topic's Portal now (runs nothing). */ +export function revealPortal(state: MatchState, lane: number): MatchState { + const next = clone(state); + next.lanes[lane].portalRevealed = true; + return next; +} diff --git a/shared/game/index.ts b/shared/game/index.ts new file mode 100644 index 0000000..14f7703 --- /dev/null +++ b/shared/game/index.ts @@ -0,0 +1,10 @@ +/** Public entry point of the WikiDeck game engine. Other teams import only from here. See docs/game/ENGINE_API.md. */ +export * from './types.ts'; +export { Rng, seedFromString, normalizeSeed, type RngState } from './rng.ts'; +export { DEFAULT_RULESET, DEFAULT_TOPIC_POOL, RulesetSchema, TopicSchema, parseRuleset } from './ruleset.ts'; +export { + ENGINE_VERSION, createMatch, legalActions, applyAction, actionProblem, isOver, result, viewFor, + serialize, deserialize, replay, validateDeck, cardPower, lanePower, laneLeader, laneCapacity, scoringPower, topicsLed, other, placeCard, revealPortal, +} from './engine.ts'; +export { KEYWORDS, PORTALS, KEYWORD_IDS, PORTAL_IDS, allies, activePortal, isOnTopic, type KeywordDef, type PortalDef, type EffectContext } from './keywords.ts'; +export { STARTER_POOL, loanerCard, previewPool, starterDeck } from './starter.ts'; diff --git a/shared/game/keywords.ts b/shared/game/keywords.ts new file mode 100644 index 0000000..ea3a621 --- /dev/null +++ b/shared/game/keywords.ts @@ -0,0 +1,95 @@ +/** + * Keyword and Portal registry (DESIGN §10.2, §10.3). Effects are code here; which + * ones a card/topic uses and their numbers are data (GameCard.keyword, + * TopicDef.portal, Ruleset.keywordsEnabled / keywordParams / portalParams). + * Owner of the effects: engine-b (claude/wikideck#3). engine-a owns the hook contract: + * + * - Hooks get an EffectContext over the engine's *working copy* of the state and may + * mutate it (e.g. `bonus` on cards). Safe: applyAction already cloned. + * Any randomness must come from ctx.rng (match RNG, resolution order, §4.2.5). + * - A keyword's hooks run only if its id is in ruleset.keywordsEnabled. + * - onReveal(ctx, self): right after `self` is pushed into its lane (§5.4). Cards revealed + * earlier (any seat, any turn) are on the board; later ones are not. self.seq is its global + * reveal number; cards revealed this turn have `turn === ctx.state.turn`. + * - endOfTurn(ctx, self): §5.5 order: initiative seat's cards first, then lanes 1→N, then seq. + * Also runs on the last turn, before scoring (§7). + * - ongoing(ctx, self, target) → delta: PURE. Called for every (self, target) pair in play, + * including self === target. ctx.rng is a throwaway copy. Don't call ctx.power on a card from + * inside ongoing (infinite recursion); read base fields instead. + * - Portals: same, plus onPortalReveal(ctx), canPlay(ctx, card, seat), capacity(ctx) → number + * (lane capacity override), allOnTopic (Disambiguation) and atScoring(ctx) → [delta0, delta1] + * (Topic power added at scoring, §7). All Portal hooks apply only once the Portal is revealed. + * Params: ruleset.portalParams[topic.id], falling back to portalParams[portal id]. + * - Hooks must not throw and must not move or remove cards (§10, v1). + */ +import type { Rng } from './rng.ts'; +import type { CardInPlay, GameCard, MatchState, PlayerId } from './types.ts'; + +/** The 9 implemented keyword ids (§10.2; edition, obscure and wildcard are disabled by default). */ +export const KEYWORD_IDS = ['viral', 'rising', 'local', 'encyclopedic', 'nostalgic', 'translated', 'edition', 'obscure', 'wildcard'] as const; +/** The 6 Portal kinds (§10.3), named after their default Topic. */ +export const PORTAL_IDS = ['main-page', 'trending', 'featured-article', 'stub', 'interwiki', 'disambiguation'] as const; + +export interface EffectContext { + state: MatchState; + rng: Rng; + /** Tunable numbers for this keyword/portal from the ruleset. */ + params: Record; + /** Lane the effect lives in. */ + lane: number; + /** Add a line to the match log (attributed to this keyword/portal). */ + log(text: string): void; + /** Current lane power of a card in play (the engine's cardPower). Not for use inside `ongoing`. */ + power(card: CardInPlay): number; +} + +export interface KeywordDef { + id: string; + name: string; + /** One short line of reminder text with {param} placeholders. */ + text: string; + onReveal?(ctx: EffectContext, self: CardInPlay): void; + endOfTurn?(ctx: EffectContext, self: CardInPlay): void; + ongoing?(ctx: EffectContext, self: CardInPlay, target: CardInPlay): number; +} + +export interface PortalDef { + id: string; + name: string; + text: string; + onPortalReveal?(ctx: EffectContext): void; + /** Runs when any card is revealed in this Topic (after the card's own onReveal). */ + onReveal?(ctx: EffectContext, card: CardInPlay): void; + ongoing?(ctx: EffectContext, target: CardInPlay): number; + /** Lets a Topic reject a card; checked when queuing and again at reveal. */ + canPlay?(ctx: EffectContext, card: GameCard, player: PlayerId): boolean; + /** Per-player lane capacity in this Topic (replaces ruleset.laneCapacity). */ + capacity?(ctx: EffectContext): number; + /** Every card here counts as on-topic. */ + allOnTopic?: boolean; + /** Topic power added to [seat 0, seat 1] here at scoring. */ + atScoring?(ctx: EffectContext): [number, number]; +} + +/** Cards on the same side of the same lane, excluding `self`. */ +export function allies(state: MatchState, self: CardInPlay): CardInPlay[] { + return state.lanes[self.lane].cards[self.owner].filter(card => card !== self); +} + +/** The lane's Portal, if it has one and it is revealed. */ +export function activePortal(state: MatchState, lane: number): PortalDef | undefined { + const l = state.lanes[lane]; + return l?.portalRevealed && l.topic.portal ? PORTALS[l.topic.portal] : undefined; +} + +/** §1.4/§6 on-topic: home stat matches the Topic's stat, or an active Disambiguation-style Portal. */ +export function isOnTopic(state: MatchState, card: CardInPlay): boolean { + const lane = state.lanes[card.lane]; + return lane.topic.stat === card.card.home || activePortal(state, card.lane)?.allOnTopic === true; +} + +/** Filled in by engine-b (§10.2). Ids must be in KEYWORD_IDS. */ +export const KEYWORDS: Record = {}; + +/** Filled in by engine-b (§10.3). Ids must be in PORTAL_IDS. */ +export const PORTALS: Record = {}; diff --git a/shared/game/rng.ts b/shared/game/rng.ts new file mode 100644 index 0000000..d680610 --- /dev/null +++ b/shared/game/rng.ts @@ -0,0 +1,56 @@ +/** + * Seeded, serialisable PRNG for the game engine (off-chain only). + * DESIGN.md §4: mulberry32(seed: uint32). The state is one uint32, so it + * round-trips through JSON and a match can be resumed or replayed exactly. + */ +export type RngState = number; + +/** Hash a string seed (e.g. a lobby id) to a uint32 with FNV-1a. */ +export function seedFromString(text: string): number { + let h = 0x811c9dc5; + for (let i = 0; i < text.length; i++) { + h ^= text.charCodeAt(i); + h = Math.imul(h, 0x01000193); + } + return h >>> 0; +} + +export function normalizeSeed(seed: number | string): number { + if (typeof seed === 'string') return seedFromString(seed); + if (!Number.isInteger(seed) || seed < 0 || seed > 0xffffffff) throw new RangeError('Seed must be a uint32 or a string'); + return seed >>> 0; +} + +/** Mutable wrapper over an RngState. The engine keeps `state` inside MatchState. */ +export class Rng { + state: RngState; + constructor(state: RngState) { this.state = state >>> 0; } + static fromSeed(seed: number | string): Rng { return new Rng(normalizeSeed(seed)); } + + /** mulberry32: float in [0, 1). */ + next(): number { + this.state = (this.state + 0x6d2b79f5) >>> 0; + let t = this.state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + } + /** Integer in [0, n): floor(next() × n), as DESIGN.md §4 specifies. */ + int(n: number): number { + if (!Number.isInteger(n) || n <= 0) throw new RangeError('Rng.int needs a positive integer bound'); + return Math.floor(this.next() * n); + } + pick(items: readonly T[]): T { + if (!items.length) throw new RangeError('Rng.pick on empty list'); + return items[this.int(items.length)]; + } + /** Fisher–Yates per DESIGN.md §4: i from n−1 down to 1, j = floor(next() × (i+1)). Returns a new array. */ + shuffle(items: readonly T[]): T[] { + const out = items.slice(); + for (let i = out.length - 1; i > 0; i--) { + const j = this.int(i + 1); + [out[i], out[j]] = [out[j], out[i]]; + } + return out; + } +} diff --git a/shared/game/ruleset.ts b/shared/game/ruleset.ts new file mode 100644 index 0000000..8297ead --- /dev/null +++ b/shared/game/ruleset.ts @@ -0,0 +1,127 @@ +/** + * Ruleset (DESIGN §9 RulesConfig): every rule number as data, so peer-hosted + * modes can vary them without running code. parseRuleset() is the only way + * untrusted JSON should become a Ruleset; its bounds keep matches short and + * guarantee termination. + */ +import { z } from 'zod'; +import { KEYWORD_IDS, PORTAL_IDS } from './keywords.ts'; +import { STATS, type Ruleset } from './types.ts'; + +const int = (min: number, max: number) => z.number().int().min(min).max(max); +const id = z.string().regex(/^[a-z0-9][a-z0-9-]{0,31}$/); +const params = z.record(z.string().regex(/^[A-Za-z0-9]{1,24}$/), z.number().finite().min(-100).max(100)) + .refine(value => Object.keys(value).length <= 8, 'At most 8 params'); +const paramTable = z.record(id, params).refine(value => Object.keys(value).length <= 32, 'At most 32 entries'); + +export const TopicSchema = z.object({ + id, name: z.string().min(1).max(32), stat: z.enum(STATS as [string, ...string[]]), portal: z.enum(PORTAL_IDS).nullable(), +}).strict(); + +export const RulesetSchema = z.object({ + version: z.string().min(1).max(16), + deckSize: int(1, 30), + maxCopiesPerPage: int(1, 30), + maxLoaners: int(0, 30), + openingHand: int(0, 10), + handLimit: int(1, 12), + mulligan: z.literal(false), // not implemented in v1 + turns: int(1, 12), + turnSeconds: int(5, 120), + afkTurns: int(1, 12), + energyByTurn: z.array(int(0, 20)).min(1).max(12), + energyCarryMax: int(0, 10), + bonusEnergy: int(0, 10), + underdog: z.boolean(), + topicCount: int(1, 5), + distinctStats: z.boolean(), + portalReveal: z.array(int(1, 12)).max(5), + laneCapacity: int(1, 8), + topicPool: z.array(TopicSchema).min(1).max(32), + keywordParams: paramTable, + portalParams: paramTable, + costThresholds: z.array(int(0, 100)).length(5), + powerByCost: z.array(int(0, 30)).length(7), + onTopicBonus: z.array(int(0, 10)).length(7), + vanillaBonus: int(0, 10), + keywordsEnabled: z.array(z.enum(KEYWORD_IDS)).max(KEYWORD_IDS.length), + ownedCards: z.boolean(), + trendUp: z.number().finite().min(-1000).max(1000), + trendDown: z.number().finite().min(-1000).max(1000), + trendMinDaily: z.number().finite().min(0).max(1e9), + uncheckedCostCap: int(1, 6), + factionSynergyCap: int(0, 12), + verifyStats: z.boolean(), + percentiles: id, + starterDecks: id, +}).strict().superRefine((rules, ctx) => { + const issue = (message: string) => ctx.addIssue({ code: 'custom', message }); + if (rules.turns * rules.turnSeconds > 240) issue('turns × turnSeconds must be ≤ 240'); + if (rules.energyByTurn.length < rules.turns) issue('energyByTurn needs one entry per turn'); + if (rules.portalReveal.length !== rules.topicCount) issue('portalReveal needs one entry per Topic'); + if (rules.openingHand > rules.handLimit) issue('openingHand > handLimit'); + if (rules.trendDown > rules.trendUp) issue('trendDown > trendUp'); + if (rules.costThresholds.some((value, i) => i > 0 && value < rules.costThresholds[i - 1])) issue('costThresholds must ascend'); + if (rules.distinctStats) { + if (rules.topicCount !== STATS.length) issue('distinctStats needs topicCount == 3'); + const stats = new Set(rules.topicPool.map(topic => topic.stat)); + if (stats.size < rules.topicCount) issue('topicPool lacks enough distinct stats'); + } else if (rules.topicPool.length < rules.topicCount) issue('topicPool smaller than topicCount'); + const topicIds = new Set(); + for (const topic of rules.topicPool) { + if (topicIds.has(topic.id)) issue(`Duplicate topic id: ${topic.id}`); + topicIds.add(topic.id); + } + if (new Set(rules.keywordsEnabled).size !== rules.keywordsEnabled.length) issue('Duplicate keywordsEnabled entry'); + for (const key of Object.keys(rules.keywordParams)) if (!(KEYWORD_IDS as readonly string[]).includes(key)) issue(`Unknown keyword: ${key}`); + for (const key of Object.keys(rules.portalParams)) + if (!topicIds.has(key) && !(PORTAL_IDS as readonly string[]).includes(key)) issue(`portalParams key is neither a Topic id nor a Portal id: ${key}`); +}); + +/** Validate untrusted ruleset JSON. Throws a ZodError with readable issues. */ +export function parseRuleset(input: unknown): Ruleset { + return RulesetSchema.parse(input) as Ruleset; +} + +/** DESIGN §10.3 default Topic pool: per stat one plain Topic and two with Portals. Portal kind = Topic id. */ +export const DEFAULT_TOPIC_POOL: Ruleset['topicPool'] = [ + { id: 'current-events', name: 'Current Events', stat: 'attention', portal: null }, + { id: 'main-page', name: 'Main Page', stat: 'attention', portal: 'main-page' }, + { id: 'trending', name: 'Trending', stat: 'attention', portal: 'trending' }, + { id: 'archive', name: 'Archive', stat: 'depth', portal: null }, + { id: 'featured-article', name: 'Featured Article', stat: 'depth', portal: 'featured-article' }, + { id: 'stub', name: 'Stub', stat: 'depth', portal: 'stub' }, + { id: 'translations', name: 'Translations', stat: 'reach', portal: null }, + { id: 'interwiki', name: 'Interwiki', stat: 'reach', portal: 'interwiki' }, + { id: 'disambiguation', name: 'Disambiguation', stat: 'reach', portal: 'disambiguation' }, +]; + +/** DESIGN §9 defaults (v1). */ +export const DEFAULT_RULESET: Ruleset = { + version: '1.0', + deckSize: 12, maxCopiesPerPage: 2, maxLoaners: 12, + openingHand: 3, handLimit: 7, mulligan: false, + turns: 6, turnSeconds: 25, afkTurns: 2, + energyByTurn: [1, 2, 3, 4, 5, 6], energyCarryMax: 1, bonusEnergy: 0, underdog: false, + topicCount: 3, distinctStats: true, portalReveal: [2, 3, 4], laneCapacity: 3, + topicPool: DEFAULT_TOPIC_POOL, + keywordParams: { + viral: { amount: 1, cap: 2, powerDelta: 0 }, rising: { amount: 1, cap: 2, powerDelta: 0 }, + local: { amount: 1, powerDelta: 0 }, encyclopedic: { amount: 2, powerDelta: 0 }, + nostalgic: { amount: 2, powerDelta: 0 }, translated: { amount: 1, powerDelta: 0 }, + edition: { amount: 2, powerDelta: 0 }, obscure: { powerDelta: 0 }, wildcard: { powerDelta: 0 }, + }, + portalParams: { + 'main-page': { amount: 1 }, trending: { factor: 2 }, 'featured-article': { amount: 2 }, + stub: { value: 2 }, interwiki: { amount: 1 }, + }, + costThresholds: [15, 35, 55, 75, 90], + powerByCost: [0, 1, 2, 4, 6, 8, 10], + onTopicBonus: [0, 1, 1, 2, 2, 3, 3], vanillaBonus: 1, + keywordsEnabled: ['viral', 'rising', 'local', 'encyclopedic', 'nostalgic', 'translated'], ownedCards: true, + trendUp: 25, trendDown: -200, trendMinDaily: 20, uncheckedCostCap: 4, + factionSynergyCap: 3, + verifyStats: true, + percentiles: 'card-sample-2026-11-16', + starterDecks: 'default', +}; diff --git a/shared/game/starter.ts b/shared/game/starter.ts new file mode 100644 index 0000000..a5b16b1 --- /dev/null +++ b/shared/game/starter.ts @@ -0,0 +1,66 @@ +/** + * PLACEHOLDER loaner cards and starter decks (DESIGN §2) so the engine, UI and + * sims can run before council-data's docs/game/starter-cards.json lands. + * Loaners are off-chain preview cards: not NFTs, never minted or moved. + * engine-b / council-data replace STARTER_POOL with derived cards (cards.ts). + */ +import { Rng } from './rng.ts'; +import type { Faction, GameCard, Stat } from './types.ts'; + +type Spec = [pageId: number, title: string, faction: Faction, cost: number, home: Stat]; + +/** DESIGN §1.3 powerByCost and §10.1 keyword choice (cost 1 = vanilla +vanillaBonus). pageIds outside shared/catalog.ts are unverified. */ +const POWER_BY_COST = [0, 1, 2, 4, 6, 8, 10]; +const VANILLA_BONUS = 1; +const FACTION_KEYWORD: Record = { + Culture: 'viral', Nature: 'rising', People: 'local', Science: 'encyclopedic', History: 'nostalgic', Space: 'translated', +}; + +export const STARTER_POOL: readonly Spec[] = [ + [22780, 'Octopus', 'Nature', 1, 'depth'], + [19331, 'Moon', 'Space', 1, 'reach'], + [23053, 'Periodic table', 'Science', 1, 'depth'], + [3383, 'Bronze Age', 'History', 1, 'depth'], + [5843419, 'Chess', 'Culture', 2, 'attention'], + [9228, 'Earth', 'Space', 2, 'reach'], + [2008, 'Ada Lovelace', 'People', 2, 'attention'], + [21830, 'Honey bee', 'Nature', 2, 'depth'], + [736, 'Albert Einstein', 'People', 3, 'reach'], + [10979, 'Fungus', 'Nature', 3, 'depth'], + [26903, 'Solar System', 'Space', 3, 'reach'], + [30758, 'Roman Empire', 'History', 3, 'depth'], + [9649, 'Evolution', 'Science', 4, 'depth'], + [8424, 'Jazz', 'Culture', 4, 'attention'], + [12898, 'Marie Curie', 'People', 4, 'reach'], + [14533, 'Silk Road', 'History', 4, 'reach'], + [19468, 'Mount Everest', 'Nature', 5, 'attention'], + [22936, 'Photosynthesis', 'Science', 5, 'depth'], + [18110, 'Leonardo da Vinci', 'People', 5, 'reach'], + [14627, 'Ancient Egypt', 'History', 5, 'attention'], + [4177, 'Black hole', 'Space', 6, 'attention'], + [25443, 'Quantum mechanics', 'Science', 6, 'depth'], + [17867, 'Library of Alexandria', 'History', 6, 'depth'], + [20217, 'Music', 'Culture', 6, 'reach'], +]; + +export function loanerCard(spec: Spec, copy = 0): GameCard { + const [pageId, title, faction, cost, home] = spec; + const keyword = cost === 1 ? null : FACTION_KEYWORD[faction]; + return { + cardId: `loaner:${pageId}:${copy}`, pageId, title, faction, rarity: 'Common', cost, + power: POWER_BY_COST[cost] + (keyword ? 0 : VANILLA_BONUS), home, trend: 0, keyword, source: 'loaner', check: 'loaner', + }; +} + +/** Every placeholder loaner card, once each (24 cards). Draft modes can sample from this. */ +export function previewPool(): GameCard[] { return STARTER_POOL.map(spec => loanerCard(spec)); } + +/** A deterministic 12-card loaner deck: 2 cards of each cost 1–6, chosen by `seed`. */ +export function starterDeck(seed: number | string): GameCard[] { + const rng = Rng.fromSeed(`starter:${seed}`); + const deck: GameCard[] = []; + for (let cost = 1; cost <= 6; cost++) { + deck.push(...rng.shuffle(STARTER_POOL.filter(spec => spec[3] === cost)).slice(0, 2).map(spec => loanerCard(spec))); + } + return deck; +} diff --git a/shared/game/types.ts b/shared/game/types.ts new file mode 100644 index 0000000..1fe5994 --- /dev/null +++ b/shared/game/types.ts @@ -0,0 +1,230 @@ +/** + * WikiDeck game engine types (off-chain). Implements docs/game/DESIGN.md ("Edit War"). + * Everything here is plain JSON data: MatchState round-trips through + * JSON.stringify/parse with no loss (no Maps, classes or functions). + * Contract: docs/game/ENGINE_API.md. Announce changes on claude/wikideck#3. + */ +import type { RngState } from './rng.ts'; + +export type PlayerId = 0 | 1; +export const PLAYERS: readonly PlayerId[] = [0, 1]; + +/** Category buckets from server/wiki.ts; a card's faction (DESIGN §1.5). */ +export type Faction = 'Space' | 'Nature' | 'People' | 'Science' | 'History' | 'Culture'; +export const FACTIONS: readonly Faction[] = ['Space', 'Nature', 'People', 'Science', 'History', 'Culture']; +export type Stat = 'attention' | 'depth' | 'reach'; +export const STATS: readonly Stat[] = ['attention', 'depth', 'reach']; +export type Rarity = 'Common' | 'Rare' | 'Epic' | 'Legendary'; + +/** + * A card as the engine sees it: already derived (DESIGN §1) by cards.ts from a + * host-frozen CardInput. The engine never reads raw snapshot stats. Hosts/modes + * may adjust fields (e.g. power) before createMatch; the engine does not re-derive. + */ +export interface GameCard { + /** Unique within one deck (the NFT card hash, or `loaner::`). */ + cardId: string; + /** null for unpinned loaners (DESIGN §2.1): copies then count per cardId. */ + pageId: number | null; + title: string; + faction: Faction; + /** Cosmetic in v1 (§1.7). */ + rarity: Rarity; + cost: number; + power: number; + home: Stat; + /** Live trend arrow, frozen at match start (§1.6). Adds to power in every Topic. */ + trend: -1 | 0 | 1; + keyword: string | null; + /** 'owned' = an NFT the player holds (never moved or burned by a match). */ + source: 'owned' | 'loaner'; + /** Host plausibility result (§1.10). Derivation already applied uncheckedCostCap. Default: 'loaner' for loaners, 'verified' for owned. */ + check?: 'verified' | 'unverified' | 'unchecked' | 'loaner'; +} + +/** A Topic (lane) definition in a ruleset's topic pool (§3). */ +export interface TopicDef { + id: string; + name: string; + stat: Stat; + /** Portal kind id in PORTALS (§10.3), or null for a plain Topic. Numbers: Ruleset.portalParams[topic id] (falls back to [portal id]). */ + portal: string | null; +} + +/** + * DESIGN §9 RulesConfig: every rule number as flat data so peer-hosted modes can + * override it. Use parseRuleset() for untrusted input. + */ +export interface Ruleset { + version: string; + deckSize: number; + maxCopiesPerPage: number; + maxLoaners: number; + openingHand: number; + handLimit: number; + mulligan: boolean; + turns: number; + turnSeconds: number; + afkTurns: number; + /** energyByTurn[t-1] is the base energy on turn t. Length must be ≥ turns. */ + energyByTurn: number[]; + /** Unspent energy carried to next turn, capped at this. */ + energyCarryMax: number; + bonusEnergy: number; + underdog: boolean; + topicCount: number; + distinctStats: boolean; + /** portalReveal[i] = turn on which Topic i's Portal is revealed (stats are always visible). Length = topicCount. */ + portalReveal: number[]; + laneCapacity: number; + topicPool: TopicDef[]; + /** Per-keyword numbers, keyed by keyword id. */ + keywordParams: Record>; + /** Per-Portal numbers, keyed by Topic id (or Portal kind id as a fallback). */ + portalParams: Record>; + costThresholds: number[]; + /** Index = cost (0–6). */ + powerByCost: number[]; + /** Index = cost (0–6): on-topic bonus. */ + onTopicBonus: number[]; + vanillaBonus: number; + /** Keyword ids whose hooks run. Cards with a disabled keyword are vanilla (derivation handles power). */ + keywordsEnabled: string[]; + ownedCards: boolean; + trendUp: number; + trendDown: number; + trendMinDaily: number; + uncheckedCostCap: number; + factionSynergyCap: number; + verifyStats: boolean; + /** Id of the percentile reference table used by derive.ts. */ + percentiles: string; + /** Id of the starter deck list. */ + starterDecks: string; +} + +export interface CardInPlay { + card: GameCard; + owner: PlayerId; + lane: number; + /** Turn the card was revealed. */ + turn: number; + /** Global reveal sequence number (1, 2, 3 … across both seats and all turns). */ + seq: number; + /** Permanent power changes from effects (on-reveal buffs etc.). */ + bonus: number; +} + +export interface QueuedPlay { cardId: string; lane: number } + +export interface PlayerState { + deck: GameCard[]; + hand: GameCard[]; + /** Energy available this turn (before queued plays). */ + energy: number; + /** Plays chosen this turn, hidden from the opponent until reveal. Order matters. */ + queue: QueuedPlay[]; + committed: boolean; + /** Consecutive timeouts with nothing queued (§7 afkTurns). */ + afk: number; + /** Energy carried into this turn (already included in `energy`). */ + carry: number; +} + +export interface LaneState { + /** Stat and name are always visible; the Portal only once portalRevealed. */ + topic: TopicDef; + portalRevealed: boolean; + cards: [CardInPlay[], CardInPlay[]]; +} + +export type MatchPhase = 'planning' | 'over'; + +export type LogEvent = + | { t: 'turnStart'; turn: number; energy: [number, number]; initiative: PlayerId } + | { t: 'portalRevealed'; lane: number; topic: TopicDef } + | { t: 'underdog'; player: PlayerId } + | { t: 'draw'; player: PlayerId; cardId: string } + | { t: 'reveal'; player: PlayerId; cardId: string; lane: number } + | { t: 'fizzle'; player: PlayerId; cardId: string; lane: number } + | { t: 'effect'; source: string; player: PlayerId; text: string } + | { t: 'concede'; player: PlayerId; afk: boolean } + | { t: 'matchOver'; result: MatchResult }; + +export interface MatchState { + schema: 'wikideck-match/1'; + engineVersion: number; + ruleset: Ruleset; + seed: number; + rng: RngState; + /** 1-based current turn. */ + turn: number; + phase: MatchPhase; + /** Player who reveals first this turn (§5.4). Alternates every turn. */ + initiative: PlayerId; + /** Last reveal sequence number handed out (CardInPlay.seq). */ + revealSeq: number; + players: [PlayerState, PlayerState]; + lanes: LaneState[]; + log: LogEvent[]; + /** Every action applied so far: (ruleset, decks, seed, actions) replays the match exactly. */ + actions: Action[]; + result: MatchResult | null; +} + +export type Action = + /** Queue a card from hand into a lane (§5.3). */ + | { type: 'play'; player: PlayerId; cardId: string; lane: number } + /** Take back a queued play this turn (refunds its energy). */ + | { type: 'undo'; player: PlayerId; cardId: string } + /** Commit the queue (empty = pass). When both have committed, the turn resolves. */ + | { type: 'commit'; player: PlayerId } + /** The host's turn timer expired for this player: commits what's queued, counts toward afkTurns if empty. */ + | { type: 'timeout'; player: PlayerId } + | { type: 'concede'; player: PlayerId }; + +export interface MatchResult { + /** null = draw. */ + winner: PlayerId | null; + reason: 'topics' | 'totalPower' | 'draw' | 'concede' | 'afk'; + topicsLed: [number, number]; + /** lanePower[lane][player] at the end, including "at scoring" Portals. */ + lanePower: [number, number][]; + totalPower: [number, number]; + turns: number; +} + +/** What one player is allowed to see. UI and AI read only this, never raw MatchState. */ +export interface PlayerView { + you: PlayerId; + ruleset: Ruleset; + turn: number; + phase: MatchPhase; + initiative: PlayerId; + energy: number; + /** Energy left after your queued plays. */ + energyLeft: number; + hand: GameCard[]; + queue: QueuedPlay[]; + committed: boolean; + deckCount: number; + opponent: { handCount: number; deckCount: number; queuedCount: number; committed: boolean }; + lanes: { + /** Always visible; `portal` is null until the Portal is revealed. */ + topic: TopicDef; + portalRevealed: boolean; + /** cards[0] = yours, cards[1] = opponent's (revealed cards only). */ + cards: [CardInPlay[], CardInPlay[]]; + /** Lane power of each card in `cards`, same shape. */ + cardPower: [number[], number[]]; + /** power[0] = yours, power[1] = opponent's. */ + power: [number, number]; + /** Who leads this Topic from your point of view. */ + leader: 'you' | 'opponent' | null; + }[]; + result: MatchResult | null; +} + +export class IllegalActionError extends Error { + constructor(message: string) { super(message); this.name = 'IllegalActionError'; } +} diff --git a/src/App.tsx b/src/App.tsx index ca9d178..b98fe80 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -10,6 +10,7 @@ import { Card, samples, imageCredit, type CardData } from './Card.tsx'; import { WalletPanel } from './WalletPanel.tsx'; import { useModalFocus } from './useModalFocus.ts'; import { ThemePicker } from './ThemePicker.tsx'; +import { LoginButton } from './auth/LoginButton.tsx'; import { TradeDesk } from './TradeDesk.tsx'; import { IS_MAINNET, NETWORK_GENESIS_TIME, NETWORK_LABEL } from '../shared/network.ts'; import { StateClient } from '../shared/rpc-client.ts'; @@ -170,7 +171,7 @@ export default function App() {
-
Explore {view}
RandomX {NETWORK_LABEL}{peerLabel}
+
Explore {view}
RandomX {NETWORK_LABEL}{peerLabel}
RPC {rpcAvailable ? 'available' : 'unavailable'}{peerLabel}{IS_MAINNET?'MAINNET · experimental · unaudited · no value promised':'TESTNET · experimental · no value promised'}{snapshot && !rpcAvailable && Showing last known state}
{error &&
{error}
} diff --git a/src/auth/LoginButton.tsx b/src/auth/LoginButton.tsx new file mode 100644 index 0000000..de8f235 --- /dev/null +++ b/src/auth/LoginButton.tsx @@ -0,0 +1,76 @@ +import { useEffect, useState, useSyncExternalStore } from 'react'; +import { Link2, LoaderCircle, LogIn, LogOut, UserRound } from 'lucide-react'; +import { getWallet, subscribeWallet, type Wallet } from '../wallet.ts'; +import { account, completeLogin, isCallback, linkWallet, login, logout, subscribeAuth, type Account } from './session.ts'; +import './auth.css'; + +export function useAccount(): Account | undefined { + return useSyncExternalStore(subscribeAuth, account, () => undefined); +} + +/** Deterministic initials avatar (LDAP accounts have no picture claim; no third-party image hosts). */ +export function Avatar({ name, seed, size = 22 }: { name: string; seed: string; size?: number }) { + let h = 0; for (const c of seed) h = (h * 31 + c.charCodeAt(0)) >>> 0; + const initials = name.split(/\s+/).filter(Boolean).slice(0, 2).map(w => [...w][0]).join('').toUpperCase() || '?'; + return ; +} + +const short = (s: string) => `${s.slice(0, 6)}…${s.slice(-4)}`; + +export function LoginButton() { + const me = useAccount(); + const [busy, setBusy] = useState(false); + const [open, setOpen] = useState(false); + const [notice, setNotice] = useState(''); + const [wallet, setWallet] = useState(); + + useEffect(() => { + if (!isCallback(location.href)) return; + setBusy(true); + completeLogin(location.href) + .then(({ returnTo }) => history.replaceState(null, '', returnTo)) + .catch(e => { history.replaceState(null, '', '/'); setNotice(e instanceof Error ? e.message : 'Login failed'); }) + .finally(() => setBusy(false)); + }, []); + useEffect(() => { + const update = () => { void getWallet().then(setWallet).catch(() => setWallet(undefined)); }; + update(); return subscribeWallet(update); + }, []); + + const run = async (fn: () => Promise) => { + setBusy(true); setNotice(''); + try { await fn(); } catch (e) { setNotice(e instanceof Error ? e.message : 'Request failed'); } + finally { setBusy(false); } + }; + + if (!me) return + + {notice && {notice}} + ; + + const linked = wallet && me.wallets.some(w => w.address === wallet.address); + return + + {open &&
+
+
{me.name}{me.username && @{me.username} · eom.dev}
+
+ LINKED WALLETS + {me.wallets.length ? me.wallets.map(w => {short(w.address)}) :

None yet.

} +
+ {linked ?

This wallet is linked.

+ : <>{wallet &&

Linking shows your eom.dev name ({me.name}) next to this wallet address on leaderboards, and anyone can look it up. You can unlink later.

}} + {notice &&

{notice}

} + +
} +
; +} diff --git a/src/auth/auth.css b/src/auth/auth.css new file mode 100644 index 0000000..3995faf --- /dev/null +++ b/src/auth/auth.css @@ -0,0 +1,21 @@ +.auth-wrap{position:relative;display:inline-flex;align-items:center;gap:8px} +.auth-avatar{display:inline-grid;place-items:center;border-radius:50%;color:#fff;font-weight:650;flex-shrink:0;line-height:1} +.auth-button .auth-avatar{margin-right:2px} +.auth-menu{position:absolute;top:calc(100% + 8px);right:0;z-index:40;width:280px;padding:14px;border-radius:10px; + background:var(--surface, #fff);color:inherit;border:1px solid rgba(127,127,127,.25);box-shadow:0 12px 32px rgba(0,0,0,.18); + display:flex;flex-direction:column;gap:10px} +.auth-menu-head{display:flex;align-items:center;gap:10px} +.auth-menu-head small,.auth-menu-section small{display:block;opacity:.65;font-size:10px;letter-spacing:.6px} +.auth-menu-section code{display:block;font-size:11px;margin-top:4px} +.auth-menu-section p,.auth-ok{font-size:11px;opacity:.8;margin:4px 0 0;display:flex;align-items:center;gap:6px} +.auth-notice{font-size:11px;max-width:260px} +.auth-consent{font-size:11px;line-height:1.5;opacity:.8;margin:0} +.auth-label{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:140px} +/* Narrow screens: the top bar has no spare width, so float the account button outside its flow. */ +@media (max-width:480px){ + .auth-label{display:none} + .auth-wrap{position:fixed;right:14px;bottom:14px;z-index:45} + .auth-wrap .auth-button{border-radius:999px;padding:6px;box-shadow:0 6px 18px rgba(0,0,0,.22)} + .auth-menu{top:auto;bottom:calc(100% + 8px);width:min(280px,calc(100vw - 28px))} + .auth-wrap>.auth-notice{position:absolute;bottom:calc(100% + 8px);right:0;width:min(260px,calc(100vw - 28px))} +} diff --git a/src/auth/session.ts b/src/auth/session.ts new file mode 100644 index 0000000..6de057d --- /dev/null +++ b/src/auth/session.ts @@ -0,0 +1,144 @@ +// eom.dev login (Dex, OIDC authorization code + PKCE S256, public client "wikideck"). +// The browser only navigates to Dex. The node exchanges the code and verifies the ID token +// (Dex sends no CORS headers), so there is no browser -> Dex fetch and no CSP change. +// Tokens live in sessionStorage (cleared with the tab), never localStorage. +import { getWallet, sign, type Wallet } from '../wallet.ts'; +import { clientLinkMessage } from '../../shared/account-link.ts'; + +export type LinkedWallet = { address: string; linkedAt: number }; +export type Account = { sub: string; issuer: string; name: string; username: string; wallets: LinkedWallet[] }; +type Session = { idToken: string; expiresAt: number; account: Account }; +type Pending = { state: string; nonce: string; verifier: string; redirectUri: string; returnTo: string; createdAt: number }; +type AuthConfig = { issuer: string; clientId: string; scopes: string; authorizationEndpoint: string; redirectUris: string[] }; + +const SESSION_KEY = 'wikideck.auth.session'; +const PENDING_KEY = 'wikideck.auth.pending'; +export const CALLBACK_PATH = '/auth/callback'; +export const NATIVE_REDIRECT = 'dev.eom.wikideck:/oauth/callback'; + +const listeners = new Set<() => void>(); +let current: Session | undefined = load(); +export function subscribeAuth(fn: () => void): () => void { listeners.add(fn); return () => { listeners.delete(fn); }; } +function notify() { for (const fn of listeners) fn(); } + +function load(): Session | undefined { + try { + const raw = sessionStorage.getItem(SESSION_KEY); + const s = raw ? JSON.parse(raw) as Session : undefined; + return s && s.expiresAt > Date.now() + 30_000 ? s : undefined; + } catch { return undefined; } +} +function save(s: Session | undefined) { + current = s; + try { if (s) sessionStorage.setItem(SESSION_KEY, JSON.stringify(s)); else sessionStorage.removeItem(SESSION_KEY); } catch { /* memory only */ } + notify(); +} +export function account(): Account | undefined { + if (current && current.expiresAt <= Date.now() + 30_000) save(undefined); + return current?.account; +} + +const b64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +const random = (n = 32) => b64url(crypto.getRandomValues(new Uint8Array(n))); +export async function pkceChallenge(verifier: string): Promise { + return b64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)))); +} + +type CapacitorGlobal = { isNativePlatform?: () => boolean; Plugins?: { Browser?: { open(o: { url: string }): Promise; close?(): Promise } } }; +const capacitor = () => (globalThis as { Capacitor?: CapacitorGlobal }).Capacitor; +export const isNative = () => Boolean(capacitor()?.isNativePlatform?.()); +export function redirectUri(): string { return isNative() ? NATIVE_REDIRECT : `${location.origin}${CALLBACK_PATH}`; } + +/** + * Node base URL. Empty on the web (same origin). Capacitor builds bundle the UI locally, so the + * app sets `globalThis.WIKIDECK_NODE_URL = 'http://192.168.1.32:3101'` (or similar) before use. + */ +export const nodeBase = () => ((globalThis as { WIKIDECK_NODE_URL?: string }).WIKIDECK_NODE_URL ?? '').replace(/\/+$/, ''); + +async function api(path: string, init: RequestInit & { token?: string } = {}): Promise { + const { token, ...rest } = init; + const res = await fetch(`${nodeBase()}/api/account/${path}`, { cache: 'no-store', signal: AbortSignal.timeout(15000), ...rest, + headers: { ...(rest.body ? { 'Content-Type': 'application/json' } : {}), ...(token ? { Authorization: `Bearer ${token}` } : {}) } }); + const data = await res.json().catch(() => ({})); + if (res.status === 401 && token) save(undefined); + if (!res.ok) throw new Error(typeof data.error === 'string' ? data.error : 'Account request failed'); + return data as T; +} + +export async function login(returnTo = location.pathname + location.search): Promise { + const config = await api('config'); + const uri = redirectUri(); + if (!config.redirectUris.includes(uri)) throw new Error(`This node is not set up for eom.dev login from ${uri}.`); + const pending: Pending = { state: random(), nonce: random(), verifier: random(48), redirectUri: uri, + returnTo: returnTo.startsWith('/') && !returnTo.startsWith('//') ? returnTo : '/', createdAt: Date.now() }; + sessionStorage.setItem(PENDING_KEY, JSON.stringify(pending)); + const url = new URL(config.authorizationEndpoint); + url.search = new URLSearchParams({ response_type: 'code', client_id: config.clientId, redirect_uri: uri, + scope: config.scopes, state: pending.state, nonce: pending.nonce, + code_challenge: await pkceChallenge(pending.verifier), code_challenge_method: 'S256' }).toString(); + // Capacitor: system browser (never a WebView) + custom-scheme redirect, per RFC 8252. + const browser = capacitor()?.Plugins?.Browser; + if (isNative() && browser) await browser.open({ url: url.toString() }); + else location.assign(url.toString()); +} + +export const isCallback = (url: string) => { + const u = new URL(url); + return (u.pathname === CALLBACK_PATH || url.startsWith(NATIVE_REDIRECT)) && (u.searchParams.has('code') || u.searchParams.has('error')); +}; + +/** Finish a login from the redirect URL. Web: called on load. Capacitor: call from App 'appUrlOpen'. */ +export async function completeLogin(url: string): Promise<{ returnTo: string }> { + const params = new URL(url).searchParams; + const raw = sessionStorage.getItem(PENDING_KEY); + sessionStorage.removeItem(PENDING_KEY); // single use + const pending = raw ? JSON.parse(raw) as Pending : undefined; + if (!pending || Date.now() - pending.createdAt > 10 * 60_000) throw new Error('Login expired. Please try again.'); + if (params.get('state') !== pending.state) throw new Error('Login state mismatch. Please try again.'); + if (params.get('error')) throw new Error(`Login cancelled: ${params.get('error_description') ?? params.get('error')}`.slice(0, 160)); + const code = params.get('code'); + if (!code) throw new Error('Login response had no code.'); + const s = await api('token', { method: 'POST', body: JSON.stringify({ code, codeVerifier: pending.verifier, + redirectUri: pending.redirectUri, nonce: pending.nonce }) }); + save(s); + if (isNative()) void capacitor()?.Plugins?.Browser?.close?.().catch(() => {}); + return { returnTo: pending.returnTo }; +} + +/** Local logout. Dex publishes no end_session endpoint, so the Dex SSO cookie may remain. */ +export function logout(): void { save(undefined); } + +export async function refreshAccount(): Promise { + if (!current) return undefined; + const me = await api('me', { token: current.idToken }); + save({ ...current, account: me }); + return me; +} + +/** + * Prove wallet ownership: the node issues a one-time nonce. The client builds the link message + * itself (shared/account-link.ts) and never signs node-supplied text, so a hostile node or a + * network attacker cannot get a transfer or trade signed. The key never leaves the client. + */ +export async function linkWallet(wallet?: Wallet, signer: (w: Wallet, message: string) => Promise = sign): Promise { + if (!current) throw new Error('Log in with your eom.dev account first.'); + const session = current; + const w = wallet ?? await getWallet(); + if (!w) throw new Error('Unlock your wallet first.'); + const token = session.idToken; + const challenge = await api<{ nonce?: unknown; message?: unknown; expiresAt?: unknown }>('challenge', + { method: 'POST', token, body: JSON.stringify({ address: w.address }) }); + const message = clientLinkMessage(session.account, w.address, challenge); + const signature = await signer(w, message); + const linked = await api('link', { method: 'POST', token, + body: JSON.stringify({ nonce: challenge.nonce, address: w.address, publicKey: w.publicKey, signature }) }); + await refreshAccount().catch(() => {}); + return linked; +} + +/** Leaderboard display names for wallet addresses (only linked wallets resolve). */ +export async function displayNames(addresses: string[]): Promise> { + if (!addresses.length) return {}; + const { names } = await api<{ names: Record }>(`names?addresses=${addresses.slice(0, 100).join(',')}`); + return names; +} diff --git a/tests/account-link.test.ts b/tests/account-link.test.ts new file mode 100644 index 0000000..6ef7a0c --- /dev/null +++ b/tests/account-link.test.ts @@ -0,0 +1,173 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { generateKeyPairSync, sign } from 'node:crypto'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import express from 'express'; +import { address } from '../server/testnet/consensus.ts'; +import { AccountStore, CHALLENGE_TTL_MS, LinkError, MAX_PENDING_PER_ACCOUNT } from '../server/account/store.ts'; +import { clientLinkMessage, linkMessage } from '../shared/account-link.ts'; +import { nftTransferMessage } from '../shared/testnet.ts'; +import { createAccountRouter } from '../server/account/router.ts'; +import { DexKeys, oidcConfig } from '../server/account/oidc.ts'; + +function wallet() { + const keys = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }); + const publicKey = keys.publicKey.export({ type: 'spki', format: 'der' }).toString('base64'); + return { publicKey, address: address(publicKey), sign: (m: string) => + sign('sha256', Buffer.from(m), { key: keys.privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64') }; +} +const ada = { sub: 'user-ada', issuer: 'https://dex.test/', name: 'Ada', username: 'ada' }; +const bob = { sub: 'user-bob', issuer: 'https://dex.test/', name: 'Bob', username: 'bob' }; + +async function withStore(fn: (s: AccountStore, clock: { now: number }) => Promise | void) { + const dir = await mkdtemp(join(tmpdir(), 'wikideck-account-')); + const clock = { now: 1_800_000_000_000 }; + const store = new AccountStore(join(dir, 'accounts.sqlite'), () => clock.now); + try { store.upsert(ada); store.upsert(bob); await fn(store, clock); } + finally { store.close(); await rm(dir, { recursive: true, force: true }); } +} +const code = (fn: () => unknown, status: number) => assert.throws(fn, e => e instanceof LinkError && e.status === status); + +test('account link: a valid wallet signature links the wallet and names resolve', () => withStore(store => { + const w = wallet(); + const c = store.challenge(ada, w.address); + const linked = store.link(ada, { nonce: c.nonce, address: w.address, publicKey: w.publicKey, signature: w.sign(c.message) }); + assert.equal(linked.address, w.address); + assert.deepEqual(store.wallets(ada.sub).map(x => x.address), [w.address]); + assert.deepEqual(store.names([w.address, 'f'.repeat(64)]), { [w.address]: 'Ada' }); +})); + +test('account link: a signature from the wrong key is rejected', () => withStore(store => { + const w = wallet(), attacker = wallet(); + const c = store.challenge(ada, w.address); + // Attacker signs with their own key but claims the victim's address and public key. + code(() => store.link(ada, { nonce: c.nonce, address: w.address, publicKey: w.publicKey, signature: attacker.sign(c.message) }), 401); + // Or presents their own public key for the victim's address. + const c2 = store.challenge(ada, w.address); + code(() => store.link(ada, { nonce: c2.nonce, address: w.address, publicKey: attacker.publicKey, signature: attacker.sign(c2.message) }), 400); + assert.deepEqual(store.wallets(ada.sub), []); +})); + +test('account link: replayed, expired and cross-account challenges are rejected', () => withStore((store, clock) => { + const w = wallet(); + const c = store.challenge(ada, w.address); + const input = { nonce: c.nonce, address: w.address, publicKey: w.publicKey, signature: w.sign(c.message) }; + store.link(ada, input); + code(() => store.link(ada, input), 409); // replay + const c2 = store.challenge(ada, w.address); + clock.now += CHALLENGE_TTL_MS + 1; + code(() => store.link(ada, { ...input, nonce: c2.nonce, signature: w.sign(c2.message) }), 409); // expired + const c3 = store.challenge(ada, w.address); + code(() => store.link(bob, { ...input, nonce: c3.nonce, signature: w.sign(c3.message) }), 409); // challenge bound to ada + // A wallet already linked to ada cannot be claimed by bob even with a fresh, valid proof. + const c4 = store.challenge(bob, w.address); + code(() => store.link(bob, { ...input, nonce: c4.nonce, signature: w.sign(c4.message) }), 409); + assert.equal(store.unlink(ada.sub, w.address), true); +})); + +test('account HTTP: login exchange, bearer auth and wallet link end to end', async () => { + const dir = await mkdtemp(join(tmpdir(), 'wikideck-account-http-')); + const rsa = generateKeyPairSync('rsa', { modulusLength: 2048 }); + const config = { ...oidcConfig({}), issuer: 'https://dex.test/' }; + const now = Math.floor(Date.now() / 1000); + const enc = (v: unknown) => Buffer.from(JSON.stringify(v)).toString('base64url'); + const nonce = 'nonce-'.padEnd(24, 'x'); + const input = `${enc({ alg: 'RS256', kid: 'k1' })}.${enc({ iss: config.issuer, sub: 'user-ada', aud: 'wikideck', + iat: now, exp: now + 600, name: 'Ada', preferred_username: 'ada', nonce })}`; + const idToken = `${input}.${sign('sha256', Buffer.from(input), rsa.privateKey).toString('base64url')}`; + let tokenBody = ''; + const fetcher = (async (url: URL | string, init?: RequestInit) => { + const u = String(url); + const json = (v: unknown, status = 200) => new Response(JSON.stringify(v), { status, headers: { 'content-type': 'application/json' } }); + if (u.endsWith('openid-configuration')) return json({ issuer: config.issuer, authorization_endpoint: 'https://dex.test/auth', + token_endpoint: 'https://dex.test/token', jwks_uri: 'https://dex.test/keys' }); + if (u.endsWith('/keys')) return json({ keys: [{ ...rsa.publicKey.export({ format: 'jwk' }), kid: 'k1' }] }); + if (u.endsWith('/token')) { tokenBody = String(init?.body); return json({ id_token: idToken, access_token: 'a', token_type: 'bearer' }); } + return json({}, 404); + }) as typeof fetch; + const app = express(); + app.use(express.json()); + app.use('/api/account', createAccountRouter({ config, dataDir: dir, keys: new DexKeys(config, fetcher), fetcher })); + const server = app.listen(0, '127.0.0.1'); + await new Promise(r => server.once('listening', r)); + const base = `http://127.0.0.1:${(server.address() as { port: number }).port}/api/account`; + const call = async (path: string, body?: unknown, token?: string) => { + const res = await fetch(base + path, { method: body ? 'POST' : 'GET', headers: { 'content-type': 'application/json', + ...(token ? { authorization: `Bearer ${token}` } : {}) }, body: body ? JSON.stringify(body) : undefined }); + return { status: res.status, body: await res.json() }; + }; + try { + const cfg = await call('/config'); + assert.equal(cfg.body.authorizationEndpoint, 'https://dex.test/auth'); + assert.equal(cfg.body.clientId, 'wikideck'); + const verifier = 'v'.repeat(43); + const bad = await call('/token', { code: 'c', codeVerifier: verifier, redirectUri: 'https://evil.test/cb', nonce }); + assert.equal(bad.status, 400); + const wrongNonce = await call('/token', { code: 'c', codeVerifier: verifier, redirectUri: config.redirectUris[0], nonce: 'z'.repeat(24) }); + assert.equal(wrongNonce.status, 401); + const login = await call('/token', { code: 'c', codeVerifier: verifier, redirectUri: config.redirectUris[0], nonce }); + assert.equal(login.status, 200); + assert.equal(login.body.account.name, 'ada'); + const sent = new URLSearchParams(tokenBody); + assert.equal(sent.get('client_id'), 'wikideck'); + assert.equal(sent.get('code_verifier'), verifier); + assert.equal(sent.get('client_secret'), null); + assert.equal((await call('/me')).status, 401); + assert.equal((await call('/me', undefined, idToken)).body.username, 'ada'); + const w = wallet(); + const ch = await call('/challenge', { address: w.address }, idToken); + const link = await call('/link', { nonce: ch.body.nonce, address: w.address, publicKey: w.publicKey, signature: w.sign(ch.body.message) }, idToken); + assert.equal(link.status, 201); + const replay = await call('/link', { nonce: ch.body.nonce, address: w.address, publicKey: w.publicKey, signature: w.sign(ch.body.message) }, idToken); + assert.equal(replay.status, 409); + assert.deepEqual((await call(`/names?addresses=${w.address}`)).body.names, { [w.address]: 'ada' }); + } finally { + await new Promise(r => server.close(r)); + await rm(dir, { recursive: true, force: true }); + } +}); + +test('account link: pending challenges are capped per account, not just globally', () => withStore(store => { + const w = wallet(); + for (let i = 0; i < MAX_PENDING_PER_ACCOUNT; i++) store.challenge(ada, w.address); + code(() => store.challenge(ada, w.address), 429); + store.challenge(bob, w.address); // other users are unaffected +})); + +test('account link (client): only a locally built link message is ever signed', () => { + const w = wallet(), now = 1_800_000_000_000; + const good = { nonce: 'a'.repeat(24), expiresAt: now + 60_000 }; + const expected = linkMessage({ issuer: ada.issuer, sub: ada.sub, address: w.address, ...good }); + assert.equal(clientLinkMessage(ada, w.address, { ...good, message: expected }, now), expected); + // A hostile node substitutes a card-transfer tuple for the link message. + const transfer = nftTransferMessage({ chainId: 'd'.repeat(64), cardHash: 'b'.repeat(64), from: w.address, to: 'c'.repeat(64), sequence: 1 } as never); + assert.throws(() => clientLinkMessage(ada, w.address, { ...good, message: transfer }, now), /Nothing was signed/); + assert.throws(() => clientLinkMessage(ada, w.address, { nonce: '["x"]', expiresAt: good.expiresAt }, now), /invalid link challenge/); + assert.throws(() => clientLinkMessage(ada, w.address, { nonce: good.nonce, expiresAt: now + 3_600_000 }, now), /invalid link challenge/); + assert.throws(() => clientLinkMessage(ada, w.address, { nonce: good.nonce, expiresAt: now - 1 }, now), /invalid link challenge/); +}); + +test('account link (client): linkWallet refuses a transfer message from the node and signs nothing', async () => { + const w = wallet(); + const store = new Map(); + const g = globalThis as Record; + const saved = { sessionStorage: g.sessionStorage, fetch: g.fetch }; + g.sessionStorage = { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => { store.set(k, v); }, + removeItem: (k: string) => { store.delete(k); } }; + store.set('wikideck.auth.session', JSON.stringify({ idToken: 'tok', expiresAt: Date.now() + 3_600_000, + account: { ...ada, wallets: [] } })); + const transfer = nftTransferMessage({ chainId: 'd'.repeat(64), cardHash: 'b'.repeat(64), from: w.address, to: 'c'.repeat(64), sequence: 1 } as never); + const requests: string[] = []; + g.fetch = (async (url: string) => { requests.push(String(url)); + return new Response(JSON.stringify({ nonce: 'a'.repeat(24), expiresAt: Date.now() + 60_000, message: transfer }), + { headers: { 'content-type': 'application/json' } }); }) as typeof fetch; + try { + const { linkWallet } = await import('../src/auth/session.ts'); + let signed = 0; + await assert.rejects(linkWallet({ address: w.address, publicKey: w.publicKey }, async () => { signed++; return 'sig'; }), /Nothing was signed/); + assert.equal(signed, 0); + assert.deepEqual(requests.map(u => u.split('/').pop()), ['challenge']); // never reached /link + } finally { g.sessionStorage = saved.sessionStorage; g.fetch = saved.fetch; } +}); diff --git a/tests/account-oidc.test.ts b/tests/account-oidc.test.ts new file mode 100644 index 0000000..e3e5d82 --- /dev/null +++ b/tests/account-oidc.test.ts @@ -0,0 +1,89 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { generateKeyPairSync, sign, type KeyObject } from 'node:crypto'; +import { DexKeys, TokenError, displayName, oidcConfig, verifyIdToken } from '../server/account/oidc.ts'; + +const config = { ...oidcConfig({}), issuer: 'https://dex.test/' }; +const NOW = 1_800_000_000_000; +const t = Math.floor(NOW / 1000); + +function rsa() { return generateKeyPairSync('rsa', { modulusLength: 2048 }); } +const main = rsa(), other = rsa(); + +export function jwt(claims: Record, key: KeyObject = main.privateKey, header: Record = { alg: 'RS256', kid: 'k1' }): string { + const enc = (v: unknown) => Buffer.from(JSON.stringify(v)).toString('base64url'); + const input = `${enc(header)}.${enc(claims)}`; + return `${input}.${sign('sha256', Buffer.from(input), key).toString('base64url')}`; +} +const good = (over: Record = {}) => ({ iss: config.issuer, sub: 'user-1', aud: 'wikideck', + iat: t - 10, exp: t + 3600, name: 'Ada Lovelace', preferred_username: 'ada', email: 'ada@example.test', nonce: 'n'.repeat(16), ...over }); + +function fakeDex(calls: string[] = []) { + const jwks = { keys: [{ ...main.publicKey.export({ format: 'jwk' }), kid: 'k1', use: 'sig', alg: 'RS256' }] }; + const fetcher = (async (url: URL | string) => { + const u = String(url); calls.push(u); + const json = (v: unknown) => new Response(JSON.stringify(v), { headers: { 'content-type': 'application/json' } }); + if (u.endsWith('/.well-known/openid-configuration')) return json({ issuer: config.issuer, + authorization_endpoint: 'https://dex.test/auth', token_endpoint: 'https://dex.test/token', jwks_uri: 'https://dex.test/keys' }); + if (u === 'https://dex.test/keys') return json(jwks); + return new Response('{}', { status: 404 }); + }) as typeof fetch; + return new DexKeys(config, fetcher, () => NOW); +} + +const rejects = (p: Promise, msg: RegExp) => assert.rejects(p, e => e instanceof TokenError && msg.test(e.message)); + +test('account: a good ID token verifies against the JWKS', async () => { + const claims = await verifyIdToken(jwt(good()), fakeDex(), config, { now: NOW, nonce: 'n'.repeat(16) }); + assert.equal(claims.sub, 'user-1'); + assert.equal(displayName(claims), 'ada'); // username preferred over real name +}); + +test('account: expired tokens are rejected (beyond clock skew)', async () => { + await rejects(verifyIdToken(jwt(good({ exp: t - 61 })), fakeDex(), config, { now: NOW }), /expired/); + // Within the 60 s skew still passes. + await verifyIdToken(jwt(good({ exp: t - 30 })), fakeDex(), config, { now: NOW }); +}); + +test('account: wrong audience and wrong issuer are rejected', async () => { + await rejects(verifyIdToken(jwt(good({ aud: 'www-membership' })), fakeDex(), config, { now: NOW }), /audience/); + await rejects(verifyIdToken(jwt(good({ aud: ['other', 'wikideck'] })), fakeDex(), config, { now: NOW }), /authorized party/); + await verifyIdToken(jwt(good({ aud: ['other', 'wikideck'], azp: 'wikideck' })), fakeDex(), config, { now: NOW }); + await rejects(verifyIdToken(jwt(good({ iss: 'https://evil.test/' })), fakeDex(), config, { now: NOW }), /issuer/); + await rejects(verifyIdToken(jwt(good({ iss: 'https://dex.test' })), fakeDex(), config, { now: NOW }), /issuer/); +}); + +test('account: forged signatures, alg confusion and unknown keys are rejected', async () => { + await rejects(verifyIdToken(jwt(good(), other.privateKey), fakeDex(), config, { now: NOW }), /signature/); + const parts = jwt(good()).split('.'); + const tampered = `${parts[0]}.${Buffer.from(JSON.stringify(good({ sub: 'admin' }))).toString('base64url')}.${parts[2]}`; + await rejects(verifyIdToken(tampered, fakeDex(), config, { now: NOW }), /signature/); + const none = `${Buffer.from(JSON.stringify({ alg: 'none', kid: 'k1' })).toString('base64url')}.${parts[1]}.`; + await rejects(verifyIdToken(none, fakeDex(), config, { now: NOW }), /algorithm/); + await rejects(verifyIdToken(jwt(good(), main.privateKey, { alg: 'RS256', kid: 'nope' }), fakeDex(), config, { now: NOW }), /signing key/); + await rejects(verifyIdToken('a.b', fakeDex(), config, { now: NOW }), /Malformed/); +}); + +test('account: nonce, future iat and nbf are enforced', async () => { + await rejects(verifyIdToken(jwt(good()), fakeDex(), config, { now: NOW, nonce: 'x'.repeat(16) }), /nonce/); + await rejects(verifyIdToken(jwt(good({ iat: t + 600 })), fakeDex(), config, { now: NOW }), /future/); + await rejects(verifyIdToken(jwt(good({ nbf: t + 600 })), fakeDex(), config, { now: NOW }), /not yet/); +}); + +test('account: JWKS is cached and discovery issuer must match', async () => { + const calls: string[] = []; + const keys = fakeDex(calls); + await verifyIdToken(jwt(good()), keys, config, { now: NOW }); + await verifyIdToken(jwt(good()), keys, config, { now: NOW }); + assert.equal(calls.filter(c => c.endsWith('/keys')).length, 1); + const bad = new DexKeys({ ...config, issuer: 'https://dex.test/other/' }, (async () => + new Response(JSON.stringify({ issuer: 'https://dex.test/' }))) as typeof fetch); + await assert.rejects(bad.meta(), /issuer mismatch/); +}); + +test('account: display names never fall back to email and are sanitised', () => { + assert.equal(displayName({ sub: 'abcdef123', preferred_username: 'ada', name: 'Ada Lovelace' }), 'ada'); + assert.equal(displayName({ sub: 'abcdef123', name: 'Ada Lovelace' }), 'Ada Lovelace'); + assert.equal(displayName({ sub: 'abcdef123' }), 'player-abcdef'); + assert.equal(displayName({ sub: 's', name: 'A\u0000B' + 'x'.repeat(100) }).length, 48); +}); diff --git a/tests/game-core.test.ts b/tests/game-core.test.ts new file mode 100644 index 0000000..05a2c81 --- /dev/null +++ b/tests/game-core.test.ts @@ -0,0 +1,212 @@ +// Core-loop tests owned by engine-a. Keyword/Portal, derivation, property and golden tests: engine-b (tests/game-*.test.ts). +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + DEFAULT_RULESET, IllegalActionError, KEYWORDS, PORTALS, Rng, applyAction, cardPower, createMatch, deserialize, isOver, + laneLeader, legalActions, loanerCard, parseRuleset, placeCard, replay, result, revealPortal, serialize, starterDeck, + STARTER_POOL, viewFor, type Action, type GameCard, type KeywordDef, type MatchState, type PlayerId, type PortalDef, type Ruleset, +} from '../shared/game/index.ts'; + +const decks = (seed = 'd'): [GameCard[], GameCard[]] => [starterDeck(`${seed}-a`), starterDeck(`${seed}-b`)]; +const commit = (s: MatchState, player: PlayerId) => applyAction(s, { type: 'commit', player }); +const commitBoth = (s: MatchState) => commit(commit(s, 0), 1); +const card = (cost: number, overrides: Partial = {}): GameCard => + ({ ...loanerCard(STARTER_POOL.find(s => s[3] === cost)!), keyword: null, trend: 0, ...overrides }); +/** A deck whose every card costs `cost`, so the first plays are predictable. */ +const flatDeck = (cost: number, prefix: string, home: GameCard['home'] = 'depth'): GameCard[] => + Array.from({ length: 12 }, (_, i) => card(cost, { cardId: `${prefix}${i}`, pageId: 1000 + Math.floor(i / 2), home })); + +/** Temporarily register a keyword/portal implementation under a v1 id. */ +function withHook(registry: Record, id: string, def: T, run: () => void) { + const saved = registry[id]; + registry[id] = def; + try { run(); } finally { if (saved === undefined) delete registry[id]; else registry[id] = saved; } +} + +function randomPlay(seed: number, ruleset: Ruleset = DEFAULT_RULESET): MatchState { + let state = createMatch(ruleset, decks(String(seed)), seed); + const chooser = Rng.fromSeed(`bot:${seed}`); + for (let steps = 0; !isOver(state); steps++) { + assert.ok(steps < 2000, 'match must terminate'); + const player = chooser.int(2) as PlayerId; + const actions = legalActions(state, player); + if (actions.length) state = applyAction(state, chooser.pick(actions)); + assert.deepEqual(deserialize(serialize(state)), state); + } + return state; +} + +test('mulberry32 matches the reference value and is seed-deterministic', () => { + assert.equal(new Rng(1).next(), 0.6270739405881613); + const seq = (r: Rng) => Array.from({ length: 8 }, () => r.next()); + assert.deepEqual(seq(Rng.fromSeed(42)), seq(Rng.fromSeed(42))); + assert.notDeepEqual(seq(Rng.fromSeed(42)), seq(Rng.fromSeed(43))); + assert.equal(Rng.fromSeed('lobby-1').state, Rng.fromSeed('lobby-1').state); +}); + +test('DEFAULT_RULESET matches DESIGN §9 and parses; bad rulesets are rejected', () => { + assert.deepEqual(parseRuleset(DEFAULT_RULESET), DEFAULT_RULESET); + assert.equal(DEFAULT_RULESET.laneCapacity, 3); + assert.deepEqual(DEFAULT_RULESET.powerByCost, [0, 1, 2, 4, 6, 8, 10]); + assert.deepEqual(DEFAULT_RULESET.onTopicBonus, [0, 1, 1, 2, 2, 3, 3]); + assert.equal(DEFAULT_RULESET.topicPool.length, 9); + for (const bad of [{ turns: 13 }, { turnSeconds: 60 }, { energyByTurn: [1, 2] }, { portalReveal: [1, 2] }, + { keywordParams: { nope: {} } }, { keywordsEnabled: ['nope'] }, { extra: 1 }, { mulligan: true }, + { costThresholds: [90, 1, 2, 3, 4] }, { onTopicBonus: 2 }, { topicCount: 2 }, { portalParams: { nope: {} } }]) + assert.throws(() => parseRuleset({ ...DEFAULT_RULESET, ...bad }), JSON.stringify(bad)); +}); + +test('setup: one Topic per stat, stats visible, Portals hidden until portalReveal, hands of 4, energy 1', () => { + const state = createMatch(DEFAULT_RULESET, decks(), 7); + assert.equal(state.turn, 1); + assert.deepEqual(state.lanes.map(l => l.topic.stat).sort(), ['attention', 'depth', 'reach']); + assert.deepEqual(state.lanes.map(l => l.portalRevealed), [false, false, false]); + for (const p of state.players) { assert.equal(p.hand.length, 4); assert.equal(p.deck.length, 8); assert.equal(p.energy, 1); } + const view = viewFor(state, 0); + assert.deepEqual(view.lanes.map(l => l.topic.stat), state.lanes.map(l => l.topic.stat)); + assert.ok(view.lanes.every(l => l.topic.portal === null && l.topic.name === '?')); + let next = commitBoth(state); + assert.deepEqual(next.lanes.map(l => l.portalRevealed), [true, false, false]); + next = commitBoth(commitBoth(next)); + assert.deepEqual(next.lanes.map(l => l.portalRevealed), [true, true, true]); +}); + +test('decks are validated: size, copies per page, keyword ids, ownedCards', () => { + const [a, b] = decks(); + assert.throws(() => createMatch(DEFAULT_RULESET, [a.slice(0, 11), b], 1), IllegalActionError); + const triple = [...a.slice(0, 9), ...[0, 1, 2].map(n => ({ ...a[0], cardId: `x${n}` }))]; + assert.throws(() => createMatch(DEFAULT_RULESET, [triple, b], 1), /copies/); + assert.throws(() => createMatch(DEFAULT_RULESET, [[{ ...a[0], keyword: 'nope' }, ...a.slice(1)], b], 1), /unknown keyword/); + const owned = [{ ...a[0], source: 'owned' as const }, ...a.slice(1)]; + assert.doesNotThrow(() => createMatch(DEFAULT_RULESET, [owned, b], 1)); + assert.throws(() => createMatch({ ...DEFAULT_RULESET, ownedCards: false }, [owned, b], 1), /owned/); +}); + +test('queued plays are hidden until reveal; undo refunds; committed seats get no actions', () => { + let state = createMatch(DEFAULT_RULESET, decks(), 11); + const play = legalActions(state, 0).find(a => a.type === 'play') as Extract; + assert.ok(play, 'turn 1 should have a 1-cost play'); + state = applyAction(state, play); + assert.equal(viewFor(state, 0).energyLeft, 0); + assert.equal(viewFor(state, 1).opponent.queuedCount, 1); + assert.equal(JSON.stringify(viewFor(state, 1)).includes(`"${play.cardId}"`), false); + assert.equal(viewFor(applyAction(state, { type: 'undo', player: 0, cardId: play.cardId }), 0).energyLeft, 1); + state = commit(state, 0); + assert.deepEqual(legalActions(state, 0), []); + state = commit(state, 1); + assert.equal(state.turn, 2); + assert.equal(viewFor(state, 1).lanes[play.lane].cards[1][0].card.cardId, play.cardId); + assert.throws(() => applyAction(state, { type: 'play', player: 0, cardId: play.cardId, lane: 0 }), IllegalActionError); +}); + +test('viewFor never leaks the opponent hand, deck order, queue, seed or RNG state', () => { + let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'mine'), flatDeck(1, 'opp')], 'leak-seed'); + const play = legalActions(state, 1).find(x => x.type === 'play')!; + state = applyAction(state, play); + const view = viewFor(state, 0); + const json = JSON.stringify(view); + for (const key of ['"seed"', '"rng"', '"deck"', '"log"', '"actions"']) assert.equal(json.includes(key), false, key); + for (const c of [...state.players[1].hand, ...state.players[1].deck, ...state.players[0].deck]) + assert.equal(json.includes(`"${c.cardId}"`), false, c.cardId); + assert.deepEqual(view.hand.map(c => c.cardId), state.players[0].hand.map(c => c.cardId)); +}); + +test('energy: energyByTurn + carry (max 1) of unspent energy', () => { + let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 3); + const first = state.players[0].hand[0].cardId; + state = applyAction(state, { type: 'play', player: 0, cardId: first, lane: 0 }); // p0 spends 1, p1 saves 1 + state = commitBoth(state); + assert.deepEqual(state.players.map(p => p.energy), [2, 3]); + state = commitBoth(state); // both save everything; carry is capped at 1 + assert.deepEqual(state.players.map(p => p.energy), [4, 4]); +}); + +test('reveal is interleaved: initiative 1st, other 1st, initiative 2nd, …; initiative alternates', () => { + let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 5); + state = commitBoth(state); // turn 2: 3 energy each (2 + carry 1) + const init = state.initiative; + const ids = (p: PlayerId) => state.players[p].hand.slice(0, 3).map(c => c.cardId); + const [mine, theirs] = [ids(init), ids(init === 0 ? 1 : 0)]; + for (const [player, cards] of [[init, mine], [init === 0 ? 1 : 0, theirs.slice(0, 2)]] as const) + cards.forEach((cardId, lane) => { state = applyAction(state, { type: 'play', player, cardId, lane }); }); + const before = state.log.length; + state = commitBoth(state); + const order = state.log.slice(before).filter(e => e.t === 'reveal').map(e => (e as { cardId: string }).cardId); + assert.deepEqual(order, [mine[0], theirs[0], mine[1], theirs[1], mine[2]]); + assert.equal(state.initiative, init === 0 ? 1 : 0); + assert.deepEqual(state.lanes.flatMap(l => [...l.cards[0], ...l.cards[1]]).map(c => c.seq).sort((x, y) => x - y), [1, 2, 3, 4, 5]); +}); + +test('lane power: base + onTopicBonus[cost] + trend, floored at 0', () => { + let state = createMatch(DEFAULT_RULESET, decks(), 5); + const stat = state.lanes[1].topic.stat; + const off = stat === 'depth' ? 'reach' : 'depth'; + state = placeCard(state, 0, 1, card(5, { cardId: 'on', home: stat, trend: 1 })); + assert.equal(cardPower(state, state.lanes[1].cards[0][0]), 8 + 3 + 1); + state = placeCard(state, 0, 1, card(2, { cardId: 'off', home: off })); + assert.equal(cardPower(state, state.lanes[1].cards[0][1]), 2); + state = placeCard(state, 1, 1, card(1, { cardId: 'neg', home: off, trend: -1, power: 0 })); + assert.equal(cardPower(state, state.lanes[1].cards[1][0]), 0); +}); + +test('consensus tie-break: equal power > 0 goes to more on-topic cards; 0–0 has no leader', () => { + let state = createMatch(DEFAULT_RULESET, decks(), 8); + const stat = state.lanes[0].topic.stat; + const off = stat === 'depth' ? 'reach' : 'depth'; + assert.equal(laneLeader(state, 0), null); + state = placeCard(state, 0, 0, card(2, { cardId: 'a', home: stat, power: 1 })); // 1 + 1 on-topic = 2 + state = placeCard(state, 1, 0, card(2, { cardId: 'b', home: off, power: 2 })); // 2 off-topic + assert.equal(laneLeader(state, 0), 0); + state = placeCard(state, 1, 0, card(1, { cardId: 'c', home: stat, power: 0 })); // +1 on-topic: 3 vs 2 + assert.equal(laneLeader(state, 0), 1); +}); + +test('Portals: capacity override and fizzle at reveal, at-scoring bonus, disabled keywords do not run', () => { + const stub: PortalDef = { id: 'stub', name: 'Stub', text: '', capacity: ctx => ctx.params.value ?? 2 }; + const mainPage: PortalDef = { id: 'main-page', name: 'Main Page', text: '', atScoring: ctx => [0, 1].map(p => ctx.state.lanes[ctx.lane].cards[p].length * (ctx.params.amount ?? 1)) as [number, number] }; + const bump: KeywordDef = { id: 'rising', name: 'Rising', text: '', onReveal: (_ctx, self) => { self.bonus += 5; } }; + withHook(PORTALS, 'stub', stub, () => withHook(PORTALS, 'main-page', mainPage, () => withHook(KEYWORDS, 'rising', bump, () => { + let state = createMatch(DEFAULT_RULESET, [flatDeck(1, 'a'), flatDeck(1, 'b')], 2); + state.lanes[0].topic = { id: 'stub', name: 'Stub', stat: 'depth', portal: 'stub' }; + state.lanes[1].topic = { id: 'main-page', name: 'Main Page', stat: 'attention', portal: 'main-page' }; + state = revealPortal(revealPortal(state, 0), 1); + state = placeCard(placeCard(state, 0, 0, card(1, { cardId: 'p1' })), 0, 0, card(1, { cardId: 'p2' })); + assert.ok(legalActions(state, 0).every(a => a.type !== 'play' || a.lane !== 0), 'Stub holds 2'); + state = placeCard(state, 1, 1, card(2, { cardId: 'r', keyword: 'rising' })); + state.ruleset.keywordsEnabled = []; + const hand = state.players[1].hand[0]; + state = applyAction(state, { type: 'play', player: 1, cardId: hand.cardId, lane: 1 }); + state.players[1].hand[0] = { ...hand, keyword: 'rising' }; // disabled: no +5 + while (!isOver(state)) state = commitBoth(state); + const r = result(state)!; + assert.equal(r.lanePower[1][1], cardPower(state, state.lanes[1].cards[1][0]) + cardPower(state, state.lanes[1].cards[1][1]) + 2); + assert.ok(state.lanes[1].cards[1].every(c => c.bonus === 0)); + }))); +}); + +test('timeouts with nothing queued concede after afkTurns; concede ends the match', () => { + let state = createMatch(DEFAULT_RULESET, decks(), 17); + state = commit(applyAction(state, { type: 'timeout', player: 0 }), 1); + assert.equal(isOver(state), false); + state = applyAction(state, { type: 'timeout', player: 0 }); + assert.deepEqual([result(state)?.winner, result(state)?.reason], [1, 'afk']); + const conceded = applyAction(createMatch(DEFAULT_RULESET, decks(), 1), { type: 'concede', player: 1 }); + assert.equal(result(conceded)?.winner, 0); + assert.deepEqual(legalActions(conceded, 0), []); +}); + +test('two passing players draw after 6 turns', () => { + let state = createMatch(DEFAULT_RULESET, decks(), 21); + while (!isOver(state)) state = commitBoth(state); + const r = result(state)!; + assert.deepEqual([r.winner, r.reason, r.turns], [null, 'draw', 6]); +}); + +test('random legal play terminates, replays exactly, and survives serialisation after every action', () => { + for (let seed = 0; seed < 20; seed++) { + const end = randomPlay(seed); + assert.ok(result(end)!.turns <= DEFAULT_RULESET.turns); + assert.deepEqual(randomPlay(seed), end); + assert.deepEqual(replay(DEFAULT_RULESET, decks(String(seed)), seed, end.actions), end); + } +}); diff --git a/tests/testnet-user-agent.test.ts b/tests/testnet-user-agent.test.ts new file mode 100644 index 0000000..818553a --- /dev/null +++ b/tests/testnet-user-agent.test.ts @@ -0,0 +1,48 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { WikipediaArticleSource } from '../server/wiki.ts'; +import { WikipediaEnrichment } from '../server/enrichment.ts'; +import { ARTICLE_USER_AGENT, ENRICHMENT_USER_AGENT, wikimediaUserAgent } from '../server/wikimedia-user-agent.ts'; + +function capture() { + const agents: string[] = []; + const fetcher: typeof fetch = async (_input, init) => { + agents.push(new Headers(init?.headers).get('User-Agent') ?? ''); + return new Response('rate limited', { status: 429, headers: { 'Content-Type': 'text/plain' } }); + }; + return { agents, fetcher }; +} +async function agentsFor(env: string | undefined) { + const previous = process.env.WIKIDECK_USER_AGENT; + if (env === undefined) delete process.env.WIKIDECK_USER_AGENT; else process.env.WIKIDECK_USER_AGENT = env; + try { + const article = capture(), enrichment = capture(); + await assert.rejects(new WikipediaArticleSource(article.fetcher).random()); + await new WikipediaEnrichment({ fetch: enrichment.fetcher }).getFresh(12345).catch(() => {}); + return { article: article.agents, enrichment: enrichment.agents }; + } finally { + if (previous === undefined) delete process.env.WIKIDECK_USER_AGENT; else process.env.WIKIDECK_USER_AGENT = previous; + } +} + +test('default Wikimedia user agents are unchanged when WIKIDECK_USER_AGENT is unset', async () => { + assert.equal(ARTICLE_USER_AGENT, 'Wikideck/0.1 (experimental Wikipedia article cards)'); + assert.equal(ENRICHMENT_USER_AGENT, 'Wikideck/0.1 (Wikipedia off-chain page enrichment)'); + const { article, enrichment } = await agentsFor(undefined); + assert.ok(article.length > 0 && article.every(a => a === ARTICLE_USER_AGENT)); + assert.ok(enrichment.length > 0 && enrichment.every(a => a === ENRICHMENT_USER_AGENT)); +}); + +test('WIKIDECK_USER_AGENT overrides both Wikimedia clients', async () => { + const ua = 'WikiDeck-testnet/0.1 (https://gitea.eom.dev/claude/wikideck; private testnet)'; + const { article, enrichment } = await agentsFor(ua); + assert.ok(article.length > 0 && article.every(a => a === ua)); + assert.ok(enrichment.length > 0 && enrichment.every(a => a === ua)); +}); + +test('blank, oversized or control-character overrides fall back to the default', () => { + for (const bad of ['', ' ', 'x'.repeat(257), 'bad\r\nX-Injected: 1', 'tab\there']) + assert.equal(wikimediaUserAgent('fallback', { WIKIDECK_USER_AGENT: bad }), 'fallback'); + assert.equal(wikimediaUserAgent('fallback', {}), 'fallback'); + assert.equal(wikimediaUserAgent('fallback', { WIKIDECK_USER_AGENT: ' Custom/1.0 (x) ' }), 'Custom/1.0 (x)'); +});