Planet AI Technical Documentation: CiucAI

The CiucAI module is a reactive and predictive artificial intelligence developed for the autonomous management of a planetary entity. It's designed for type A planets, that can only generate Carbon resources, has five energy cells and can build a rocket. Its main function is the controlled generation of resources and the implementation of a dynamic defensive strategy against asteroids. The AI operates on a state model that statistically adapts to external environmental conditions.


0. File Structure

The project is organized into modules to separate functionality and provide a clear interface for external users:

This modular structure allows external users to interact with the AI by importing the main crate and calling only the exposed functions, keeping internal details encapsulated.

1. Architecture and State Model

Data Structure (CiucAI)

The AI's internal state is maintained via the following key fields:

Field Type Function
state AIState Defines the current operating regime: SafeState or StatisticState.
estimate_sunray_ms f64 Estimate of the average time interval between Sunray events (ms). Crucial for prediction.
estimate_asteroid_ms f64 Estimate of the average time interval between Asteroid events (ms). Indicator of the threat level.
count_asteroids u32 Sampling metrics required to enable the transition to the statistic state.
count_sunrays u32 Sampling metrics required to enable the transition to the statistic state.
last_time_asteroid i64 Timestamp that rapresents the last asteroid event registred.
last_time_sunray i64 Timestamp that rapresents the last sunray event registred.

Core Constants

The AI relies on a small set of predefined constants that regulate safety behavior, thresholds, and adaptation logic across SafeState and StatisticState. These constants influence the strategies implemented in generate_carbon_safe_state(), generate_carbon_statistic_state(), on_sunray(), and on_asteroid().

Constant Usage Value
safe::SAFE_CELLS Minimum number of charged energy cells that must always be preserved in SafeState.
Used by generate_carbon_safe_state().
3
statistic::SAFE_CELLS_NEAR_ASTEROID Minimum number of charged energy cells that must be preserved in StatisticState when an asteroid is considered near.
Used by generate_carbon_statistic_state().
2
statistic::SAFE_CELLS_FAR_ASTEROID Minimum number of charged energy cells that must be preserved in StatisticState when an asteroid is considered far.
Used by generate_carbon_statistic_state().
1
statistic::SUNRAY_IMMINENT_THRESHOLD Fraction of the estimated sunray interval after which a sunray is considered imminent in StatisticState.
Used by generate_carbon_statistic_state().
0.75
statistic::ASTEROID_FAR_THRESHOLD Fraction of the estimated asteroid interval under which the asteroid is considered far in StatisticState.
Used by generate_carbon_statistic_state().
0.5

AI states (AIState)

State Description Carbon Generation Strategy
SafeState Conservative state (default/fallback). Absolute priority to defense. Strict generation: requires more than safe::CELLS charged cells to allow the conversion of a single cell.
StatisticState High-efficiency predictive state. Priority to efficiency based on calculated risk. Dynamic generation: variable safety threshold 1 or 2 cells based on EMA estimates.

2. Prediction and Transition Mechanisms

Time Estimation (Exponential Moving Average - EMA)

The prediction of time intervals between events is managed using EMA with a smoothing factor alpha = 0.3. This technique provides a reactive estimate, giving more weight to recent observations.

$$ \text{EMA}_{\text{new}} = \alpha \cdot \text{Sample} + (1 - \alpha) \cdot \text{EMA}_{\text{previous}} $$ $$ \text{Where } \alpha = 0.3 $$

Transition Logic (change_state)

The state transition is conditioned by data maturity (at least 3 samples) and the risk/opportunity balance:

Carbon Generation in SafeState

In SafeState, Carbon generation is still triggered via the central generate_carbon() function, but the logic is delegated to the dedicated generate_carbon_safe_state() strategy. The AI follows a conservative rule designed to preserve a stable energy buffer.

Fixed Safety Threshold

Carbon generation is allowed only if the number of charged energy cells exceeds the fixed threshold safe::CELLS = 3.

