@hadoku/game-server 0.0.0-stage → 0.1.5

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.
Files changed (119) hide show
  1. package/LICENSE +21 -0
  2. package/dist/base-path.d.ts +29 -0
  3. package/dist/base-path.js +30 -0
  4. package/dist/busy.d.ts +40 -0
  5. package/dist/busy.js +23 -0
  6. package/dist/capacity.d.ts +9 -0
  7. package/dist/capacity.js +6 -0
  8. package/dist/config.d.ts +247 -0
  9. package/dist/config.js +271 -0
  10. package/dist/edge-auth.d.ts +43 -0
  11. package/dist/edge-auth.js +47 -0
  12. package/dist/erase/anonymise.d.ts +7 -0
  13. package/dist/erase/anonymise.js +7 -0
  14. package/dist/erase/index.d.ts +18 -0
  15. package/dist/erase/index.js +20 -0
  16. package/dist/erase/legacy-ids.d.ts +7 -0
  17. package/dist/erase/legacy-ids.js +24 -0
  18. package/dist/erase/recordings.d.ts +26 -0
  19. package/dist/erase/recordings.js +128 -0
  20. package/dist/erase/rooms.d.ts +63 -0
  21. package/dist/erase/rooms.js +67 -0
  22. package/dist/gate.d.ts +27 -0
  23. package/dist/gate.js +15 -0
  24. package/dist/http/client-events.d.ts +25 -0
  25. package/dist/http/client-events.js +15 -0
  26. package/dist/http/page.d.ts +26 -0
  27. package/dist/http/page.js +35 -0
  28. package/dist/http/prepared.d.ts +14 -0
  29. package/dist/http/prepared.js +16 -0
  30. package/dist/http/request.d.ts +59 -0
  31. package/dist/http/request.js +37 -0
  32. package/dist/http/room-core.d.ts +160 -0
  33. package/dist/http/room-core.js +278 -0
  34. package/dist/http/trim.d.ts +23 -0
  35. package/dist/http/trim.js +76 -0
  36. package/dist/http/usage.d.ts +22 -0
  37. package/dist/http/usage.js +16 -0
  38. package/dist/kernel.d.ts +4 -0
  39. package/dist/kernel.js +26 -0
  40. package/dist/log.d.ts +9 -0
  41. package/dist/log.js +9 -0
  42. package/dist/people.d.ts +105 -0
  43. package/dist/people.js +145 -0
  44. package/dist/play/clock.d.ts +39 -0
  45. package/dist/play/clock.js +81 -0
  46. package/dist/play/diagnostics.d.ts +21 -0
  47. package/dist/play/diagnostics.js +35 -0
  48. package/dist/play/engine-runtime.d.ts +200 -0
  49. package/dist/play/engine-runtime.js +309 -0
  50. package/dist/play/game-adapter.d.ts +158 -0
  51. package/dist/play/game-adapter.js +1 -0
  52. package/dist/play/host.d.ts +482 -0
  53. package/dist/play/host.js +950 -0
  54. package/dist/play/jvm-transport.d.ts +25 -0
  55. package/dist/play/jvm-transport.js +1 -0
  56. package/dist/play/local-jvm.d.ts +325 -0
  57. package/dist/play/local-jvm.js +829 -0
  58. package/dist/play/match/hosted.d.ts +92 -0
  59. package/dist/play/match/hosted.js +151 -0
  60. package/dist/play/match/outcome.d.ts +26 -0
  61. package/dist/play/match/outcome.js +21 -0
  62. package/dist/play/match/shell.d.ts +378 -0
  63. package/dist/play/match/shell.js +613 -0
  64. package/dist/play/recording/retention.d.ts +36 -0
  65. package/dist/play/recording/retention.js +89 -0
  66. package/dist/play/recording/writer.d.ts +185 -0
  67. package/dist/play/recording/writer.js +90 -0
  68. package/dist/play/relay-socket.d.ts +128 -0
  69. package/dist/play/relay-socket.js +194 -0
  70. package/dist/play/runtimes/in-process.d.ts +47 -0
  71. package/dist/play/runtimes/in-process.js +43 -0
  72. package/dist/play/runtimes/relay-match.d.ts +166 -0
  73. package/dist/play/runtimes/relay-match.js +240 -0
  74. package/dist/play/runtimes/relay.d.ts +128 -0
  75. package/dist/play/runtimes/relay.js +183 -0
  76. package/dist/play/runtimes/streamed.d.ts +116 -0
  77. package/dist/play/runtimes/streamed.js +148 -0
  78. package/dist/play/start-queue.d.ts +65 -0
  79. package/dist/play/start-queue.js +187 -0
  80. package/dist/room/avatar.d.ts +1 -0
  81. package/dist/room/avatar.js +28 -0
  82. package/dist/room/caller.d.ts +21 -0
  83. package/dist/room/caller.js +1 -0
  84. package/dist/room/constants.d.ts +27 -0
  85. package/dist/room/constants.js +27 -0
  86. package/dist/room/events.d.ts +59 -0
  87. package/dist/room/events.js +174 -0
  88. package/dist/room/identity.d.ts +89 -0
  89. package/dist/room/identity.js +98 -0
  90. package/dist/room/lobby.d.ts +426 -0
  91. package/dist/room/lobby.js +880 -0
  92. package/dist/room/membership.d.ts +64 -0
  93. package/dist/room/membership.js +76 -0
  94. package/dist/room/provisioning.d.ts +22 -0
  95. package/dist/room/provisioning.js +46 -0
  96. package/dist/room/record.d.ts +63 -0
  97. package/dist/room/record.js +39 -0
  98. package/dist/room/room-list.d.ts +67 -0
  99. package/dist/room/room-list.js +66 -0
  100. package/dist/room/seats.d.ts +39 -0
  101. package/dist/room/seats.js +58 -0
  102. package/dist/room/session.d.ts +91 -0
  103. package/dist/room/session.js +156 -0
  104. package/dist/room/socket-auth.d.ts +2 -0
  105. package/dist/room/socket-auth.js +10 -0
  106. package/dist/room/watching.d.ts +35 -0
  107. package/dist/room/watching.js +72 -0
  108. package/dist/room/watchparty-link.d.ts +1 -0
  109. package/dist/room/watchparty-link.js +17 -0
  110. package/dist/stream/alloc.d.ts +115 -0
  111. package/dist/stream/alloc.js +368 -0
  112. package/dist/stream/index.d.ts +66 -0
  113. package/dist/stream/index.js +293 -0
  114. package/dist/telemetry.d.ts +46 -0
  115. package/dist/telemetry.js +25 -0
  116. package/dist/testPort.d.ts +1 -0
  117. package/dist/testPort.js +28 -0
  118. package/package.json +36 -4
  119. package/README.md +0 -3
