Rules for everyone who edits code in this repo. Numbers, formulas and module maps live in docs/AI_CHEATSHEET.md and its docs/cheatsheet/ files; this file links to them rather than repeating values. Code comments cite these rules as CODE_GUIDES.md#<section>, so keep the section headings stable.
- Machine scripts run existing machines and coordinate them. They don't set machines up.
- Exceptions: deploys from a control panel that need operator input, and undeploying machines whose step is finished.
- Founding outposts happens only in
autoplay/. Each founding raises the cost of the next outpost (outposts can be decommissioned, so it is not permanent). Code that founds an outpost logs why in itsdebug()trail.
- Plan save-agnostic. Code must work on an empty map and on a crowded one.
- Discover at runtime: capability probing, building discovery via
outpost_network, location queries. No hardcoded save-specific ids or coordinates. - Decide only from data a script can read in game: components,
points_of_interest(),journal, the archive. Never hardcode world knowledge or read the save file to drive behavior. - Exempt: formulas and fixed game limits (kit prices, building caps, fixed rates).
- A live save shows how a mechanic works. It doesn't show which cases matter, so don't rank a case as rare because the current save already handles it.
- Partly known world data (unsurveyed sites): use runtime-derived priors with a confidence value, or request a survey trip. Don't guess.
The game runs a restricted Python interpreter. CPython, Pyright and the offline tests accept code that fails in game.
- Import only our own
lib/modules and the game modules listed in stub_tests.md §10. No standard library (time,copy,os,sys, ...). Enforced bytests/test_game_imports.py. - No module-level import cycles between
lib/modules. In game,from X import NAMEgets a half-loaded module and raisesImportError. Break a cycle by importing inside the function that needs it. The same test checks the highest tier's copies. - Keep module bodies cheap. The game runs a
lib/module's body, together with every module it imports for the first time, as one unit under the 10,000-step cap (decompiledexecuteModuleBodySync); going over ends the importing script withStepLimitErrorat whatever line hit the cap. The autoplay planner's import chain sits close to it: a few module-level comprehensions (~1,300 steps of tile offset tables) crashed it at load. Build tables lazily on first use (grid_geom._offsets()), not at module level. - One-line imports only. The game parser rejects
from x import (a, b). Enforced bytests/test_game_syntax.py;ruff.tomlinscripts/andautoplay/keeps Ruff from wrapping imports. - No backslash line continuation. Wrap a long expression in parentheses instead. Enforced by
tests/test_game_syntax.py. - Check a builtin before using it: "Built-in Functions" in docs/guide/builtins_and_commands.md and docs/guide/language_reference.md. Known missing:
frozenset(use a tuple),id(). Enforced bytests/test_game_builtins.py. - No
withstatements. Don't rely onfinally: a stopped script is killed without unwinding. - Unsure about other syntax: check that an existing lib already uses it live.
- Never set or delete an attribute on a game object (a machine, vehicle or other
Component). Since build 58191a1 this raisesAttributeError("object attribute 'x' is read-only" for a game field). Keep per-machine values in our own class or a dict keyed by machine id. - Hardware-changing calls on another machine (e.g.
input.eject()) work only from that machine's own script, even when the docs don't say "self only". A remote script may read (count(),stacks()) and userun_control. Coordinate cross-machine changes through the archive or Signal Bus.
- Source lives in
scripts/<tier>/.lib/x.pymeans the logical modulex, physically atscripts/<tier>/lib/x.pyfor the highest tier that defines it (dev_workflow.md §9). - Put reusable logic in small, focused
lib/modules (module map, cheatsheet §0). - Entrypoint scripts (
solar.py,rover.py,status_panel.py, ...) stay thin. They use shared controllers fromlib/and never keep their own copies of tier lists, thresholds or budget formulas. - One definition per constant. Before adding one, look upwards: does it exist already?
- Used in one function or class: define it there.
- Shared, and tied to one module's logic: define it in that module and import it from there (Plants bands in
plant_terraformer_common, tier ladders initem_tiers, claim expiry infleet_claims_common). - A fixed game fact (ids, sizes, rates) used in several places:
lib/game_rules.py, in its section. It imports nothing; never put our tunables there.
- Controllers composed of mixins (vehicle, drone, pioneer, harvester, plant terraformer, ...) type
selfthrough one_hostproperty per mixin:Methods useif TYPE_CHECKING: from vehicle import VehicleController class VehicleMiningMixin: @property def _host(self) -> "VehicleController": return self # type: ignore[return-value]
self._host.<attr>, includingself._host.log. - Don't use a fake base class (
_Base = Controller if TYPE_CHECKING else object). It creates an inheritance cycle at the composition site. - After changing mixin typing, run Pyright on the composition site (
lib/vehicle.py,lib/drone.py, ...), not only on the mixin file. - Vehicle layout (layer table: docs/plans/mixin_refactor/README.md):
- A mixin is one ability and calls only lower layers. No role loop inside a mixin.
- A
Job(lib/job_*.py) owns its role's state and step logic and never stores state on the host. It types the host underTYPE_CHECKING;pioneer.py,rover.pyanddrone.pyimport the job modules. Drone jobs derive fromDroneJob(lib/drone_job.py);FleetUnitMixin.run_job_loop()runs both kinds. - Mission state has one writer,
VehicleClaimsMixin/DroneClaimsMixinbegin_mission/end_mission. Readers useself.mission;current_target*are read-only property shims. - Pure math and archive I/O are module functions with explicit arguments.
- Probe capabilities at runtime and handle missing or unpowered components.
- Every
except Exceptionthat recovers callsswallowed(where, error)fromlib/swallow.pyas its first line. A broad except can't tell a missing component from a bug in our own call. Usage and the allowed exceptions: cheatsheet §0b.
The Data Archive has a fixed key-count cap that doesn't grow with fleet or building count. Keys and conventions: archive_ipc.md §4.
- One shared dict per concern, never one key per entity. Store per-entity state as
{entity_id: value}under one key (e.g.vehicle.recall,drone.home_depots), written viaarchive.transaction(). - Never use
__proto__,prototypeorconstructoras a dictionary key anywhere in a value:set()/transaction()refuse the whole value (invalid_value). Store such names as values (a list of entries) instead. Check the result status of a new key's first write. - Prune entries for entities that no longer exist.
- Keep data bounded: fixed-size histories, compact summaries, JSON-safe structures. No large binary data or unbounded logs.
- Use the archive for telemetry, production history and order tracking, so every component sees one consistent state.
- Persist enough state to resume after a power loss or restart. Example: a smelter mid-production resumes its run; a rover in transit resumes its trip and finishes the mission.
- Use the Signal Bus (
get_component("comms")) for real-time orders and event broadcasts. Check message age withlatest_info()and treat stale messages as missing. - When a publisher is missing or stale, fall back to reading the component directly.
Use TreeConsole (lib/tree_console.py) for all console output, never ad hoc get_component("console").print(). Pattern and format: cheatsheet §0a.
- Info level: major blocks and outcomes, skimmable at a glance.
debug(): the decision trail: which branch was taken, candidates considered and rejected, computed thresholds and estimates. With debug on, the log tells the whole story of a run.trace(): per-item and hot-loop detail. Never put per-item lines at info level, also not in one-off probe scripts. Prefer aggregates (counts, group-by) to listing items.- Every console call costs 0.1 s of simulation time, even when hidden (docs/BENCHMARK.md).
TreeConsolebuffers consecutive debug lines into one message. Calllog.flush()before everysleep(). - Wrap each coherent unit of work (trip, order cycle, build, sweep, active tick phase) in
log.start(...)…log.end(<outcome>). Close everystart()on every path: earlyreturn, error branch,continue,break. Enforced bytests/test_log_blocks_balanced.py. For a debug block around a whole function with several exits, prefer@method_block()/log.run()(cheatsheet §0a, "Wrapped blocks"). - Each top-level
run*loop starts every tick withreset_all(), because an escaping exception leaves a block open (tests/test_reset_in_run_loops.py). - No block on an idle tick.
Above 50 running scripts, every running script (sleeping ones included) shrinks every other script's step allowance. The count matters, not how busy each script is. Model and numbers: dev_workflow.md §1d-1, measurements in docs/BENCHMARK.md.
- Don't add a running script where an existing one can do the work.
- Prefer scripts that end when their machine has nothing to do and get restarted (
run_control.start()) when it does, where the machine's idle state is acceptable. - Cache discovery and pure geometry. Compute shared results once centrally (the
orchestrator_automation.pyAutomation, published to the archive), not in every instance. - Replace per-item Python loops with builtins and comprehensions.
- A Control Room card loop ends with
panel_pace.pace(panel); never let a card redraw every tick. Its cost is the Python that builds a frame, not the widgets. FluidPort.connections()re-validates the pipe analysis over every machine on each call (O(machines)), even when nothing changed. Cache its result in hot loops;connected_id()is cheap.- Optimizing tick cost, in this order:
- Cut real work: repeated reads of the same key or discovery inside a loop, per-item calls that one bulk read covers (
stacks()over onecount()per item), repeated walks that one pass covers. - Then consider
lib/atomic.py(run_atomic/run_batched/run_chunked) for the remaining read-only, non-logging work. It avoids the per-tick step limiter but doesn't reduce work. Each callback is capped at 10,000 steps; exceeding the cap ends the script. No writes, archive writes, scans or sleeps inside a callback. Logging through the passed-inlog(TreeConsole) orswallowed()is fine inside these runners:atomic.console_print()queues the lines and writes them after the call. Rawmap()/sorted(key=)/lru_cachecallbacks stay log-free. Size chunks withdevtools/perf/step_profile.py.
- Cut real work: repeated reads of the same key or discovery inside a loop, per-item calls that one bulk read covers (
Implement these exactly as the linked sections describe; don't second-guess them.
- Power grid: tiered load shedding by
PowerGridManager(lib/power.py). It is deliberately not "protect terraforming first". Tiers and thresholds: power_fluids.md §1a. - Vehicles and drones: vehicles_drones.md.
- There-and-back energy budget with a safety margin, a hard emergency-reserve floor and per-vehicle calibrated Wh/m (
lib/vehicle_energy.py, §2a). - Atomic site reservations in the archive with heartbeat renewal and timeout expiry (
lib/vehicle_claims.py). - Deadlock and terrain-stall detection, staggered base staging slots (
lib/vehicle_navigation.py).
- There-and-back energy budget with a safety margin, a hard emergency-reserve floor and per-vehicle calibrated Wh/m (
- Production: demand-driven (production_logistics.md,
lib/production.py).- Harvest and mine to match active recipe and Earth order deficits. Don't overproduce when inventory or storage is full.
- Plan ahead from current and upcoming orders, placed blueprints and available resources.
- Demand priority: one ladder (
lib/priority.py, fabricator_demand.md §2a-p). A new demand gets a band on an existing ladder; never a parallel flag, tier list or side key. Haulers rank by band only; the fine value breaks ties inside machines and the dock planner. - Stock netting: one count per question. "Make more of X?" nets against
SourceCache.fab_have()/network_have(): stock plus what producers already hold (output not yet in storage, one unit per running craft, loaded inputs). "Can I take X now?" and "protect X" countheld_stock()/local_stock(). Moving a unit between storage and a machine must never change a target. A new producer reports its holdings throughSourceCache, never a private stock read. Mechanics: production_logistics.md, "Pipeline netting".
- Display names belong to the player. Never key logic on them; use
.id. Code may preseed a name only when it creates the machine (pioneer_commission.commission_name()), may carry the old name over when it replaces one (thefleet_upgradedrone swap), and may replace a name it gave itself (a Pioneer refit,pioneer_refit.is_code_name()). An operator-set script variable that names a machine (HOME_DEPOT) may accept a display name; resolve it to the id once.
- Comments, docstrings and the cheatsheet describe what the code does now, plus any non-obvious constraint. No narration: no "previously X", "now Y", "was changed because", "bug fixed on …", "found live". Remove narration you find in files you touch.
- The reason for a change goes in the commit message. Lasting design decisions go to the matching topic file in docs/design_history/ (hub: docs/DESIGN_HISTORY.md).
- A tunable constant (margin, tier, threshold, stale-tick count, budget) has one documented home in the cheatsheet. Update it in the same change as the code. Elsewhere, link to it or name the constant.
- Offline suite:
python -m unittest discover -s tests. Details: stub_tests.md §10. - Extend the shared fake world in
tests/game_stubs.py; never add a private fake. - A bug found in game: name the general mechanic behind it, check every other place it can hit, and fix or report those too. Model the mechanic in the shared fakes so every controller's tests can exercise it.
- Ruff config:
ruff.toml, which the game's VS Code extension also reads. Never fix RUF100 under--select: it then strips every noqa for a rule outside the selection. ruff formatexcludes Markdown (game reference text keeps hand layout).- Pyright config:
pyrightconfig.json. It reads the gitignored.pyright-resolved/libcopies, so run.venv/Scripts/python.exe devtools/scripts_sync.py resolve-previewafter editingscripts/*/lib(plainpythonlackstyper); stale copies hide cross-module errors. - When you restructure a function or file listed in a scan ignore file (
devtools/code_scan/*_ignore.txt), recheck its reason in the same change; re-pin (size_scan.py --pin) or drop the entry. The size scan re-flags entries that grew past their pin.
- Conventional Commits:
<type>(<scope>): <imperative summary>. Types:feat,fix,refactor,perf,docs,test,chore,build,ci,style,revert. - Subject: imperative, 50 characters when possible, 72 at most, no trailing period.
- Body only when needed: the non-obvious why, breaking changes, migration notes. Wrap at 72.
- State intent; the diff shows what changed.