World System Orchestration

This document details the architecture of the WorldSystem orchestrator and the world_system_builder module that configures it. It also provides a guide for extending the simulation by adding new sectors.

WorldSystem - The Central Orchestrator

Purpose: The WorldSystem class (proxima_model/world_system/world_system.py) is a Mesa Model subclass and the heart of the simulation. It owns the shared EventBus and the per-sector instances, runs the main per-step power/metrics/policy pipeline, and hands off to the EvaluationEngine and PolicyEngine.

Core Responsibilities:

  • Sector Initialization: _initialize_sectors() iterates config["agents_config"] and calls SectorFactory.create_sector(sector_name, self, sector_config, self.event_bus) for each entry, storing the result in self.sectors[sector_name]. A sector that fails to construct is logged and skipped (not fatal to the rest of the simulation).

  • Event Bus: WorldSystem creates a single EventBus instance and passes it to every sector at construction time. WorldSystem itself never publishes or subscribes — the bus exists purely so sectors can communicate directly (e.g. manufacturing publishing resource_allocated events to whichever sector made a ResourceRequest; see world_system_defs.EventType for the full list of event names in use).

  • Simulation Loop (step method): Defines the exact order of operations for each simulation step (below).

  • Power Allocation: Delegates the actual power-generation and distribution logic to the EnergySector, but is responsible for collecting demand from every other sector first and feeding the allocations back.

  • Coordination: Acts as the intermediary between the sectors, the EvaluationEngine, and the PolicyEngine.

Simulation Step Lifecycle

WorldSystem.step() executes the following sequence every simulation step:

  1. Identify power consumers (_get_power_consumers): Every sector in self.sectors except "energy" (excluded by name) that exposes a get_power_demand method.

  2. Aggregate power demand: Calls get_power_demand() on each power consumer and clamps the result to >= 0, producing a {sector_name: demand} dict.

    Ordering is load-bearing here: this happens before step() is called on any sector this timestep. Some sectors — notably ManufacturingSector — decide task/robot assignment for the step inside get_power_demand() rather than inside step(), precisely so the demand number they report reflects the assignment about to execute, not the previous step’s. If get_power_demand() were called after step(), or assignment were deferred to step(), the power allocation for a step would always be one step stale. See documentation/sectors/manufacturing_sector.md section B for the sector-side half of this contract.

  3. Allocate power: Passes the full demand dict to energy_sector.allocate_power(sector_demands) (a no-op {} if no energy sector was configured). Internally allocate_power:

    • Re-clamps/snapshots the demands and sums them into total_demand.

    • Calls the energy sector’s own step(total_demand) — this is the energy sector’s step() method; it runs generation/charge-discharge logic and returns available_power. This is the only place the energy sector’s step() runs — it is excluded from the generic per-sector step loop below.

    • If available_power covers total_demand, every sector gets exactly what it asked for.

    • Otherwise splits available_power across sectors proportionally to demand (default), or via an equal/max-min-fair split if allocation_mode == AllocationMode.EQUAL.

    • Returns a {sector_name: allocated_power} dict.

  4. Step all consuming sectors: Calls sector.step(allocated_power) on each power consumer identified in step 1, passing its share from step 3.

  5. Collect metrics (_collect_sector_metrics): Calls get_metrics() on every sector in self.sectors (including energy this time), not just the power consumers.

  6. Assemble model metrics: self.model_metrics = {"environment": {"step": self.steps}, **sector_metrics}.

  7. Evaluate performance: Passes sector_metrics and dust_decay_per_step to self.evaluation_engine.evaluate(...). The resulting performance_metrics and scores are merged into self.model_metrics["performance"].

  8. Apply policies: Passes the complete EvaluationResult to self.policy.apply_policies(evaluation_result), which applies effects (e.g. throttling) that sectors read back on their next step.

world_system_builder - The Configuration Builder

