Skip to content

Latest commit

 

History

History
60 lines (49 loc) · 30.1 KB

stub_tests.md

File metadata and controls

60 lines (49 loc) · 30.1 KB

Stub Tests and Headless Simulation (§10, §10b, §10c)

Part of AI_CHEATSHEET.md. Covers tests/ stub tests, devtools/simulation/headless/ and the after-game-update checklist. Split from dev_workflow.md.

§10 Stub Tests (tests/)

Offline unittest suite for the production modules (production.py + production_*.py, storage.py, smelter.py, fabricator.py, supply_dock.py, site_supply.py, site_plan.py), no game needed. Run from repo root: python -m unittest discover -s tests (stdlib only).

  • tests/game_stubs.py: the one shared fake world (World): outposts (OutpostRef, .is_home bool, buildings(type_id)), home Inventory, Warehouses, Lead Casks, Smelters, Fabricators (recipes, input/output buffers, running flag), Supply Docks and Earth Orders (orders service; nothing ships), Tanks and fluid ports, Batteries, Steam Turbines, power grids (power_control), run_control, fleet, computer (deploy/undeploy), comms, Drones, Pioneers, Drone Depots, Habitats, shop, journal, construction blueprints, notebook (transaction()), clock, console; add_building() places any other spec type. Port locality per docs: "inventory" connects at home only, a remote port reaches only its own outpost's storage ("not_local" otherwise). Nothing crafts by itself; a test sets buffers/stock/running and calls a controller method.
    • Defaults (slot counts, capacities, powerDraw, recipes, defaultData) come from tests/game_spec.json, the committed extract of the decompiled game (devtools/game_update/extract_game_spec.py). tests/test_stub_contract.py checks every fake's method names, parameter names and literal Result statuses against that spec.
    • Extend game_stubs, never add a private fake. A test needing more adds the method/state there (with contract-test coverage), or keeps a small local subclass for odd behaviour (class _Drone(Drone)). tests/test_no_private_fakes.py fails on any test class named like a game_stubs class (with or without leading _) that does not subclass it.
    • tests/test_service_coverage.py fails when code in scripts/ or autoplay/ requests a service (get_component("<literal>"), machine/outpost ids excluded) that World does not fake; its KNOWN_GAPS lists the accepted ones (transmitter, nocturna, research, ...) and must shrink when a fake lands.
    • After a game update (full list: §10c): rerun python devtools/game_update/extract_game_spec.py (needs the decompiled simworker from the private internals/ submodule), review the tests/game_spec.json diff for renamed methods, new statuses and changed defaults, then run the suite.
  • tests/harness.py: installs get_component/sleep builtins, puts every tier's lib/ on sys.path like the sync resolver's lib_chain(): TEST_TIER = 4 down to 0 first, then higher tiers ascending, resets module state per test (archive.archive.notebook, storage._recent_busy, swallow dedupe, module TreeConsoles). StubTestCase fails any test during which swallowed() reported a bug-class exception.
  • CPython is more permissive than the game's interpreter: a test passing does not prove an import or builtin exists in game. The game has no standard library; its module registry (decompiled simworker) holds exactly: random, functools, re, dataclasses, enum, json, heapq, traceback, math, itertools, operator, string, collections (Counter, defaultdict, OrderedDict, deque, namedtuple); type-only (erased) typing, collections.abc, types, user_stubs; plus builtins/__builtins__ and __future__. No time, copy, os, sys. tests/test_game_imports.py fails on any other import in scripts/ outside our own lib modules (imports under if TYPE_CHECKING: are skipped); keep its GAME_MODULES in step with this list. The same file also fails on a module-level import cycle between lib modules, built from the highest tier's copy of each (the stub tests load TEST_TIER = 4 copies and miss tier-5 cycles): in game a module re-entered mid-load is half-initialized, so from X import NAME raises ImportError when NAME sits below X's imports. script_parking therefore imports power inside _power_module(). Check builtins against the "Built-in Functions" section of docs/guide/builtins_and_commands.md and docs/guide/language_reference.md.
  • tests/sample_world.py: seeded synthetic save for tests and profiling. build_sample_world(size) (SIZES: small/medium/large) gives home + remote outposts, Warehouses and Large Warehouses holding at most one item per slot (5 / 15), a tiered recipe tree (ore → ingot → alloy → part → component → kit, 20 smelter + 60 fabricator recipes), stocked Inventory, Smelters, Fabricators, home and remote Supply Docks, active orders, gas/liquid Tanks, Batteries, one power grid per outpost over its buildings, Drone Depots with docked Drones, Pioneers, Habitats ("large" counts of these follow a late-game live save). route_scenario(size) gives the dest/source dicts of the drone hauler and Pioneer route planners. Extend it (not a private copy) when a new test or profile needs more of the world; test_sample_world.py smoke-tests every size.
  • devtools/perf/step_profile.py: counts CPython opcodes of one lib code path on the sample world, total and per function (inclusive), with a steps/ticks estimate (OPCODES_PER_STEP = 2.5, scheduler share at --scripts, default 112). Stub and copy frames are not counted. Work inside run_atomic() is reported apart (calls, opcodes, largest single call) and counted as at most one tick per call; --direct-only lists functions by the opcodes left outside atomic calls. --list shows the targets (fabricator, smelter, dock_plan, demands, haul, pull, wildlife_ration, wildlife_plan); add one per hot path worth tracking. Use it to compare code versions and to size lib/atomic.py chunks by their worst case; the numbers are estimates, not game measurements (§1d-1, docs/BENCHMARK.md).
  • devtools/perf/tick_profile.py: times lib functions in game ticks inside a headless run of a real save (§10b). It patches a save_scripts.py copy: every top-level function of --modules and every plain method of --classes is wrapped, and the timers run only inside the --gate call (default demand_publisher:Refresh.run_next, one sample per demand task). Each gated call logs PROF <label> total=<T> :: ... (debug), and the tool prints the median ticks and calls per function per label (--min-total drops warm-cache samples; --summarize CONSOLE_LOG re-reads a run). Read the numbers as shares: the wrappers add ~40%, and roughly double the total when hot helpers such as priority are wrapped. Never leave timers on outside the gate: their overhead pushed other run_atomic() callbacks over the 10,000-step cap. Use it where step_profile.py misleads: the synthetic worlds understated the demand refresh tasks 10-300x.
  • devtools/simulation/scan_stop_eval.py: how often the pairing method for sonar scan stops (contacts < 2 × range apart pair up, grow to maximal groups, stop in the middle) leaves a member out of range, on every seed's real contacts (node devtools/simulation/headless/sources.mjs --pois RANGE, the game's points_of_interest() list function exported by simhost.mjs as __ctPoiList). Reports failed groups (fixable by a better middle vs no single stop possible), missed contacts, and stop counts against a greedy cover over lib/scan_groups.py's crossing candidates. --middle centroid|bbox|mec, --ranges basic,wide,deep, --no-biomass.
  • devtools/perf/log_block_timing.py: reads the newest save's per-script logs (logs/<script>.log and rotations) and times every TreeConsole block (┏━/┗━) per script kind: count, median/max, median in ticks, self time without timed children, total and share of the observed window. Debug blocks are timed by their HH:MM:SS game clock, info blocks by tick, joined by a game-seconds-per-tick ratio calibrated from the logs. Times are wall game time and include sleeps/waits; --exclude drops travel/wait blocks, --since <ISO> measures only code deployed after that time (check git log for earlier perf commits on a block before reworking it). The census lines (§1d-1) give N over time: med_N is the median N at the blocks' start, med_st the median cost in steps (ticks × floor(50000 / N)), comparable across windows with different N; --sort steps ranks by total steps. Without census lines both columns show -. --headless <run dir or console.log> reads a run.mjs run instead of a save; --since then takes a tick, and --sec-per-tick overrides the calibration for runs with few debug flushes.
  • devtools/code_scan/clean_code_scan.py: one entry point for the clean-code scans, clones, features and size below. All use devtools/code_scan/scan_common.py scanned_files() and keep reviewed "leave as is" verdicts in their own ignore file, so a rerun lists only new candidates. Rerun after large refactors.
  • devtools/code_scan/size_scan.py (clean_code_scan.py size): files over --max-lines (default 1000) and functions over Ruff's C901 complexity, PLR0912 branches or PLR0915 statements limits (Ruff defaults 10/12/50, --max-complexity/--max-branches/--max-statements). Size is a smell, not a defect, so ruff.toml keeps these rules off and this scan lists candidates worst first (highest value/limit ratio). Needs the repo .venv Ruff. Hit ids are <file>::<qualname> (<module> for a file hit); reviewed keeps go in devtools/code_scan/size_scan_ignore.txt.
  • devtools/code_scan/feature_scan.py (clean_code_scan.py features): code a supported interpreter feature would simplify: value_class (@dataclass), ordering (total_ordering), property_pair, delegation (__getattr__), registry (__init_subclass__), tuple_return/tuple_index (named fields), elif_chain (match), dict_shape and ipc_key (TypedDict + StrEnum; archive and comms keys resolved to their strings, (?) when not). Hit ids are <file>::<pattern>::<subject> (no line numbers); reviewed keeps go in devtools/code_scan/feature_scan_ignore.txt. --summary for counts, -p to pick patterns, --all to show ignored ids. Text-only resolution: check feature support in game (§10 game module list) and read the code before converting.
  • devtools/code_scan/clone_scan.py (clean_code_scan.py clones): near-duplicate function scan over the same files plus scripts/contract/ and scripts/onboarding/. Bodies are normalized (names and args to _, constants to their type), compared with difflib (--min-ratio, default 0.85), and grouped into clusters; --pairs lists pairs. nolib marks a side in a tier that cannot import lib/. Reviewed pairs that stay apart go in devtools/code_scan/clone_scan_ignore.txt (file::qualname ~ file::qualname # reason, no line numbers). A high ratio means the same shape only: diff both functions before merging. Takes ~40 s.
  • devtools/perf/repeat_read_scan.py: static scan of the highest-tier copy of every file under scripts/ for game reads (stacks(), buildings(), get_component(), ...) and calls into functions that do them, made inside a loop or comprehension. Score = read weight × LOOP_N (8) per enclosing loop, callees summed by bare-name resolution; flags invariant (direct read without loop-bound names, hoistable) and atomic (reached from lib/atomic.py runners, ×0.1). Joined with log_block_timing.py (same --since/--exclude), hits are grouped under the slowest timed block whose log.start() function reaches them; [waits] marks blocks whose code can sleep()/mine(). Heuristic: verify each hit in code and check git log for earlier perf work first. --no-logs gives the static ranking.
  • Test files per module (test_production.py, test_smelter.py, test_fabricator.py, test_site_supply.py, test_factory_sites.py for per-site targets, the site plan, consumer hauling, stranded ore eviction and remote docks), home and remote-outpost cases.
  • Pyright: pyrightconfig.json has a tests environment resolving lib imports via .pyright-resolved/lib, falling back to scripts/4_controlpanel/lib.
  • Typed self in scripts: every non-lib/ script that uses the game-injected self declares its type with from typing import TYPE_CHECKING / if TYPE_CHECKING: / from user_stubs import <name> as self. TYPE_CHECKING is false in game, so the import never runs. <name> is the slot prefix (o2gen, heater, drone, ...), the contract id for a contract script, or an entry in STEM_ALIASES/SELF_TYPE_OVERRIDES (devtools/self_typing.py). Each name is bound as <name>: T = ...: the game language server exports only names user_stubs.py binds, so a bare <name>: T gives "Module 'user_stubs' has no export" (hover still shows T). The names live in a marked block at the end of the save's user_stubs.py (player-owned: the game creates it once and never overwrites it; the in-game editor, the VS Code extension and Pyright all read it). Every sync rewrites that block in the save (sync_user_stubs(), text outside the block kept, backup in devtools/.sync-backups/), and resolve-preview writes the merged copy to .pyright-resolved/stubs/user_stubs.py. The block is generated from the game's language server (external-ide/server/server.cjs, scriptPrefix + machines.<type_id>.name) and the save's __builtins__.pyi (class = PascalCase of type_id, else matched by display name). A prefix shared by several types (drone) is a union; each contract gets a ContractScript subclass typed with its own <Id>Contract. New script: python devtools/self_typing.py apply; tests/test_self_typed.py fails on a script that uses self without the declaration. SELF_TYPE_OVERRIDES also holds panel (the injected panel global, imported under its own name). COMPONENT_EXPORTS in the same file lists component classes re-exported from user_stubs for the typed accessors in lib/components.py.

§10b Headless Simulation (devtools/simulation/headless/)

Runs the decompiled simworker in Node at full CPU speed: real systems, Python interpreter and step budget, no UI, no wall clock. Needs Node ≥ 20 and the internals/ submodule. Findings, speed table and the plan for later phases: docs/plans/headless_sim.md.

  • simhost.mjs: Sim.create() loads the simworker with a run-time export shim (cached as devtools/simulation/headless/.cache/sim-<hash>.mjs, gitignored; the decompiled code is never committed). load(saveJsonText) (running scripts resume), newGame(seed), setScript(id, source), tick(n), serialize(), terraformIndex() (researchRates.terraform.lastValue), onConsole(fn) (script lines and crashes), systemMs() (wall time per system). create({skipSystems, keepDebug, logLevels}): skips DEFAULT_SKIP_SYSTEMS (AchievementSystem) and clears every script/library debug flag on load unless told otherwise (a flagged source makes the scheduler snapshot debug state at every step). newGame()/load() also write the console.log_levels archive dict (cheatsheet §0a Log levels) as DEFAULT_LOG_LEVELS ({"*": "debug"}) with logLevels entries merged over it; logLevels: null keeps the save's dict. load() also confirms the running build in the system.good_version archive entry (the build hash comes from the simworker's get_game_version literal), so an older save's controllers don't halt at lib/version_guard.py; create({keepVersionGuard: true}) / run.mjs --keep-version-guard keeps the save's entry. Free debug (patchFreeDebug(), on unless create({paidDebug: true})): a debug-level console call returns without the flush yield, so it no longer pauses the script until the next tick (in game every console call costs that 0.1 s). Scripts log the full debug/trace trail into console.log but pay game time only for info/warn/error lines; string building and TreeConsole buffering still cost interpreter steps. Measured: 40 console.debug() calls take 41 ticks paid, 1 tick free. load(save, {libs}) replaces the save's libraryScripts sources (source, deployedSource, active variant) with {module: source}, so an old save runs current lib/ code; a module the save lacks is added as a new library entry (the game's load gives it an incarnation id), listed in sim.libraries.added. Control Room panels draw into a no-op OffscreenCanvas stub. One Sim per process (module-level state). After a game update: the shim finds the minified names it needs (core, SimHost, state load/serialize, command registry) in the worker bootstrap by stable strings (BOOTSTRAP_PATTERNS), so a rebuild usually needs no change; a pattern that no longer matches stops the load with its key. The optional patches (per-system timing / --skip-systems, --sticky-fluids, free debug) and the scheduler console taps only warn ([headless] simworker changed: ...) and switch off; sim.features says which are on.
  • run.mjs: CLI, options in its header. --save (by default its slots and lib/ get the repo's current scripts: run.mjs calls save_scripts.py into <out>/latest_scripts and passes it as --scripts/--libs; --as-saved keeps the save's own code, and --scripts, --libs, --deploy-templates or --policy also turn this off), --hours, --until-tp, --deploy-templates <dir> (in-process stand-in for the earlygame runner's deploy loop, EARLY_DEPLOY_MAP), --out <dir> (console.log, metrics.jsonl, final_save.json), --profile, --skip-systems, --keep-debug, --log-levels <json|file|save> (e.g. '{"power": "trace"}'), --lib-tier <dir> (with --deploy-templates: once <dir>/.criteria is met, adds <dir>/lib through library.create, switches templates to <dir> first, redeploys every changed machine script and runs orchestrator_automation.py and builder_automation.py (fleet commission, so queued Pioneers get built) in new Automations via automation.create, as the player sets them up in game), --paid-debug, --libs <dir> (e.g. scripts/4_controlpanel/lib), --scripts <dir> (<slotId>.py into each slot; new slots run, running ones restart, stopped ones stay stopped), --fail-on-error, --field-seed N (with --save: the Harvester field of seed N, fresh; the rest of the world stays the save's). A new game (no --save) has no generator and its first purchases are the player's, so without --policy the Terraform Index stays 0; run.mjs warns. Focused runs: --scenario FILE (docs/headless/scenarios.md) sets each subsystem's mode (real, off; terraforming park, standin, scale; power trim, topup; logistics mover; plants produce, cash; construction instant: mechanisms and boundaries in docs/headless/standins.md, fidelity per mode in docs/headless/ab_results.md), feeds and drains items (flows), seeds archive keys and holds the step allowance at the full base's value (virtual script count); --standin SUB=MODE[,k=v] overrides one subsystem (e.g. --standin plants=produce,forage_h=4000; sweep=false on a stopping mode leaves that group's archive left-overs); --script-set PATH|none picks the script-set profile (stubs, budget record, orchestrator markers, request protocol; default profiles/code_terraform.json, docs/headless/standins.md "Profile"). --include-autoplay stages autoplay/ too (its lib modules through save_scripts.py --include-autoplay, the planner Automation infra_planner_automation.py created after load); without it, a save holding autoplay libs or slots runs their stale copies, and every --save run but --as-saved warns, naming them (the default staging through save_scripts.py; a run staging its own scripts through save_scripts.py --check, which skips what its --scripts/--libs replace). Below the lib tier the warning stays quiet (scripts_sync.build_index()'s gate); --include-autoplay and --strip-autoplay act at every tier. --strip-autoplay (excludes --include-autoplay) loads none of it: autoplay slots get an empty script, autoplay lib modules are dropped from the loaded copy (strip_autoplay.json in the staged lib/, passed as Sim.load(save, {dropLibs}); the save file and the caller's save object stay unchanged), and a slot or lib still importing one is reported. --auto-approve N answers the planners every N ticks (OK on every outpost suggestion marker, approved on every open BUILD-card proposal; [approve] lines in console.log; founding itself never executes headless, docs/headless/standins.md). The older flags are sugar for the same: --only-scripts harvester_1 (every other group off, the ids kept), --stock ITEM=N (flow keep), --drain ITEM:TICKS (flow after), --park (terraforming park); summary.json reports standins (modes, allowance, flows, stubs, profile, leftovers, sweepLive, revived, and per mode wakes, standin, scale, mover, trim, topup, produce, cash, instant; field list in docs/headless/scenarios.md) plus the old stocked/drained.
  • field.mjs: port of the game's Harvester field generator (a pure function of the world seed). --seeds A-B value statistics, --show SEED, --check SAVE (port vs a save's grid; run after a game update). Seed scoring: docs/plans/scoring_map_seeds.md.
  • harvest_model.mjs: offline model of the early Harvester on a field (µs per field; route-exact against headless runs). harvest_policies.mjs: route policies for it (hybrid = the current 0_cold_boot harvester.py), --eval/--grid over a random field sample, --check against headless runs, reachPossible() (admissible bound for scans). seedscan.mjs: scans all world seeds by recipes and Harvester score (--score reach). seedconfirm.mjs: runs a scan's top seeds in fresh headless games and compares credits with the model (--rank scan|cr|20k). Same plan doc.
  • devtools/simulation/seed_quality.py recipes: port of the game's seed recipe generator (a pure function of the world seed) scored against the fixed biosite supply. --seeds A-B, --show SEED, --check SAVE (port vs a save's recipeMap; run after a game update). Same plan doc.
  • sources.mjs: the seed's vents, exotic deposits and fluid wells from the game's own generators (exported by the shim, __ctWorldGen); --seed N, --seeds A-B, --in FILE.jsonl [--out], scores in docs/plans/scoring_map_seeds.md Part 3. The game's UI thread (main-*.js), not the worker, runs them: vents and deposits on a new game, then wells and anomalies on every load (each skipped when its kind exists). Sim.newGame() calls all four in that order (simhost.mjs generateWorld()), and swap_seed.py writes them into the swapped save via sources.mjs --emit.
  • devtools/play/swap_seed.py --save FILE --seed N [--apply] (a save tool, not part of headless runs): swaps a young save's world seed and regenerates the seed-decided state (seed, planet.plants.recipeMap, harvesting.grid, planet.sources, planet.geologicalAnomalies) in the save and its .h*.json snapshots, from the Python ports (seed_quality.recipes(), its own field(), a copy of field.mjs). --save is explicit, never auto-detected; close the game first; refuses a save with progress unless --force; backups in devtools/.sync-backups/seed-swap/. Dry run without --apply. Best all-round seed: scoring_map_seeds.md.
  • Save inputs (run.mjs --save, field.mjs --check, save_scripts.py --save, seed_quality.py recipes --check) take plain .json or gzipped .json.gz, detected by magic bytes (devtools/simulation/headless/savefile.mjs, devtools/savefile.py). Sample saves in internals/sample_saves/ are gzipped.
  • devtools/play/decision_recorder.py (a save tool, outside the game): watches a manual run's save file, logs every change, asks in the terminal for a reason at major changes, and writes gzipped save copies to internals/sample_saves/<YYYYMMDD>_<commit>/ as headless start points. It also appends new script console lines from console/<save id>.json to console.jsonl.gz there. Details in its docstring; purpose in building_planner.md.
  • devtools/play/save_diff.py (a save tool): diffs consecutive kept saves of a recorder run (buildings per outpost against the building cap, tiers, tech, orders, purchases, power, fluids, running scripts, stock), matches each owner reason from events.jsonl to the rows it explains and lists the unexplained decision rows. Reports carry save details, so --out goes to private storage. Purpose in save_database.md.
  • save_scripts.py: maps the repo's current scripts onto a save's slots for --scripts, so an old save runs current scripts and libs. run.mjs --save runs it by default; call it by hand for another commit's scripts (A/B). .venv/Scripts/python.exe devtools/simulation/headless/save_scripts.py --save <save.json> --out <dir> writes <dir>/<slotId>.py for each slot whose resolved source differs and <dir>/lib/ for --libs. Matching, placeholders and renumbering follow scripts_sync.py's sync_file(); placeholders come from the slot's code in the save or the template default, and a slot with neither is skipped and listed. A marker naming a renamed role (RENAMED_ROLES) maps to the current role; a slot holding a removed role (RETIRED_ROLES) gets an empty script, so its old code doesn't crash on current libs. Add both maps' entries when a role is renamed or removed. --tier defaults to the tier the save's progress meets (.criteria, as scripts_sync.py picks it, without the high-water mark).
  • --policy plan.json (policy.mjs): plays the Shop and Inventory from a build-order plan, through the UI commands (Sim.buy/deploy/undeploy/sell/drop). This also works before Ship Computer. The tier-0 solar.py buyer is switched off; with --lib-tier the policy keeps placing buildings and lib/early_buyer.py (state generators False) buys the vehicles (§2m). From the lib tier on the policy powers only what it deploys. --until-pioneer waits for a ready scout Pioneer. summary.json reports reachedH, tpH, POIs, net worth and brownout seconds. Build-order search driver and results: devtools/simulation/buildorder_search.py, early_optimization.md.
  • Patched-module cache: keyed on the raw simworker plus simhost.mjs, so an unchanged build starts in about 1 s. It is written atomically for parallel runs.
  • Reading a save from the save folder is fine; the harness never writes there.

