Spaces:
Paused
Phase 0: split tools/selfplay.js into a browser-safe core + tools/selfplay-cli.js
Browse filesdocs/competitions-and-elo.md's Phase 0: tools/selfplay.js ended with a
module-scope `process.argv[1]` guard, which throws ReferenceError the
moment the file is imported anywhere without a `process` global (a browser
main thread, or a Worker) β the blocker every later phase in that doc
depends on being gone.
- tools/selfplay.js now keeps ONLY the pure core: createSelfPlayState,
tickSelfPlay, runSelfPlayMatch, fingerprint, and the DT constant they
share. Zero `process`/`document` references anywhere in the file, not
even in a comment. Function bodies are byte-for-byte unchanged from
before the split.
- tools/selfplay-cli.js is the new Node CLI entry point (parseArgs, runCmd,
USAGE, main, and the process.argv[1]-guarded invocation line), importing
the four core functions from "./selfplay.js". `node tools/selfplay-cli.js
run ...` behaves identically to the old `node tools/selfplay.js run ...`
β same flags, same output.
- tools/ailab.js's import of createSelfPlayState/runSelfPlayMatch from
"./selfplay.js" and test/ai-selfplay.test.js's imports plus its
tickSelfPlay source-scan (readFileSync of this same file) both keep
working unmodified.
- TDD: added a source-scan test to test/ai-selfplay.test.js, right after
its existing tickSelfPlay source-scan, modeled on
test/engine-purity.test.js's Math.random/Date.now idiom β asserts
tools/selfplay.js's full source has no bare `process`/`document` token.
Confirmed red against the pre-split file (failed on line 197) before
making the split green.
- Updated docs/competitions-and-elo.md's Phase 0 section only: the Files
line now names tools/selfplay-cli.js definitely, plus a short status
note on where the split landed. Grepped the repo for stale
"node tools/selfplay.js run" examples afterward; none left.
Full suite: 2062/2062 passing (2061 baseline + 1 new test), 0 failures.
node --check is clean on both files. CLI sanity-run
(`node tools/selfplay-cli.js run --world ferros --seed 1`) prints a normal
winner/reason/time result end to end.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013z8dVULQ6Xk8k2YsCF3FS1
- docs/competitions-and-elo.md +7 -2
- test/ai-selfplay.test.js +23 -0
- tools/selfplay-cli.js +65 -0
- tools/selfplay.js +6 -58
|
@@ -198,13 +198,18 @@ The blocker, and nothing else.
|
|
| 198 |
- Keep the file *itself* free of DOM too, so the same module runs in Node, on the main thread, and in
|
| 199 |
a Worker.
|
| 200 |
|
| 201 |
-
**Files:** `tools/selfplay.js` (
|
| 202 |
**Tests:** existing `test/ai-selfplay.test.js` stays green; add a case asserting the core module's
|
| 203 |
source contains no bare `process`/`document` reference (the `test/engine-purity.test.js` idiom,
|
| 204 |
pointed at this file).
|
| 205 |
-
**Done when:** `node tools/selfplay.js run β¦` still works and the core imports cleanly with `process`
|
| 206 |
deleted from the global scope.
|
| 207 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
### Phase 1 β `elo.js`, and an AI-vs-AI **Quick Duel** in the game *(M)*
|
| 209 |
|
| 210 |
The thinnest end-to-end slice: two AI entrants, a real match, a real rating change.
|
|
|
|
| 198 |
- Keep the file *itself* free of DOM too, so the same module runs in Node, on the main thread, and in
|
| 199 |
a Worker.
|
| 200 |
|
| 201 |
+
**Files:** `tools/selfplay.js` (pure core) and `tools/selfplay-cli.js` (CLI entry point).
|
| 202 |
**Tests:** existing `test/ai-selfplay.test.js` stays green; add a case asserting the core module's
|
| 203 |
source contains no bare `process`/`document` reference (the `test/engine-purity.test.js` idiom,
|
| 204 |
pointed at this file).
|
| 205 |
+
**Done when:** `node tools/selfplay-cli.js run β¦` still works and the core imports cleanly with `process`
|
| 206 |
deleted from the global scope.
|
| 207 |
|
| 208 |
+
**Status: done.** The split landed exactly this way β `tools/selfplay.js` now holds only
|
| 209 |
+
`createSelfPlayState`/`tickSelfPlay`/`runSelfPlayMatch`/`fingerprint` (plus the `DT` they share) with
|
| 210 |
+
zero `process`/`document` references, and `tools/selfplay-cli.js` took the CLI half
|
| 211 |
+
(`parseArgs`/`runCmd`/`USAGE`/`main`) β run it as `node tools/selfplay-cli.js run β¦`.
|
| 212 |
+
|
| 213 |
### Phase 1 β `elo.js`, and an AI-vs-AI **Quick Duel** in the game *(M)*
|
| 214 |
|
| 215 |
The thinnest end-to-end slice: two AI entrants, a real match, a real rating change.
|
|
@@ -325,3 +325,26 @@ test("the self-play think ordering stays bounded to one cycle and one direction
|
|
| 325 |
assert.equal((body.match(/runAI\(/g) || []).length, 1,
|
| 326 |
"exactly one explicit runAI call in tickSelfPlay β a second would widen the information edge");
|
| 327 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
assert.equal((body.match(/runAI\(/g) || []).length, 1,
|
| 326 |
"exactly one explicit runAI call in tickSelfPlay β a second would widen the information edge");
|
| 327 |
});
|
| 328 |
+
|
| 329 |
+
/* ============================================================
|
| 330 |
+
5. BROWSER IMPORTABILITY (docs/competitions-and-elo.md Phase 0) β tools/selfplay.js is the pure
|
| 331 |
+
core every later phase needs to import from a browser main thread and from a Worker, neither of
|
| 332 |
+
which has a `process` or `document` global. Same "scan the source for a global this file must
|
| 333 |
+
never reference" idiom test/engine-purity.test.js uses for the engine's Math.random/Date.now ban,
|
| 334 |
+
pointed at this file instead of engine/ β and stricter: no `deterministic-exempt`-style opt-out,
|
| 335 |
+
because the requirement is that the reference doesn't exist at all, not that it's guarded.
|
| 336 |
+
============================================================ */
|
| 337 |
+
|
| 338 |
+
test("tools/selfplay.js has no bare `process` or `document` reference anywhere in its source", () => {
|
| 339 |
+
const src = readFileSync(new URL("../tools/selfplay.js", import.meta.url), "utf8");
|
| 340 |
+
const FORBIDDEN = /\bprocess\b|\bdocument\b/;
|
| 341 |
+
const offenders = [];
|
| 342 |
+
src.split("\n").forEach((line, i) => {
|
| 343 |
+
if (FORBIDDEN.test(line)) offenders.push(`${i + 1}: ${line.trim()}`);
|
| 344 |
+
});
|
| 345 |
+
assert.deepEqual(offenders, [],
|
| 346 |
+
"tools/selfplay.js must have zero `process`/`document` references β not even inside a guarded " +
|
| 347 |
+
"comment (e.g. `typeof process !== \"undefined\"`) β so importing it from a browser (main thread " +
|
| 348 |
+
"or Worker) can never throw a ReferenceError. Move CLI-only code to tools/selfplay-cli.js:\n"
|
| 349 |
+
+ offenders.join("\n"));
|
| 350 |
+
});
|
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* ============================================================
|
| 2 |
+
SELF-PLAY CLI β the Node entry point for tools/selfplay.js's pure self-play core. Split out (see
|
| 3 |
+
docs/competitions-and-elo.md Phase 0) so tools/selfplay.js itself stays free of `process`/
|
| 4 |
+
`document` and can be imported from a browser main thread or a Worker, not just Node. This file
|
| 5 |
+
is Node-only by design β it's the thing that CAN'T be imported from a browser β so all of that
|
| 6 |
+
lives here instead.
|
| 7 |
+
|
| 8 |
+
Usage
|
| 9 |
+
node tools/selfplay-cli.js run [--world ferros] [--seed 1] [--minutes 40]
|
| 10 |
+
[--ai-strategy default] [--ai-difficulty medium]
|
| 11 |
+
[--player-strategy default] [--player-difficulty medium]
|
| 12 |
+
============================================================ */
|
| 13 |
+
|
| 14 |
+
"use strict";
|
| 15 |
+
|
| 16 |
+
import { createSelfPlayState, runSelfPlayMatch } from "./selfplay.js";
|
| 17 |
+
|
| 18 |
+
function parseArgs(argv) {
|
| 19 |
+
const out = { _: [] };
|
| 20 |
+
for (let i = 0; i < argv.length; i++) {
|
| 21 |
+
const a = argv[i];
|
| 22 |
+
if (a.startsWith("--")) out[a.slice(2)] = (argv[i + 1] && !argv[i + 1].startsWith("--")) ? argv[++i] : "true";
|
| 23 |
+
else out._.push(a);
|
| 24 |
+
}
|
| 25 |
+
return out;
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
function runCmd(args) {
|
| 29 |
+
const state = createSelfPlayState({
|
| 30 |
+
planetId: args.world || "ferros",
|
| 31 |
+
seed: args.seed !== undefined ? Number(args.seed) : 1,
|
| 32 |
+
matchTimeLimit: args.minutes !== undefined ? Number(args.minutes) * 60 : undefined,
|
| 33 |
+
ai: { strategy: args["ai-strategy"], difficulty: args["ai-difficulty"] },
|
| 34 |
+
playerAi: { strategy: args["player-strategy"], difficulty: args["player-difficulty"] },
|
| 35 |
+
});
|
| 36 |
+
const result = runSelfPlayMatch(state);
|
| 37 |
+
const unitsOf = o => [...state.units.values()].filter(u => u.owner === o).length;
|
| 38 |
+
const buildingsOf = o => [...state.buildings.values()].filter(b => b.owner === o).length;
|
| 39 |
+
console.log(`world=${state.planetId} seed=${state.seed}`);
|
| 40 |
+
console.log(`ai: strategy=${state.ai.strategy} difficulty=${state.ai.difficulty}`);
|
| 41 |
+
console.log(`player: strategy=${state.playerAi.strategy} difficulty=${state.playerAi.difficulty}`);
|
| 42 |
+
console.log(`--`);
|
| 43 |
+
console.log(`over=${result.over} winner=${result.winner} reason=${result.winReason} `
|
| 44 |
+
+ `time=${result.time.toFixed(1)}s tick=${result.tick}`);
|
| 45 |
+
console.log(`ai: units=${unitsOf("ai")} buildings=${buildingsOf("ai")} `
|
| 46 |
+
+ `resources=${JSON.stringify(state.players.ai.resources)}`);
|
| 47 |
+
console.log(`player: units=${unitsOf("player")} buildings=${buildingsOf("player")} `
|
| 48 |
+
+ `resources=${JSON.stringify(state.players.player.resources)}`);
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
const USAGE = `SELF-PLAY β drive BOTH sides of a skirmish with the real AI (Tier 1).
|
| 52 |
+
|
| 53 |
+
node tools/selfplay-cli.js run [--world ferros] [--seed 1] [--minutes 40]
|
| 54 |
+
[--ai-strategy default] [--ai-difficulty medium]
|
| 55 |
+
[--player-strategy default] [--player-difficulty medium]`;
|
| 56 |
+
|
| 57 |
+
function main(argv) {
|
| 58 |
+
const args = parseArgs(argv);
|
| 59 |
+
const cmd = args._[0];
|
| 60 |
+
if (cmd === "run") { runCmd(args); return; }
|
| 61 |
+
console.log(USAGE);
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
// Only run the CLI when invoked directly, so a test can import the functions above.
|
| 65 |
+
if (process.argv[1] && new URL(import.meta.url).pathname === process.argv[1]) main(process.argv.slice(2));
|
|
@@ -18,14 +18,15 @@
|
|
| 18 |
or double-spend the other's actions. See engine/aiCommon.js's
|
| 19 |
controllerFor/otherOwner and the fairness test in test/ai-selfplay.test.js.
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
| 25 |
|
| 26 |
Deterministic by construction: the map seeds from mulberry32, and the sim
|
| 27 |
itself has zero Math.random/Date.now (engine/ is purity-guarded). Two runs
|
| 28 |
-
|
| 29 |
below and test/ai-selfplay.test.js.
|
| 30 |
============================================================ */
|
| 31 |
|
|
@@ -142,56 +143,3 @@ export function fingerprint(state) {
|
|
| 142 |
const playerAi = JSON.stringify(state.playerAi);
|
| 143 |
return JSON.stringify({ units, builds, res, fogs, ai, playerAi, tick: state.tick, time: state.time, over: state.over, winner: state.winner });
|
| 144 |
}
|
| 145 |
-
|
| 146 |
-
/* ============================================================
|
| 147 |
-
CLI
|
| 148 |
-
============================================================ */
|
| 149 |
-
|
| 150 |
-
function parseArgs(argv) {
|
| 151 |
-
const out = { _: [] };
|
| 152 |
-
for (let i = 0; i < argv.length; i++) {
|
| 153 |
-
const a = argv[i];
|
| 154 |
-
if (a.startsWith("--")) out[a.slice(2)] = (argv[i + 1] && !argv[i + 1].startsWith("--")) ? argv[++i] : "true";
|
| 155 |
-
else out._.push(a);
|
| 156 |
-
}
|
| 157 |
-
return out;
|
| 158 |
-
}
|
| 159 |
-
|
| 160 |
-
function runCmd(args) {
|
| 161 |
-
const state = createSelfPlayState({
|
| 162 |
-
planetId: args.world || "ferros",
|
| 163 |
-
seed: args.seed !== undefined ? Number(args.seed) : 1,
|
| 164 |
-
matchTimeLimit: args.minutes !== undefined ? Number(args.minutes) * 60 : undefined,
|
| 165 |
-
ai: { strategy: args["ai-strategy"], difficulty: args["ai-difficulty"] },
|
| 166 |
-
playerAi: { strategy: args["player-strategy"], difficulty: args["player-difficulty"] },
|
| 167 |
-
});
|
| 168 |
-
const result = runSelfPlayMatch(state);
|
| 169 |
-
const unitsOf = o => [...state.units.values()].filter(u => u.owner === o).length;
|
| 170 |
-
const buildingsOf = o => [...state.buildings.values()].filter(b => b.owner === o).length;
|
| 171 |
-
console.log(`world=${state.planetId} seed=${state.seed}`);
|
| 172 |
-
console.log(`ai: strategy=${state.ai.strategy} difficulty=${state.ai.difficulty}`);
|
| 173 |
-
console.log(`player: strategy=${state.playerAi.strategy} difficulty=${state.playerAi.difficulty}`);
|
| 174 |
-
console.log(`--`);
|
| 175 |
-
console.log(`over=${result.over} winner=${result.winner} reason=${result.winReason} `
|
| 176 |
-
+ `time=${result.time.toFixed(1)}s tick=${result.tick}`);
|
| 177 |
-
console.log(`ai: units=${unitsOf("ai")} buildings=${buildingsOf("ai")} `
|
| 178 |
-
+ `resources=${JSON.stringify(state.players.ai.resources)}`);
|
| 179 |
-
console.log(`player: units=${unitsOf("player")} buildings=${buildingsOf("player")} `
|
| 180 |
-
+ `resources=${JSON.stringify(state.players.player.resources)}`);
|
| 181 |
-
}
|
| 182 |
-
|
| 183 |
-
const USAGE = `SELF-PLAY β drive BOTH sides of a skirmish with the real AI (Tier 1).
|
| 184 |
-
|
| 185 |
-
node tools/selfplay.js run [--world ferros] [--seed 1] [--minutes 40]
|
| 186 |
-
[--ai-strategy default] [--ai-difficulty medium]
|
| 187 |
-
[--player-strategy default] [--player-difficulty medium]`;
|
| 188 |
-
|
| 189 |
-
function main(argv) {
|
| 190 |
-
const args = parseArgs(argv);
|
| 191 |
-
const cmd = args._[0];
|
| 192 |
-
if (cmd === "run") { runCmd(args); return; }
|
| 193 |
-
console.log(USAGE);
|
| 194 |
-
}
|
| 195 |
-
|
| 196 |
-
// Only run the CLI when invoked directly, so a test can import the functions above.
|
| 197 |
-
if (process.argv[1] && new URL(import.meta.url).pathname === process.argv[1]) main(process.argv.slice(2));
|
|
|
|
| 18 |
or double-spend the other's actions. See engine/aiCommon.js's
|
| 19 |
controllerFor/otherOwner and the fairness test in test/ai-selfplay.test.js.
|
| 20 |
|
| 21 |
+
This file is the pure core ONLY β createSelfPlayState, tickSelfPlay, runSelfPlayMatch,
|
| 22 |
+
fingerprint, plus the DT they share. It has no Node-only or DOM-only global anywhere in it, so
|
| 23 |
+
it can be imported from a browser main thread or a Worker, not just Node (docs/
|
| 24 |
+
competitions-and-elo.md, Phase 0). The CLI entry point lives in tools/selfplay-cli.js, which
|
| 25 |
+
imports these exports β run `node tools/selfplay-cli.js run [--world ferros] [--seed 1] β¦`.
|
| 26 |
|
| 27 |
Deterministic by construction: the map seeds from mulberry32, and the sim
|
| 28 |
itself has zero Math.random/Date.now (engine/ is purity-guarded). Two runs
|
| 29 |
+
from the same seed produce byte-identical results β see fingerprint()
|
| 30 |
below and test/ai-selfplay.test.js.
|
| 31 |
============================================================ */
|
| 32 |
|
|
|
|
| 143 |
const playerAi = JSON.stringify(state.playerAi);
|
| 144 |
return JSON.stringify({ units, builds, res, fogs, ai, playerAi, tick: state.tick, time: state.time, over: state.over, winner: state.winner });
|
| 145 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|