Purpose: proxima_model/world_system/world_system_builder.py translates raw database documents (world system, experiment, environment, component templates, goals) into the plain configuration dict that WorldSystem.__init__ consumes directly — no further transformation happens between the builder’s output and the sectors’ configs.

Entry point — build_world_system_config(world_system_id, experiment_id, db, resume_state=True):

  • Loads the world_systems, experiments, and environments documents, plus every component_templates document (keyed by _id).

  • Builds the base dict with keys sim_time, hours_per_step, p_need (hardcoded 2.0), agents_config, environment_name, metrics, resources, and dust_decay_per_step — these are read back by WorldSystem.__init__ as self.config.get("hours_per_step", 1) → self.time_scale, self.config.get("goals", {}), self.config.get("metrics", []), and self.config.get("dust_decay_per_step", 0.0).

  • For each sector, instantiates that sector’s builder with component_templates, calls .build(...) on the matching slice of active_components[0] (the function assumes a single component-group dict), and stores the result under config["agents_config"][sector_name]. If resume_state is true and world_system["latest_state"]["sectors"][sector_name] exists, that persisted state dict is attached to the sector’s config as latest_state so the sector can resume mid-run instead of starting fresh.

  • Finally builds config["goals"] via GoalsSystemBuilder.

Sector builders (all subclass ComponentBuilder except GoalsSystemBuilder):

Builder

Produces (agents_config[name])

EnergySectorBuilder

generators, storages lists, split by template type (power_generator / power_storage)

ScienceSectorBuilder

science_rovers list

ManufacturingSectorBuilder

isru_robots list plus initial_stocks (passed through from the world system document, not templates)

EquipmentManufacturingSectorBuilder

initial_stocks / minimum_levels merged from any component entry containing an equipment_stock / minimum_levels key (no templates involved)

TransportationSectorBuilder

rockets, fuel_generators lists, plus every field of TransportationConfig defaulted and then overridden by any component entry that has no template_id (treated as sector-level config, not a component instance)

ConstructionSectorBuilder

printing_robots, assembly_robots lists, plus max_concurrent_projects / shell_storage_capacity defaults overridable the same way as transportation

GoalsSystemBuilder

performance_goals list, loaded from db.find_by_id("goals", goal_id) for each ID in active_goal_ids, skipping anything that isn’t a performance_goal type document

ComponentBuilder (base class): Provides _get_template(template_id) (logs and returns None on a miss) and _merge_config(component, template), which layers template["config"], then template["default_config"], then the component instance’s own config (instance values win), and wraps the result in a ComponentConfig dataclass.

Dataclasses defined but only partially used:

  • ComponentConfig and PerformanceGoal are actively constructed and consumed (PerformanceGoal.to_dict() feeds GoalsSystemBuilder’s output).

  • WorldSystemConfig is defined with the “proper” field names (e.g. time_scale) but is never instantiated anywhere in the codebase — build_world_system_config assembles and returns a plain dict (using hours_per_step, not time_scale) instead. See the TODO below.

Example — a manufacturing config as emitted into agents_config:

{
  "sector_name": "manufacturing",
  "initial_stocks": { "H2O_kg": 5.0, "He3_kg": 10.0 },
  "isru_robots": [
    {
      "template_id": "comp_isru_robot",
      "subtype": "standard",
      "config": { "ice_extraction_power_kWh": 5.0, "isru_modes": ["ICE_EXTRACTION", "HE3_EXTRACTION"] },
      "quantity": 4,
      "metric_contributions": [
        { "metric_id": "IND-DUST-COV", "contribution_type": "predefined", "contribution_value": 0.01 }
      ]
    }
  ],
  "latest_state": { "...": "only present when resume_state=True and a prior run persisted state" }
}

How to Add a New Sector

Adding a new sector to the simulation involves four main steps:

Step 1: Create the Sector Class

Create a new Python file for your sector (e.g., new_sector.py) under proxima_model/sphere_engine/. The class must implement the following methods to integrate with WorldSystem:

