@hadoku/game-server 0.1.18 → 0.1.20

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/dist/config.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Runtime config for a game-server app — the PLATFORM half (w119 §C).
2
+ * Runtime config for a game-server app — the PLATFORM half (w119 §C, w120 §K).
3
3
  *
4
4
  * `createConfig` is a factory: every value it returns comes from the `env` object and `envPrefix`
5
5
  * it is called with (defaults: `process.env` and `'CARDTABLE'`), read when the factory RUNS, never
@@ -7,17 +7,25 @@
7
7
  * env objects, build two independent configs — which is what lets a second game on
8
8
  * `@hadoku/game-server` (bomberman) set its own `BOMBERMAN_*` variables instead of cardtable's.
9
9
  *
10
- * `export const CONFIG = createConfig()` below is cardtable's own instance, built the moment this
11
- * module is first imported — kept for every file that already does `import { CONFIG } from
12
- * '@hadoku/game-server/config'` and must keep working unchanged.
10
+ * `export const CONFIG` below is cardtable's own instance — kept for every file that already does
11
+ * `import { CONFIG } from '@wolffm/game-server/config'` and must keep working unchanged, field
12
+ * access and all (an `edge-auth.test.ts` case casts it to a mutable mapped type and swaps a field
13
+ * for the case, then restores it). w120 §K: it is no longer built "the moment this module is
14
+ * first imported" — {@link lazyConfig} defers the one `createConfig()` call (the tier floor's
15
+ * fail-closed check included) to the first property READ of any kind, which in production is the
16
+ * app's own boot (`apps/server/src/index.ts`'s first `CONFIG.host`), not merely the module graph
17
+ * happening to reach this file. Before this wave, importing `config.ts` for ANY reason — even a
18
+ * test three hops away that never touches a field — ran the whole factory as a side effect.
13
19
  *
14
20
  * What is NOT here any more: Magic-only settings (catalog, art mirror, draft bot, tournaments,
15
- * sounds, draft timing, the Forge-hosting envs, the room-stream envs) moved to
16
- * `games/magic/server/src/config.ts`'s `createMagicConfig`/`MAGIC_CONFIG` — a game with no Forge
17
- * engine has no business reading `CARDTABLE_DRAFT_BOT_PICK_MS`. Cardtable's deployment-only ArchiveBot
18
- * settings moved there too (not to `apps/server`): the only two readers,
19
- * `games/magic/server/src/plugins/{listen,routes}.ts`, are in the `magic` layer, which may not
20
- * import `apps/server` (the `site` layer) — see `scripts/layers/layers.json`'s allowed directions.
21
+ * sounds, draft timing, the Forge-hosting envs, the room-stream envs, `playWorkDir`) moved to
22
+ * `games/magic/server/src/config.ts`'s `createMagicConfig`/`MAGIC_CONFIG` (itself lazy the same
23
+ * way) — a game with no Forge engine has no business reading `CARDTABLE_DRAFT_BOT_PICK_MS`.
24
+ * Cardtable's deployment-only ArchiveBot settings moved to `apps/server/src/plugins/archivebot.ts`
25
+ * (w120 §K): its two readers, `games/magic/server/src/plugins/{listen,routes}.ts`, are in the
26
+ * `magic` layer, which may not import `apps/server` (the `site` layer) — see
27
+ * `scripts/layers/layers.json`'s allowed directions; the site plugin injects the settings onto
28
+ * `ctx.state.archivebot` instead.
21
29
  * Survey: `~/.cache/cardtable-manager/bomberman-survey-2026-11-16.md` §3 has the classification
22
30
  * with the original line numbers.
23
31
  */
@@ -150,22 +158,30 @@ export interface GameServerConfig {
150
158
  /** Everything a game-server app needs that is not specific to any one game (w119 §C). */
151
159
  export declare function createConfig(options?: CreateConfigOptions): GameServerConfig;
152
160
  /**
153
- * Cardtable's own instance, built once at this module's first import (every existing
154
- * `import { CONFIG } from '@wolffm/game-server/config'` keeps working unchanged). Not `as const`:
155
- * several test suites (`edge-auth.test.ts`) cast this to a mutable mapped type and swap individual
156
- * fields for a case, then restore them — that only works on a plain object, which this is.
161
+ * Wraps `factory` so it runs on first property access instead of as a side effect of merely
162
+ * importing the module that calls this (w120 §K). Until then, `target` is an empty, extensible
163
+ * plain object: `materialize()` calls `factory()` exactly once (cached in `built`) and then
164
+ * delegates every trap straight to the real result through `Reflect`, so after the first access
165
+ * `target` behaves exactly like `factory()`'s own return value always did — a live getter on it
166
+ * (`MagicConfig.playSeed`'s "read this each time") stays live, and a plain field stays a plain,
167
+ * writable, enumerable one. Exported for `games/magic/server/src/config.ts`'s `MAGIC_CONFIG`,
168
+ * which wants the same deferral.
169
+ */
170
+ export declare function lazyConfig<T extends object>(factory: () => T): T;
171
+ /**
172
+ * Cardtable's own instance (every existing `import { CONFIG } from '@wolffm/game-server/config'`
173
+ * keeps working unchanged) — built on first property access, not at import ({@link lazyConfig}).
174
+ * Not `as const`: several test suites (`edge-auth.test.ts`) cast this to a mutable mapped type and
175
+ * swap individual fields for a case, then restore them — that only works on a plain object, which
176
+ * this still is once materialized.
157
177
  */
158
178
  export declare const CONFIG: GameServerConfig;
159
179
  /**
160
- * Where a Forge match's run directories go (`CARDTABLE_PLAY_WORK_DIR`). Takes the
161
- * environment as an argument, as `play/host.ts`'s `jvmHostConfig` does, so a test
162
- * can point one host at its own directory.
163
- *
164
- * Stays here rather than moving to Magic's config (w119 §C survey calls this Forge-match specific)
165
- * because `play/local-jvm.ts` — out of this lane's ownership — imports it directly from this
166
- * module; moving it would break that file's import with no file in this wave's briefs allowed to
167
- * fix it. `local-jvm.ts` itself is written generic over "any JVM-hosted engine", so this is
168
- * defensible as the local JVM launcher's own platform-level default, not only Forge's.
180
+ * `webDir/index.html` — a function, not a plain constant, so reading it cannot itself be the
181
+ * thing that forces {@link CONFIG} to materialize merely by being imported (w120 §K: this was
182
+ * `export const INDEX_HTML = join(CONFIG.webDir, …)`, which read `CONFIG.webDir` the moment this
183
+ * module was first imported, defeating `lazyConfig` for every field, floor check included). Both
184
+ * readers (`apps/server/src/index.ts`, `games/magic/server/src/plugins/routes.ts`) call this from
185
+ * inside their own boot step, not at their own module's top level.
169
186
  */
170
- export declare function playWorkDir(env?: NodeJS.ProcessEnv): string;
171
- export declare const INDEX_HTML: string;
187
+ export declare function indexHtml(): string;
package/dist/config.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Runtime config for a game-server app — the PLATFORM half (w119 §C).
2
+ * Runtime config for a game-server app — the PLATFORM half (w119 §C, w120 §K).
3
3
  *
4
4
  * `createConfig` is a factory: every value it returns comes from the `env` object and `envPrefix`
5
5
  * it is called with (defaults: `process.env` and `'CARDTABLE'`), read when the factory RUNS, never
@@ -7,21 +7,28 @@
7
7
  * env objects, build two independent configs — which is what lets a second game on
8
8
  * `@hadoku/game-server` (bomberman) set its own `BOMBERMAN_*` variables instead of cardtable's.
9
9
  *
10
- * `export const CONFIG = createConfig()` below is cardtable's own instance, built the moment this
11
- * module is first imported — kept for every file that already does `import { CONFIG } from
12
- * '@hadoku/game-server/config'` and must keep working unchanged.
10
+ * `export const CONFIG` below is cardtable's own instance — kept for every file that already does
11
+ * `import { CONFIG } from '@wolffm/game-server/config'` and must keep working unchanged, field
12
+ * access and all (an `edge-auth.test.ts` case casts it to a mutable mapped type and swaps a field
13
+ * for the case, then restores it). w120 §K: it is no longer built "the moment this module is
14
+ * first imported" — {@link lazyConfig} defers the one `createConfig()` call (the tier floor's
15
+ * fail-closed check included) to the first property READ of any kind, which in production is the
16
+ * app's own boot (`apps/server/src/index.ts`'s first `CONFIG.host`), not merely the module graph
17
+ * happening to reach this file. Before this wave, importing `config.ts` for ANY reason — even a
18
+ * test three hops away that never touches a field — ran the whole factory as a side effect.
13
19
  *