This static strategy ensures:

Generation Strategy in StatisticState

In StatisticState, Carbon generation is handled by generate_carbon(), which delegates to generate_carbon_statistic_state(). The safety threshold (minimum number of charged cells to preserve) is dynamically modulated in real time based on risk and opportunity indicators.

Risk Modulation (Asteroid)

The reserved energy threshold depends on the predicted arrival time of the next asteroid:

Opportunity Modulation (Sunray)

If the time since the last sunray exceeds 75% of the estimated interval (tracked internally via on_sunray() and estimate_sunray_ms), the safety threshold is reduced by 1 because resupply is likely.

This adaptive strategy allows generate_carbon_statistic_state() to balance safety and productivity depending on the predicted environmental conditions.


3. Event Management and Interactions

Primary Event Handling

Interaction with Protocols

The AI manages communications with the Orchestrator and Explorers in compliance with the game protocols (implementation of the PlanetAI trait). Each received message triggers an internal handler and may result in a response message being sent back.

Message (Protocol) Source Response / Action
Sunray Orchestrator Execution of on_sunray.
Sends SunrayAck { planet_id }.
InternalStateRequest Orchestrator Sends InternalStateResponse { planet_id, planet_state }.
KillPlanet Orchestrator Logs shutdown event.
Sends KillPlanetResult { planet_id }.
handle_asteroid Orchestrator Execution of on_asteroid.
Returns an optional Rocket.
SupportedResourceRequest { explorer_id } Explorer Sends SupportedResourceResponse { resource_list } using generator.all_available_recipes().
SupportedCombinationRequest { explorer_id } Explorer Sends SupportedCombinationResponse { combination_list } using combinator.all_available_recipes().
GenerateResourceRequest { Carbon } Explorer Execution of generate_carbon.
If successful: sends GenerateResourceResponse { Carbon }.
If failed: logs an error (no response sent).
GenerateResourceRequest { unsupported type } Explorer Logs that the resource cannot be generated.
No response sent.
CombineResourceRequest Explorer Logs missing combination rules.
No response sent.
AvailableEnergyCellRequest { explorer_id } Explorer Sends AvailableEnergyCellResponse { available_cells }.

4. Logging Policies

The CiucAI module uses a unified logging system to track internal actions, state transitions, and communication with external actors. Logs are produced through the internal log() function and follow consistent rules.

Internal Actions

Communication with Orchestrator and Explorers

Non-Critical Errors

This logging strategy ensures full traceability of decisions and communication while maintaining uninterrupted AI execution.


5. Tests: Validation of CiucAI Behavior

The following table summarizes the set of unit tests defined inside the tests module. Each test validates a critical aspect of the AI’s behavior, such as event handling, resource generation, and the correct communication with Orchestrator and Explorer.

Test Name Category Verified Function Description
test_asteroid_with_no_rocket Orchestrator → Planet Asteroid handling Ensures the AI has no rockets initially and correctly answers with rocket = None.
test_asteroid_with_rocket Orchestrator → Planet Planetary defense After receiving at least one sunray, the AI must build a rocket and use it properly.
test_asteroid_is_the_rocket_rebuild Orchestrator → Planet Rocket reconstruction Validates that after every asteroid impact the rocket is automatically rebuilt.
test_available_energy_cell_request Explorer → Planet Energy availability Checks that the AI correctly reports the number of charged energy cells.
test_supported_resource_request Explorer → Planet Supported resources The AI must report that the only supported resource is Carbon.
test_supported_combination_request Explorer → Planet Supported combinations Verifies that no resource combinations are supported (empty list).
test_generate_carbon_safe_state Explorer → Planet Carbon generation (SafeState) In SafeState, generation only occurs with ≥ 4 charged cells. The test validates allowed and forbidden cases.
test_generate_carbon_static_state Explorer → Planet Carbon generation (StaticState) Validates the dynamic generation thresholds based on risk/opportunity in StaticalState.