# /proxima_model/sphere_engine/new_sector.py

class NewSector:
    def __init__(self, model, config, event_bus):
        self.model = model
        self.config = config
        self.event_bus = event_bus
        # ... your initialization logic ...

    def get_power_demand(self) -> float:
        # Called on every sector BEFORE any sector's step() for this timestep.
        # If your sector needs to decide "what will I do this step" before it
        # can report an accurate number (like ManufacturingSector's task
        # assignment), do that planning here rather than in step().
        return 100.0

    def step(self, allocated_power: float):
        # Execute the sector's logic for one step, using allocated_power
        # (<= what get_power_demand() asked for) to gate what can be done.
        pass

    def get_metrics(self) -> dict:
        # Called on every sector (including energy) after all sectors have stepped.
        return {
            "metric_contributions": {
                "IND-DUST-COV": 0.5
            }
        }

Step 2: Create the Sector Builder

In world_system_builder.py, create a new builder class for your sector, subclassing ComponentBuilder if it needs template merging.

# /proxima_model/world_system/world_system_builder.py
# ... existing code ...

class NewSectorBuilder(ComponentBuilder):
    def build(self, components: List[Dict[str, Any]]) -> Dict[str, Any]:
        config = {"sector_name": "new_sector", "some_parameter": "default"}
        # ... your logic to process components and build the config dict ...
        logger.info("✅ Configured new sector")
        return config

Step 3: Register the Sector in SectorFactory

In proxima_model/sphere_engine/sector_factory.py, import your new sector class and add a branch to the if/elif chain in SectorFactory.create_sector (there is no registry dict — dispatch is a hardcoded string match on the lower-cased sector_type):

# /proxima_model/sphere_engine/sector_factory.py
from .new_sector import NewSector  # <-- IMPORT

class SectorFactory:
    @staticmethod
    def create_sector(sector_type: str, model, config, event_bus) -> Any:
        sector_type = sector_type.lower().strip()
        ...
        elif sector_type == "new_sector":          # <-- ADD BRANCH
            return NewSector(model, config, event_bus)
        ...

WorldSystem._initialize_sectors() will pick it up automatically as long as config["agents_config"] contains a "new_sector" key — no changes to world_system.py are needed.

Step 4: Integrate the Builder

In world_system_builder.py, in build_world_system_config, instantiate and run your new builder before the goals section is built:

# /proxima_model/world_system/world_system_builder.py
# ... existing code ...

def build_world_system_config(...):
    # ... existing builder calls ...

    construction_builder = ConstructionSectorBuilder(component_templates)
    config["agents_config"]["construction"] = construction_builder.build(components_dict.get("construction", []))

    # Add your new builder here
    new_sector_builder = NewSectorBuilder(component_templates)
    config["agents_config"]["new_sector"] = new_sector_builder.build(components_dict.get("new_sector", []))

    # Build goals configuration
    goals_builder = GoalsSystemBuilder(db)
    # ... existing code ...

Finally, add a "new_sector": [...] entry under active_components[0] in your world system JSON/document to define its components; the builder will process it on the next run.

TODO: Potential Improvements

  • [ ] Resolve the WorldSystemConfig dead code: It documents the “intended” config shape (including time_scale), but build_world_system_config never instantiates it and instead returns a hand-built dict keyed hours_per_step. Either construct WorldSystemConfig and derive the dict from it (giving validation via __post_init__), or remove the dataclass to stop it drifting further from reality.

  • [ ] Replace the energy-sector name check with a role/interface check: _get_power_consumers() excludes the energy sector by comparing name != "energy" rather than checking for an explicit “is a power producer” capability. A world system that names its energy sector anything else, or a config with more than one producer-like sector, would silently misbehave.

  • [ ] Make failed sector initialization more visible: _initialize_sectors() only logs and continues if SectorFactory.create_sector raises, which means a misconfigured sector can silently vanish from self.sectors rather than failing the run loudly.