@phantomblip/game-core 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dave Haslam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,47 @@
1
- # Temporary Holding Version
1
+ # @phantomblip/game-core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The contract a Phantom Blip game module is written against, plus the engine that runs it.
4
+
5
+ A game is a pure state machine (`GameDefinition`): no framework, JSON-serializable state, deterministic given the state and the actions. A turn is a sequence of actions composed one at a time. The same functions drive the browser table, the server's move check, the bots' self-play and hot-seat.
6
+
7
+ ## Install
8
+
9
+ ```
10
+ npm install @phantomblip/game-core
11
+ ```
12
+
13
+ In a module made with `npm create @phantomblip/module`, it is already a dependency.
14
+
15
+ ## What is in it
16
+
17
+ - Contract types: `GameDefinition`, `Bot`, `BotContext`, `ModuleManifest`, `ModuleRules`, `BotFactories`.
18
+ - The turn engine: `composeTurn`, `validateTurn`, `playGame`, `runSeries`.
19
+ - Seeded random numbers: `createRng`, and a `randomBot` to start from.
20
+ - `checkModule`, the conformance check `module-kit check` runs, and `MODULE_PROTOCOL`.
21
+ - Bot helpers (`@phantomblip/game-core/bots`) and the harness (`@phantomblip/game-core/harness`).
22
+
23
+ ## Smallest useful example
24
+
25
+ Play one seeded game between two random bots:
26
+
27
+ ```ts
28
+ import { playGame, randomBot } from "@phantomblip/game-core";
29
+ import { gameDef } from "./src/index";
30
+
31
+ const result = playGame(gameDef, [randomBot(), randomBot()], { seed: 1 });
32
+ console.log(result.winner, result.reason, result.turns);
33
+ ```
34
+
35
+ `result.log` holds every turn, so the same game can be replayed.
36
+
37
+ ## Before 1.0
38
+
39
+ This is version 0.1.x. Expect the SDK to change between releases. `MODULE_PROTOCOL` is the promise of compatibility between a module and the site that runs it.
40
+
41
+ ## Documentation
42
+
43
+ How to build and run a module: see the `@phantomblip/module-kit` README.
44
+
45
+ ## License
46
+
47
+ MIT
@@ -0,0 +1,51 @@
1
+ import type { Bot, Seat } from "../types.js";
2
+ import type { Rng } from "../rng.js";
3
+ /**
4
+ * A beam planner generic over the game (fork 1). Lifted from Alien Frontiers
5
+ * into game-core for Islebound (spec §4.1). It imports nothing from any game.
6
+ */
7
+ export interface PlannerHooks<S, A> {
8
+ /** The actions worth searching from `s`. */
9
+ candidates(s: S, seat: Seat): A[];
10
+ /** The state after `a`. Never mutates `s`; never advances the turn. */
11
+ step(s: S, seat: Seat, a: A): S;
12
+ /** Value of `s` for `seat`. */
13
+ evaluate(s: S, seat: Seat): number;
14
+ /** An action that consumes hidden information or randomness and so ends the line. Islebound's reveals depend on the state (a renown gain that crosses 7), so the hook sees it. */
15
+ isReveal(a: A, s: S, seat: Seat): boolean;
16
+ /** Expected value of taking the reveal `a` from `s`. */
17
+ revealValue(s: S, seat: Seat, a: A): number;
18
+ /** Nodes one `revealValue` call costs against `maxNodes` (it evaluates many outcomes). Default 1. */
19
+ revealCost?(s: S, seat: Seat, a: A): number;
20
+ }
21
+ export interface PlanOptions {
22
+ beam: number;
23
+ maxNodes: number;
24
+ }
25
+ export interface RankedLine<A> {
26
+ first: A;
27
+ line: A[];
28
+ value: number;
29
+ }
30
+ export interface PlannerProfile extends PlanOptions {
31
+ name: string;
32
+ temperature: number;
33
+ }
34
+ /**
35
+ * Beam search over the rest of this segment from `base`. Each line ends at a
36
+ * reveal or when the beam runs out of children; its value is the best value
37
+ * seen along it. Returns one line per distinct first action, best first.
38
+ * Deterministic: node budget only, ties broken by enumeration order.
39
+ */
40
+ export declare function rankLines<S, A>(hooks: PlannerHooks<S, A>, base: S, seat: Seat, opts: PlanOptions): RankedLine<A>[];
41
+ /** Softmax pick over choices sorted best first; temperature 0 takes the first. */
42
+ export declare function sample<C>(choices: readonly {
43
+ c: C;
44
+ value: number;
45
+ }[], temperature: number, rng: Rng): C;
46
+ /**
47
+ * A bot that plans a line per segment and follows it. `turnOf` is the game's
48
+ * segment counter (the memo key). The turn may be unable to end (must-dock, a
49
+ * pending choice), in which case "end" is never offered or returned.
50
+ */
51
+ export declare function profileBot<S, A>(profile: PlannerProfile, hooks: PlannerHooks<S, A>, turnOf: (s: S) => number): Bot<S, A>;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Beam search over the rest of this segment from `base`. Each line ends at a
3
+ * reveal or when the beam runs out of children; its value is the best value
4
+ * seen along it. Returns one line per distinct first action, best first.
5
+ * Deterministic: node budget only, ties broken by enumeration order.
6
+ */
7
+ export function rankLines(hooks, base, seat, opts) {
8
+ const best = new Map();
9
+ const record = (line, value) => {
10
+ const key = JSON.stringify(line[0]);
11
+ const prev = best.get(key);
12
+ if (!prev || value > prev.value)
13
+ best.set(key, { first: line[0], line, value });
14
+ };
15
+ let nodes = 0;
16
+ let frontier = [{ state: base, line: [], value: hooks.evaluate(base, seat) }];
17
+ while (frontier.length && nodes < opts.maxNodes) {
18
+ const next = [];
19
+ for (const n of frontier) {
20
+ for (const a of hooks.candidates(n.state, seat)) {
21
+ if (nodes >= opts.maxNodes)
22
+ break;
23
+ const line = [...n.line, a];
24
+ if (hooks.isReveal(a, n.state, seat)) {
25
+ const cost = hooks.revealCost?.(n.state, seat, a) ?? 1;
26
+ if (nodes + cost > opts.maxNodes)
27
+ continue; // cannot afford the reveal: skip it, a cheaper child may still fit
28
+ nodes += cost;
29
+ record(line, hooks.revealValue(n.state, seat, a));
30
+ continue;
31
+ }
32
+ nodes++;
33
+ const state = hooks.step(n.state, seat, a);
34
+ const value = hooks.evaluate(state, seat);
35
+ record(line, value);
36
+ next.push({ state, line, value });
37
+ }
38
+ }
39
+ next.sort((x, y) => y.value - x.value);
40
+ frontier = next.slice(0, opts.beam);
41
+ }
42
+ return [...best.values()].sort((x, y) => y.value - x.value);
43
+ }
44
+ /** Softmax pick over choices sorted best first; temperature 0 takes the first. */
45
+ export function sample(choices, temperature, rng) {
46
+ if (temperature <= 0)
47
+ return choices[0].c;
48
+ const top = choices[0].value;
49
+ const weights = choices.map((x) => Math.exp((x.value - top) / temperature));
50
+ let r = rng.float() * weights.reduce((a, b) => a + b, 0);
51
+ for (let i = 0; i < choices.length; i++) {
52
+ r -= weights[i];
53
+ if (r <= 0)
54
+ return choices[i].c;
55
+ }
56
+ return choices[choices.length - 1].c;
57
+ }
58
+ /**
59
+ * A bot that plans a line per segment and follows it. `turnOf` is the game's
60
+ * segment counter (the memo key). The turn may be unable to end (must-dock, a
61
+ * pending choice), in which case "end" is never offered or returned.
62
+ */
63
+ export function profileBot(profile, hooks, turnOf) {
64
+ let memo = null;
65
+ const key = (a) => JSON.stringify(a);
66
+ return {
67
+ name: profile.name,
68
+ chooseAction: ({ state, seat, soFar, rng, def, legal, canEnd }) => {
69
+ if (legal.length === 0)
70
+ return "end";
71
+ if (soFar.length > 0 && memo && memo.turn === turnOf(state) && key(memo.line.slice(0, soFar.length)) === key(soFar)) {
72
+ const nextA = memo.line[soFar.length];
73
+ if (nextA === undefined && canEnd)
74
+ return "end";
75
+ const match = nextA === undefined ? undefined : legal.find((a) => key(a) === key(nextA));
76
+ if (match)
77
+ return match;
78
+ }
79
+ const view = def.playerView(state, seat);
80
+ let base = view;
81
+ for (const a of soFar)
82
+ base = hooks.step(base, seat, a);
83
+ const lines = rankLines(hooks, base, seat, profile);
84
+ const choices = lines.map((l) => ({ c: l, value: l.value }));
85
+ if (canEnd)
86
+ choices.push({ c: "end", value: hooks.evaluate(base, seat) });
87
+ if (choices.length === 0)
88
+ return legal[0]; // budget exhausted before any child: stay legal
89
+ choices.sort((a, b) => b.value - a.value);
90
+ const pick = sample(choices, profile.temperature, rng);
91
+ if (pick === "end") {
92
+ memo = null;
93
+ return "end";
94
+ }
95
+ memo = { turn: turnOf(state), line: [...soFar, ...pick.line] };
96
+ return legal.find((a) => key(a) === key(pick.first)) ?? legal[0];
97
+ },
98
+ };
99
+ }
@@ -0,0 +1 @@
1
+ export { randomBot } from "./random.js";
@@ -0,0 +1 @@
1
+ export { randomBot } from "./random.js";
@@ -0,0 +1,7 @@
1
+ import type { Bot } from "../types.js";
2
+ /**
3
+ * Uniform random legal play. Exists to find crashes and dead ends, not to
4
+ * play well. When ending the turn is optional it ends with probability
5
+ * 1/(legal+1) so optional-action games still terminate.
6
+ */
7
+ export declare function randomBot<S, A>(): Bot<S, A>;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Uniform random legal play. Exists to find crashes and dead ends, not to
3
+ * play well. When ending the turn is optional it ends with probability
4
+ * 1/(legal+1) so optional-action games still terminate.
5
+ */
6
+ export function randomBot() {
7
+ return {
8
+ name: "random",
9
+ chooseAction: ({ legal, canEnd, rng }) => {
10
+ if (legal.length === 0)
11
+ return "end";
12
+ if (canEnd && rng.int(legal.length + 1) === 0)
13
+ return "end";
14
+ return rng.pick(legal);
15
+ },
16
+ };
17
+ }
@@ -0,0 +1,55 @@
1
+ import { type Rng } from "../rng.js";
2
+ import type { Bot, GameDefinition, Seat } from "../types.js";
3
+ export interface TurnRecord<A> {
4
+ turn: number;
5
+ seat: Seat;
6
+ actions: A[];
7
+ }
8
+ export interface GameResult<A> {
9
+ winner: Seat | null;
10
+ reason: string;
11
+ turns: number;
12
+ log: TurnRecord<A>[];
13
+ }
14
+ export interface PlayOptions {
15
+ seed: number;
16
+ /** Turns after which the game is declared a draw. */
17
+ turnCap?: number;
18
+ /** Safety valve against a game whose turn never completes. */
19
+ maxActionsPerTurn?: number;
20
+ }
21
+ export type Validation = {
22
+ ok: true;
23
+ } | {
24
+ ok: false;
25
+ error: string;
26
+ };
27
+ /**
28
+ * Replays `actions` through `legalActions`/`canEndTurn`, so the server and
29
+ * the harness accept exactly what the UI would have allowed.
30
+ */
31
+ export declare function validateTurn<S, A, O>(def: GameDefinition<S, A, O>, state: S, seat: Seat, actions: readonly A[]): Validation;
32
+ /** Structural equality on JSON-shaped actions. */
33
+ export declare function sameAction<A>(a: A, b: A): boolean;
34
+ /**
35
+ * Lets `bot` compose one complete turn for `seat` through the same
36
+ * legalActions/canEndTurn gates the UI enforces. Shared by the harness and
37
+ * the server's bot auto-play, so both accept exactly the same turns.
38
+ * Never mutates `state`; throws if the bot misbehaves.
39
+ */
40
+ export declare function composeTurn<S, A, O>(def: GameDefinition<S, A, O>, bot: Bot<S, A>, state: S, seat: Seat, rng: Rng, maxActions?: number): A[];
41
+ export declare function playGame<S, A, O>(def: GameDefinition<S, A, O>, bots: readonly Bot<S, A>[], opts: PlayOptions): GameResult<A>;
42
+ export interface SeriesOptions {
43
+ games: number;
44
+ seed: number;
45
+ turnCap?: number;
46
+ }
47
+ export interface SeriesStats<A> {
48
+ games: number;
49
+ wins: number[];
50
+ draws: number;
51
+ avgTurns: number;
52
+ reasons: Record<string, number>;
53
+ results: GameResult<A>[];
54
+ }
55
+ export declare function runSeries<S, A, O>(def: GameDefinition<S, A, O>, bots: readonly Bot<S, A>[], opts: SeriesOptions): SeriesStats<A>;
@@ -0,0 +1,104 @@
1
+ import { createRng } from "../rng.js";
2
+ /**
3
+ * Replays `actions` through `legalActions`/`canEndTurn`, so the server and
4
+ * the harness accept exactly what the UI would have allowed.
5
+ */
6
+ export function validateTurn(def, state, seat, actions) {
7
+ if (def.currentSeat(state) !== seat) {
8
+ return { ok: false, error: `not seat ${seat}'s turn` };
9
+ }
10
+ const soFar = [];
11
+ for (let i = 0; i < actions.length; i++) {
12
+ const a = actions[i];
13
+ const legal = def.legalActions(state, seat, soFar);
14
+ if (!legal.some((l) => sameAction(l, a))) {
15
+ return { ok: false, error: `action ${i} is illegal: ${JSON.stringify(a)}` };
16
+ }
17
+ soFar.push(a);
18
+ }
19
+ if (!def.canEndTurn(state, seat, soFar)) {
20
+ return { ok: false, error: "incomplete turn" };
21
+ }
22
+ return { ok: true };
23
+ }
24
+ /** Structural equality on JSON-shaped actions. */
25
+ export function sameAction(a, b) {
26
+ return JSON.stringify(a) === JSON.stringify(b);
27
+ }
28
+ /**
29
+ * Lets `bot` compose one complete turn for `seat` through the same
30
+ * legalActions/canEndTurn gates the UI enforces. Shared by the harness and
31
+ * the server's bot auto-play, so both accept exactly the same turns.
32
+ * Never mutates `state`; throws if the bot misbehaves.
33
+ */
34
+ export function composeTurn(def, bot, state, seat, rng, maxActions = 64) {
35
+ const soFar = [];
36
+ for (;;) {
37
+ const legal = def.legalActions(state, seat, soFar);
38
+ const canEnd = def.canEndTurn(state, seat, soFar);
39
+ if (legal.length === 0) {
40
+ if (!canEnd)
41
+ throw new Error("dead end: no legal actions and cannot end turn");
42
+ break;
43
+ }
44
+ const choice = bot.chooseAction({ state, seat, soFar, legal, canEnd, rng, def: def });
45
+ if (choice === "end") {
46
+ if (!canEnd)
47
+ throw new Error(`bot ${bot.name} ended an incomplete turn`);
48
+ break;
49
+ }
50
+ if (!legal.some((l) => sameAction(l, choice))) {
51
+ throw new Error(`bot ${bot.name} chose an illegal action: ${JSON.stringify(choice)}`);
52
+ }
53
+ soFar.push(choice);
54
+ if (soFar.length > maxActions)
55
+ throw new Error(`turn exceeded ${maxActions} actions`);
56
+ }
57
+ return soFar;
58
+ }
59
+ export function playGame(def, bots, opts) {
60
+ const rng = createRng(opts.seed);
61
+ const turnCap = opts.turnCap ?? 200;
62
+ const maxActions = opts.maxActionsPerTurn ?? 64;
63
+ let state = def.setup({ options: def.defaultOptions, seed: opts.seed, playerCount: bots.length });
64
+ const log = [];
65
+ for (let turn = 1;; turn++) {
66
+ const t = def.isTerminal(state);
67
+ if (t.over)
68
+ return { winner: t.winner, reason: t.reason ?? "terminal", turns: turn - 1, log };
69
+ if (turn > turnCap)
70
+ return { winner: null, reason: "turn cap", turns: turn - 1, log };
71
+ const seat = def.currentSeat(state);
72
+ const bot = bots[seat];
73
+ if (!bot)
74
+ throw new Error(`no bot for seat ${seat}`);
75
+ let soFar;
76
+ try {
77
+ soFar = composeTurn(def, bot, state, seat, rng, maxActions);
78
+ }
79
+ catch (e) {
80
+ throw new Error(`turn ${turn}: ${e.message}`);
81
+ }
82
+ state = def.applyTurn(state, seat, soFar);
83
+ log.push({ turn, seat, actions: soFar });
84
+ }
85
+ }
86
+ export function runSeries(def, bots, opts) {
87
+ const seeds = createRng(opts.seed);
88
+ const wins = bots.map(() => 0);
89
+ const reasons = {};
90
+ const results = [];
91
+ let draws = 0;
92
+ let totalTurns = 0;
93
+ for (let g = 0; g < opts.games; g++) {
94
+ const r = playGame(def, bots, { seed: seeds.int(2 ** 31), ...(opts.turnCap !== undefined ? { turnCap: opts.turnCap } : {}) });
95
+ results.push(r);
96
+ totalTurns += r.turns;
97
+ reasons[r.reason] = (reasons[r.reason] ?? 0) + 1;
98
+ if (r.winner === null)
99
+ draws++;
100
+ else
101
+ wins[r.winner] = (wins[r.winner] ?? 0) + 1;
102
+ }
103
+ return { games: opts.games, wins, draws, avgTurns: totalTurns / opts.games, reasons, results };
104
+ }
@@ -0,0 +1,14 @@
1
+ export type { Bot, BotContext, GameDefinition, Seat, Terminal } from "./types.js";
2
+ export { createRng } from "./rng.js";
3
+ export type { Rng } from "./rng.js";
4
+ export { composeTurn, playGame, runSeries, validateTurn, sameAction } from "./harness/index.js";
5
+ export type { GameResult, PlayOptions, SeriesOptions, SeriesStats, TurnRecord, Validation } from "./harness/index.js";
6
+ export { randomBot } from "./bots/index.js";
7
+ export { rankLines, profileBot, sample } from "./bots/beam.js";
8
+ export type { PlannerHooks, PlannerProfile, PlanOptions, RankedLine } from "./bots/beam.js";
9
+ export { seedState, xoshiroNext, xoshiroFloat } from "./xoshiro.js";
10
+ export type { XoshiroState } from "./xoshiro.js";
11
+ export { MODULE_PROTOCOL, SEAT_FILLS, playerCountsOf } from "./module.js";
12
+ export type { BotFactories, GameModule, ModuleManifest, ModuleRules, OptionField } from "./module.js";
13
+ export { checkManifest, checkModule } from "./module-check.js";
14
+ export type { CheckOptions } from "./module-check.js";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { createRng } from "./rng.js";
2
+ export { composeTurn, playGame, runSeries, validateTurn, sameAction } from "./harness/index.js";
3
+ export { randomBot } from "./bots/index.js";
4
+ export { rankLines, profileBot, sample } from "./bots/beam.js";
5
+ export { seedState, xoshiroNext, xoshiroFloat } from "./xoshiro.js";
6
+ export { MODULE_PROTOCOL, SEAT_FILLS, playerCountsOf } from "./module.js";
7
+ export { checkManifest, checkModule } from "./module-check.js";
@@ -0,0 +1,22 @@
1
+ import { type GameModule } from "./module.js";
2
+ export interface CheckOptions {
3
+ /** Seed for the playthrough. Default 1. */
4
+ seed?: number;
5
+ /** Turns the default bot gets to finish a game. Default 600. */
6
+ turnCap?: number;
7
+ /** False skips the playthrough (structure checks only). Default true. */
8
+ play?: boolean;
9
+ /**
10
+ * The id the module must have: its package's `gameModule.id` (which the generator ties to the folder). Each module's
11
+ * conformance test passes it, so a copied module whose manifest was not renamed fails instead of pointing
12
+ * assetUrl(manifest.id, ...) at another game's art.
13
+ */
14
+ id?: string;
15
+ }
16
+ /**
17
+ * Everything wrong with a manifest alone, in words: nothing here needs the module's code. Safe on any value, so a
18
+ * packaged manifest.json can be checked before any of its code is loaded.
19
+ */
20
+ export declare function checkManifest(manifest: unknown): string[];
21
+ /** Everything wrong with a module, in words. An empty list means it conforms. */
22
+ export declare function checkModule(m: GameModule, opts?: CheckOptions): string[];
@@ -0,0 +1,186 @@
1
+ import { playGame, validateTurn } from "./harness/index.js";
2
+ import { MODULE_PROTOCOL, playerCountsOf } from "./module.js";
3
+ /** True when `v` holds something JSON would drop or rewrite: a function, a class instance, NaN. */
4
+ function hasNonJson(v) {
5
+ if (v === null || typeof v === "string" || typeof v === "boolean")
6
+ return false;
7
+ if (typeof v === "number")
8
+ return !Number.isFinite(v);
9
+ if (typeof v !== "object")
10
+ return true;
11
+ if (Array.isArray(v))
12
+ return v.some(hasNonJson);
13
+ const proto = Object.getPrototypeOf(v);
14
+ if (proto !== Object.prototype && proto !== null)
15
+ return true;
16
+ return Object.values(v).some(hasNonJson);
17
+ }
18
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
19
+ const isPlain = (v) => isObject(v) && (Object.getPrototypeOf(v) === Object.prototype || Object.getPrototypeOf(v) === null);
20
+ const WRONG_TYPE = "is missing or has the wrong type";
21
+ /**
22
+ * Everything wrong with a manifest alone, in words: nothing here needs the module's code. Safe on any value, so a
23
+ * packaged manifest.json can be checked before any of its code is loaded.
24
+ */
25
+ export function checkManifest(manifest) {
26
+ if (!isObject(manifest))
27
+ return [`manifest ${WRONG_TYPE}: it must be a JSON object`];
28
+ const wrong = [];
29
+ for (const k of ["id", "name", "version"])
30
+ if (typeof manifest[k] !== "string")
31
+ wrong.push(`manifest.${k} ${WRONG_TYPE}`);
32
+ for (const k of ["protocol", "minPlayers", "maxPlayers"])
33
+ if (typeof manifest[k] !== "number")
34
+ wrong.push(`manifest.${k} ${WRONG_TYPE}`);
35
+ for (const k of ["seats", "options"])
36
+ if (!Array.isArray(manifest[k]))
37
+ wrong.push(`manifest.${k} ${WRONG_TYPE}`);
38
+ if (!isPlain(manifest.bots))
39
+ wrong.push(`manifest.bots ${WRONG_TYPE}`);
40
+ if (!isObject(manifest.rules) || typeof manifest.rules.kind !== "string")
41
+ wrong.push(`manifest.rules ${WRONG_TYPE}`);
42
+ if (manifest.playerCounts !== undefined && !Array.isArray(manifest.playerCounts))
43
+ wrong.push(`manifest.playerCounts ${WRONG_TYPE}`);
44
+ if (wrong.length > 0)
45
+ return wrong;
46
+ const mf = manifest;
47
+ const out = [];
48
+ if (!/^[a-z0-9-]{1,40}$/.test(mf.id))
49
+ out.push(`id "${mf.id}" must match ^[a-z0-9-]{1,40}$`);
50
+ if (mf.protocol > MODULE_PROTOCOL || mf.protocol < 1)
51
+ out.push(`protocol ${mf.protocol} is not supported (host is ${MODULE_PROTOCOL})`);
52
+ if (mf.seats.length !== mf.maxPlayers)
53
+ out.push(`seats lists ${mf.seats.length} entries for maxPlayers ${mf.maxPlayers}`);
54
+ // A span that is not a small whole number would make the default counts a runaway array.
55
+ const span = mf.maxPlayers - mf.minPlayers;
56
+ if (mf.playerCounts === undefined && !(Number.isInteger(span) && span >= 0 && span < 1000))
57
+ out.push("playerCounts fall outside min and max players");
58
+ else {
59
+ const counts = playerCountsOf(mf);
60
+ if (counts.length === 0 || counts.some((c) => typeof c !== "number" || c < mf.minPlayers || c > mf.maxPlayers))
61
+ out.push("playerCounts fall outside min and max players");
62
+ }
63
+ try {
64
+ if (hasNonJson(mf) || JSON.stringify(JSON.parse(JSON.stringify(mf))) !== JSON.stringify(mf))
65
+ out.push("manifest is not plain JSON data");
66
+ }
67
+ catch {
68
+ out.push("manifest is not plain JSON data");
69
+ }
70
+ if (!Object.hasOwn(mf.bots, mf.defaultBot) || !mf.bots[mf.defaultBot]?.offered)
71
+ out.push(`defaultBot "${mf.defaultBot}" is missing or not offered`);
72
+ if (mf.resignedBot !== undefined && !Object.hasOwn(mf.bots, mf.resignedBot))
73
+ out.push(`resignedBot "${mf.resignedBot}" is not in the manifest`);
74
+ if (mf.rules.kind === "pdf" && !mf.rules.file)
75
+ out.push("rules.file is empty");
76
+ if (mf.reasons !== undefined) {
77
+ const r = mf.reasons;
78
+ // A plain object only: null, an array or a Map would throw below or slip past as "no strings to check".
79
+ if (!isPlain(r) || Object.values(r).some((v) => typeof v !== "string"))
80
+ out.push("reasons must map each reason code to a string");
81
+ }
82
+ return out;
83
+ }
84
+ /** Everything wrong with a module, in words. An empty list means it conforms. */
85
+ export function checkModule(m, opts = {}) {
86
+ const { manifest: mf, rules, bots } = m;
87
+ const out = checkManifest(mf);
88
+ // Past a malformed shape the checks below would read fields that are not there.
89
+ if (out.some((p) => p.includes(WRONG_TYPE)))
90
+ return out;
91
+ const def = rules.def;
92
+ if (opts.id !== undefined && mf.id !== opts.id)
93
+ out.push(`manifest id "${mf.id}" differs from the package's gameModule.id "${opts.id}"`);
94
+ if (mf.id !== def.id)
95
+ out.push(`manifest id "${mf.id}" differs from the definition's "${def.id}"`);
96
+ if (mf.name !== def.name)
97
+ out.push(`manifest name "${mf.name}" differs from the definition's "${def.name}"`);
98
+ if (mf.minPlayers !== def.minPlayers || mf.maxPlayers !== def.maxPlayers)
99
+ out.push("manifest player counts differ from the definition's");
100
+ for (const k of Object.keys(mf.bots))
101
+ if (typeof bots[k] !== "function")
102
+ out.push(`bot "${k}" is in the manifest but has no factory`);
103
+ for (const k of Object.keys(bots))
104
+ if (!Object.hasOwn(mf.bots, k))
105
+ out.push(`bot factory "${k}" is not in the manifest`);
106
+ // A playthrough of a malformed module only buries the real problem.
107
+ if (out.length > 0 || opts.play === false)
108
+ return out;
109
+ const seed = opts.seed ?? 1;
110
+ const turnCap = opts.turnCap ?? 600;
111
+ const counts = playerCountsOf(mf);
112
+ const factory = bots[mf.defaultBot];
113
+ if (!factory)
114
+ return out;
115
+ for (const count of counts) {
116
+ const problem = playthrough(m, factory, count, seed, turnCap);
117
+ if (problem)
118
+ out.push(`${count} players: ${problem}`);
119
+ }
120
+ return out;
121
+ }
122
+ /**
123
+ * One seeded game of the default bot against itself, then the log replayed
124
+ * from a fresh setup the way the server would, and from replayStart of the
125
+ * finished state the way the replay viewer would. Returns the first thing
126
+ * that goes wrong, or null.
127
+ */
128
+ function playthrough(m, factory, count, seed, turnCap) {
129
+ const { rules } = m;
130
+ const def = rules.def;
131
+ let result;
132
+ try {
133
+ // playGame seats one player per bot and sets up with def.defaultOptions.
134
+ result = playGame(def, Array.from({ length: count }, () => factory()), { seed, turnCap });
135
+ }
136
+ catch (e) {
137
+ return `the default bot could not play a game: ${e.message}`;
138
+ }
139
+ if (result.reason === "turn cap" && result.turns >= turnCap)
140
+ return `the default bot did not finish within the turn cap of ${turnCap}`;
141
+ let state;
142
+ try {
143
+ state = def.setup({ options: def.defaultOptions, seed, playerCount: count });
144
+ for (const rec of result.log) {
145
+ const v = validateTurn(def, state, rec.seat, rec.actions);
146
+ if (!v.ok)
147
+ return `replay: turn ${rec.turn} fails validateTurn: ${v.error}`;
148
+ state = def.applyTurn(state, rec.seat, rec.actions);
149
+ }
150
+ if (!def.isTerminal(state).over)
151
+ return "replay: the log does not end in a terminal state (setup or applyTurn is not deterministic)";
152
+ }
153
+ catch (e) {
154
+ return `replay: the log could not be replayed: ${e.message}`;
155
+ }
156
+ let start;
157
+ try {
158
+ start = rules.replayStart(state);
159
+ }
160
+ catch (e) {
161
+ return `replayStart threw on a finished state: ${e.message}`;
162
+ }
163
+ // null means the viewer cannot rebuild this game; a state must be one the log replays from to the same end.
164
+ if (start === null || start === undefined)
165
+ return null;
166
+ const ended = JSON.stringify(def.isTerminal(state));
167
+ let replayed = start;
168
+ for (const rec of result.log) {
169
+ try {
170
+ replayed = def.applyTurn(replayed, rec.seat, rec.actions);
171
+ }
172
+ catch (e) {
173
+ return `replayStart: turn ${rec.turn} could not be replayed from its state: ${e.message}`;
174
+ }
175
+ }
176
+ let got;
177
+ try {
178
+ got = JSON.stringify(def.isTerminal(replayed));
179
+ }
180
+ catch (e) {
181
+ return `replayStart: the state the log replays to cannot be scored: ${e.message}`;
182
+ }
183
+ if (got !== ended)
184
+ return `replayStart: the log replayed from its state ends ${got}, not ${ended} as the game did`;
185
+ return null;
186
+ }
@@ -0,0 +1,79 @@
1
+ import type { Bot, GameDefinition } from "./types.js";
2
+ /** Host-to-module protocol. Bump on a breaking change to any entry-point shape. */
3
+ export declare const MODULE_PROTOCOL = 1;
4
+ /** Seat colors every game shares. Eight is the platform ceiling; the first four are fixed. */
5
+ export declare const SEAT_FILLS: readonly ["#E8B33A", "#62A9F2", "#6FBF73", "#E3645B", "#4FC3B8", "#E060D8", "#C9B8F5", "#D8C9A0"];
6
+ /** A table option the setup page offers as a select. */
7
+ export interface OptionField {
8
+ name: string;
9
+ label: string;
10
+ choices: {
11
+ value: string;
12
+ label: string;
13
+ }[];
14
+ defaultValue: string;
15
+ /** How the chosen string becomes an engine option. */
16
+ kind: "number" | "string" | "boolean";
17
+ }
18
+ /** Plain data describing a module. Must survive JSON.stringify unchanged. */
19
+ export interface ModuleManifest {
20
+ id: string;
21
+ name: string;
22
+ version: string;
23
+ protocol: number;
24
+ minPlayers: number;
25
+ maxPlayers: number;
26
+ /** Seat counts a table may have, when not every count from min to max is playable. */
27
+ playerCounts?: number[];
28
+ /** One entry per seat the game can hold. */
29
+ seats: {
30
+ name: string;
31
+ fill: string;
32
+ }[];
33
+ tagline: string;
34
+ description: string;
35
+ options: OptionField[];
36
+ /** `offered: false` keeps an older bot playable at existing tables without listing it for new ones. */
37
+ bots: Record<string, {
38
+ label: string;
39
+ offered: boolean;
40
+ }>;
41
+ defaultBot: string;
42
+ /** The bot that plays a resigned seat when the game will not accept an empty turn. */
43
+ resignedBot?: string;
44
+ /** True when the first mover is decided at setup, not by seat order. */
45
+ openingRoll?: boolean;
46
+ rules: {
47
+ kind: "pdf";
48
+ file: string;
49
+ } | {
50
+ kind: "page";
51
+ };
52
+ /**
53
+ * Engine reason code to verdict sentence ("tie-break" to "Tied on renown; …"). The host has no wording of its own:
54
+ * a code not listed here reads as the code itself ("tie-break.").
55
+ */
56
+ reasons?: Record<string, string>;
57
+ /** True when the module's UI entry has a standalone replay page (`ui.ReplayPage`, served at /replay/<id>). */
58
+ replayPage?: boolean;
59
+ cover?: string;
60
+ }
61
+ type AnyDefinition = GameDefinition<any, any, any>;
62
+ type AnyBotOf = Bot<any, any>;
63
+ export interface ModuleRules {
64
+ def: AnyDefinition;
65
+ /** False while the module's rules data is unverified: it cannot leave in_dev. */
66
+ ready: boolean;
67
+ /** The position a stored state's log replays from, or null when the viewer cannot rebuild it. */
68
+ replayStart(state: unknown): unknown | null;
69
+ /** Partnership games: the team of each seat, or null when everyone plays alone. */
70
+ teamsFor?(playerCount: number): number[] | null;
71
+ }
72
+ export type BotFactories = Record<string, () => AnyBotOf>;
73
+ export interface GameModule {
74
+ manifest: ModuleManifest;
75
+ rules: ModuleRules;
76
+ bots: BotFactories;
77
+ }
78
+ export declare const playerCountsOf: (m: ModuleManifest) => number[];
79
+ export {};
package/dist/module.js ADDED
@@ -0,0 +1,5 @@
1
+ /** Host-to-module protocol. Bump on a breaking change to any entry-point shape. */
2
+ export const MODULE_PROTOCOL = 1;
3
+ /** Seat colors every game shares. Eight is the platform ceiling; the first four are fixed. */
4
+ export const SEAT_FILLS = ["#E8B33A", "#62A9F2", "#6FBF73", "#E3645B", "#4FC3B8", "#E060D8", "#C9B8F5", "#D8C9A0"];
5
+ export const playerCountsOf = (m) => m.playerCounts ?? Array.from({ length: m.maxPlayers - m.minPlayers + 1 }, (_, i) => m.minPlayers + i);
package/dist/rng.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ /** Deterministic PRNG (mulberry32). Same seed → same sequence, on every runtime. */
2
+ export interface Rng {
3
+ /** Float in [0, 1). */
4
+ float(): number;
5
+ /** Integer in [0, n). */
6
+ int(n: number): number;
7
+ /** Uniformly chosen element. Throws on empty input. */
8
+ pick<T>(items: readonly T[]): T;
9
+ /** New independent stream derived from this one (for per-game seeds). */
10
+ fork(): Rng;
11
+ }
12
+ export declare function createRng(seed: number): Rng;
package/dist/rng.js ADDED
@@ -0,0 +1,25 @@
1
+ export function createRng(seed) {
2
+ let a = seed >>> 0;
3
+ const float = () => {
4
+ a = (a + 0x6d2b79f5) >>> 0;
5
+ let t = a;
6
+ t = Math.imul(t ^ (t >>> 15), t | 1);
7
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
8
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
9
+ };
10
+ const rng = {
11
+ float,
12
+ int: (n) => {
13
+ if (!Number.isInteger(n) || n <= 0)
14
+ throw new Error(`int(n) needs a positive integer, got ${n}`);
15
+ return Math.floor(float() * n);
16
+ },
17
+ pick: (items) => {
18
+ if (items.length === 0)
19
+ throw new Error("pick() on empty array");
20
+ return items[Math.floor(float() * items.length)];
21
+ },
22
+ fork: () => createRng(Math.floor(float() * 4294967296)),
23
+ };
24
+ return rng;
25
+ }
@@ -0,0 +1,53 @@
1
+ import type { Rng } from "./rng.js";
2
+ export type Seat = number;
3
+ export type Terminal = {
4
+ over: false;
5
+ } | {
6
+ over: true;
7
+ winner: Seat | null;
8
+ reason?: string;
9
+ };
10
+ /**
11
+ * The contract every game implements. A game is a pure state machine:
12
+ * no framework imports, JSON-serialisable state, deterministic given
13
+ * (state, actions). A *turn* is a sequence of actions composed one at a
14
+ * time via `legalActions`; the same functions drive the browser UI,
15
+ * server-side validation, the self-play harness, and hot-seat.
16
+ */
17
+ export interface GameDefinition<S, A, O = Record<string, unknown>> {
18
+ id: string;
19
+ name: string;
20
+ minPlayers: number;
21
+ maxPlayers: number;
22
+ defaultOptions: O;
23
+ setup(args: {
24
+ options: O;
25
+ seed: number;
26
+ playerCount: number;
27
+ }): S;
28
+ currentSeat(state: S): Seat;
29
+ /** Actions that may legally be appended to the partial turn `soFar`. */
30
+ legalActions(state: S, seat: Seat, soFar: readonly A[]): A[];
31
+ /** Whether `soFar` is a complete turn that may be committed. */
32
+ canEndTurn(state: S, seat: Seat, soFar: readonly A[]): boolean;
33
+ /** Apply a complete, already-validated turn. Must not mutate `state`. */
34
+ applyTurn(state: S, seat: Seat, actions: readonly A[]): S;
35
+ isTerminal(state: S): Terminal;
36
+ /** What `seat` is allowed to see. Identity for perfect-information games. */
37
+ playerView(state: S, seat: Seat): S;
38
+ }
39
+ export interface BotContext<S, A> {
40
+ state: S;
41
+ seat: Seat;
42
+ /** Actions already chosen this turn. */
43
+ soFar: readonly A[];
44
+ legal: A[];
45
+ canEnd: boolean;
46
+ rng: Rng;
47
+ def: GameDefinition<S, A, unknown>;
48
+ }
49
+ /** Returns the next action, or "end" to commit the turn (only valid when canEnd). */
50
+ export interface Bot<S, A> {
51
+ name: string;
52
+ chooseAction(ctx: BotContext<S, A>): A | "end";
53
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Full-seed randomness shared by the dice-placement games (lifted 2026-10 for Islebound; Artifacts Inc, Backgammon and Alien Frontiers keep their own copies until next touched).
3
+ *
4
+ * The seed is up to 53 bits (the platform draws it from a CSPRNG). game-core's
5
+ * createRng keeps only `seed >>> 0`, so a client could enumerate 2^32 seeds
6
+ * against the visible opening and read the A/B/C pile order; a 32-bit dice
7
+ * state is pinned by a dozen observed rolls. Here every stream is a 128-bit
8
+ * xoshiro128** state filled from the whole seed plus a salt through a
9
+ * splitmix32 mixer, so neither attack is feasible (spec §2.7).
10
+ */
11
+ export type XoshiroState = [number, number, number, number];
12
+ /** Four 32-bit words from (seed hi, seed lo, salt) via splitmix32; never all zero. */
13
+ export declare function seedState(seed: number, salt: number): XoshiroState;
14
+ /** xoshiro128** (Blackman & Vigna): one 32-bit output; advances `s` in place (words stay unsigned). */
15
+ export declare function xoshiroNext(s: XoshiroState): number;
16
+ /** A float in [0, 1) from the stream. */
17
+ export declare const xoshiroFloat: (s: XoshiroState) => number;
@@ -0,0 +1,32 @@
1
+ /** Four 32-bit words from (seed hi, seed lo, salt) via splitmix32; never all zero. */
2
+ export function seedState(seed, salt) {
3
+ const hi = Math.floor(seed / 4294967296) >>> 0;
4
+ const lo = seed >>> 0;
5
+ let x = (hi ^ Math.imul(lo, 0x9e3779b9) ^ Math.imul(salt + 1, 0x85ebca6b)) >>> 0;
6
+ const mix = () => {
7
+ x = (x + 0x9e3779b9) >>> 0;
8
+ let z = x;
9
+ z = Math.imul(z ^ (z >>> 16), 0x21f0aaad);
10
+ z = Math.imul(z ^ (z >>> 15), 0x735a2d97);
11
+ return (z ^ (z >>> 15)) >>> 0;
12
+ };
13
+ const s = [(mix() ^ lo) >>> 0, (mix() ^ hi) >>> 0, (mix() ^ (salt >>> 0)) >>> 0, mix()];
14
+ if ((s[0] | s[1] | s[2] | s[3]) === 0)
15
+ s[3] = 1;
16
+ return s;
17
+ }
18
+ const rotl = (v, k) => ((v << k) | (v >>> (32 - k))) >>> 0;
19
+ /** xoshiro128** (Blackman & Vigna): one 32-bit output; advances `s` in place (words stay unsigned). */
20
+ export function xoshiroNext(s) {
21
+ const result = Math.imul(rotl(Math.imul(s[1], 5) >>> 0, 7), 9) >>> 0;
22
+ const t = (s[1] << 9) >>> 0;
23
+ s[2] = (s[2] ^ s[0]) >>> 0;
24
+ s[3] = (s[3] ^ s[1]) >>> 0;
25
+ s[1] = (s[1] ^ s[2]) >>> 0;
26
+ s[0] = (s[0] ^ s[3]) >>> 0;
27
+ s[2] = (s[2] ^ t) >>> 0;
28
+ s[3] = rotl(s[3], 11);
29
+ return result;
30
+ }
31
+ /** A float in [0, 1) from the stream. */
32
+ export const xoshiroFloat = (s) => xoshiroNext(s) / 4294967296;
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@phantomblip/game-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ },
12
+ "./bots": {
13
+ "types": "./dist/bots/index.d.ts",
14
+ "default": "./dist/bots/index.js"
15
+ },
16
+ "./harness": {
17
+ "types": "./dist/harness/index.d.ts",
18
+ "default": "./dist/harness/index.js"
19
+ }
20
+ },
21
+ "license": "MIT",
22
+ "engines": {
23
+ "node": ">=22"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "LICENSE",
28
+ "README.md",
29
+ "*.css"
30
+ ]
31
+ }