Files
wikideck/server/game/store.ts
claudeandClaude Opus 5.5 adc78409fe host-pvp: multi-engine host, owned-deck seats, invites, quick match, Elo, ?v= polling (#56)
- Mode schema wikideck.mode/2: required `engine` (editwar | duel); Night 1
  wikideck.mode/1 documents are rejected with a clear message. Deck policies:
  constructed (owned NFT token ids, minConfirmations), starter (Edit War only),
  draft with source preview (Edit War only) or collections. limits.rated and
  limits.accountsOnly.
- ModeHost runs every engine it is given, chosen per mode. Duel modes refuse
  loaner policies at startup (BRIEF decision 1).
- Seats: eom.dev account via Dex ID token (body or JWT bearer on seat-creating
  routes), player id sha256('acct:'+iss+'\n'+sub); guests only in Edit War.
- Constructed decks resolved through an injected OwnershipPort (#57), cards built
  by the engine's fromChain; creator's deck re-resolved at join.
- Private lobbies + invite codes (GET /invites/:code, POST /invites/:code/join),
  quick match (POST /modes/:id/quick), lobby state version with 204 on ?v=.
- Elo (1200, K 24) per mode for rated account-vs-account matches, recomputed
  from matches.jsonl; records carry engine, rated, tokens. /modes/:id/ladder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:27:37 -05:00

118 lines
5.6 KiB
TypeScript

/**
* Off-chain match records for this node: an append-only JSON-lines file plus in-memory
* aggregates (leaderboards, host totals). Nothing here touches the ledger.
*/
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { z } from 'zod';
export const MatchRecordSchema = z.object({
matchId: z.string().regex(/^[a-f0-9]{32}$/),
modeId: z.string().max(40),
modeVersion: z.number().int(),
/** Engine the match ran on (absent in Night 1 records: `editwar`). */
engine: z.enum(['editwar', 'duel']).optional(),
/** Counted for Elo: the mode was rated and both seats were eom.dev accounts. */
rated: z.boolean().optional(),
/** Host-chosen seed. Together with decks and actions it lets anyone replay the match. */
seed: z.string().max(128),
/** The resolved ruleset the match ran under (mode overrides already applied). */
rules: z.unknown(),
players: z.array(z.object({ id: z.string().regex(/^[a-f0-9]{64}$/), name: z.string().max(24),
account: z.boolean().optional() }).strict()).length(2),
winner: z.union([z.literal(0), z.literal(1), z.null()]),
reason: z.string().max(40),
startedAt: z.number().int(),
endedAt: z.number().int(),
decks: z.array(z.array(z.unknown()).max(64)).length(2),
actions: z.array(z.object({ seat: z.union([z.literal(0), z.literal(1)]), action: z.unknown() }).strict()).max(2000),
/** Constructed modes: the NFT token ids each seat played, in deck order (recap references). */
tokens: z.array(z.array(z.string().max(128)).max(64)).length(2).optional(),
}).strict();
export type MatchRecord = z.infer<typeof MatchRecordSchema>;
export type LeaderboardEntry = { playerId: string; name: string; wins: number; losses: number; draws: number; played: number;
/** Elo (start 1200, K 24) from rated matches; null if the player has none in this mode. */
rating: number | null; ratedPlayed: number };
/** Elo constants (engineer review §3). Ratings are recomputed by replaying records in order. */
export const ELO_START = 1200;
export const ELO_K = 24;
/** New ratings for [seat0, seat1] after one game; winner null is a draw. */
export function eloUpdate(r0: number, r1: number, winner: 0 | 1 | null): [number, number] {
const e0 = 1 / (1 + 10 ** ((r1 - r0) / 400));
const s0 = winner === null ? 0.5 : winner === 0 ? 1 : 0;
const d = ELO_K * (s0 - e0);
return [r0 + d, r1 - d];
}
type ModeAgg = { matches: number; players: Map<string, LeaderboardEntry> };
const KEEP_RECENT = 500;
export class MatchStore {
private readonly file: string | null;
private readonly modes = new Map<string, ModeAgg>();
private readonly recent = new Map<string, MatchRecord>();
private readonly allPlayers = new Set<string>();
total = 0;
/** `directory` null keeps records in memory only (tests). */
constructor(directory: string | null) {
this.file = directory ? join(directory, 'matches.jsonl') : null;
if (!directory || !this.file) return;
mkdirSync(directory, { recursive: true, mode: 0o700 });
if (!existsSync(this.file)) return;
for (const line of readFileSync(this.file, 'utf8').split('\n')) {
if (!line.trim()) continue;
const parsed = MatchRecordSchema.safeParse(safeJson(line));
if (parsed.success) this.index(parsed.data); // A torn last line after a crash is skipped.
}
}
add(record: MatchRecord): void {
const valid = MatchRecordSchema.parse(record);
if (this.file) appendFileSync(this.file, JSON.stringify(valid) + '\n', { mode: 0o600 });
this.index(valid);
}
get(matchId: string): MatchRecord | undefined { return this.recent.get(matchId); }
modeMatches(modeId: string): number { return this.modes.get(modeId)?.matches ?? 0; }
modePlayers(modeId: string): number { return this.modes.get(modeId)?.players.size ?? 0; }
distinctPlayers(): number { return this.allPlayers.size; }
leaderboard(modeId: string, limit = 20): LeaderboardEntry[] {
const players = [...(this.modes.get(modeId)?.players.values() ?? [])];
// Rated players first, by Elo; then everyone else by W/L (the cut-order fallback).
return players.sort((a, b) => (b.rating ?? -Infinity) - (a.rating ?? -Infinity) || b.wins - a.wins || a.losses - b.losses ||
b.played - a.played || a.playerId.localeCompare(b.playerId)).slice(0, limit)
.map(p => ({ ...p, rating: p.rating === null ? null : Math.round(p.rating) }));
}
private index(r: MatchRecord): void {
this.total++;
const agg = this.modes.get(r.modeId) ?? { matches: 0, players: new Map() };
this.modes.set(r.modeId, agg);
agg.matches++;
const entries = r.players.map((p, seat) => {
this.allPlayers.add(p.id);
const e = agg.players.get(p.id) ?? { playerId: p.id, name: p.name, wins: 0, losses: 0, draws: 0, played: 0, rating: null, ratedPlayed: 0 };
e.name = p.name; e.played++;
if (r.winner === null) e.draws++; else if (r.winner === seat) e.wins++; else e.losses++;
agg.players.set(p.id, e);
return e;
});
// Elo only for rated matches between two account seats that actually played (no aborted 0-action games).
if (r.rated && r.players.every(p => p.account) && r.actions.length > 0 && r.reason !== 'abandoned') {
const [a, b] = entries as [LeaderboardEntry, LeaderboardEntry];
[a.rating, b.rating] = eloUpdate(a.rating ?? ELO_START, b.rating ?? ELO_START, r.winner);
a.ratedPlayed++; b.ratedPlayed++;
}
this.recent.set(r.matchId, r);
if (this.recent.size > KEEP_RECENT) this.recent.delete(this.recent.keys().next().value!);
}
}
function safeJson(line: string): unknown { try { return JSON.parse(line); } catch { return null; } }