@@ -0,0 +1,829 @@
1
+ /**
2
+ * `--host` bridge JVMs on THIS machine: the local `JvmLauncher` (`jvm-transport.ts` is the seam;
3
+ * `remote/launcher.ts` is the same seam over a claw's agent). The coordinator (`host.ts`) places
4
+ * matches into JVMs; this file starts them, reaches their line streams and settles what they
5
+ * leave on disk.
6
+ *
7
+ * What is generic to any process hosted this way — the fifo transport, pid liveness, the run-dir
8
+ * and crash-record bookkeeping — lives in `engine-runtime.ts`; what is here is Forge's own:
9
+ * compiling and launching the bridge, its preferences, and `stageRunDir`'s Forge-specific profile
10
+ * layout. `forgeEngineRuntime` at the bottom of this file is `EngineRuntime` mapped onto that, and
11
+ * `LocalJvm`'s own spawn (below) launches through its `argv`, appending only the host id `argv`'s
12
+ * sketch has no room for — `host.ts` itself still places matches through `localJvmLauncher`'s
13
+ * `JvmLauncher`, not `EngineRuntime` directly; lifting the pool itself onto `EngineRuntime`, so a
14
+ * non-Forge engine shares the same coordinator, is w105's.
15
+ *
16
+ * ## The run directory
17
+ *
18
+ * Every local JVM gets `<workDir>/<hostId>` (`stageRunDir`): Forge's profile, a `res` symlink,
19
+ * empty user and cache dirs, two fifos, `launch.json` (its pid), the coordinator's `jvm.json` and
20
+ * per-match streams, and `bridge.stderr.txt`. `workDir` is on tmpfs by default, so a directory
21
+ * nobody removes is RAM nobody gets back. What happens to it is decided when the JVM is gone:
22
+ *
23
+ * - **A clean end is removed whole**: the coordinator asked the JVM to go and it went.
24
+ * - **Anything else is a crash record**, pruned to `CRASH_RECORD_FILES` (stderr, the
25
+ * coordinator's `jvm.json` with every match's decks, and a `crash.json` saying how it ended).
26
+ * The exit reason names its path.
27
+ * - **Crash records are bounded**: the newest `CRASH_RECORDS_KEPT`, none older than
28
+ * `CRASH_RECORD_MAX_AGE_MS`.
29
+ * - **The boot sweep** (`sweepRunDirs`, run when the launcher is made) removes what an earlier
30
+ * process left, and spares a directory some process is standing in (`/proc/<pid>/cwd` — so
31
+ * another server's live JVM survives), one changed in the last `RUN_DIR_FRESH_MS`, and crash
32
+ * records within the bound. A live directory whose `launch.json` pid IS the process standing in
33
+ * it is one of ours, and `running()` offers it back. A live one-match JVM from before many
34
+ * matches per JVM (`m-…`, `spare-…`) is ended: nothing re-attaches one any more. Where `/proc`
35
+ * cannot be read the sweep does nothing and says so.
36
+ *
37
+ * ## A JVM outlives its server (Wave 22, §E)
38
+ *
39
+ * A deploy must not end live games, so a JVM survives the server that started it:
40
+ *
41
+ * 1. **The transport is not an inherited pipe**, which dies with its process. The run dir holds
42
+ * two named pipes, `in.fifo` and `out.fifo`, and the JVM's stdin/stdout are fds on those. Both
43
+ * ends open them **`O_RDWR`**, which on Linux succeeds without a peer and means neither side
44
+ * ever sees EOF (each is its own last writer). The bridge exits on stdin EOF. stderr is an
45
+ * `O_APPEND` fd on `bridge.stderr.txt`, for the same reason.
46
+ * 2. **The JVM is not in our process group, and nothing kills it on the way out**: `detached`,
47
+ * `unref`, and no exit hook.
48
+ * 3. **The next process finds it** by `launch.json`, confirmed through `/proc/<pid>/cwd` (a
49
+ * recycled pid is some other program, in some other directory), and `attach` re-opens the
50
+ * fifos. Lines the JVM wrote while nobody was attached are still in `out.fifo`, so they are the
51
+ * first ones read. Rebuilding each MATCH from its history is the coordinator's (`host.ts`).
52
+ *
53
+ * ## The bridge, compiled once
54
+ *
55
+ * See `bridgeLaunch`.
56
+ *
57
+ * ## Configuration (environment)
58
+ *
59
+ * CARDTABLE_FORGE_JAR the fat jar, `forge-gui-desktop-*-jar-with-dependencies.jar` (required)
60
+ * CARDTABLE_FORGE_RES Forge's `forge-gui/res` directory (required)
61
+ * CARDTABLE_JAVA a JDK 21 `java`; default: `$JAVA_HOME/bin/java`, then `java` on `PATH`,
62
+ * the fleet's managed JDK (`defaultJava`, D14 amended 2026-11-02)
63
+ * CARDTABLE_PLAY_WORK_DIR per-JVM run directories; default `<os tmpdir>/cardtable-play`
64
+ * CARDTABLE_PLAY_JVM_OPTS extra JVM flags, space-separated; an `-Xmx` here beats `JVM_HEAP_MB`
65
+ * CARDTABLE_PLAY_WARM_JVM `0` to keep no JVM booted ahead of a match; default on
66
+ * CARDTABLE_PLAY_MATCHES_PER_JVM matches one JVM hosts at most; default `MATCHES_PER_JVM`
67
+ * CARDTABLE_PLAY_BRIDGE_CACHE where the compiled bridge is kept; default `~/.cache/cardtable/bridge`
68
+ * CARDTABLE_AI_FLAT_MC how hard the AI a person plays thinks: `off`, `base`, `lite` or `max`
69
+ * (`AiFlatMc`); default `AI_FLAT_MC`. Read per match, so a restart of the
70
+ * server flips it for every match started after, on JVMs already running too
71
+ *
72
+ * The bridge needs a JDK — `javac` to compile, or `jdk.compiler` for the source launcher it falls
73
+ * back to — which is why the user-local Temurin comes first, ahead of whatever `java` is on `PATH`
74
+ * (on the production host that is a JRE with no `javac`).
75
+ */
76
+ import { spawn, spawnSync } from 'node:child_process';
77
+ import { createHash, randomBytes } from 'node:crypto';
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';
80
+ import { basename, dirname, join, resolve } from 'node:path';
81
+ import { createInterface } from 'node:readline';
82
+ import { playWorkDir } from '../config.js';
83
+ import { bridgeDiagnostics } from './diagnostics.js';
84
+ 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
+ /**
86
+ * Forge's server drops a client it has read nothing from for this long
87
+ * (`FServerManager.HEARTBEAT_TIMEOUT_SECONDS`, `forge.net.heartbeatTimeout`, default 45 s;
88
+ * its clients write a heartbeat every 15 s). Every client of a bridge's server is a
89
+ * loopback `FGameClient` in the same JVM, so the only thing that silences one is the
90
+ * whole JVM pausing — and a dropped client is never reconnected: the seat's every later
91
+ * press is lost (hosting-test-plan C2b: a 60 s pause wedged the match for good). A day is
92
+ * far past any pause a JVM comes back from; a JVM that stops for longer is
93
+ * `UNRESPONSIVE_MS`'s to end (host.ts), not Forge's.
94
+ */
95
+ export const FORGE_HEARTBEAT_TIMEOUT_S = 86_400;
96
+ /**
97
+ * Flags every bridge JVM gets, before the heap cap and the operator's `jvmOpts` (so a later flag
98
+ * of theirs wins). `ExitOnOutOfMemoryError`: G1 has no GC-overhead limit, and without this a JVM
99
+ * out of heap never exits — its games die of `OutOfMemoryError` and the JVM limps on
100
+ * (hosting-test-plan B4: 62 % GC, act p99 14.6 s). With it the JVM exits (code 3), which fails
101
+ * every match on it through the exit path.
102
+ */
103
+ export const BRIDGE_JVM_FLAGS = ['-XX:+ExitOnOutOfMemoryError', `-Dforge.net.heartbeatTimeout=${FORGE_HEARTBEAT_TIMEOUT_S}`];
104
+ const AI_FLAT_MC_LEVELS = ['off', 'base', 'lite', 'max'];
105
+ /** `CARDTABLE_AI_FLAT_MC`'s default. See docs/planning/flat-mc-ai.md for the measurement behind it. */
106
+ export const AI_FLAT_MC = 'off';
107
+ /**
108
+ * `CARDTABLE_AI_FLAT_MC`: unset is {@link AI_FLAT_MC}; anything that is not a level is `off`, so a
109
+ * typo made while turning it down in a hurry never leaves it on.
110
+ */
111
+ export function aiFlatMcFrom(raw) {
112
+ if (raw === undefined || raw.trim() === '')
113
+ return AI_FLAT_MC;
114
+ const level = raw.trim().toLowerCase();
115
+ return AI_FLAT_MC_LEVELS.find((l) => l === level) ?? 'off';
116
+ }
117
+ /**
118
+ * See host.ts, "Many matches per JVM". `CARDTABLE_PLAY_MATCHES_PER_JVM` overrides it. 25 since
119
+ * 2026-10-28: a claw's 4 GB slice holds one JVM, and two claws at 25 make the operator's 50
120
+ * concurrent matches. A slice held 50 paced matches inside every quality gate (hosting-test-plan
121
+ * A2), so 25 is half of what was proven; the limit is the slice's 4 cores, not the heap.
122
+ */
123
+ export const MATCHES_PER_JVM = 25;
124
+ /**
125
+ * Each JVM's heap cap: the budget for {@link MATCHES_PER_JVM} matches. A JVM is ~172 MB live idle
126
+ * and ~10 MB per match (Wave 9 lane D; 4–9 MB in hosting-test-plan B3), so 25 matches live in
127
+ * ~420 MB of a 2 GB heap. G1 does not hand committed heap back, so a JVM's RSS is budgeted at its
128
+ * peak: ~2.3 GB with metaspace, code cache and Netty.
129
+ */
130
+ export const JVM_HEAP_MB = 2048;
131
+ /** Where compiled bridges are kept, shared by every tree on the host (keyed by `bridgeVersion`). */
132
+ export function defaultBridgeCache(env = process.env) {
133
+ return resolve(env.CARDTABLE_PLAY_BRIDGE_CACHE ?? join(env.XDG_CACHE_HOME ?? join(homedir(), '.cache'), 'cardtable', 'bridge'));
134
+ }
135
+ /**
136
+ * Resolve the JVM host's configuration, or say exactly what is missing. `bridgeSource` is the game's
137
+ * own bridge (Magic's is `@hadoku/magic-server/root`'s `BRIDGE_SOURCE`): the platform knows no game's tree.
138
+ */
139
+ export function jvmHostConfig(bridgeSource, env = process.env) {
140
+ const jar = env.CARDTABLE_FORGE_JAR ?? '';
141
+ const res = env.CARDTABLE_FORGE_RES ?? '';
142
+ if (jar === '')
143
+ return { ok: false, reason: 'CARDTABLE_FORGE_JAR is not set' };
144
+ if (!existsSync(jar))
145
+ return { ok: false, reason: `CARDTABLE_FORGE_JAR does not exist: ${jar}` };
146
+ if (res === '')
147
+ return { ok: false, reason: 'CARDTABLE_FORGE_RES is not set' };
148
+ if (!existsSync(join(res, 'cardsfolder'))) {
149
+ return { ok: false, reason: `CARDTABLE_FORGE_RES is not Forge's res/ (no cardsfolder): ${res}` };
150
+ }
151
+ if (!existsSync(bridgeSource))
152
+ return { ok: false, reason: `bridge source not found: ${bridgeSource}` };
153
+ return {
154
+ ok: true,
155
+ config: {
156
+ java: env.CARDTABLE_JAVA ?? defaultJava(env),
157
+ jar: resolve(jar),
158
+ res: resolve(res),
159
+ workDir: playWorkDir(env),
160
+ jvmOpts: (env.CARDTABLE_PLAY_JVM_OPTS ?? '').split(/\s+/).filter((s) => s !== ''),
161
+ bridgeSource,
162
+ bridgeCache: defaultBridgeCache(env),
163
+ stopGraceMs: 5000,
164
+ warmJvm: env.CARDTABLE_PLAY_WARM_JVM !== '0',
165
+ perJvm: positiveInt(env.CARDTABLE_PLAY_MATCHES_PER_JVM, MATCHES_PER_JVM),
166
+ aiFlatMc: aiFlatMcFrom(env.CARDTABLE_AI_FLAT_MC),
167
+ },
168
+ };
169
+ }
170
+ /* ── The bridge, compiled once ───────────────────────────────────────── */
171
+ /**
172
+ * A compiled bridge nobody has launched for this long is removed when the next
173
+ * one is compiled. Far past `ORPHAN_MAX_MS`, so no JVM that could still load a
174
+ * class from it is alive.
175
+ */
176
+ export const BRIDGE_CACHE_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;
177
+ export function bridgeLaunch(config, log) {
178
+ const source = { args: ['-cp', config.jar, config.bridgeSource], how: 'source' };
179
+ const javac = join(dirname(config.java), 'javac');
180
+ if (!existsSync(javac))
181
+ return source;
182
+ const main = basename(config.bridgeSource, '.java');
183
+ let dir;
184
+ try {
185
+ // The main's own name is part of the directory, not just the version: two
186
+ // mains compiling the same siblings (PlayBridge.java and PoolService.java,
187
+ // most of the time) must never share one, or a reader that finds ITS
188
+ // main's class already there could be looking at a directory ANOTHER
189
+ // process is still mid-write on the OTHER main's classes. One main, one
190
+ // directory, keeps the rename below the only thing that makes a directory
191
+ // visible at all — no reader ever sees a half-written one.
192
+ dir = join(config.bridgeCache, `${main}-${bridgeVersion(config)}`);
193
+ }
194
+ catch (err) {
195
+ log({ evt: 'bridge-compile-failed', error: err.message });
196
+ return source;
197
+ }
198
+ const compiled = { args: ['-cp', `${dir}:${config.jar}`, main], how: 'compiled' };
199
+ if (existsSync(join(dir, `${main}.class`))) {
200
+ try {
201
+ // Launched now, so not stale: the pruning below goes by this.
202
+ const now = new Date();
203
+ utimesSync(dir, now, now);
204
+ return compiled;
205
+ }
206
+ catch {
207
+ // Pruned by another process between the check and here. Compile it again.
208
+ }
209
+ }
210
+ const staging = `${dir}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`;
211
+ const started = Date.now();
212
+ try {
213
+ mkdirSync(staging, { recursive: true });
214
+ const javacRun = spawnSync(javac, ['-proc:none', '-nowarn', '-cp', config.jar, '-sourcepath', dirname(config.bridgeSource), '-d', staging, config.bridgeSource], { encoding: 'utf8', timeout: 120_000 });
215
+ if (javacRun.status !== 0 || !existsSync(join(staging, `${main}.class`))) {
216
+ throw new Error(`javac exited ${javacRun.status ?? javacRun.signal ?? javacRun.error?.message}: ${(javacRun.stderr ?? '').slice(-2000)}`);
217
+ }
218
+ try {
219
+ renameSync(staging, dir);
220
+ }
221
+ catch (err) {
222
+ // Another process put the same version there first. Theirs is as good as ours.
223
+ if (!existsSync(join(dir, `${main}.class`)))
224
+ throw err;
225
+ }
226
+ log({ evt: 'bridge-compiled', dir, ms: Date.now() - started });
227
+ }
228
+ catch (err) {
229
+ log({ evt: 'bridge-compile-failed', error: err.message });
230
+ return source;
231
+ }
232
+ finally {
233
+ rmSync(staging, { recursive: true, force: true });
234
+ }
235
+ try {
236
+ for (const entry of readdirSync(config.bridgeCache)) {
237
+ const other = join(config.bridgeCache, entry);
238
+ if (other !== dir && Date.now() - statSync(other).mtimeMs > BRIDGE_CACHE_MAX_AGE_MS)
239
+ rmSync(other, { recursive: true, force: true });
240
+ }
241
+ }
242
+ catch (err) {
243
+ // Housekeeping only: the bridge this JVM needs is compiled and in place.
244
+ log({ evt: 'bridge-cache-prune-failed', dir: config.bridgeCache, error: err.message });
245
+ }
246
+ return compiled;
247
+ }
248
+ /**
249
+ * Every input that decides a compiled bridge's cache directory. Not just
250
+ * `config.bridgeSource`'s own bytes: `javac`'s `-sourcepath` (above) can pull
251
+ * ANY `.java` file beside it into the compile, so the key has to cover every
252
+ * sibling in that directory, hashed in a fixed (sorted) order for a
253
+ * deterministic digest — otherwise an edit to a file that IS referenced,
254
+ * with the referencing file itself unchanged, would keep the old key and so
255
+ * silently serve a stale compiled class for it.
256
+ *
257
+ * Covering the whole directory means `PlayBridge.java`'s own key also changes
258
+ * when `PoolService.java` changes, and vice versa, even on an edit that
259
+ * changes nothing either file's compile actually depends on. Accepted for
260
+ * simplicity: the alternative is having `javac` report exactly which
261
+ * siblings it resolved for THAT compile (it does not expose this), and
262
+ * tracking it per bridge source — real staleness is worse than an occasional
263
+ * needless recompile.
264
+ *
265
+ * Exported so the key itself is unit-testable (`host.test.ts`, "an edited
266
+ * SIBLING .java changes the key too") without a real compile.
267
+ */
268
+ export function bridgeVersion(config) {
269
+ const dir = dirname(config.bridgeSource);
270
+ const siblings = readdirSync(dir)
271
+ .filter((f) => f.endsWith('.java'))
272
+ .sort();
273
+ const hash = createHash('sha256');
274
+ for (const file of siblings)
275
+ hash.update(readFileSync(join(dir, file)));
276
+ const jar = statSync(config.jar);
277
+ hash.update(JSON.stringify([config.jar, jar.size, jar.mtimeMs, realpathSync(config.java)]));
278
+ return hash.digest('hex').slice(0, 24);
279
+ }
280
+ /* ── A JVM that outlives us: the fifos and the launch record ─────────── */
281
+ /** `{hostId, pid, startedAt}`: what a later process finds a running JVM by. Written at launch. */
282
+ export const LAUNCH_RECORD_FILE = 'launch.json';
283
+ // JVM_TMP_DIR's own doc (`engine-runtime.ts`): Forge's lz4-java unpacks a native `.so` there on
284
+ // every boot and only removes it on a clean JVM exit, which a SIGKILLed bridge never has — so
285
+ // under the default `/tmp` every killed match leaked one copy (3,036 of them on the host's
286
+ // RAM-backed /tmp, 2026-10-10). Inside the run dir it goes wherever the run dir goes: removed on
287
+ // a clean end, pruned on a crash.
288
+ /**
289
+ * Write `file` whole or not at all: into a temporary file beside it, then renamed over
290
+ * it. `writeFileSync` in place truncates first, so a full disk left `jvm.json` empty and
291
+ * its match un-re-attachable (hosting-test-plan C6); here a failed write leaves the old
292
+ * file as it was, and throws.
293
+ */
294
+ export function writeFileAtomic(file, text) {
295
+ const tmp = `${file}.tmp-${process.pid}-${randomBytes(4).toString('hex')}`;
296
+ try {
297
+ writeFileSync(tmp, text);
298
+ renameSync(tmp, file);
299
+ }
300
+ catch (err) {
301
+ rmSync(tmp, { force: true });
302
+ throw err;
303
+ }
304
+ }
305
+ /**
306
+ * Forge resolves `res/` against the working directory (`ForgeConstants.RES_DIR`
307
+ * is "res/" when the version string carries no "git"), and reads its user and
308
+ * cache dirs from `forge.profile.properties` there. So each match gets its own
309
+ * directory — the same staging `scripts/spike/tierc/run.sh` does — and
310
+ * nothing is written into the Forge build it reads from. Exported for
311
+ * `multi-match.jvm.test.ts`, which stages a `--host` JVM itself.
312
+ */
313
+ export function stageRunDir(config, name) {
314
+ const run = join(config.workDir, name);
315
+ rmSync(run, { recursive: true, force: true });
316
+ mkdirSync(join(run, 'user', 'decks', 'constructed'), { recursive: true });
317
+ mkdirSync(join(run, 'user', 'preferences'), { recursive: true });
318
+ mkdirSync(join(run, 'cache'), { recursive: true });
319
+ mkdirSync(join(run, JVM_TMP_DIR), { recursive: true });
320
+ symlinkSync(config.res, join(run, 'res'));
321
+ makeFifos(run);
322
+ writeFileSync(join(run, 'forge.profile.properties'), [
323
+ `userDir=${run}/user/`,
324
+ `cacheDir=${run}/cache/`,
325
+ `decksDir=${run}/user/decks/`,
326
+ `decksConstructedDir=${run}/user/decks/constructed/`,
327
+ '',
328
+ ].join('\n'));
329
+ // ForgeConstants.MAIN_PREFS_FILE = <userDir>/preferences/forge.preferences
330
+ // (ForgeConstants.java:247,275); AbstractPreferences reads it line by line
331
+ // before FModel.initialize's callback runs (AbstractPreferences.java:41-67).
332
+ writeFileSync(join(run, 'user', 'preferences', 'forge.preferences'), forgePreferencesFile());
333
+ return run;
334
+ }
335
+ /**
336
+ * Forge preferences every match runs with, and why each one is here.
337
+ *
338
+ * These are **Forge's own settings**, not rules: each turns off a desktop-UI
339
+ * behaviour that makes no sense for a browser client, and the file is the
340
+ * documented way to set them (`AbstractPreferences`). A JVM is one match, so
341
+ * the file is written per run directory and nothing outlives it.
342
+ */
343
+ export const FORGE_PREFERENCES = {
344
+ /**
345
+ * Wave 19, #12 — *"when i cast preordain it showed the whole library with
346
+ * all the cards numbered? thats quite odd"*.
347
+ *
348
+ * With this pref true (its default, `ForgePreferences.java:157`),
349
+ * `PlayerControllerHuman.arrangeForScry` hands the GUI
350
+ * `player.getCardsIn(ZoneType.Library)` — **the whole library** — as the
351
+ * pile to rearrange, with only the scried cards `manipulable`
352
+ * (`PlayerControllerHuman.java:1006-1012`). The desktop UI renders that as
353
+ * a drag inside its library display; a browser client has no such display
354
+ * and draws every row, most of them cards the seat is not allowed to see
355
+ * and so cannot name.
356
+ *
357
+ * **Re-measured wave 64 §S (S10), against the pinned jar
358
+ * (`702b207eda874df8bae60435284f40836ed8799c`), with this pref flipped
359
+ * BOTH ways on the exact same scripted Preordain (`scenarios/w62-scry.state`,
360
+ * a 6-card library): `true` (Forge's default) sends `manipulateCardList`
361
+ * with all 6 cards and 2 `manipulable` — still exactly the bug #12
362
+ * complains about, numbers scaling with the library — and `false` (this
363
+ * file's override) sends `order` instead, title "Select cards to be put
364
+ * on the bottom of your library", `sourceChoices` carrying ONLY the two
365
+ * scried cards. The pref is still the one thing deciding which of these
366
+ * two asks Forge opens for a scry — nothing else in this file or in
367
+ * `auto.ts` branches on it — so it is still needed, and the value stays
368
+ * `'false'`. The method name `order` was missing from this comment before
369
+ * this measurement (`docs/.../wave62-evidence/S/scry.md`, 2026-10-08,
370
+ * independently confirmed the same false-branch shape for Serum Visions
371
+ * and Preordain, from the UI side rather than this pref's own doc) — this
372
+ * paragraph is what was stale, not the mechanism.
373
+ */
374
+ UI_SELECT_FROM_CARD_DISPLAYS: 'false',
375
+ /**
376
+ * Forge asks a blank `PLAYER_NAME` for a name before any match with one human seat
377
+ * (`HostedMatch.java:269`, `GamePlayerUtil.setPlayerName`'s "Personalize Forge Gameplay"),
378
+ * which is every game against the AI on a fresh profile. The bridge answered it with Forge's
379
+ * own default, `Human`, which Forge then saved (prod, 2026-11-09, `bridge-diagnostics` on
380
+ * the backstop host). Set to that default here, nothing changes but the prompt: seat names come from the
381
+ * match's spec, never from this preference.
382
+ */
383
+ PLAYER_NAME: 'Human',
384
+ };
385
+ function forgePreferencesFile() {
386
+ return [
387
+ '# Written per run directory by packages/game-server/src/play/host.ts. See FORGE_PREFERENCES.',
388
+ ...Object.entries(FORGE_PREFERENCES).map(([key, value]) => `${key}=${value}`),
389
+ '',
390
+ ].join('\n');
391
+ }
392
+ /* ── What is left of a run directory ─────────────────────────────────── */
393
+ /** Crash records kept at most, newest first. See "The run directory". */
394
+ export const CRASH_RECORDS_KEPT = 20;
395
+ /** A crash record older than this is removed. */
396
+ export const CRASH_RECORD_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
397
+ /** The boot sweep leaves a directory changed this recently: another process may be staging it. */
398
+ export const RUN_DIR_FRESH_MS = 60_000;
399
+ /**
400
+ * What a crashed JVM's directory is pruned to. `crash.json` marks it as a record; `jvm.json` is the
401
+ * coordinator's record of the matches it hosted, with their decks, so one can be replayed.
402
+ */
403
+ export const CRASH_RECORD_FILES = ['bridge.stderr.txt', 'jvm.json', 'crash.json'];
404
+ /** The tail of `bridge.stderr.txt` read for {@link bridgeDiagnostics}: the end of a long match is what a report is about. */
405
+ const DIAGNOSTICS_READ_BYTES = 4 * 1024 * 1024;
406
+ /** {@link bridgeDiagnostics} of a run directory's `bridge.stderr.txt`; none for a JVM that never wrote one. */
407
+ function runDirDiagnostics(run) {
408
+ const path = join(run, 'bridge.stderr.txt');
409
+ if (!existsSync(path))
410
+ return [];
411
+ const size = statSync(path).size;
412
+ const fd = openSync(path, 'r');
413
+ try {
414
+ const length = Math.min(size, DIAGNOSTICS_READ_BYTES);
415
+ const buf = Buffer.alloc(length);
416
+ readSync(fd, buf, 0, length, size - length);
417
+ return bridgeDiagnostics(buf.toString('utf8'));
418
+ }
419
+ finally {
420
+ closeSync(fd);
421
+ }
422
+ }
423
+ /**
424
+ * JVM host ids (`h-…`), and the one-match JVMs (`m-…`, `spare-…`) of the servers before many
425
+ * matches per JVM, which a boot still ends and removes. Nothing else under `workDir` is ours.
426
+ */
427
+ const RUN_DIR_NAME = /^(h|m|spare)-[0-9a-f]{12}$/;
428
+ /** A run directory from before many matches per JVM: one match each, re-attached by nothing now. */
429
+ const LEGACY_RUN_DIR = /^(m|spare)-/;
430
+ /** Keep the diagnostics, drop Forge's scaffolding (the `res` symlink is unlinked, never followed). */
431
+ function keepCrashRecord(run, record) {
432
+ const keep = new Set(CRASH_RECORD_FILES);
433
+ for (const entry of readdirSync(run)) {
434
+ if (!keep.has(entry))
435
+ rmSync(join(run, entry), { recursive: true, force: true });
436
+ }
437
+ writeFileAtomic(join(run, CRASH_MARKER), `${JSON.stringify(record, null, 2)}\n`);
438
+ }
439
+ /** `<run>/launch.json`, or null when it is missing, unreadable or not one. */
440
+ export function readLaunchRecord(run) {
441
+ try {
442
+ const r = JSON.parse(readFileSync(join(run, LAUNCH_RECORD_FILE), 'utf8'));
443
+ if (typeof r.hostId !== 'string' || typeof r.pid !== 'number')
444
+ return null;
445
+ return { hostId: r.hostId, pid: r.pid, startedAt: typeof r.startedAt === 'string' ? r.startedAt : new Date(0).toISOString() };
446
+ }
447
+ catch {
448
+ return null;
449
+ }
450
+ }
451
+ /** The pid a one-match JVM's own record named (`jvm.json`, or `jvm.degraded.json` once its stream broke). */
452
+ function legacyPid(run) {
453
+ for (const file of ['jvm.json', 'jvm.degraded.json']) {
454
+ try {
455
+ const pid = JSON.parse(readFileSync(join(run, file), 'utf8')).pid;
456
+ if (typeof pid === 'number')
457
+ return pid;
458
+ }
459
+ catch {
460
+ // Not this one; the other, or none.
461
+ }
462
+ }
463
+ return null;
464
+ }
465
+ /**
466
+ * Remove the run directories an earlier process left behind, and hand back the JVMs that are
467
+ * still running. See "The run directory" and "A JVM outlives its server" in the module header for
468
+ * what it spares and why.
469
+ */
470
+ export function sweepRunDirs(workDir, now = Date.now()) {
471
+ const result = { removed: [], live: [], fresh: [], crashes: { kept: [], removed: [] }, running: [], killed: [] };
472
+ const cwds = processCwds();
473
+ if (cwds === null)
474
+ return { ...result, skipped: '/proc is not readable, so a live run directory cannot be told from a dead one' };
475
+ for (const { name, dir, mtimeMs } of runDirs(workDir, RUN_DIR_NAME)) {
476
+ if (cwds.some((cwd) => cwdIsUnder(cwd, dir))) {
477
+ // LIVE. Some process is standing here, so the directory is not ours to remove on a
478
+ // guess — that guard is why another server's JVM survives. The only question asked is
479
+ // whose it is, answered by the directory's own record: a pid that IS the process
480
+ // standing here. Its `run` string is deliberately not compared — `runDirs` resolves
481
+ // `workDir` through `realpath` and the writer did not.
482
+ if (LEGACY_RUN_DIR.test(name)) {
483
+ const pid = legacyPid(dir);
484
+ if (pid !== null && pidIsStandingIn(pid, dir) === true) {
485
+ killPid(pid);
486
+ rmSync(dir, { recursive: true, force: true });
487
+ result.killed.push(name);
488
+ continue;
489
+ }
490
+ }
491
+ else {
492
+ const launch = readLaunchRecord(dir);
493
+ if (launch !== null && launch.hostId === name && pidIsStandingIn(launch.pid, dir) === true) {
494
+ result.running.push({ hostId: name, pid: launch.pid, run: dir, startedAt: launch.startedAt });
495
+ }
496
+ }
497
+ result.live.push(name);
498
+ continue;
499
+ }
500
+ if (existsSync(join(dir, CRASH_MARKER)))
501
+ continue; // the bound decides, below
502
+ if (now - mtimeMs < RUN_DIR_FRESH_MS)
503
+ result.fresh.push(name);
504
+ else {
505
+ rmSync(dir, { recursive: true, force: true });
506
+ result.removed.push(name);
507
+ }
508
+ }
509
+ result.running.sort((a, b) => Date.parse(a.startedAt) - Date.parse(b.startedAt));
510
+ result.crashes = pruneCrashRecords(workDir, RUN_DIR_NAME, CRASH_MARKER, CRASH_RECORDS_KEPT, CRASH_RECORD_MAX_AGE_MS, now);
511
+ return result;
512
+ }
513
+ /* ── One JVM's transport, over its fifos ─────────────────────────────── */
514
+ /**
515
+ * Every local JVM this process is talking to and has not seen exit or let go. There is no
516
+ * `process.on('exit')` hook that kills them, on purpose: a JVM is meant to outlive this process
517
+ * (see "A JVM outlives its server"), and what must not is the coordinator's `reapOnExit`'s.
518
+ */
519
+ const live = new Set();
520
+ /** Number of bridge JVMs this process currently has running. */
521
+ export function liveJvmCount() {
522
+ return live.size;
523
+ }
524
+ /** `{"t":"stop","match":<hostId>}`: the coordinator asking the JVM itself to go (`PlayBridge.handle`). */
525
+ function isHostStop(line, hostId) {
526
+ if (!line.startsWith('{"t":"stop"'))
527
+ return false;
528
+ try {
529
+ return JSON.parse(line).match === hostId;
530
+ }
531
+ catch {
532
+ return false;
533
+ }
534
+ }
535
+ /**
536
+ * One `--host` JVM on this machine, either end of whose fifos may be opened by a process that
537
+ * did not start it. Addressed by **pid**: a JVM re-attached from an earlier server is nobody's
538
+ * child, so its death is noticed by polling rather than by an `exit` event.
539
+ *
540
+ * Its run directory is settled when it is gone. **A clean end is removed whole**: the
541
+ * coordinator asked the JVM to go (`{"t":"stop"}` to its host id) and it went, by itself
542
+ * (`halt(0)`) or by the `kill()` that followed. **Anything else is a crash record**: a JVM that
543
+ * exited on its own, non-zero, by a signal, or that the coordinator killed without asking first
544
+ * (the liveness watchdog does exactly that).
545
+ */
546
+ class LocalJvm {
547
+ config;
548
+ hostId;
549
+ run;
550
+ log;
551
+ pid;
552
+ /** Null only in `attach` mode: a re-attached JVM is nobody's child, watched by {@link watchPid} instead. */
553
+ engineProcess = null;
554
+ io;
555
+ lineListener = null;
556
+ exitListener = null;
557
+ /** Exited, killed, or released: nothing more goes either way. */
558
+ gone = false;
559
+ askedToStop = false;
560
+ killedByUs = false;
561
+ watch = null;
562
+ constructor(config, hostId, run, source, log) {
563
+ this.config = config;
564
+ this.hostId = hostId;
565
+ this.run = run;
566
+ this.log = log;
567
+ this.io = openJvmIo(run, log);
568
+ if (source.mode === 'attach') {
569
+ this.pid = source.pid;
570
+ live.add(this);
571
+ log({ evt: 'jvm-attached', id: hostId, pid: this.pid, run });
572
+ this.read();
573
+ this.watchPid();
574
+ return;
575
+ }
576
+ // stderr is an appended FILE, not a pipe: a pipe dies with this process and the JVM must
577
+ // not. It is also what a crash record keeps.
578
+ const stderrFd = openSync(join(run, 'bridge.stderr.txt'), 'a');
579
+ // The child gets its OWN fds on the fifos, closed here once it holds them.
580
+ const childIn = openSync(join(run, IN_FIFO), 'r+');
581
+ const childOut = openSync(join(run, OUT_FIFO), 'r+');
582
+ // `.how` alone, for the log below; the flags and the actual `child_process.spawn` call both
583
+ // come from `forgeEngineRuntime`, not from a second, hand-built copy here — "--host hostId"
584
+ // is appended after it because the sketch's `argv(dir, size)` carries no host id,
585
+ // `forgeEngineRuntime`'s doc names that gap.
586
+ const runtime = forgeEngineRuntime(config, log);
587
+ const bridge = bridgeLaunch(config, log);
588
+ const argv = [...runtime.argv(run, { memoryMb: source.xmxMb }), '--host', hostId];
589
+ let engineProcess;
590
+ try {
591
+ engineProcess = runtime.spawn(argv, run, { stdin: childIn, stdout: childOut, stderr: stderrFd });
592
+ }
593
+ finally {
594
+ for (const fd of [childIn, childOut, stderrFd])
595
+ closeSync(fd);
596
+ }
597
+ this.engineProcess = engineProcess;
598
+ this.pid = engineProcess.pid;
599
+ live.add(this);
600
+ log({ evt: 'jvm-spawned', id: hostId, pid: this.pid, run, bridge: bridge.how });
601
+ writeFileAtomic(join(run, LAUNCH_RECORD_FILE), `${JSON.stringify({ hostId, pid: this.pid, startedAt: new Date().toISOString() })}\n`);
602
+ this.read();
603
+ engineProcess.onError((err) => this.finish(`the JVM could not be started: ${err.message}`, { code: null, signal: null }));
604
+ engineProcess.onExit((code, signal) => {
605
+ this.log({ evt: 'jvm-exited', id: hostId, pid: this.pid, code, signal });
606
+ this.finish(this.askedToStop ? 'stopped' : `the JVM exited (code ${code}, signal ${signal}); see ${run}/bridge.stderr.txt`, { code, signal });
607
+ });
608
+ }
609
+ send(line) {
610
+ if (this.gone)
611
+ return;
612
+ if (isHostStop(line, this.hostId))
613
+ this.askedToStop = true;
614
+ this.io.write(line);
615
+ }
616
+ onLine(listener) {
617
+ this.lineListener = listener;
618
+ }
619
+ onExit(listener) {
620
+ this.exitListener = listener;
621
+ }
622
+ /**
623
+ * SIGKILL, confirmed: synchronous, so `reapOnExit` can rely on it with `process.exit` a
624
+ * statement away (see "Going down"). The pid is signalled only once `/proc/<pid>/cwd` says it
625
+ * is the process standing in THIS run directory — a recycled pid is some other program.
626
+ */
627
+ kill() {
628
+ if (this.gone)
629
+ return;
630
+ this.killedByUs = true;
631
+ if (pidIsRunning(this.pid)) {
632
+ if (!pidIsStandingInRun(this.pid, this.run)) {
633
+ this.log({ evt: 'jvm-reap-refused', id: this.hostId, pid: this.pid, run: this.run, why: 'that pid is not the process standing in this run dir' });
634
+ return;
635
+ }
636
+ try {
637
+ process.kill(this.pid, 'SIGKILL');
638
+ }
639
+ catch {
640
+ // ESRCH — it went between the check and here, which is the outcome we wanted.
641
+ }
642
+ }
643
+ const deadline = Date.now() + REAP_CONFIRM_MS;
644
+ while (pidIsRunning(this.pid) && Date.now() < deadline)
645
+ sleepSync(5);
646
+ if (pidIsRunning(this.pid)) {
647
+ this.log({ evt: 'jvm-reap-failed', id: this.hostId, pid: this.pid, run: this.run, afterMs: REAP_CONFIRM_MS });
648
+ return;
649
+ }
650
+ this.log({ evt: 'jvm-killed', id: this.hostId, pid: this.pid, run: this.run });
651
+ this.finish(this.askedToStop ? 'stopped' : `the JVM was killed; see ${this.run}/bridge.stderr.txt`, { code: null, signal: 'SIGKILL' });
652
+ }
653
+ /** Let go without killing and without settling the run directory: it is the next server's handle. */
654
+ release() {
655
+ if (this.gone)
656
+ return;
657
+ this.gone = true;
658
+ this.detach();
659
+ this.log({ evt: 'jvm-handed-over', id: this.hostId, pid: this.pid, run: this.run });
660
+ }
661
+ /** Is the JVM still there? False once it is gone, killed or let go. */
662
+ alive() {
663
+ return !this.gone;
664
+ }
665
+ read() {
666
+ createInterface({ input: this.io.lines }).on('line', (text) => {
667
+ if (!this.gone)
668
+ this.lineListener?.(text);
669
+ });
670
+ }
671
+ /**
672
+ * An attached JVM is nobody's child, so there is no `exit` event for it. The cwd check is not
673
+ * repeated here: the sweep established that this pid is the process standing in this run dir,
674
+ * and a pid that dies is not reissued to a process that then stands in the same directory.
675
+ */
676
+ watchPid() {
677
+ const timer = setInterval(() => {
678
+ if (pidIsRunning(this.pid))
679
+ return;
680
+ this.log({ evt: 'jvm-exited', id: this.hostId, pid: this.pid, code: null, signal: null, attached: true });
681
+ this.finish(this.askedToStop ? 'stopped' : `the JVM exited; see ${this.run}/bridge.stderr.txt`, { code: null, signal: null });
682
+ }, PID_POLL_MS);
683
+ timer.unref();
684
+ this.watch = timer;
685
+ }
686
+ detach() {
687
+ live.delete(this);
688
+ if (this.watch !== null)
689
+ clearInterval(this.watch);
690
+ this.engineProcess?.dispose();
691
+ this.io.close();
692
+ }
693
+ finish(reason, how) {
694
+ if (this.gone)
695
+ return;
696
+ this.gone = true;
697
+ this.detach();
698
+ // An attached JVM has no exit code to read — nobody waited on it — so a stop that was asked
699
+ // for is taken at its word.
700
+ const clean = this.askedToStop && (this.killedByUs || this.engineProcess === null || (how.code === 0 && how.signal === null));
701
+ this.exitListener?.(reason);
702
+ this.settle(clean ? 'clean' : { reason, ...how });
703
+ }
704
+ /** The JVM is gone and its stderr is flushed: remove a clean end's directory, keep a crash's diagnostics. */
705
+ settle(ending) {
706
+ try {
707
+ if (ending === 'clean') {
708
+ this.logDiagnostics();
709
+ rmSync(this.run, { recursive: true, force: true });
710
+ this.log({ evt: 'run-dir-removed', id: this.hostId, run: this.run });
711
+ return;
712
+ }
713
+ keepCrashRecord(this.run, { id: this.hostId, ...ending, at: new Date().toISOString() });
714
+ const pruned = pruneCrashRecords(this.config.workDir, RUN_DIR_NAME, CRASH_MARKER, CRASH_RECORDS_KEPT, CRASH_RECORD_MAX_AGE_MS);
715
+ this.log({ evt: 'run-dir-kept', id: this.hostId, run: this.run, files: [...CRASH_RECORD_FILES], pruned: pruned.removed });
716
+ }
717
+ catch (err) {
718
+ this.log({ evt: 'run-dir-settle-failed', id: this.hostId, run: this.run, error: err.message });
719
+ }
720
+ }
721
+ /** What the bridge said about itself, logged before a removal takes its stderr: see {@link bridgeDiagnostics}. */
722
+ logDiagnostics() {
723
+ try {
724
+ const lines = runDirDiagnostics(this.run);
725
+ if (lines.length > 0)
726
+ this.log({ evt: 'bridge-diagnostics', id: this.hostId, lines });
727
+ }
728
+ catch (err) {
729
+ this.log({ evt: 'bridge-diagnostics-failed', id: this.hostId, run: this.run, error: err.message });
730
+ }
731
+ }
732
+ }
733
+ /**
734
+ * `--host` JVMs on this machine, one run directory each (`<workDir>/<hostId>`), reached over the
735
+ * directory's fifos so a later process can take one back. The boot sweep runs here, once, when the
736
+ * launcher is made: it removes what an earlier process left and finds the JVMs still running.
737
+ */
738
+ export function localJvmLauncher(config, options = {}) {
739
+ const log = options.log ?? (() => undefined);
740
+ /** Running JVMs from an earlier server, not yet attached. */
741
+ const found = new Map();
742
+ let swept = null;
743
+ if (options.sweep ?? true) {
744
+ try {
745
+ swept = sweepRunDirs(config.workDir);
746
+ for (const r of swept.running)
747
+ found.set(r.hostId, { pid: r.pid, run: r.run });
748
+ log({
749
+ evt: 'run-dirs-swept',
750
+ workDir: config.workDir,
751
+ removed: swept.removed.length,
752
+ live: swept.live,
753
+ fresh: swept.fresh,
754
+ killed: swept.killed,
755
+ running: [...found.keys()],
756
+ crashRecords: swept.crashes.kept.length,
757
+ crashRecordsRemoved: swept.crashes.removed.length,
758
+ ...(swept.skipped === undefined ? {} : { skipped: swept.skipped }),
759
+ });
760
+ }
761
+ catch (err) {
762
+ // A sweep that fails leaves directories behind; it must not stop play from starting.
763
+ log({ evt: 'run-dir-sweep-failed', workDir: config.workDir, error: err.message });
764
+ }
765
+ }
766
+ return {
767
+ swept,
768
+ launch(hostId, opts) {
769
+ const run = join(config.workDir, hostId);
770
+ try {
771
+ stageRunDir(config, hostId);
772
+ return new LocalJvm(config, hostId, run, { mode: 'spawn', xmxMb: opts.xmxMb }, log);
773
+ }
774
+ catch (err) {
775
+ rmSync(run, { recursive: true, force: true });
776
+ throw err;
777
+ }
778
+ },
779
+ running: () => Promise.resolve([...found.keys()]),
780
+ attach(hostId) {
781
+ const at = found.get(hostId);
782
+ if (at === undefined)
783
+ throw new Error(`there is no running JVM ${hostId} to attach to`);
784
+ found.delete(hostId);
785
+ return new LocalJvm(config, hostId, at.run, { mode: 'attach', pid: at.pid }, log);
786
+ },
787
+ };
788
+ }
789
+ /* ── EngineRuntime: Forge's bridge JVM as the first implementation ──── */
790
+ /**
791
+ * `EngineRuntime` (`engine-runtime.ts`) mapped onto Forge's own code. `LocalJvm`'s constructor
792
+ * (below) launches through this `spawn` — the actual `child_process.spawn` call lives here, not
793
+ * in `LocalJvm`, which only builds the argv and hands it over — rather than building the child
794
+ * process itself; `host.ts` itself still places matches through `localJvmLauncher`'s
795
+ * `JvmLauncher`, never `EngineRuntime` directly — lifting the POOL onto `EngineRuntime`, so a
796
+ * non-Forge engine shares the same coordinator, is still ahead of this.
797
+ *
798
+ * One honest gap, unchanged: the sketch's `argv(dir, size)` carries no host id, so Forge's real
799
+ * spawn appends `'--host', hostId` itself, after exactly these flags — the interface doesn't carry
800
+ * a host id to launch with.
801
+ */
802
+ export function forgeEngineRuntime(config, log) {
803
+ return {
804
+ artifacts: { jar: config.jar, res: config.res, bridgeSource: config.bridgeSource },
805
+ argv: (dir, size) => {
806
+ const bridge = bridgeLaunch(config, log);
807
+ return [
808
+ '-Djava.awt.headless=true',
809
+ `-Djava.io.tmpdir=${join(dir, JVM_TMP_DIR)}`,
810
+ ...BRIDGE_JVM_FLAGS,
811
+ `-Xmx${size.memoryMb}m`,
812
+ ...config.jvmOpts,
813
+ ...bridge.args,
814
+ ];
815
+ },
816
+ // ~172 MB live idle (JVM_HEAP_MB's doc, above: Wave 9 lane D; 4–9 MB in hosting-test-plan B3).
817
+ overheadMb: 172,
818
+ perProcess: config.perJvm ?? MATCHES_PER_JVM,
819
+ health: () => ({ recycle: false }),
820
+ // `detached` puts it in its own process group, so a signal aimed at ours never reaches it;
821
+ // `unref` keeps it off our event loop — the same two reasons `LocalJvm`'s own spawn call
822
+ // used to carry, now exercised here instead of at the call site.
823
+ spawn: (argv, cwd, io) => {
824
+ const child = spawn(config.java, argv, { cwd, stdio: [io.stdin, io.stdout, io.stderr], detached: true });
825
+ child.unref();
826
+ return wrapChildProcess(child);
827
+ },
828
+ };
829
+ }