§10c After a Game Update

Tools that copy or port game internals. Run each check on the new build before relying on the tool. Each step names its pass condition: a step whose condition holds needs no judgment; anything else (a failing check, a feature the fix would drop, an unclear diff) goes back to a reviewer.

A fresh save of the new build: node devtools/simulation/headless/run.mjs --seed N --hours 0.001 --out DIR writes DIR/final_save.json (bare state, accepted by all checks below).

  1. API docs: export the DOCS Manual in game, run python devtools/game_update/split_docs_manual.py, review its routing report and git diff (docs/README.md).
  2. Shared fakes: python devtools/game_update/extract_game_spec.py, review the tests/game_spec.json diff (renamed methods, new statuses, changed defaults), then run the suite (§10). Pass: exit 0, unresolved 0, no duplicates, coverage ok. The coverage line lists any docs/components/*.md or scriptable machine without an api entry, i.e. methods the extractor missed (new registration style); a doc file named apart from its API id goes in DOC_API_ALIASES. Tables are found by anchor strings, not minified names.
  3. Seed generators: on fresh saves of 3 seeds, python devtools/simulation/seed_quality.py recipes --check SAVE.json and node devtools/simulation/headless/field.mjs --check SAVE.json (pass: port matches). devtools/play/swap_seed.py relies on both ports (its field() is a copy of field.mjs: fix both). Round trip: copy seed A's save to save_test_a.json, swap_seed.py --save save_test_a.json --seed B --apply; pass when seed, planet.plants.recipeMap, harvesting.grid, planet.sources and planet.geologicalAnomalies equal seed B's fresh save. Don't swap a seed until all pass.
  4. Headless: needs the new decompiled simworker in internals/; the patched-module cache rebuilds itself (§10b). Pass: the fresh-save run prints no [headless] line, and node --test "devtools/simulation/headless/test/*.test.mjs" is green (anchor policy and the per-patch table: docs/headless/anchors.md). Every simworker changed: warning means a lost feature (a hook not found) or a pattern step slower than SLOW_STEP_MS (a quadratic scan; first build takes well under 1 s otherwise). Then load a sample save (latest scripts by default): no crash, errored 0, no Game version changed line. Then node devtools/simulation/headless/anchors.mjs: prints the feature table, the five scale anchor counts and the instant wait count (want 1 each) for the current internals/ worker, exit 1 on any miss; a lost scale anchor means that stand-in mode falls back to standin, a lost instantBuild anchor leaves construction instant finishing jobs in the state only, until the pattern in anchors.mjs is updated (docs/headless/anchors.md, "After a game update").
  5. devtools/play/game_speed.py: finds the sim clock by pattern in the simWorker bundle; "sim clock not found" means the pattern needs updating (§8a).
  6. Changes the changelog leaves out: python devtools/game_update/simworker_diff.py diffs the previous internals/ simworker commit against the working file, ignoring minifier renames (--old/--new take a revision or a .js path). Writes devtools/game_update/.simworker-diff/<old>_<new>.md (gitignored: decompiled code). Read Number changes first (a constant that moved, with its table row), then Code changes and Added (code); Text changes often name a behaviour change too (a description that says 25× instead of 5×). Editor and tutorial chunks are hidden unless --all. Findings go into the build's adoption notes, not into tracked copies of the code.