14
20
  * What is NOT here any more: Magic-only settings (catalog, art mirror, draft bot, tournaments,
15
- * sounds, draft timing, the Forge-hosting envs, the room-stream envs) moved to
16
- * `games/magic/server/src/config.ts`'s `createMagicConfig`/`MAGIC_CONFIG` — a game with no Forge
17
- * engine has no business reading `CARDTABLE_DRAFT_BOT_PICK_MS`. Cardtable's deployment-only ArchiveBot
18
- * settings moved there too (not to `apps/server`): the only two readers,
19
- * `games/magic/server/src/plugins/{listen,routes}.ts`, are in the `magic` layer, which may not
20
- * import `apps/server` (the `site` layer) — see `scripts/layers/layers.json`'s allowed directions.
21
+ * sounds, draft timing, the Forge-hosting envs, the room-stream envs, `playWorkDir`) moved to
22
+ * `games/magic/server/src/config.ts`'s `createMagicConfig`/`MAGIC_CONFIG` (itself lazy the same
23
+ * way) — a game with no Forge engine has no business reading `CARDTABLE_DRAFT_BOT_PICK_MS`.
24
+ * Cardtable's deployment-only ArchiveBot settings moved to `apps/server/src/plugins/archivebot.ts`
25
+ * (w120 §K): its two readers, `games/magic/server/src/plugins/{listen,routes}.ts`, are in the
26
+ * `magic` layer, which may not import `apps/server` (the `site` layer) — see
27
+ * `scripts/layers/layers.json`'s allowed directions; the site plugin injects the settings onto
28
+ * `ctx.state.archivebot` instead.
21
29
  * Survey: `~/.cache/cardtable-manager/bomberman-survey-2026-11-16.md` §3 has the classification
22
30
  * with the original line numbers.
23
31
  */
24
- import { tmpdir } from 'node:os';
25
32
  import { fileURLToPath } from 'node:url';
26
33
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
27
34
  import { assertFloor as kernelAssertFloor } from '@wolffm/service-kernel/auth';
@@ -79,24 +86,43 @@ export function createConfig(options = {}) {
79
86
  };
80
87
  }
81
88
  /**
82
- * Cardtable's own instance, built once at this module's first import (every existing
83
- * `import { CONFIG } from '@wolffm/game-server/config'` keeps working unchanged). Not `as const`:
84
- * several test suites (`edge-auth.test.ts`) cast this to a mutable mapped type and swap individual
85
- * fields for a case, then restore them — that only works on a plain object, which this is.
89
+ * Wraps `factory` so it runs on first property access instead of as a side effect of merely
90
+ * importing the module that calls this (w120 §K). Until then, `target` is an empty, extensible
91
+ * plain object: `materialize()` calls `factory()` exactly once (cached in `built`) and then
92
+ * delegates every trap straight to the real result through `Reflect`, so after the first access
93
+ * `target` behaves exactly like `factory()`'s own return value always did — a live getter on it
94
+ * (`MagicConfig.playSeed`'s "read this each time") stays live, and a plain field stays a plain,
95
+ * writable, enumerable one. Exported for `games/magic/server/src/config.ts`'s `MAGIC_CONFIG`,
96
+ * which wants the same deferral.
86
97
  */
87
- export const CONFIG = createConfig();
98
+ export function lazyConfig(factory) {
99
+ let built;
100
+ const materialize = () => (built ??= factory());
101
+ return new Proxy({}, {
102
+ get: (_t, prop) => Reflect.get(materialize(), prop),
103
+ set: (_t, prop, value) => Reflect.set(materialize(), prop, value),
104
+ has: (_t, prop) => Reflect.has(materialize(), prop),
105
+ ownKeys: () => Reflect.ownKeys(materialize()),
106
+ getOwnPropertyDescriptor: (_t, prop) => Reflect.getOwnPropertyDescriptor(materialize(), prop),
107
+ deleteProperty: (_t, prop) => Reflect.deleteProperty(materialize(), prop),
108
+ });
109
+ }
88
110
  /**
89
- * Where a Forge match's run directories go (`CARDTABLE_PLAY_WORK_DIR`). Takes the
90
- * environment as an argument, as `play/host.ts`'s `jvmHostConfig` does, so a test
91
- * can point one host at its own directory.
92
- *
93
- * Stays here rather than moving to Magic's config (w119 §C survey calls this Forge-match specific)
94
- * because `play/local-jvm.ts` — out of this lane's ownership — imports it directly from this
95
- * module; moving it would break that file's import with no file in this wave's briefs allowed to
96
- * fix it. `local-jvm.ts` itself is written generic over "any JVM-hosted engine", so this is
97
- * defensible as the local JVM launcher's own platform-level default, not only Forge's.
111
+ * Cardtable's own instance (every existing `import { CONFIG } from '@wolffm/game-server/config'`
112
+ * keeps working unchanged) — built on first property access, not at import ({@link lazyConfig}).
113
+ * Not `as const`: several test suites (`edge-auth.test.ts`) cast this to a mutable mapped type and
114
+ * swap individual fields for a case, then restore them — that only works on a plain object, which
115
+ * this still is once materialized.
116
+ */
117
+ export const CONFIG = lazyConfig(createConfig);
118
+ /**
119
+ * `webDir/index.html` — a function, not a plain constant, so reading it cannot itself be the
120
+ * thing that forces {@link CONFIG} to materialize merely by being imported (w120 §K: this was
121
+ * `export const INDEX_HTML = join(CONFIG.webDir, …)`, which read `CONFIG.webDir` the moment this
122
+ * module was first imported, defeating `lazyConfig` for every field, floor check included). Both
123
+ * readers (`apps/server/src/index.ts`, `games/magic/server/src/plugins/routes.ts`) call this from
124
+ * inside their own boot step, not at their own module's top level.
98
125
  */
99
- export function playWorkDir(env = process.env) {
100
- return resolve(env.CARDTABLE_PLAY_WORK_DIR ?? join(tmpdir(), 'cardtable-play'));
126
+ export function indexHtml() {
127
+ return join(CONFIG.webDir, 'index.html');
101
128
  }
102
- export const INDEX_HTML = join(CONFIG.webDir, 'index.html');
@@ -66,6 +66,10 @@ function seatOpStatus(res, reason) {
66
66
  res.status(400).json({ error: 'not a seat this room has' });
67
67
  return;
68
68
  }
69
+ if (reason === 'no-bot-seat') {
70
+ res.status(409).json({ error: 'this room has no seat the bot can take' });
71
+ return;
72
+ }
69
73
  res.status(400).json({ error: reason });
70
74
  }
71
75
  /** Every one of the leader's three seat ops, per caller: a burst of 10, then one every 10 s — the same shape as a join attempt, spent only by a leader who is actually a member of the room (checked before this is asked). */
@@ -126,8 +126,6 @@ export interface SeatSpec {
126
126
  /** Forge's player name. Shown to both seats, so never an identity. */
127
127
  name: string;
128
128
  ai: boolean;
129
- /** `.dck` text, or null for a random Forge precon. */
130
- deck: string | null;
131
129
  }
