Merge remote-tracking branch 'origin/night/2026-11-16' into night/mobile-android/polish

This commit is contained in:
2026-11-17 00:30:18 -05:00
19 changed files with 359 additions and 30 deletions
+4
View File
@@ -13,6 +13,10 @@ A 3-node **testnet-only** fixture on poweredge-r350. It is reachable on the LAN
- It mines to 4 disposable wallets (alice, bob, carol, dave) and writes chain-bound encrypted browser backups to `$STATE_DIR/wallets/`.
- It never changes consensus code. Speed comes from the protocol's own testnet parameters: the initial target accepts 1/16 of hashes, and each 10-block retarget at most quadruples the difficulty.
- Each template costs several Wikipedia API calls, and Wikipedia rate-limits our egress IP. The miner therefore paces templates (`MIN_GAP`, default 45 s) and backs off exponentially on failure.
- `compose.lan.yaml` also sets, per node:
- `WIKIDECK_USER_AGENT`, a Wikimedia-policy UA with a project URL (#19). Without it, Wikipedia returned 429 to our egress and templates failed.
- the game-mode env from #22: A = classic and trending, B = draft, C = all three.
- `autodeploy.sh` follows the integration branch. Run it from a dedicated detached worktree: `git worktree add --detach ../deploy-src origin/night/2026-11-16 && cd ../deploy-src && deploy/night/autodeploy.sh`. It polls the Gitea API every 3 min and redeploys whenever the head moves.
- `testnet.sh` has `up`, `mine N [workers]`, `status` and `down`. Run it from the repo root on a checkout of the integration branch. `up` rebuilds the image from that checkout; the ledgers persist in the named volumes.
Never point this at mainnet or the live `wikideck` namespace.
+40
View File
@@ -0,0 +1,40 @@
#!/bin/sh
# sim-testnet: keep the wikideck-night testnet on the integration branch head.
# Run from the root of a *dedicated* checkout (e.g. a detached git worktree): it checks out
# each new head of $BRANCH and runs `deploy/night/testnet.sh rolling` (ledgers persist in the volumes):
# nodes restart one at a time, and deploys wait (up to FORCE_AFTER) while matches or lobbies are live,
# because lobbies are in memory and a restart ends games in progress.
# Head detection uses the public Gitea API, which also works where SSH auth isn't available.
set -u
BRANCH=${BRANCH:-night/2026-11-16}
API=${API:-https://gitea.eom.dev/api/v1/repos/claude/wikideck}
INTERVAL=${INTERVAL:-180}
LOG=${LOG:-/tmp/wikideck-night-autodeploy.log}
FORCE_AFTER=${FORCE_AFTER:-900} # defer while matches/lobbies are live, but at most this many seconds
deferred_since=
enc=$(printf %s "$BRANCH" | sed 's#/#%2F#g')
while :; do
new=$(node -e "fetch('$API/branches/$enc',{signal:AbortSignal.timeout(15000)}).then(r=>r.json()).then(b=>console.log(b.commit.id)).catch(()=>{})")
cur=$(git rev-parse HEAD)
if [ -z "$new" ]; then echo "WARN branch API failed"
elif [ "$new" != "$cur" ]; then
if ! git fetch -q origin "+refs/heads/$BRANCH:refs/remotes/origin/$BRANCH" 2>"$LOG"; then
echo "WARN fetch failed: $(tail -1 "$LOG")"
else
busy=$(deploy/night/testnet.sh busy 2>/dev/null || echo 0)
now=$(date +%s)
if [ "${busy:-0}" -gt 0 ] && { [ -z "$deferred_since" ] || [ $((now - deferred_since)) -lt "$FORCE_AFTER" ]; }; then
[ -z "$deferred_since" ] && { deferred_since=$now; echo "DEFER ${new%"${new#???????}"}: $busy live matches/lobbies"; }
sleep 60; continue
fi
[ -n "$deferred_since" ] && [ "${busy:-0}" -gt 0 ] && echo "FORCE deploy after ${FORCE_AFTER}s ($busy still live)"
deferred_since=
git checkout -q --detach "$new"
echo "DEPLOY start $(git log --oneline -1 | cut -c1-90)"
if deploy/night/testnet.sh rolling >"$LOG" 2>&1; then
sleep 20; echo "DEPLOY ok $(git rev-parse --short HEAD): $(deploy/night/testnet.sh status 2>&1 | tr '\n' ' ')"
else echo "DEPLOY FAILED $(git rev-parse --short HEAD): $(tail -3 "$LOG" | tr '\n' ' ')"; fi
fi
fi
sleep "$INTERVAL"
done
+18 -1
View File
@@ -2,6 +2,8 @@
# sim-testnet: private 3-node testnet fixture for WikiDeck Night 1 (poweredge-r350, LAN only).
# Usage (from the repo root):
# deploy/night/testnet.sh up build the image from this checkout and (re)start the 3 nodes
# deploy/night/testnet.sh rolling build, then restart node-a, b, c one at a time (waits for /healthz)
# deploy/night/testnet.sh busy print live matches + open lobbies across the 3 nodes
# deploy/night/testnet.sh mine N [W] mine N real RandomX blocks with W workers (default 4, max 8)
# deploy/night/testnet.sh status tip/height of each node
# deploy/night/testnet.sh down stop the nodes (volumes, i.e. the ledgers, are kept)
@@ -15,6 +17,21 @@ DC="docker compose -p $P -f compose.testnet.yaml -f deploy/night/compose.lan.yam
case "${1:-}" in
up) $DC build node-a && $DC up -d --no-build ;;
down) $DC down ;;
rolling)
# Never take the whole testnet dark: one node at a time, each must pass /healthz before the next.
$DC build node-a
for n in a b c; do
port=$(( 3100 + $(printf %d "'$n") - 96 ))
$DC up -d --no-build --no-deps node-$n
i=0
until node -e "fetch('http://$LAN_IP:$port/healthz',{signal:AbortSignal.timeout(3000)}).then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"; do
i=$((i+1)); [ $i -ge 60 ] && { echo "node-$n not healthy after 120 s"; exit 1; }; sleep 2
done
echo "node-$n healthy"
done ;;
busy)
# Sum of liveMatches + openLobbies over all hosted modes on all nodes (unreachable node counts 0).
node -e "Promise.all([3101,3102,3103].map(p=>fetch('http://$LAN_IP:'+p+'/api/game/modes',{signal:AbortSignal.timeout(5000)}).then(r=>r.json()).then(m=>m.modes.reduce((t,x)=>t+(x.stats?.liveMatches??0)+(x.stats?.openLobbies??0),0)).catch(()=>0))).then(v=>console.log(v.reduce((a,b)=>a+b,0)))" ;;
mine)
mkdir -p "$STATE_DIR"
W=${3:-4}
@@ -28,5 +45,5 @@ case "${1:-}" in
for port in 3101 3102 3103; do
docker run --rm --network host wikideck:testnet node -e "fetch('http://$LAN_IP:$port/p2p/status').then(r=>r.json()).then(s=>console.log($port,'blocks',s.size,'tip',s.tip.slice(0,16))).catch(e=>console.log($port,'DOWN',e.message))"
done ;;
*) sed -n 2,9p "$0"; exit 1 ;;
*) sed -n 2,11p "$0"; exit 1 ;;
esac
+6 -1
View File
@@ -48,7 +48,8 @@ const r = result(state); // { winner: 0 | 1 | null, reason, topicsLed, lanePow
| `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. |
| `STARTER_DECKS`, `starterDeckById(id, rules?)` | The 4 DESIGN §2.1 starter decks (`stargazers`, `field-guide`, `headliners`, `pioneers`), derived through `deriveCard` with the given rules (a `Ruleset` works). **Use these for new players.** |
| `starterDeck(seed)`, `previewPool()` | Older placeholder loaners (seeded 12-card deck / every placeholder once). Kept for tests and draft prototypes; `previewPool()` moves to `starter-cards.json` in a follow-up. |
| `starterDeck(seed)` | Older placeholder loaner deck (seeded, 2 per cost from `STARTER_POOL`). Kept for tests and tools; not a §2.1 starter deck. |
| `previewPool(rules?)` | The 20 frozen `docs/game/starter-cards.json` loaners (council-data), derived via §1 against the `card-sample-2026-11-16` percentile table. For loaner slots and draft modes. |
| `deriveCard(input, table, rules?)`, `deriveDeck(inputs, table, rules?)` | DESIGN §1 + §10.1: `CardInput` → `GameCard`. **Hosts only**: run on host-frozen, plausibility-checked inputs, never on client JSON. A `Ruleset` can be passed as `rules`. |
| `placeCard(state, seat, lane, card)`, `revealPortal(state, lane)` | Test helpers for building boards by hand. |
@@ -110,6 +111,10 @@ interface GameCard {
- **Never build `GameCard`s from client JSON.** `validateDeck` only checks shapes and ranges; a client could send cost 1 / power 30. Constructed modes must re-derive on the host.
- Both seats can hold the same loaner `cardId`. The engine keys per seat, so UIs should key cards by `owner + cardId`.
- Modes may adjust `GameCard` fields such as `power` before `createMatch`. The engine does not re-derive them.
- **`check` and `pinned` are host decisions, not player input.** Build loaner inputs only from shipped data (`STARTER_DECKS`,
`previewPool()`, `LOANER_SNAPSHOTS`), and set `check` for owned cards from the host's own §1.10 check. Otherwise a client could
send `check: 'loaner', pinned: {cost: 1, …}` for any card.
- **`obscure` leaks in v1.** `viewFor` does not mask Obscure cards yet. Modes must not put `obscure` in `keywordsEnabled` until it does.
- 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.
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env node
// Generates shared/game/card-data.ts from council-data's frozen files (docs/game/*.json).
// The engine does no I/O, so the data is embedded as constants. Rerun after the JSON changes:
// node scripts/game-card-data.mjs
import { readFileSync, writeFileSync } from 'node:fs';
const root = new URL('../', import.meta.url);
const sample = JSON.parse(readFileSync(new URL('docs/game/card-sample.json', root), 'utf8'));
const starter = JSON.parse(readFileSync(new URL('docs/game/starter-cards.json', root), 'utf8'));
// DESIGN §1.1: 99 ascending cut points per stat. Cut k (1..99) is the value at rank floor(k·n/100)
// of the sample's sorted scores; null attention is excluded from its table.
function cuts(values) {
const sorted = values.filter(v => typeof v === 'number').sort((a, b) => a - b);
if (sorted.length < 2) throw new Error('sample too small');
return Array.from({ length: 99 }, (_, i) => sorted[Math.min(sorted.length - 1, Math.floor((i + 1) * sorted.length / 100))]);
}
// Prefer council-data's published table (card-sample.json `percentiles`); fall back to computing it.
const official = sample.percentiles && ['attention', 'depth', 'reach'].every(stat => sample.percentiles[stat]?.length === 99);
const table = official ? { attention: sample.percentiles.attention, depth: sample.percentiles.depth, reach: sample.percentiles.reach }
: Object.fromEntries(['attention', 'depth', 'reach'].map(stat => [stat, cuts(sample.cards.map(c => c.stats?.[stat]))]));
const method = official ? sample.percentilesMethod : 'computed here: value at rank floor(k*n/100)';
const daysIn = month => { const [y, m] = month.split('-').map(Number); return new Date(Date.UTC(y, m, 0)).getUTCDate(); };
const pool = starter.cards.map(c => ({
pageId: c.pageId, title: c.title, category: c.category,
stats: { attention: c.stats.attention ?? null, depth: c.stats.depth, reach: c.stats.reach },
trendPercent: c.trendPercent ?? null,
dailyAverage: typeof c.monthlyViews === 'number' && c.latestMonth ? Math.round(c.monthlyViews / daysIn(c.latestMonth) * 100) / 100 : null,
}));
const out = `// GENERATED by scripts/game-card-data.mjs from docs/game/card-sample.json (${sample.cards.length} cards,
// generated ${sample.generatedAt}) and docs/game/starter-cards.json (frozen ${starter.frozenAt}). Do not edit by hand.
// Percentiles: ${method}
import type { PercentileTable } from './derive.ts';
import type { Faction } from './types.ts';
/** DESIGN §1.1 reference table "card-sample-2026-11-16": 99 cut points per stat. */
export const CARD_SAMPLE_PERCENTILES: PercentileTable = ${JSON.stringify(table)};
export interface LoanerSnapshot {
pageId: number; title: string; category: Faction;
stats: { attention: number | null; depth: number; reach: number };
trendPercent: number | null; dailyAverage: number | null;
}
/** Frozen loaner pool (§2): real snapshots of random articles, for filling deck slots and draft modes. */
export const LOANER_SNAPSHOTS: readonly LoanerSnapshot[] = ${JSON.stringify(pool, null, 1).replace(/\n\s*/g, ' ')};
`;
writeFileSync(new URL('shared/game/card-data.ts', root), out);
console.log(`card-data.ts: ${pool.length} loaners, percentile tables from ${sample.cards.length} sample cards`);
+6 -2
View File
@@ -49,10 +49,14 @@ Signed link message (off-chain, domain-tagged):
- 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:
- Wire the system browser and the redirect (for example in `src/native.ts`):
```ts
App.addListener('appUrlOpen', ({ url }) => { if (isCallback(url)) void completeLogin(url); });
import { Browser } from '@capacitor/browser';
import { completeLogin, isCallback, setNativeBrowser } from './auth/session.ts';
setNativeBrowser(Browser);
onDeepLink(u => { if (isCallback(u.href)) void completeLogin(u.href); });
```
Without `setNativeBrowser`, native login refuses to open (it never falls back to the WebView).
## Known limits
- **Logout is local.** Dex publishes no `end_session_endpoint`, so its SSO cookie remains.
+17
View File
@@ -0,0 +1,17 @@
// GENERATED by scripts/game-card-data.mjs from docs/game/card-sample.json (236 cards,
// generated 2026-11-17T04:19:07.777994+00:00) and docs/game/starter-cards.json (frozen 2026-11-17). Do not edit by hand.
// Percentiles: cut point i (1..99) = nearest-rank i-th percentile of the sample snapshot score (sorted ascending, index ceil(i*n/100)-1). Use with DESIGN.md §1.1 counting.
import type { PercentileTable } from './derive.ts';
import type { Faction } from './types.ts';
/** DESIGN §1.1 reference table "card-sample-2026-11-16": 99 cut points per stat. */
export const CARD_SAMPLE_PERCENTILES: PercentileTable = {"attention":[14,14,16,17,18,19,19,19,20,20,21,21,21,22,22,22,23,23,23,24,24,24,24,25,25,25,26,26,26,27,27,27,27,28,28,28,28,29,29,30,30,30,30,30,30,31,31,31,31,32,32,33,33,34,34,34,35,35,35,35,35,36,36,37,37,38,38,38,39,39,40,40,40,41,41,42,42,43,44,44,45,46,47,48,49,49,50,51,53,53,55,56,57,59,61,62,62,64,68],"depth":[50,51,51,53,53,54,54,54,54,54,55,55,55,56,56,57,57,57,57,57,58,58,58,58,58,58,59,59,59,59,59,60,60,60,60,61,61,61,61,61,61,62,62,62,62,62,63,63,63,63,63,64,64,64,64,64,64,65,65,65,65,65,66,66,66,66,67,67,67,67,67,68,68,68,68,69,69,69,69,69,70,70,71,71,71,72,72,72,73,73,74,75,75,76,78,78,79,80,83],"reach":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10,10,10,10,10,10,10,10,10,10,10,10,10,16,16,16,16,16,16,16,16,16,16,16,16,16,20,20,20,20,20,20,20,20,23,23,23,23,23,26,26,26,26,26,28,28,28,28,30,30,30,30,30,32,32,32,33,33,33,35,36,36,36,37,38,39,40,41,43,43,44,45,45,47,49,50,50,51,52,55,55,59]};
export interface LoanerSnapshot {
pageId: number; title: string; category: Faction;
stats: { attention: number | null; depth: number; reach: number };
trendPercent: number | null; dailyAverage: number | null;
}
/** Frozen loaner pool (§2): real snapshots of random articles, for filling deck slots and draft modes. */
export const LOANER_SNAPSHOTS: readonly LoanerSnapshot[] = [ { "pageId": 4961906, "title": "Chinese star maps", "category": "Space", "stats": { "attention": 44, "depth": 74, "reach": 16 }, "trendPercent": -13.6, "dailyAverage": 14.1 }, { "pageId": 78154568, "title": "Lithodes mamillifer", "category": "Nature", "stats": { "attention": 20, "depth": 53, "reach": 10 }, "trendPercent": -34.8, "dailyAverage": 0.48 }, { "pageId": 23256692, "title": "Coelogyne trinervis", "category": "Nature", "stats": { "attention": 23, "depth": 53, "reach": 30 }, "trendPercent": -42.9, "dailyAverage": 0.77 }, { "pageId": 53418112, "title": "2012 United States presidential straw poll in Guam", "category": "Nature", "stats": { "attention": 37, "depth": 65, "reach": 0 }, "trendPercent": 15.3, "dailyAverage": 5.58 }, { "pageId": 273706, "title": "Pallas's cat", "category": "Nature", "stats": { "attention": 77, "depth": 80, "reach": 65 }, "trendPercent": -0.7, "dailyAverage": 1355.65 }, { "pageId": 20139020, "title": "Samuel Yeatman", "category": "People", "stats": { "attention": 14, "depth": 56, "reach": 10 }, "trendPercent": -25, "dailyAverage": 0.19 }, { "pageId": 51796741, "title": "Alex Piquero", "category": "People", "stats": { "attention": 36, "depth": 65, "reach": 0 }, "trendPercent": -51, "dailyAverage": 4.87 }, { "pageId": 3560741, "title": "Martin Taylor (businessman)", "category": "People", "stats": { "attention": 41, "depth": 63, "reach": 20 }, "trendPercent": 1.1, "dailyAverage": 8.68 }, { "pageId": 2806760, "title": "Jess Harnell", "category": "People", "stats": { "attention": 69, "depth": 79, "reach": 45 }, "trendPercent": -2.8, "dailyAverage": 463.68 }, { "pageId": 13799810, "title": "Levophacetoperane", "category": "Science", "stats": { "attention": 37, "depth": 61, "reach": 16 }, "trendPercent": -1.8, "dailyAverage": 5.32 }, { "pageId": 36740675, "title": "The Best of Men", "category": "Science", "stats": { "attention": 45, "depth": 63, "reach": 23 }, "trendPercent": -3.4, "dailyAverage": 15.35 }, { "pageId": 4426773, "title": "Agda (programming language)", "category": "Science", "stats": { "attention": 56, "depth": 69, "reach": 36 }, "trendPercent": 7.8, "dailyAverage": 78.68 }, { "pageId": 48469081, "title": "Dr. John L. Butler House", "category": "History", "stats": { "attention": 17, "depth": 56, "reach": 0 }, "trendPercent": -23.1, "dailyAverage": 0.32 }, { "pageId": 33454946, "title": "Tydeus Painter", "category": "History", "stats": { "attention": 22, "depth": 54, "reach": 20 }, "trendPercent": -13.6, "dailyAverage": 0.61 }, { "pageId": 74291637, "title": "Pullman porter affair", "category": "History", "stats": { "attention": 39, "depth": 68, "reach": 0 }, "trendPercent": -10.4, "dailyAverage": 6.94 }, { "pageId": 15105978, "title": "Well", "category": "History", "stats": { "attention": 64, "depth": 78, "reach": 70 }, "trendPercent": -6.4, "dailyAverage": 233.77 }, { "pageId": 50869430, "title": "Felt, Not Heard", "category": "Culture", "stats": { "attention": 21, "depth": 57, "reach": 0 }, "trendPercent": -45.5, "dailyAverage": 0.58 }, { "pageId": 14761136, "title": "RBMX", "category": "Culture", "stats": { "attention": 26, "depth": 66, "reach": 10 }, "trendPercent": 21.4, "dailyAverage": 1.1 }, { "pageId": 31946653, "title": "Cody Floatplane", "category": "Culture", "stats": { "attention": 33, "depth": 65, "reach": 20 }, "trendPercent": -11, "dailyAverage": 2.87 }, { "pageId": 247636, "title": "Canadian Grand Prix", "category": "Culture", "stats": { "attention": 62, "depth": 79, "reach": 55 }, "trendPercent": 4.3, "dailyAverage": 172.23 } ];
+11 -4
View File
@@ -35,6 +35,8 @@ export interface DerivationRules {
powerByCost: readonly number[];
vanillaBonus: number;
keywordsEnabled: readonly string[];
/** v1.1 hook: 'home' gives Culture cards a home-stat keyword instead of viral (§10.1). Default 'faction' (v1). */
cultureKeyword?: 'faction' | 'home';
keywordParams: Record<string, Record<string, number>>;
trendUp: number;
trendDown: number;
@@ -106,11 +108,15 @@ export function trendFor(live: CardInput['live'], rules: Pick<DerivationRules, '
* §10.1: cost 1 → vanilla (+vanillaBonus); edition if enabled and the deck has another
* copy; else the faction keyword if enabled; else vanilla without the bonus.
*/
export function keywordFor(faction: Faction, cost: number, hasCopyInDeck: boolean, rules: Pick<DerivationRules, 'keywordsEnabled'>):
/** v1.1 option (critic, #3): Culture keyword by home stat when `cultureKeyword: 'home'`. */
export const CULTURE_HOME_KEYWORD: Record<Stat, string> = { attention: 'viral', depth: 'encyclopedic', reach: 'translated' };
export function keywordFor(faction: Faction, cost: number, hasCopyInDeck: boolean,
rules: Pick<DerivationRules, 'keywordsEnabled' | 'cultureKeyword'>, home: Stat = 'attention'):
{ keyword: string | null; vanilla: boolean } {
if (cost === 1) return { keyword: null, vanilla: true };
if (hasCopyInDeck && rules.keywordsEnabled.includes('edition')) return { keyword: 'edition', vanilla: false };
const keyword = FACTION_KEYWORD[faction];
const keyword = faction === 'Culture' && rules.cultureKeyword === 'home' ? CULTURE_HOME_KEYWORD[home] : FACTION_KEYWORD[faction];
return rules.keywordsEnabled.includes(keyword) ? { keyword, vanilla: false } : { keyword: null, vanilla: false };
}
@@ -123,12 +129,13 @@ export function deriveCard(input: CardInput, table: PercentileTable, rules: Deri
const faction = pinned ? pinned.faction : input.category;
const base = rules.powerByCost[cost];
if (base === undefined) throw new RangeError(`powerByCost has no entry for cost ${cost}`);
const { keyword, vanilla } = keywordFor(faction, cost, hasCopyInDeck, rules);
const home = pinned ? pinned.home : homeStat(pct);
const { keyword, vanilla } = keywordFor(faction, cost, hasCopyInDeck, rules, home);
const delta = keyword ? Math.max(-3, Math.min(0, rules.keywordParams[keyword]?.powerDelta ?? 0)) : 0;
return {
cardId: input.cardId, pageId: input.pageId, title: input.title, faction, rarity: pinned ? 'Common' : input.rarity,
cost, power: Math.max(0, base + (vanilla ? rules.vanillaBonus : 0) + delta),
home: pinned ? pinned.home : homeStat(pct), trend: pinned ? 0 : trendFor(input.live, rules), keyword,
home, trend: pinned ? 0 : trendFor(input.live, rules), keyword,
source: input.check === 'loaner' ? 'loaner' : 'owned', check: input.check,
};
}
+2 -1
View File
@@ -1,7 +1,7 @@
/** 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 { DEFAULT_RULESET, RULESET_V1_0, 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,
@@ -17,3 +17,4 @@ export {
export {
STARTER_POOL, STARTER_DECKS, loanerCard, loanerInput, previewPool, starterDeck, starterDeckById, type StarterDeckDef,
} from './starter.ts';
export { CARD_SAMPLE_PERCENTILES, LOANER_SNAPSHOTS, type LoanerSnapshot } from './card-data.ts';
+4 -2
View File
@@ -115,7 +115,7 @@ export const KEYWORDS: Record<string, KeywordDef> = {
let earlier = 0;
for (const lane of ctx.state.lanes) for (const card of lane.cards[self.owner])
if (card !== self && card.turn === ctx.state.turn) earlier++;
const gain = Math.min(earlier * amount(ctx, 1), ctx.params.cap ?? 2);
const gain = Math.min((ctx.params.base ?? 0) + earlier * amount(ctx, 1), ctx.params.cap ?? 2); // base: v1.1 hook, 0 in v1
if (gain > 0) { self.bonus += gain; ctx.log(`${self.card.title}: Viral +${gain}`); }
},
},
@@ -139,7 +139,9 @@ export const KEYWORDS: Record<string, KeywordDef> = {
id: 'encyclopedic', name: 'Encyclopedic', text: '+{amount} power if there are no other cards here.',
onReveal(ctx, self) {
const [mine, theirs] = ctx.state.lanes[self.lane].cards;
if (mine.every(card => card === self) && theirs.length === 0) {
// sides: v1.1 hook. 2 (v1) = both sides must be empty; 1 = only your side.
const sides = ctx.params.sides ?? 2;
if (mine.every(card => card === self) && (sides === 1 || theirs.length === 0)) {
self.bonus += amount(ctx, 2);
ctx.log(`${self.card.title}: Encyclopedic +${amount(ctx, 2)}`);
}
+7 -3
View File
@@ -46,6 +46,7 @@ export const RulesetSchema = z.object({
vanillaBonus: int(0, 10),
keywordsEnabled: z.array(z.enum(KEYWORD_IDS)).max(KEYWORD_IDS.length),
ownedCards: z.boolean(),
cultureKeyword: z.enum(['faction', 'home']).default('faction'), // default keeps pre-v1.1 stored rulesets parseable
trendUp: z.number().finite().min(-1000).max(1000),
trendDown: z.number().finite().min(-1000).max(1000),
trendMinDaily: z.number().finite().min(0).max(1e9),
@@ -96,8 +97,8 @@ export const DEFAULT_TOPIC_POOL: Ruleset['topicPool'] = [
{ id: 'disambiguation', name: 'Disambiguation', stat: 'reach', portal: 'disambiguation' },
];
/** DESIGN §9 defaults (v1). */
export const DEFAULT_RULESET: Ruleset = {
/** DESIGN §9 v1.0 rules, frozen: the §12 golden match is pinned to these. */
export const RULESET_V1_0: Ruleset = {
version: '1.0',
deckSize: 12, maxCopiesPerPage: 2, maxLoaners: 12,
openingHand: 3, handLimit: 7, mulligan: false,
@@ -118,10 +119,13 @@ export const DEFAULT_RULESET: Ruleset = {
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,
keywordsEnabled: ['viral', 'rising', 'local', 'encyclopedic', 'nostalgic', 'translated'], ownedCards: true, cultureKeyword: 'faction',
trendUp: 25, trendDown: -200, trendMinDaily: 20, uncheckedCostCap: 4,
factionSynergyCap: 3,
verifyStats: true,
percentiles: 'card-sample-2026-11-16',
starterDecks: 'default',
};
/** DESIGN §9 defaults: the current rules version. */
export const DEFAULT_RULESET: Ruleset = RULESET_V1_0;
+64 -5
View File
@@ -4,6 +4,7 @@
* 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 { CARD_SAMPLE_PERCENTILES, LOANER_SNAPSHOTS } from './card-data.ts';
import { DEFAULT_DERIVATION, deriveCard, type CardInput, type DerivationRules } from './derive.ts';
import { Rng } from './rng.ts';
import type { Faction, GameCard, Stat } from './types.ts';
@@ -53,8 +54,17 @@ export function loanerCard(spec: Spec, copy = 0): GameCard {
};
}
/** 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)); }
/**
* The frozen loaner pool (DESIGN §2): council-data's docs/game/starter-cards.json snapshots, derived by §1
* against the card-sample percentile table. For filling loaner slots and draft modes; not the starter decks.
* Ids are `loaner:<pageId>`. `rules` lets a mode's curve apply to loaners exactly as to owned cards.
*/
export function previewPool(rules: DerivationRules = DEFAULT_DERIVATION): GameCard[] {
return LOANER_SNAPSHOTS.map(l => deriveCard({
cardId: `loaner:${l.pageId}`, pageId: l.pageId, title: l.title, category: l.category, rarity: 'Common',
snapshot: { stats: l.stats }, live: { trendPercent: l.trendPercent, dailyAverage: l.dailyAverage }, check: 'loaner',
}, CARD_SAMPLE_PERCENTILES, rules));
}
/** A deterministic 12-card loaner deck: 2 cards of each cost 1–6, chosen by `seed`. */
export function starterDeck(seed: number | string): GameCard[] {
@@ -70,8 +80,57 @@ export function starterDeck(seed: number | string): GameCard[] {
type Pin = [cost: number, title: string, faction: Faction, home: Stat];
/** Real pageIds for the shared/catalog.ts cards; the others have none yet (§2.1), see loanerPageId. */
const CATALOG_PAGE_IDS: Record<string, number> = { Moon: 19331, 'Periodic table': 23053, Octopus: 22780, 'Albert Einstein': 736 };
/** Real pageIds for every §2.1 starter card (council-data, docs/game/starter-cards.json `starterDeckPageIds`, #28). */
const CATALOG_PAGE_IDS: Record<string, number> = {
"Moon": 19331,
"Electron": 9476,
"Mars": 14640471,
"Periodic table": 23053,
"Saturn": 44474,
"Photosynthesis": 24544,
"Black hole": 4650,
"Quantum mechanics": 25202,
"Milky Way": 2589714,
"DNA": 7955,
"Sun": 26751,
"Theory of relativity": 30001,
"Octopus": 22780,
"Stonehenge": 27633,
"Axolotl": 235589,
"Rosetta Stone": 26428,
"Coral reef": 87410,
"Roman Empire": 25507,
"Honey bee": 58261,
"Ancient Egypt": 874,
"Amazon rainforest": 48139,
"Blue whale": 4925,
"Great Wall of China": 5094570,
"World War II": 32927,
"Haiku": 13217,
"Ada Lovelace": 974,
"Jazz": 15613,
"Marie Curie": 20408,
"Mona Lisa": 70889,
"Frida Kahlo": 162276,
"Chess": 5134,
"Leonardo da Vinci": 18079,
"The Beatles": 29812,
"William Shakespeare": 32897,
"Olympic Games": 22576,
"Wolfgang Amadeus Mozart": 33163,
"Sputnik 1": 28484,
"Nikola Tesla": 21473,
"Hubble Space Telescope": 40203,
"Isaac Newton": 14627,
"Neil Armstrong": 21247,
"Jupiter": 38930,
"Galileo Galilei": 29688374,
"Albert Einstein": 736,
"International Space Station": 15043,
"Apollo 11": 662,
"Charles Darwin": 8145410,
"Solar System": 26903,
};
export interface StarterDeckDef { id: string; name: string; cards: readonly Pin[] }
@@ -105,7 +164,7 @@ export const STARTER_DECKS: readonly StarterDeckDef[] = [
const kebab = (title: string) => title.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
/** §2.1: the real pageId for the shared/catalog.ts cards, null for the rest (copies then count per cardId). */
/** §2.1: the card's real pageId; null only if council-data has none (copies then count per cardId). */
export function loanerPageId(title: string): number | null {
return Object.hasOwn(CATALOG_PAGE_IDS, title) ? CATALOG_PAGE_IDS[title] : null;
}
+2
View File
@@ -91,6 +91,8 @@ export interface Ruleset {
/** Keyword ids whose hooks run. Cards with a disabled keyword are vanilla (derivation handles power). */
keywordsEnabled: string[];
ownedCards: boolean;
/** v1.1 hook (derive.ts): 'home' gives Culture cards a home-stat keyword. v1: 'faction'. */
cultureKeyword: 'faction' | 'home';
trendUp: number;
trendDown: number;
trendMinDaily: number;
+18 -5
View File
@@ -44,8 +44,19 @@ export async function pkceChallenge(verifier: string): Promise<string> {
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<void>; close?(): Promise<void> } } };
type NativeBrowser = { open(o: { url: string }): Promise<void>; close?(): Promise<void> };
type CapacitorGlobal = { isNativePlatform?: () => boolean; Plugins?: { Browser?: NativeBrowser } };
const capacitor = () => (globalThis as { Capacitor?: CapacitorGlobal }).Capacitor;
let nativeBrowser: NativeBrowser | undefined;
/**
* Native apps: pass the imported `@capacitor/browser` plugin so login opens in the system
* browser (Custom Tab / SFSafariViewController), never inside the WebView. Example (src/native.ts):
* import { Browser } from '@capacitor/browser';
* setNativeBrowser(Browser);
* onDeepLink(u => { if (isCallback(u.href)) void completeLogin(u.href); });
*/
export function setNativeBrowser(browser: NativeBrowser): void { nativeBrowser = browser; }
const browserPlugin = () => nativeBrowser ?? capacitor()?.Plugins?.Browser;
export const isNative = () => Boolean(capacitor()?.isNativePlatform?.());
export function redirectUri(): string { return isNative() ? NATIVE_REDIRECT : `${location.origin}${CALLBACK_PATH}`; }
@@ -77,9 +88,11 @@ export async function login(returnTo = location.pathname + location.search): Pro
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());
const browser = browserPlugin();
if (isNative()) {
if (!browser) throw new Error('System browser unavailable: the app must call setNativeBrowser(Browser).');
await browser.open({ url: url.toString() });
} else location.assign(url.toString());
}
export const isCallback = (url: string) => {
@@ -101,7 +114,7 @@ export async function completeLogin(url: string): Promise<{ returnTo: string }>
const s = await api<Session>('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(() => {});
if (isNative()) void browserPlugin()?.close?.().catch(() => {});
return { returnTo: pending.returnTo };
}
+33
View File
@@ -0,0 +1,33 @@
import test from 'node:test';
import assert from 'node:assert/strict';
// Capacitor: login must open the system browser with the custom-scheme redirect, never the WebView.
test('account native: login opens the system browser with PKCE and the app redirect', async () => {
const g = globalThis as Record<string, unknown>;
const saved = { Capacitor: g.Capacitor, sessionStorage: g.sessionStorage, fetch: g.fetch, location: g.location };
const store = new Map<string, string>();
g.sessionStorage = { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => { store.set(k, v); },
removeItem: (k: string) => { store.delete(k); } };
g.Capacitor = { isNativePlatform: () => true, Plugins: {} };
let assigned = '';
g.location = { origin: 'https://localhost', pathname: '/', search: '', assign: (u: string) => { assigned = u; } };
g.fetch = (async () => new Response(JSON.stringify({ issuer: 'https://dex.eom.dev/', clientId: 'wikideck',
scopes: 'openid profile email groups', authorizationEndpoint: 'https://dex.eom.dev/auth',
redirectUris: ['dev.eom.wikideck:/oauth/callback'] }), { headers: { 'content-type': 'application/json' } })) as typeof fetch;
try {
const auth = await import('../src/auth/session.ts');
await assert.rejects(auth.login(), /setNativeBrowser/);
assert.equal(assigned, '', 'never navigates the WebView to Dex');
const opened: string[] = [];
auth.setNativeBrowser({ open: async ({ url }) => { opened.push(url); } });
await auth.login();
const url = new URL(opened[0]);
assert.equal(url.origin + url.pathname, 'https://dex.eom.dev/auth');
assert.equal(url.searchParams.get('redirect_uri'), 'dev.eom.wikideck:/oauth/callback');
assert.equal(url.searchParams.get('code_challenge_method'), 'S256');
assert.equal(url.searchParams.get('client_id'), 'wikideck');
const pending = JSON.parse(store.get('wikideck.auth.pending')!);
assert.equal(url.searchParams.get('state'), pending.state);
assert.equal(auth.isCallback(`dev.eom.wikideck:/oauth/callback?code=c&state=${pending.state}`), true);
} finally { Object.assign(g, saved); }
});
+26
View File
@@ -144,3 +144,29 @@ test('pinned values replace §1.1–1.5 for loaners only (§2.1)', () => {
const cheap = deriveCard(input(stats, { check: 'loaner', pinned: { ...pinned, cost: 1 } }), TABLE);
assert.deepEqual([cheap.power, cheap.keyword], [2, null], 'vanillaBonus still applies to pinned cost-1');
});
test('cultureKeyword (v1.1 hook): home gives Culture cards {attention: viral, depth: encyclopedic, reach: translated}', () => {
const home = { ...RULES, cultureKeyword: 'home' as const };
const culture = (stats: CardInput['snapshot']['stats']) => input(stats, { category: 'Culture' });
assert.equal(deriveCard(culture({ attention: 80, depth: 40, reach: 40 }), TABLE).keyword, 'viral', 'v1 default: faction');
assert.equal(deriveCard(culture({ attention: 80, depth: 40, reach: 40 }), TABLE, home).keyword, 'viral');
assert.equal(deriveCard(culture({ attention: 40, depth: 80, reach: 40 }), TABLE, home).keyword, 'encyclopedic');
assert.equal(deriveCard(culture({ attention: 40, depth: 40, reach: 80 }), TABLE, home).keyword, 'translated');
assert.equal(deriveCard(input({ attention: 40, depth: 40, reach: 80 }, { category: 'History' }), TABLE, home).keyword, 'nostalgic', 'other factions unchanged');
assert.equal(deriveCard(culture({ attention: 5, depth: 5, reach: 5 }), TABLE, home).keyword, null, 'cost 1 still vanilla');
});
test('a full Ruleset works as DerivationRules (hosts can derive with the mode rules)', async () => {
const { DEFAULT_RULESET } = await import('../shared/game/index.ts');
const a = deriveCard(input({ attention: 81, depth: 71, reach: 61 }), TABLE, DEFAULT_RULESET);
const b = deriveCard(input({ attention: 81, depth: 71, reach: 61 }), TABLE);
assert.deepEqual(a, b);
});
test('parseRuleset accepts a stored pre-v1.1 ruleset without cultureKeyword (defaults to faction)', async () => {
const { parseRuleset, RULESET_V1_0 } = await import('../shared/game/index.ts');
const { cultureKeyword: _omit, ...old } = structuredClone(RULESET_V1_0);
const parsed = parseRuleset(old);
assert.equal(parsed.cultureKeyword, 'faction');
assert.deepEqual(parsed, RULESET_V1_0);
});
+4 -4
View File
@@ -8,7 +8,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
DEFAULT_RULESET, applyAction, createMatch, isOver, lanePower, result, starterDeck, topicsLed,
RULESET_V1_0, applyAction, createMatch, isOver, lanePower, result, starterDeck, topicsLed,
type Action, type GameCard, type MatchState, type PlayerId, type Ruleset, type Stat, type Faction,
} from '../shared/game/index.ts';
@@ -55,7 +55,7 @@ const PLAN: [PlayerId, string, number][][] = [
];
function setup(): MatchState {
const rules: Ruleset = { ...DEFAULT_RULESET };
const rules: Ruleset = structuredClone(RULESET_V1_0); // §12 is pinned to the v1.0 ruleset
const state = createMatch(rules, [starterDeck('golden-a'), starterDeck('golden-b')], 1);
const pool = state.ruleset.topicPool;
const find = (id: string) => pool.find(t => t.id === id) ?? assert.fail(`topic ${id} missing from the default pool`);
@@ -77,8 +77,8 @@ function playTurn(state: MatchState, plays: [PlayerId, string, number][]): Match
return applyAction(state, { type: 'commit', player: 1 });
}
test('§12 golden: rules defaults match the frozen §9 values', opts, () => {
for (const [key, value] of Object.entries(FROZEN)) assert.deepEqual((DEFAULT_RULESET as unknown as Record<string, unknown>)[key], value, key);
test('§12 golden: RULESET_V1_0 matches the frozen §9 v1.0 values', opts, () => {
for (const [key, value] of Object.entries(FROZEN)) assert.deepEqual((RULESET_V1_0 as unknown as Record<string, unknown>)[key], value, key);
});
test('§12 golden: final Topic powers 19–15, 15–19, 13–10; Ana (p0) wins 2–1', opts, () => {
+22
View File
@@ -227,3 +227,25 @@ test('no keyword or Portal hook moves or removes cards (§10 v1 constraint)', ()
assert.deepEqual(count(), before, id);
}
});
// ---- v1.1 config hooks (default to v1) ----
test('viral base (v1.1 hook): gain = min(base + earlier × amount, cap); base 0 by default', () => {
const s = board();
assert.equal(reveal(s, 0, 1, card({ keyword: 'viral' })).bonus, 0, 'v1: nothing earlier, no gain');
s.ruleset.keywordParams.viral = { amount: 1, cap: 3, base: 1 };
const t = board(); t.ruleset.keywordParams.viral = { amount: 1, cap: 3, base: 1 };
assert.equal(reveal(t, 0, 1, card({ keyword: 'viral' })).bonus, 1, 'base alone');
place(t, 0, 0, card()); place(t, 0, 2, card()); place(t, 0, 2, card());
assert.equal(reveal(t, 0, 0, card({ keyword: 'viral' })).bonus, 3, 'capped at 3');
});
test('encyclopedic sides (v1.1 hook): 1 ignores the opponent side; default 2 is v1', () => {
const s = board();
place(s, 1, 0, card());
assert.equal(reveal(s, 0, 0, card({ keyword: 'encyclopedic' })).bonus, 0);
const t = board(); t.ruleset.keywordParams.encyclopedic = { amount: 2, sides: 1 };
place(t, 1, 0, card());
assert.equal(reveal(t, 0, 0, card({ keyword: 'encyclopedic' })).bonus, 2);
place(t, 0, 1, card());
assert.equal(reveal(t, 0, 1, card({ keyword: 'encyclopedic' })).bonus, 0, 'own card still blocks');
});
+24 -2
View File
@@ -30,12 +30,13 @@ test('starter cards follow §10.1 and the power curve like owned cards', () => {
}
});
test('all 6 factions and all 4 shared/catalog.ts cards (with real pageIds) are covered', () => {
test('all 6 factions covered; every starter card has a real pageId, catalog ones as in shared/catalog.ts', () => {
const all = STARTER_DECKS.flatMap(d => starterDeckById(d.id));
assert.equal(new Set(all.map(c => c.faction)).size, 6);
const ids = Object.fromEntries(all.map(c => [c.title, c.pageId]));
assert.deepEqual([ids.Moon, ids['Periodic table'], ids.Octopus, ids['Albert Einstein']], [19331, 23053, 22780, 736]);
for (const c of all) if (!['Moon', 'Periodic table', 'Octopus', 'Albert Einstein'].includes(c.title)) assert.equal(c.pageId, null, c.title);
for (const c of all) assert.ok(Number.isInteger(c.pageId) && c.pageId! > 0, `${c.title} has a real pageId`);
assert.equal(new Set(all.map(c => c.pageId)).size, all.length, 'no two starter cards share a pageId');
});
test('every starter deck passes engine deck validation and starts a match against every other', () => {
@@ -50,3 +51,24 @@ test('modes changing the curve change loaners too; unknown ids are rejected', ()
assert.ok(flat.every(c => c.power === 3));
assert.throws(() => starterDeckById('nope'), RangeError);
});
test('previewPool derives the frozen starter-cards.json loaners through §1', async () => {
const { previewPool, LOANER_SNAPSHOTS, CARD_SAMPLE_PERCENTILES, DEFAULT_RULESET, validateDeck } = await import('../shared/game/index.ts');
const pool = previewPool();
assert.equal(pool.length, LOANER_SNAPSHOTS.length);
assert.deepEqual(previewPool(), pool, 'deterministic');
for (const stat of ['attention', 'depth', 'reach'] as const) {
const cuts = CARD_SAMPLE_PERCENTILES[stat];
assert.equal(cuts.length, 99);
assert.ok(cuts.every((v, i) => i === 0 || v >= cuts[i - 1]), `${stat} cuts ascend`);
}
assert.equal(new Set(pool.map(c => c.cardId)).size, pool.length);
for (const c of pool) {
assert.equal(c.source, 'loaner');
assert.match(c.cardId, /^loaner:\d+$/);
assert.ok(c.cost >= 1 && c.cost <= 6);
assert.equal(c.power, DEFAULT_DERIVATION.powerByCost[c.cost] + (c.keyword === null && c.cost === 1 ? DEFAULT_DERIVATION.vanillaBonus : 0));
}
// 12 of them make a legal loaner deck.
assert.deepEqual(validateDeck(DEFAULT_RULESET, pool.slice(0, 12)), []);
});