132
130
  /**
133
131
  * A bot game: Forge's AI against Forge's AI, best of `bestOf`, each game drawn past `gameS` seconds
@@ -139,24 +137,27 @@ export interface HeadlessRules {
139
137
  gameS: number;
140
138
  }
141
139
  /**
142
- * What a match needs to start, generic over the game `G`'s own extra fields (w119 §C). Only
143
- * `seats` (its length) and {@link MatchSpec.headless} (its presence) are read by this file's own
144
- * coordinator — everything else below is opaque to it: spread onto `config.json` (`bridgeConfig`)
145
- * and kept whole in `JvmRecord`, never interpreted here.
140
+ * What a match needs to start, generic over the game `G`'s own extra fields (w119 §C, w120 §K).
141
+ * Only `seats` (its length) and {@link MatchSpec.headless} (its presence) are read by this file's
142
+ * own coordinator — everything else below is opaque to it: spread onto `config.json`
143
+ * (`bridgeConfig`) and kept whole in `JvmRecord`, never interpreted here.
146
144
  *
147
145
  * `G`'s default, `unknown` (so `KnownFields & unknown` simplifies back to `KnownFields`), keeps every existing bare `MatchSpec` (no type
148
- * argument) call site reading exactly the shape below — every field here was Forge-specific
149
- * before this wave, and still is; nothing is removed. One thing DID move (w119 §C.3): `seats` is
150
- * a plain array, not the old 2-tuple with "seat 0 is never AI" encoded in its type (that rule is
151
- * `socket.ts`'s/the bridge's to enforce, not this type's) — so `runtimes/relay-match.ts`'s
152
- * pod-sized, no-AI roster no longer needs `as unknown as MatchSpec` to fit it.
153
- *
154
- * A fuller split — moving `.dck` text, puzzle scenarios, hand smoothing and coin-toss rigging out
155
- * of this base into a Magic-only `G` — would need edits to files outside w119 §C's ownership
156
- * (`packages/game-server/src/play/placement/coordinator.ts`, and most of `games/magic/server/src/
157
- * play/*`'s own `MatchSpec` readers: `match.ts`, `botgames.ts`, `parked.ts`, `deck-colors.ts`,
158
- * `table-game.ts`, `art.ts`, `recording/{recorder,rebuild}.ts`, `match/registry.ts`,
159
- * `http/routes.ts`), so it is deferred; see the wave report.
146
+ * argument) call site reading exactly the shape below. w120 §K moved the four fields that were
147
+ * Forge-only in principle AND in practice — `.dck` text (off {@link SeatSpec}), puzzle scenarios
148
+ * (`scenario`/`skipOpening`/`restore`) and coin-toss rigging (`chooser`) — out of this base and
149
+ * into Magic's own `games/magic/server/src/play/forge-spec.ts` (`ForgeMatchSpec`/`ForgeSeatSpec`),
150
+ * which every Magic reader of a real match's spec now imports instead of this bare type:
151
+ * `match.ts` (`SeatSpecWithIdentity`/`MatchSpecWithIdentity`), `botgames.ts`, `parked.ts`,
152
+ * `deck-colors.ts`, `table-game.ts`, `art.ts`, `recording/{recorder,rebuild}.ts`,
153
+ * `match/{registry,forge-session}.ts`, `socket.ts`, `http/routes.ts`. `format`, `handSmoothing`,
154
+ * `clockMs`, `seed` and `headless` stay here: none of the four were named by the brief, each is
155
+ * arguably generic to any room-hosted game (a format id, a clock, a seed, a bot game), and
156
+ * `fixtures/toy-game/*` and `runtimes/relay-match.ts` build a bare `MatchSpec` directly, so moving
157
+ * them would widen this change past what was asked. `seats` is a plain array, not the old 2-tuple
158
+ * with "seat 0 is never AI" encoded in its type (that rule is `socket.ts`'s/the bridge's to
159
+ * enforce, not this type's) — so `runtimes/relay-match.ts`'s pod-sized, no-AI roster needs no
160
+ * `as unknown as MatchSpec` to fit it.
160
161
  */
161
162
  export type MatchSpec<G = unknown> = {
162
163
  /** Every seat this match starts with. */
@@ -166,31 +167,14 @@ export type MatchSpec<G = unknown> = {
166
167
  /** Seeds Forge's shuffles and the precon pick, for a repeatable test run. Omitted in play. */
167
168
  seed?: number;
168
169
  /**
169
- * Wave 33 §S — a TEST-only starting position: the text of a Forge puzzle file's
170
- * `[state]` section (`humanlife=`, `humanhand=`, `humanbattlefield=`,
171
- * `activephase=`, … — `GameState.parseLine` in the deploy tree's forge-build
172
- * cache has the full key list), with `human…` keys applying to seat 0 and
173
- * `ai…` keys to seat 1. `bridgeConfig` spreads it onto `config.json` like every
174
- * other `MatchSpec` field; `PlayBridge.java`'s `configFrom` reads it and
175
- * `BridgeGui.hostMatch` applies it from `HostedMatch`'s own start-game hook —
176
- * see that method's doc. Omitted in play: `socket.ts`'s `parseStartBody`
177
- * accepts this key only behind `CARDTABLE_PLAY_PROBE=1` and refuses it
178
- * otherwise, so production never sends one.
179
- */
180
- scenario?: string;
181
- /**
182
- * Start on {@link scenario}'s board with no coin toss and no mulligan — Forge's
183
- * own Puzzle game type, which skips both (`GameAction.startGame`). Set only by
184
- * `socket.ts` for a board-state room's own scenario; a test's scenario keeps the
185
- * ordinary opening its drivers click through.
170
+ * Opaque per-game resume text, opened and written by `G`'s own `GameAdapter.restoreSpec`
171
+ * (`game-adapter.ts`) — never read here. `fixtures/toy-game/rules.ts`'s `playToy` reads its own
172
+ * JSON-encoded checkpoint back from this; Magic's `ForgeMatchSpec.scenario`
173
+ * (`games/magic/server/src/play/forge-spec.ts`, w120 §K) is the Forge-shaped equivalent, kept
174
+ * apart from this generic field because `PlayBridge.java`'s `configFrom` reads `scenario` by
175
+ * that exact key, not whatever a non-Forge `G` happens to call its own resume data.
186
176
  */
187
- skipOpening?: boolean;
188
- /**
189
- * {@link scenario} is this match's own turn-start snapshot (`restoredSpec`): its board goes back
190
- * as it was, running no replacement effect ("enters tapped", "you may pay 2 life"), where a
191
- * board room's scenario plays each permanent's entry. Implies {@link skipOpening}.
192
- */
193
- restore?: boolean;
177
+ resumeData?: string;
194
178
  /**
195
179
  * The room's format id (`room/lobby.ts`'s `FormatId`): what a card-name ask is
196
180
  * narrowed to (`names.ts`). Inert in the JVM — `configFrom` never reads it — and
@@ -205,20 +189,6 @@ export type MatchSpec<G = unknown> = {
205
189
  * spec built directly, as the jvm suites build theirs, deals what it always did.
206
190
  */
207
191
  handSmoothing?: boolean;
208
- /**
209
- * Wave 71 §E — names the seat Forge asks to choose play or draw. Every game we
210
- * host is a fresh Forge `Match`, so Forge always treats it as the FIRST game of
211
- * that match and tosses a coin (`GameAction.determineFirstTurnPlayer`,
212
- * `forge/forge-game/src/main/java/forge/game/GameAction.java:2364-2416`) rather
213
- * than asking the previous loser — this field is how the room still names that
214
- * player. `PlayBridge.java`'s `startMatch` rigs the coin toss so the named seat
215
- * is the one Forge asks (`SeatGui`'s `updateButtons` with `label1:'Play',
216
- * label2:'Draw'`), which makes the published `coinToss.winner` (`match.ts:1055`)
217
- * that seat too — the client's existing flip/notice needs no change. Omitted:
218
- * byte-identical to today, an unrigged coin toss. Never set alongside a change
219
- * to `forge/` — a fork change is a jar switch, and that switch is the operator's.
220
- */
221
- chooser?: 0 | 1;
222
192
  /**
223
193
  * The chess clock: each seat's time left, in ms, when this game starts — a room
224
194
  * with the clock on carries what the series' last game left (`play/clock.ts`).
@@ -161,8 +161,14 @@ export declare function defaultBridgeCache(env?: NodeJS.ProcessEnv): string;
161
161
  /**
162
162
  * Resolve the JVM host's configuration, or say exactly what is missing. `bridgeSource` is the game's
163
163
  * own bridge (Magic's is `@hadoku/magic-server/root`'s `BRIDGE_SOURCE`): the platform knows no game's tree.
164
+ *
165
+ * `workDir`, when given, is INJECTED by the caller rather than read here (w120 §K: Magic's own
166
+ * `games/magic/server/src/config.ts` has its own `playWorkDir`, which every Magic caller —
167
+ * `plugins/library.ts`, `play/scenario.ts`, `play/recording/rebuild.ts` — passes through this
168
+ * param). Omitted, this file falls back to its own generic default, unchanged from before this
169
+ * param existed, for every other caller (scripts, the UI's jvm harness) that passes none.
164
170
  */
165
- export declare function jvmHostConfig(bridgeSource: string, env?: NodeJS.ProcessEnv): JvmAvailability;
171
+ export declare function jvmHostConfig(bridgeSource: string, env?: NodeJS.ProcessEnv, workDir?: string): JvmAvailability;
166
172
  /**
167
173
  * A compiled bridge nobody has launched for this long is removed when the next
168
174
  * one is compiled. Far past `ORPHAN_MAX_MS`, so no JVM that could still load a
@@ -76,10 +76,9 @@
76
76
  import { spawn, spawnSync } from 'node:child_process';
77
77
  import { createHash, randomBytes } from 'node:crypto';
78
78
  import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync, } from 'node:fs';
79
- import { homedir } from 'node:os';
79
+ import { homedir, tmpdir } from 'node:os';
80
80
  import { basename, dirname, join, resolve } from 'node:path';
81
81
  import { createInterface } from 'node:readline';
82
- import { playWorkDir } from '../config.js';
83
82
  import { bridgeDiagnostics } from './diagnostics.js';
84
83
  import { CRASH_MARKER, IN_FIFO, JVM_TMP_DIR, OUT_FIFO, PID_POLL_MS, REAP_CONFIRM_MS, cwdIsUnder, defaultJava, killPid, makeFifos, openJvmIo, pidIsRunning, pidIsStandingIn, pidIsStandingInRun, positiveInt, processCwds, pruneCrashRecords, runDirs, sleepSync, wrapChildProcess, } from './engine-runtime.js';
85
84
  /**
@@ -135,8 +134,14 @@ export function defaultBridgeCache(env = process.env) {
135
134
  /**
136
135
  * Resolve the JVM host's configuration, or say exactly what is missing. `bridgeSource` is the game's
137
136
  * own bridge (Magic's is `@hadoku/magic-server/root`'s `BRIDGE_SOURCE`): the platform knows no game's tree.
137
+ *
138
+ * `workDir`, when given, is INJECTED by the caller rather than read here (w120 §K: Magic's own
139
+ * `games/magic/server/src/config.ts` has its own `playWorkDir`, which every Magic caller —
140
+ * `plugins/library.ts`, `play/scenario.ts`, `play/recording/rebuild.ts` — passes through this
141
+ * param). Omitted, this file falls back to its own generic default, unchanged from before this
142
+ * param existed, for every other caller (scripts, the UI's jvm harness) that passes none.
138
143
  */
139
- export function jvmHostConfig(bridgeSource, env = process.env) {
144
+ export function jvmHostConfig(bridgeSource, env = process.env, workDir) {
140
145
  const jar = env.CARDTABLE_FORGE_JAR ?? '';
141
146
  const res = env.CARDTABLE_FORGE_RES ?? '';
142
147
  if (jar === '')
@@ -156,7 +161,7 @@ export function jvmHostConfig(bridgeSource, env = process.env) {
156
161
  java: env.CARDTABLE_JAVA ?? defaultJava(env),
157
162
  jar: resolve(jar),
158
163
  res: resolve(res),
159
- workDir: playWorkDir(env),
164
+ workDir: workDir ?? resolve(env.CARDTABLE_PLAY_WORK_DIR ?? join(tmpdir(), 'cardtable-play')),
160
165
  jvmOpts: (env.CARDTABLE_PLAY_JVM_OPTS ?? '').split(/\s+/).filter((s) => s !== ''),
161
166
  bridgeSource,
162
167
  bridgeCache: defaultBridgeCache(env),
@@ -28,7 +28,7 @@ import { RelaySession } from './relay.js';
28
28
  * like this one needs no `as unknown as MatchSpec` to fit it any more.
29
29
  */
30
30
  function relaySpec(seatCount) {
31
- const seats = Array.from({ length: seatCount }, (_, seat) => ({ ai: false, name: `Seat ${seat}`, deck: null }));
31
+ const seats = Array.from({ length: seatCount }, (_, seat) => ({ ai: false, name: `Seat ${seat}` }));
32
32
  return { seats };
33
33
  }
34
34
  /**
@@ -166,6 +166,19 @@ export interface RoomTypeHooks<G, I extends RoomCreateInput = RoomCreateInput> {
166
166
  seatsFixed(room: LobbyRoom<G>): boolean;
167
167
  /** Whether the AI and closed seats are the event's, not anybody's to change. */
168
168
  fieldFixed?(room: LobbyRoom<G>): boolean;
169
+ /**
170
+ * The leader's three atomic ops' fallback seat lineup for a room this type says does NOT
171
+ * `usesSeats` — wave 120 §S2: a 1v1 room's one `RoomTable` IS its seats, so the leader's
172
+ * remove, lower-capacity AND bot-replace reach it too, through the same table `gameSeatsOf`'s
173
+ * own non-pod branch already reads, rather than the room's own (unused, always-empty)
174
+ * `room.seats`. Undefined declines: the plain `not-draft` every other seat op already answers.
175
+ * `botReplacesHuman` still checks the target's own `supportsBot` before it does anything with
176
+ * it — a 1v1 room's table is not offered an AI seat (see `GenericSeatTarget.supportsBot`'s own
177
+ * header), but the route now answers that truthfully (`'no-bot-seat'`), never the `not-draft`
178
+ * that would wrongly say this room does not seat through game seats at all. Not consulted for
179
+ * `sitSeat`/`standSeat`/`aiSeat`/`closeSeat`, which stay gated on `usesSeats` exactly as before.
180
+ */
181
+ extraSeatTarget?(room: LobbyRoom<G>): GenericSeatTarget | undefined;
169
182
  /** The most game seats the room grows to. */
170
183
  seatCeiling(room: LobbyRoom<G>): number;
171
184
  /** The game seats grown to hold `seat`. */
@@ -188,6 +201,23 @@ export interface RoomTypeHooks<G, I extends RoomCreateInput = RoomCreateInput> {
188
201
  */
189
202
  subPlaceOf?(room: LobbyRoom<G>, rest: string): boolean;
190
203
  }
204
+ /**
205
+ * A generic seat lineup the leader's atomic ops can read and write — `room.seats` itself (every
206
+ * room type that `usesSeats`), or, via `RoomTypeHooks.extraSeatTarget`, wherever ELSE a type that
207
+ * does NOT keeps its seating (wave 120 §S2: a 1v1 room's one `RoomTable`).
208
+ */
209
+ export interface GenericSeatTarget {
210
+ read(): GameSeats;
211
+ write(seats: GameSeats): void;
212
+ /**
213
+ * Whether this lineup has an AI-occupies-a-seat idea at all — `botReplacesHuman`'s own gate,
214
+ * checked before it ever picks a seat. `room.seats` always does (`AI_SEAT`). A 1v1 room's one
215
+ * table does not (wave 120 §S2): `false` here is what lets that route answer a truthful,
216
+ * specific refusal (`'no-bot-seat'`) instead of the plain `not-draft` a room that does not seat
217
+ * through game seats AT ALL answers — a 1v1 room now does, for the other two ops.
218
+ */
219
+ supportsBot: boolean;
220
+ }
191
221
  /** The fewest seats a room is left with when its seats are closed: one player and one more. */
192
222
  export declare const MIN_OPEN_SEATS = 2;
193
223
  export type CreateResult<V> = {
@@ -278,7 +308,7 @@ export type BotReplacesHumanResult<V> = {
278
308
  evicted: string | null;
279
309
  } | {
280
310
  ok: false;
281
- reason: 'no-room' | 'not-member' | 'not-leader' | 'not-draft' | 'not-lobby' | 'historical' | 'bad-seat';
311
+ reason: 'no-room' | 'not-member' | 'not-leader' | 'not-draft' | 'not-lobby' | 'historical' | 'bad-seat' | 'no-bot-seat';
282
312
  };
283
313
  export interface AvatarChange {
284
314
  roomId: string;
@@ -445,10 +475,12 @@ export declare class RoomLobby<V extends PlatformRoomView, I extends RoomCreateI
445
475
  * Idempotent: a target who holds none is still answered `ok`. Never touches membership — they
446
476
  * stay in the room, watching (this file's own "a player or a spectator, never neither",
447
477
  * 2026-11-02). `targetId` need not be `memberId`; this is the leader acting on someone else,
448
- * which is exactly what `standSeat` (self-service) cannot do. `leaveGameSeat` already IS this
449
- * operation's contract — `@wolffm/rooms-protocol@0.45.95`'s own `removeFromSeat(table,
450
- * participantId)` is `unseatParticipant(table, participantId, { hold: false })`, the same shape —
451
- * so no `seat-eviction.ts` entry exists for this one; see that file's header for the two that do.
478
+ * which is exactly what `standSeat` (self-service) cannot do. Resolved through `#seatOpRoom`
479
+ * (wave 120 §S2), not `#seatRoom`: a room that does not `usesSeats` gets one more chance at
480
+ * `hooks.extraSeatTarget` before the plain `not-draft` — a 1v1 room's one table, for instance.
481
+ * The library's own `removeFromSeat(table, participantId)` is `unseatParticipant(table,
482
+ * participantId, { hold: false })`, the same shape a plain null-out already was, so the target
483
+ * array is mutated directly here rather than through `seat-table-adapter.ts`.
452
484
  */
453
485
  removeFromSeat(roomId: string, memberId: string, targetId: string): RemoveFromSeatResult<V>;
454
486
  /**
@@ -459,11 +491,17 @@ export declare class RoomLobby<V extends PlatformRoomView, I extends RoomCreateI
459
491
  * default `memberSeats` view reads them as open same as any other non-member string — a room
460
492
  * type that wants its view to tell "AI"/"closed" from "open" gives itself its own `seatsView`
461
493
  * (same as Magic's pod view carries AI through `podAi`, a field of its own, not this one's).
494
+ * Resolved through `#seatOpRoom` (wave 120 §S2): see `removeFromSeat`'s header.
462
495
  */
463
496
  lowerSeatCapacity(roomId: string, memberId: string, count: number): LowerSeatCapacityResult<V>;
464
497
  /**
465
498
  * The leader puts the AI in `seat`, evicting whoever holds it first — a human to the spectator
466
- * row — instead of `aiSeat`'s refusal on an occupied seat. Already the AI's: a no-op.
499
+ * row — instead of `aiSeat`'s refusal on an occupied seat. Already the AI's: a no-op. Resolved
500
+ * through `#seatOpRoom` (wave 120 §S2): see `removeFromSeat`'s header. A room whose target
501
+ * does not `supportsBot` (a 1v1 room's one table — no AI-occupies-a-seat idea of its own) is
502
+ * refused `'no-bot-seat'`, a truthful, specific reason — never the plain `not-draft`, which
503
+ * would wrongly say this room does not seat through game seats at all (it does, for the other
504
+ * two ops), and never an invented AI seat the table has nowhere to show.
467
505
  */
468
506
  botReplacesHuman(roomId: string, memberId: string, seat: number): BotReplacesHumanResult<V>;
469
507
  /**
@@ -45,7 +45,7 @@ import { addRoomMember, isMemberReady, isRoomMember, passwordAdmits, removeRoomM
45
45
  import { makeSecret, mintRoomId } from "./provisioning.js";
46
46
  import { AI_SEAT, CLOSED_SEAT, leaveGameSeat, memberSeats, setGameSeat, takeGameSeat } from "./record.js";
47
47
  import { isOfferedRoom, isSweepableRoom, NO_BUSY_HOOK, sortRoomsByCreation } from "./room-list.js";
48
- import { lowerCapacity, replaceWithBot } from "./seat-eviction.js";
48
+ import { lowerCapacity, replaceWithBot } from "./seat-table-adapter.js";
49
49
  import { watchpartyRoomId } from "./watchparty-link.js";
50
50
  /** The fewest seats a room is left with when its seats are closed: one player and one more. */
51
51
  export const MIN_OPEN_SEATS = 2;
@@ -606,6 +606,43 @@ export class RoomLobby {
606
606
  #inReach(room, hooks, seat) {
607
607
  return Number.isInteger(seat) && seat >= 0 && seat < hooks.seatCeiling(room) && seat <= room.seats.length;
608
608
  }
609
+ /**
610
+ * `removeFromSeat`/`lowerSeatCapacity`/`botReplacesHuman`'s own resolver (wave 120 §S2) — the
611
+ * same checks as `#seatRoom`, but a room that does NOT `usesSeats` gets one more chance:
612
+ * `hooks.extraSeatTarget`, a type's OWN seat lineup for just these three ops (a 1v1 room's one
613
+ * table). `generic` tells the caller whether `target` IS `room.seats` (so `trimSeats` applies)
614
+ * or the type's own stand-in (which trims nothing — a fixed-size table, never grown or shrunk
615
+ * this way). `room.seats` always `supportsBot` (its `AI_SEAT` marker); a type's own stand-in
616
+ * says for itself.
617
+ */
618
+ #seatOpRoom(roomId, memberId) {
619
+ const room = this.#rooms.get(roomId);
620
+ if (room === undefined)
621
+ return { refused: 'no-room' };
622
+ if (!isRoomMember(room, memberId))
623
+ return { refused: 'not-member' };
624
+ const hooks = this.hooksOf(room);
625
+ if (hooks.usesSeats(room)) {
626
+ if (hooks.seatsFixed(room))
627
+ return { refused: 'not-lobby' };
628
+ return {
629
+ room,
630
+ hooks,
631
+ generic: true,
632
+ target: {
633
+ read: () => room.seats,
634
+ write: (seats) => {
635
+ room.seats = seats;
636
+ },
637
+ supportsBot: true,
638
+ },
639
+ };
640
+ }
641
+ const target = hooks.extraSeatTarget?.(room);
642
+ if (target === undefined)
643
+ return { refused: 'not-draft' };
644
+ return { room, hooks, generic: false, target };
645
+ }
609
646
  /**
610
647
  * Take a game seat. `seat` absent takes the first open one (their own counts as open), growing the
611
648
  * room by one past the last when none is; given, it must be open and in reach. Moves the caller from
@@ -715,10 +752,12 @@ export class RoomLobby {
715
752
  * Idempotent: a target who holds none is still answered `ok`. Never touches membership — they
716
753
  * stay in the room, watching (this file's own "a player or a spectator, never neither",
717
754
  * 2026-11-02). `targetId` need not be `memberId`; this is the leader acting on someone else,
718
- * which is exactly what `standSeat` (self-service) cannot do. `leaveGameSeat` already IS this
719
- * operation's contract — `@wolffm/rooms-protocol@0.45.95`'s own `removeFromSeat(table,
720
- * participantId)` is `unseatParticipant(table, participantId, { hold: false })`, the same shape —
721
- * so no `seat-eviction.ts` entry exists for this one; see that file's header for the two that do.
755
+ * which is exactly what `standSeat` (self-service) cannot do. Resolved through `#seatOpRoom`
756
+ * (wave 120 §S2), not `#seatRoom`: a room that does not `usesSeats` gets one more chance at
757
+ * `hooks.extraSeatTarget` before the plain `not-draft` — a 1v1 room's one table, for instance.
758
+ * The library's own `removeFromSeat(table, participantId)` is `unseatParticipant(table,
759
+ * participantId, { hold: false })`, the same shape a plain null-out already was, so the target
760
+ * array is mutated directly here rather than through `seat-table-adapter.ts`.
722
761
  */
723
762
  removeFromSeat(roomId, memberId, targetId) {
724
763
  const room = this.#rooms.get(roomId);
@@ -730,13 +769,17 @@ export class RoomLobby {
730
769
  return { ok: false, reason: 'not-leader' };
731
770
  if (!isRoomMember(room, targetId))
732
771
  return { ok: false, reason: 'target-not-member' };
733
- const found = this.#seatRoom(roomId, memberId);
772
+ const found = this.#seatOpRoom(roomId, memberId);
734
773
  if ('refused' in found)
735
774
  return { ok: false, reason: found.refused };
736
- const { room: r, hooks } = found;
737
- if (!leaveGameSeat(r, targetId))
775
+ const { room: r, hooks, target, generic } = found;
776
+ const seats = target.read();
777
+ const at = seats.indexOf(targetId);
778
+ if (at === -1)
738
779
  return { ok: true, room: this.view(r) };
739
- hooks.trimSeats(r);
780
+ target.write(seats.map((s, i) => (i === at ? null : s)));
781
+ if (generic)
782
+ hooks.trimSeats(r);
740
783
  this.persist(r);
741
784
  this.log({ event: 'seat-removed-by-leader', roomId, memberId, targetId });
742
785
  hooks.seatsChanged?.(r);
@@ -750,6 +793,7 @@ export class RoomLobby {
750
793
  * default `memberSeats` view reads them as open same as any other non-member string — a room
751
794
  * type that wants its view to tell "AI"/"closed" from "open" gives itself its own `seatsView`
752
795
  * (same as Magic's pod view carries AI through `podAi`, a field of its own, not this one's).
796
+ * Resolved through `#seatOpRoom` (wave 120 §S2): see `removeFromSeat`'s header.
753
797
  */
754
798
  lowerSeatCapacity(roomId, memberId, count) {
755
799
  const room = this.#rooms.get(roomId);
@@ -759,19 +803,21 @@ export class RoomLobby {
759
803
  return { ok: false, reason: 'not-member' };
760
804
  if (room.leader !== memberId)
761
805
  return { ok: false, reason: 'not-leader' };
762
- const found = this.#seatRoom(roomId, memberId);
806
+ const found = this.#seatOpRoom(roomId, memberId);
763
807
  if ('refused' in found)
764
808
  return { ok: false, reason: found.refused };
765
- const { room: r, hooks } = found;
809
+ const { room: r, hooks, target, generic } = found;
766
810
  if (hooks.fieldFixed?.(r) === true)
767
811
  return { ok: false, reason: 'historical' };
768
812
  if (!Number.isInteger(count) || count < MIN_OPEN_SEATS)
769
813
  return { ok: false, reason: 'too-few' };
770
- const { seats, evicted } = lowerCapacity(r.seats, count);
771
- if (evicted.length === 0 && seats.every((s, i) => s === r.seats[i]))
814
+ const before = target.read();
815
+ const { seats, evicted } = lowerCapacity(before, count);
816
+ if (evicted.length === 0 && seats.every((s, i) => s === before[i]))
772
817
  return { ok: true, room: this.view(r), evicted };
773
- r.seats = seats;
774
- hooks.trimSeats(r);
818
+ target.write(seats);
819
+ if (generic)
820
+ hooks.trimSeats(r);
775
821
  this.persist(r);
776
822
  this.log({ event: 'seat-capacity-lowered', roomId, memberId, count, evicted: evicted.length });
777
823
  hooks.seatsChanged?.(r);
@@ -779,7 +825,12 @@ export class RoomLobby {
779
825
  }
780
826
  /**
781
827
  * The leader puts the AI in `seat`, evicting whoever holds it first — a human to the spectator
782
- * row — instead of `aiSeat`'s refusal on an occupied seat. Already the AI's: a no-op.
828
+ * row — instead of `aiSeat`'s refusal on an occupied seat. Already the AI's: a no-op. Resolved
829
+ * through `#seatOpRoom` (wave 120 §S2): see `removeFromSeat`'s header. A room whose target
830
+ * does not `supportsBot` (a 1v1 room's one table — no AI-occupies-a-seat idea of its own) is
831
+ * refused `'no-bot-seat'`, a truthful, specific reason — never the plain `not-draft`, which
832
+ * would wrongly say this room does not seat through game seats at all (it does, for the other
833
+ * two ops), and never an invented AI seat the table has nowhere to show.
783
834
  */
784
835
  botReplacesHuman(roomId, memberId, seat) {
785
836
  const room = this.#rooms.get(roomId);
@@ -789,20 +840,24 @@ export class RoomLobby {
789
840
  return { ok: false, reason: 'not-member' };
790
841
  if (room.leader !== memberId)
791
842
  return { ok: false, reason: 'not-leader' };
792
- const found = this.#seatRoom(roomId, memberId);
843
+ const found = this.#seatOpRoom(roomId, memberId);
793
844
  if ('refused' in found)
794
845
  return { ok: false, reason: found.refused };
795
- const { room: r, hooks } = found;
846
+ const { room: r, hooks, target, generic } = found;
796
847
  if (hooks.fieldFixed?.(r) === true)
797
848
  return { ok: false, reason: 'historical' };
849
+ if (!target.supportsBot)
850
+ return { ok: false, reason: 'no-bot-seat' };
798
851
  if (!this.#inReach(r, hooks, seat) || seat >= r.seats.length)
799
852
  return { ok: false, reason: 'bad-seat' };
800
- const { seats, evicted } = replaceWithBot(r.seats, seat);
801
- if (evicted === null && seats[seat] === r.seats[seat])
853
+ const before = target.read();
854
+ const { seats, evicted } = replaceWithBot(before, seat);
855
+ if (evicted === null && seats[seat] === before[seat])
802
856
  return { ok: true, room: this.view(r), evicted: null };
803
- r.seats = seats;
857
+ target.write(seats);
804
858
  hooks.aiSeated?.(r, seat, true);
805
- hooks.trimSeats(r);
859
+ if (generic)
860
+ hooks.trimSeats(r);
806
861
  this.persist(r);
807
862
  this.log({ event: 'seat-bot-replaced-human', roomId, memberId, seat, evicted: evicted !== null });
808
863
  hooks.seatsChanged?.(r);
@@ -0,0 +1,25 @@
1
+ import { type GameSeats } from './record.js';
2
+ /**
3
+ * Close seats from the TOP down until `count` are open, evicting any occupant first (a human —
4
+ * returned, for the caller to tell they are now watching — an AI simply gone). Mirrors the
5
+ * library's own `setSeatCapacity`, which this does NOT call: that function TRUNCATES
6
+ * `seats.length`, while cardtable keeps every seat's index stable (a closed seat stays addressable
7
+ * — P2's op-mapping gap, "composing `closeSeat` plus eviction is the likely fit"). Eviction is
8
+ * always highest seat first, never a caller-chosen one — same reasoning as `setSeatCapacity`'s own
9
+ * doc. A seat already closed is skipped, never counted against `count` twice.
10
+ */
11
+ export declare function lowerCapacity(seats: GameSeats, count: number): {
12
+ seats: GameSeats;
13
+ evicted: readonly string[];
14
+ };
15
+ /**
16
+ * The AI takes `seat`, evicting its human occupant first (returned, for the caller to tell they
17
+ * are now watching). Addressed by SEAT, not by the human's id — cardtable's leader picks a seat,
18
+ * empty or occupied, the same way `aiSeat` always has, and an empty seat has no occupant id to
19
+ * address by. P2's own op mapping: `occupantOf` + `replaceWithBot` for an occupied seat,
20
+ * `seatBot` for an empty one (the library's `replaceWithBot` answers null with nobody to replace).
21
+ */
22
+ export declare function replaceWithBot(seats: GameSeats, seat: number): {
23
+ seats: GameSeats;
24
+ evicted: string | null;
25
+ };
@@ -0,0 +1,87 @@
1
+ /**
2
+ * `GameSeats` (`record.ts`'s plain `(string | null)[]` with `AI_SEAT`/`CLOSED_SEAT` markers in
3
+ * place), as a `@wolffm/rooms-protocol` `SeatTable` the library's own ops can act on — and back.
4
+ * Replaces wave 119 §S's own hand-rolled array code for these two ops, now that
5
+ * `@wolffm/rooms-protocol@0.45.99` (watchparty P2, wave 120) gives `SeatTable` the closed-seat
6
+ * idea cardtable's own array always had:
7
+ * `closeSeat`/`isClosed`, and `Seat.closed?: boolean` that keeps a seat in place — never truncating
8
+ * `seats.length` — exactly the shape `GameSeats` already stores on disk and sends over the wire.
9
+ *
10
+ * Stateless and discarded after each call: a `GameSeats` array has never carried a reservation or
11
+ * a remembered seat (nothing to lose by building a fresh `SeatTable` with `remembered: {}`,
12
+ * `reservations: {}`, `reservationTtlMs: 0` each time), and the round trip back to `GameSeats`
13
+ * drops them again — so `record.ts`'s stored and wire shape is UNCHANGED by this file existing;
14
+ * only the two operations that used to be hand-rolled array code now call the published functions.
15
+ */
16
+ import { closeSeat, isClosed, occupantOf, removeFromSeat, replaceWithBot as libReplaceWithBot, seatBot, unseatBot } from '@wolffm/rooms-protocol';
17
+ import { AI_SEAT, CLOSED_SEAT } from "./record.js";
18
+ function gameSeatsToTable(seats) {
19
+ return {
20
+ capacity: seats.length,
21
+ seats: seats.map((holder, id) => ({
22
+ id,
23
+ occupant: holder === null || holder === CLOSED_SEAT ? null : holder === AI_SEAT ? { kind: 'bot', botId: AI_SEAT } : { kind: 'human', participantId: holder },
24
+ ...(holder === CLOSED_SEAT ? { closed: true } : {}),
25
+ })),
26
+ remembered: {},
27
+ reservations: {},
28
+ reservationTtlMs: 0,
29
+ };
30
+ }
31
+ function tableToGameSeats(table) {
32
+ return table.seats.map((seat) => {
33
+ if (seat.closed === true)
34
+ return CLOSED_SEAT;
35
+ if (seat.occupant === null)
36
+ return null;
37
+ return seat.occupant.kind === 'bot' ? AI_SEAT : seat.occupant.participantId;
38
+ });
39
+ }
40
+ /**
41
+ * Close seats from the TOP down until `count` are open, evicting any occupant first (a human —
42
+ * returned, for the caller to tell they are now watching — an AI simply gone). Mirrors the
43
+ * library's own `setSeatCapacity`, which this does NOT call: that function TRUNCATES
44
+ * `seats.length`, while cardtable keeps every seat's index stable (a closed seat stays addressable
45
+ * — P2's op-mapping gap, "composing `closeSeat` plus eviction is the likely fit"). Eviction is
46
+ * always highest seat first, never a caller-chosen one — same reasoning as `setSeatCapacity`'s own
47
+ * doc. A seat already closed is skipped, never counted against `count` twice.
48
+ */
49
+ export function lowerCapacity(seats, count) {
50
+ const table = gameSeatsToTable(seats);
51
+ const evicted = [];
52
+ let open = table.seats.filter((s) => s.closed !== true).length;
53
+ for (let id = table.seats.length - 1; id >= 0 && open > count; id--) {
54
+ if (isClosed(table, id))
55
+ continue;
56
+ const occupant = occupantOf(table, id);
57
+ if (occupant?.kind === 'human') {
58
+ removeFromSeat(table, occupant.participantId);
59
+ evicted.push(occupant.participantId);
60
+ }
61
+ else if (occupant?.kind === 'bot') {
62
+ unseatBot(table, id);
63
+ }
64
+ closeSeat(table, id);
65
+ open--;
66
+ }
67
+ return { seats: tableToGameSeats(table), evicted };
68
+ }
69
+ /**
70
+ * The AI takes `seat`, evicting its human occupant first (returned, for the caller to tell they
71
+ * are now watching). Addressed by SEAT, not by the human's id — cardtable's leader picks a seat,
72
+ * empty or occupied, the same way `aiSeat` always has, and an empty seat has no occupant id to
73
+ * address by. P2's own op mapping: `occupantOf` + `replaceWithBot` for an occupied seat,
74
+ * `seatBot` for an empty one (the library's `replaceWithBot` answers null with nobody to replace).
75
+ */
76
+ export function replaceWithBot(seats, seat) {
77
+ const table = gameSeatsToTable(seats);
78
+ const occupant = occupantOf(table, seat);
79
+ if (occupant?.kind === 'bot')
80
+ return { seats, evicted: null };
81
+ if (occupant?.kind === 'human') {
82
+ libReplaceWithBot(table, occupant.participantId);
83
+ return { seats: tableToGameSeats(table), evicted: occupant.participantId };
84
+ }
85
+ seatBot(table, seat);
86
+ return { seats: tableToGameSeats(table), evicted: null };
87
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/game-server",
3
- "version": "0.1.18",
4
- "gitHead": "028a4236d9e2a79e34c820620c566e20c7174d5c",
3
+ "version": "0.1.20",
4
+ "gitHead": "368a12a609c1d1ebb096c5b78e18ca64a098c4a6",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "The server parts any hosted game shares, above the kernel: the app config and edge auth, the room core (identity, seats, sessions, membership, the room list, the generic room routes), match hosting (the host contract, local and remote JVMs, placement, the start queue, recordings, the in-process and relay runtimes), streams, erase, telemetry and usage. Knows no game; Magic plugs in from apps/server. MIT; imports only node built-ins, express, socket.io, @wolffm/* and the platform packages.",
@@ -16,9 +16,9 @@
16
16
  "play/remote/"
17
17
  ],
18
18
  "dependencies": {
19
- "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.18",
20
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.18",
21
- "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.51",
19
+ "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.20",
20
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.20",
21
+ "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.53",
22
22
  "@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.1.27",
23
23
  "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.99",
24
24
  "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.99",
@@ -1,54 +0,0 @@
1
- /**
2
- * The leader's three atomic "evict, then act" seat operations (wave 119 §S), isolated here so a
3
- * future swap is a one-file edit.
4
- *
5
- * `@wolffm/rooms-protocol@0.45.95` (watchparty d02dbdfb, published while this lane ran) gives its
6
- * own `SeatTable` the same three operations: `removeFromSeat(table, participantId)`,
7
- * `replaceWithBot(table, participantId)`, and the pre-existing `setSeatCapacity(table, capacity)`
8
- * for "lower capacity under occupants, evicting someone" — its own doc calls that the one and
9
- * only way to do it on a `SeatTable`.
10
- *
11
- * Cardtable's rooms are NOT on `SeatTable`. They are `GameSeats` (`record.ts`): a plain
12
- * `(string | null)[]` with `AI_SEAT`/`CLOSED_SEAT` markers IN PLACE, because a leader can close
13
- * one specific seat (`CLOSED_SEAT`, `closeSeat`) while every seat around it, including a HIGHER
14
- * one, stays open — Magic's draft pods do this (`pods.ts`'s `POD_CLOSED`). `SeatTable.capacity`
15
- * has no such idea: its own `setSeatCapacity` doc says so explicitly — "this table has no concept
16
- * of a specific seat that is closed while a higher one stays open… inventing one would be a
17
- * second notion of capacity." That is not a gap to fix here; it is a different, deliberate design
18
- * for a different shape of room, and reconciling the two (or deciding cardtable keeps its own) is
19
- * a separate, larger item than this wave's (the survey's §7 "two parallel seat implementations"
20
- * open risk).
21
- *
22
- * So this file does not call `@wolffm/rooms-protocol` at all. It gives `GameSeats` the SAME
23
- * contract those three operations have — evict first, in the same call, so there is never a tick
24
- * with a stale seat and a fresh one both claiming the member — against cardtable's own array.
25
- * `room/lobby.ts`'s `removeFromSeat` method needs no function of its own here: `record.ts`'s
26
- * `leaveGameSeat` already IS this contract (vacate one seat, remembered nowhere since `GameSeats`
27
- * has no sticky memory, which is fine — a stood member re-sits through `sitSeat` like anyone
28
- * else). `lowerCapacity` and `replaceWithBot` below are the two that are genuinely new.
29
- *
30
- * If cardtable's seat storage is ever migrated onto `SeatTable` (resolving the `CLOSED_SEAT` gap
31
- * first), THIS file is what gets replaced with calls to the published functions — `room/lobby.ts`'s
32
- * three methods would not need to change at all, since they already call through here.
33
- */
34
- import { type GameSeats } from './record.js';
35
- /**
36
- * Close seats from the TOP down until `count` are open, evicting any occupant first (a human —
37
- * returned, for the caller to tell they are now watching — an AI simply gone). Mirrors
38
- * `@wolffm/rooms-protocol`'s `setSeatCapacity`: eviction is always highest seat first, never a
39
- * caller-chosen one — same reasoning as that function's own doc.
40
- */
41
- export declare function lowerCapacity(seats: GameSeats, count: number): {
42
- seats: GameSeats;
43
- evicted: readonly string[];
44
- };
45
- /**
46
- * The AI takes `seat`, evicting its human occupant first (returned, for the caller to tell they
47
- * are now watching). Addressed by SEAT, not by the human's id (`@wolffm/rooms-protocol`'s
48
- * `replaceWithBot` takes the participant) — cardtable's leader picks a seat, empty or occupied,
49
- * the same way `aiSeat` always has, and an empty seat has no occupant id to address by.
50
- */
51
- export declare function replaceWithBot(seats: GameSeats, seat: number): {
52
- seats: GameSeats;
53
- evicted: string | null;
54
- };
@@ -1,68 +0,0 @@
1
- /**
2
- * The leader's three atomic "evict, then act" seat operations (wave 119 §S), isolated here so a
3
- * future swap is a one-file edit.
4
- *
5
- * `@wolffm/rooms-protocol@0.45.95` (watchparty d02dbdfb, published while this lane ran) gives its
6
- * own `SeatTable` the same three operations: `removeFromSeat(table, participantId)`,
7
- * `replaceWithBot(table, participantId)`, and the pre-existing `setSeatCapacity(table, capacity)`
8
- * for "lower capacity under occupants, evicting someone" — its own doc calls that the one and
9
- * only way to do it on a `SeatTable`.
10
- *
11
- * Cardtable's rooms are NOT on `SeatTable`. They are `GameSeats` (`record.ts`): a plain
12
- * `(string | null)[]` with `AI_SEAT`/`CLOSED_SEAT` markers IN PLACE, because a leader can close
13
- * one specific seat (`CLOSED_SEAT`, `closeSeat`) while every seat around it, including a HIGHER
14
- * one, stays open — Magic's draft pods do this (`pods.ts`'s `POD_CLOSED`). `SeatTable.capacity`
15
- * has no such idea: its own `setSeatCapacity` doc says so explicitly — "this table has no concept
16
- * of a specific seat that is closed while a higher one stays open… inventing one would be a
17
- * second notion of capacity." That is not a gap to fix here; it is a different, deliberate design
18
- * for a different shape of room, and reconciling the two (or deciding cardtable keeps its own) is
19
- * a separate, larger item than this wave's (the survey's §7 "two parallel seat implementations"
20
- * open risk).
21
- *
22
- * So this file does not call `@wolffm/rooms-protocol` at all. It gives `GameSeats` the SAME
23
- * contract those three operations have — evict first, in the same call, so there is never a tick
24
- * with a stale seat and a fresh one both claiming the member — against cardtable's own array.
25
- * `room/lobby.ts`'s `removeFromSeat` method needs no function of its own here: `record.ts`'s
26
- * `leaveGameSeat` already IS this contract (vacate one seat, remembered nowhere since `GameSeats`
27
- * has no sticky memory, which is fine — a stood member re-sits through `sitSeat` like anyone
28
- * else). `lowerCapacity` and `replaceWithBot` below are the two that are genuinely new.
29
- *
30
- * If cardtable's seat storage is ever migrated onto `SeatTable` (resolving the `CLOSED_SEAT` gap
31
- * first), THIS file is what gets replaced with calls to the published functions — `room/lobby.ts`'s
32
- * three methods would not need to change at all, since they already call through here.
33
- */
34
- import { AI_SEAT, CLOSED_SEAT } from "./record.js";
35
- /**
36
- * Close seats from the TOP down until `count` are open, evicting any occupant first (a human —
37
- * returned, for the caller to tell they are now watching — an AI simply gone). Mirrors
38
- * `@wolffm/rooms-protocol`'s `setSeatCapacity`: eviction is always highest seat first, never a
39
- * caller-chosen one — same reasoning as that function's own doc.
40
- */
41
- export function lowerCapacity(seats, count) {
42
- const result = [...seats];
43
- const evicted = [];
44
- let open = result.filter((s) => s !== CLOSED_SEAT).length;
45
- for (let seat = result.length - 1; seat >= 0 && open > count; seat--) {
46
- const holder = result[seat] ?? null;
47
- if (holder === CLOSED_SEAT)
48
- continue;
49
- if (holder !== null && holder !== AI_SEAT)
50
- evicted.push(holder);
51
- result[seat] = CLOSED_SEAT;
52
- open--;
53
- }
54
- return { seats: result, evicted };
55
- }
56
- /**
57
- * The AI takes `seat`, evicting its human occupant first (returned, for the caller to tell they
58
- * are now watching). Addressed by SEAT, not by the human's id (`@wolffm/rooms-protocol`'s
59
- * `replaceWithBot` takes the participant) — cardtable's leader picks a seat, empty or occupied,
60
- * the same way `aiSeat` always has, and an empty seat has no occupant id to address by.
61
- */
62
- export function replaceWithBot(seats, seat) {
63
- const holder = seats[seat] ?? null;
64
- if (holder === AI_SEAT)
65
- return { seats, evicted: null };
66
- const evicted = holder !== null && holder !== CLOSED_SEAT ? holder : null;
67
- return { seats: seats.map((s, i) => (i === seat ? AI_SEAT : s)), evicted };
68
- }