#include "evo/processes/ecosystem.hpp" #include "evo/processes/ensemble.hpp" #include "evo/simulation/world.hpp" #include "evo/telemetry/sinks.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { struct Options { std::uint64_t seed{123456}; std::uint64_t ticks{1000}; std::uint64_t entities{8}; std::uint64_t episodes{1}; std::uint64_t tick_limit{2000}; std::uint64_t seeds_per_cell{8}; std::uint64_t strategies{3}; std::filesystem::path load, save, output, metrics; bool verify_replay{}; bool ecosystem{}; bool ensemble{}; bool help{}; }; std::expected number(std::string_view text) { std::uint64_t value{}; const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value); if (error != std::errc{} || end != text.data() + text.size()) { return std::unexpected{evo::Error::invalid_arguments}; } return value; } std::expected validate_paths(const Options& options) { auto paths = std::array{options.load, options.save, options.output, options.metrics}; for (auto& path : paths) { if (!path.empty()) { std::error_code error; path = std::filesystem::weakly_canonical(path, error); if (error) { return std::unexpected{evo::Error::io_failure}; } } } for (std::size_t first = 0; first < paths.size(); ++first) { for (std::size_t second = first + 1; second < paths.size(); ++second) { if (paths[first].empty() || paths[second].empty()) { continue; } if (paths[first] == paths[second]) { return std::unexpected{evo::Error::invalid_arguments}; } std::error_code error; const auto first_exists = std::filesystem::exists(paths[first], error); if (error) { return std::unexpected{evo::Error::io_failure}; } const auto second_exists = std::filesystem::exists(paths[second], error); if (error) { return std::unexpected{evo::Error::io_failure}; } if (first_exists && second_exists) { const auto same = std::filesystem::equivalent(paths[first], paths[second], error); if (error) { return std::unexpected{evo::Error::io_failure}; } if (same) { return std::unexpected{evo::Error::invalid_arguments}; } } } } return {}; } std::expected parse(int argc, char** argv) { Options options; bool initial_state_option = false; bool entities_option = false; bool ticks_option = false; bool episodes_option = false; bool tick_limit_option = false; bool ensemble_option = false; for (int index = 1; index < argc; ++index) { const std::string_view key{argv[index]}; if (key == "--help") { options.help = true; continue; } if (key == "--verify-replay") { options.verify_replay = true; continue; } if (key == "--ecosystem") { options.ecosystem = true; continue; } if (key == "--ensemble") { options.ensemble = true; continue; } if (++index >= argc) { return std::unexpected{evo::Error::invalid_arguments}; } const std::string_view value{argv[index]}; if (key == "--seed" || key == "--ticks" || key == "--entities" || key == "--episodes" || key == "--tick-limit" || key == "--seeds-per-cell" || key == "--strategies") { const auto parsed = number(value); if (!parsed) { return std::unexpected{parsed.error()}; } if (key == "--seed") { options.seed = *parsed; initial_state_option = true; } else if (key == "--entities") { options.entities = *parsed; initial_state_option = true; entities_option = true; } else if (key == "--episodes") { options.episodes = *parsed; episodes_option = true; } else if (key == "--tick-limit") { options.tick_limit = *parsed; tick_limit_option = true; } else if (key == "--seeds-per-cell") { options.seeds_per_cell = *parsed; ensemble_option = true; } else if (key == "--strategies") { options.strategies = *parsed; ensemble_option = true; } else { options.ticks = *parsed; ticks_option = true; } } else if (key == "--load") { options.load = value; } else if (key == "--save") { options.save = value; } else if (key == "--output") { options.output = value; } else if (key == "--metrics") { options.metrics = value; } else { return std::unexpected{evo::Error::invalid_arguments}; } } if (options.entities > evo::max_entities || (!options.load.empty() && initial_state_option)) { return std::unexpected{evo::Error::invalid_arguments}; } // Every option must belong to the selected mode. An option that is accepted and // then ignored lets a measurement script succeed while running another workload. const bool proof_only = entities_option || ticks_option || options.verify_replay || !options.load.empty() || !options.save.empty() || !options.metrics.empty(); if (options.ecosystem && options.ensemble) { return std::unexpected{evo::Error::invalid_arguments}; } if (options.ecosystem) { // Ensemble mode counts seeds per cell, not episodes, so --episodes here // would name a quantity this mode does not have. if (proof_only || ensemble_option || options.episodes == 0 || options.tick_limit == 0) { return std::unexpected{evo::Error::invalid_arguments}; } } else if (options.ensemble) { if (proof_only || episodes_option || options.tick_limit == 0 || options.seeds_per_cell < 2 || options.strategies == 0 || options.strategies > evo::processes::max_strategies) { return std::unexpected{evo::Error::invalid_arguments}; } } else if (episodes_option || tick_limit_option || ensemble_option) { return std::unexpected{evo::Error::invalid_arguments}; } if (const auto valid = validate_paths(options); !valid) { return std::unexpected{valid.error()}; } return options; } std::expected initial_world(const Options& options) { if (options.load.empty()) { evo::SimulationWorld world{options.seed}; for (std::uint64_t index = 0; index < options.entities; ++index) { const auto created = world.create_entity(); if (!created) { return std::unexpected{created.error()}; } } return world; } std::ifstream input{options.load, std::ios::binary | std::ios::ate}; const auto length = input.tellg(); if (!input || length < 0 || length > static_cast(evo::max_snapshot_bytes)) { return std::unexpected{evo::Error::io_failure}; } evo::Snapshot bytes(static_cast(length)); input.seekg(0); if (!bytes.empty()) { input.read(reinterpret_cast(bytes.data()), static_cast(bytes.size())); } if (!input) { return std::unexpected{evo::Error::io_failure}; } return evo::SimulationWorld::restore(bytes); } std::expected advance(evo::SimulationWorld& world, std::uint64_t ticks) { if (ticks > std::numeric_limits::max() - world.current_tick().value) { return std::unexpected{evo::Error::tick_exhausted}; } for (std::uint64_t tick = 0; tick < ticks; ++tick) { if (const auto result = world.tick(); !result) { return result; } } return {}; } std::expected write_report(const Options& options, const std::string& text) { std::ofstream output_file; if (!options.output.empty()) { if (const auto valid = validate_paths(options); !valid) { return valid; } output_file.open(options.output); if (!output_file) { return std::unexpected{evo::Error::io_failure}; } } auto& output = options.output.empty() ? std::cout : output_file; output << text; output.flush(); if (!options.output.empty()) { output_file.close(); } if (!output) { return std::unexpected{evo::Error::io_failure}; } return {}; } // CLI-local fixture constants. They are measurement inputs, not simulation rules, // and are deliberately not exported by the library. See ADR-0029. evo::accounting::Inventory bundle(std::uint64_t value) { using namespace evo::accounting; return {{value}, {Femtograms{value}, Femtograms{value}, Femtograms{value}, Femtograms{value}}}; } evo::processes::StrategyConfig grazer() { return {bundle(20), bundle(3), 900, bundle(30), bundle(20), 50}; } evo::processes::StrategyConfig forager() { return {bundle(20), bundle(2), 1000, bundle(24), bundle(16), 70}; } std::expected run_ecosystem(const Options& options) { using namespace evo::processes; const ProducerConfig plants{{{10}, 1}, {2, 1}, 1000, {1}, bundle(1).matter}; const EcosystemConfig config{plants, {100'000}, bundle(200).matter, {bundle(4)}, 800, 14, options.tick_limit}; const std::array founders{grazer(), forager()}; std::uint64_t ticks{}, births{}, predation{}, lifespan{}, extinctions{}, survivors{}; std::uint64_t shortest = std::numeric_limits::max(), longest{}, fingerprint{}; for (std::uint64_t index = 0; index < options.episodes; ++index) { if (options.seed > std::numeric_limits::max() - index) { return std::unexpected{evo::Error::invalid_arguments}; } auto episode = EcosystemEpisode::create(config, founders, options.seed + index); if (!episode) { return std::unexpected{evo::Error::invalid_arguments}; } const auto summary = episode->run(); if (!summary) { return std::unexpected{evo::Error::replay_mismatch}; } if (summary->ticks > std::numeric_limits::max() - ticks) { return std::unexpected{evo::Error::tick_exhausted}; } ticks += summary->ticks; births += summary->births; predation += summary->predation_deaths; lifespan += summary->lifespan_deaths; extinctions += summary->extinction_tick != 0 ? 1 : 0; survivors += summary->surviving_lineages; shortest = std::min(shortest, summary->ticks); longest = std::max(longest, summary->ticks); fingerprint ^= summary->fingerprint + 0x9e3779b97f4a7c15ULL + (fingerprint << 6U) + (fingerprint >> 2U); } std::ostringstream report; report << "{\"rules_version\":" << evo::rules_version << ",\"mode\":\"ecosystem\",\"seed\":" << options.seed << ",\"episodes\":" << options.episodes << ",\"tick_limit\":" << options.tick_limit << ",\"ticks\":" << ticks << ",\"births\":" << births << ",\"predation_deaths\":" << predation << ",\"lifespan_deaths\":" << lifespan << ",\"extinctions\":" << extinctions << ",\"surviving_lineages\":" << survivors << ",\"shortest\":" << shortest << ",\"longest\":" << longest << ",\"fingerprint\":\"" << std::hex << std::setfill('0') << std::setw(16) << fingerprint << std::dec << "\"}\n"; return write_report(options, report.str()); } // The ensemble fixture, again CLI-local measurement input rather than a rule. The // ancestor's investment fraction sits at the schema floor because intake scales // with surface while investment scales with mass: at any larger fraction no // organism in this world can fund a birth from feeding within an episode, and the // resource axis would measure nothing. See ADR-0035. evo::biology::GenomeDraft ensemble_ancestor() { using evo::biology::Capability; evo::biology::GenomeDraft source; source.id = 1; source.origin_event = 1; source.development_version = 1; source.capabilities = {{Capability::energy_conversion, 400, 0}, {Capability::membrane, 120, 0}, {Capability::target_size, 2'000, 0}, {Capability::ingestion, 1'000'000, 0}, {Capability::reproduction, 1, 0}}; return source; } std::expected run_ensemble_mode(const Options& options) { using namespace evo::processes; constexpr std::uint32_t reference_temperature = 293'150U; const auto ancestor = evo::biology::Genome::create(ensemble_ancestor()); if (!ancestor) { return std::unexpected{evo::Error::invalid_arguments}; } const auto founders = diverge_founders(*ancestor, static_cast(options.strategies), options.seed); if (!founders) { return std::unexpected{evo::Error::invalid_arguments}; } const ProducerConfig plants{{{50}, 1}, {50, 1}, 1000, {1}, bundle(1).matter}; const EcosystemConfig world{plants, {10'000'000}, bundle(200).matter, {bundle(4)}, 800, 10, options.tick_limit}; const EnsembleConfig plan{{{reference_temperature - 15'000U, 1'000}, {reference_temperature, 1'000}, {reference_temperature + 15'000U, 1'000}, {reference_temperature, 8'000}}, options.seeds_per_cell, options.tick_limit, 300, 10}; evo::biology::LineageArchive archive; const auto measured = run_ensemble(archive, *founders, world, plan, options.seed); if (!measured) { return std::unexpected{evo::Error::invalid_arguments}; } std::ostringstream report; report << "{\"rules_version\":" << evo::rules_version << ",\"mode\":\"ensemble\",\"seed\":" << options.seed << ",\"strategies\":" << founders->size() << ",\"seeds_per_cell\":" << options.seeds_per_cell << ",\"tick_limit\":" << options.tick_limit << ",\"episodes\":" << measured->episodes << ",\"ticks\":" << measured->ticks << ",\"archived_genomes\":" << measured->archived_genomes << ",\"archived_organisms\":" << measured->archived_organisms << ",\"cells\":["; for (std::size_t index = 0; index < measured->cells.size(); ++index) { const auto& cell = measured->cells[index]; report << (index == 0 ? "" : ",") << "{\"temperature_millikelvin\":" << cell.cell.temperature_millikelvin << ",\"nutrients\":" << cell.cell.nutrients << ",\"ticks\":" << cell.ticks << ",\"extinctions\":" << cell.extinctions << ",\"halves\":["; // Both halves are reported, never merged: a difference that shows in one // and not the other is an artifact of the seeds. See ADR-0035. const std::array halves{&cell.first_half, &cell.second_half}; for (std::size_t half = 0; half < halves.size(); ++half) { report << (half == 0 ? "[" : ",["); for (std::size_t which = 0; which < halves[half]->size(); ++which) { const auto& outcome = (*halves[half])[which]; report << (which == 0 ? "" : ",") << "{\"genome\":" << outcome.genome << ",\"episodes\":" << outcome.episodes << ",\"births\":" << outcome.births << ",\"organisms\":" << outcome.organisms << ",\"lived_ticks\":" << outcome.lived_ticks << ",\"thermal_shortfall\":" << outcome.thermal_shortfall << ",\"scheduled_lifespan\":" << outcome.scheduled_lifespan << "}"; } report << "]"; } report << "]}"; } report << "],\"fingerprint\":\"" << std::hex << std::setfill('0') << std::setw(16) << measured->fingerprint << std::dec << "\"}\n"; return write_report(options, report.str()); } std::expected run(const Options& options) { if (options.ecosystem) { return run_ecosystem(options); } if (options.ensemble) { return run_ensemble_mode(options); } auto loaded = initial_world(options); if (!loaded) { return std::unexpected{loaded.error()}; } auto world = std::move(*loaded); std::optional replay; if (options.verify_replay) { replay = world; } if (const auto result = advance(world, options.ticks); !result) { return result; } if (replay) { const auto half = options.ticks / 2; if (const auto result = advance(*replay, half); !result) { return result; } auto restored = evo::SimulationWorld::restore(replay->serialize()); if (!restored) { return std::unexpected{restored.error()}; } if (const auto result = advance(*restored, options.ticks - half); !result) { return result; } if (restored->serialize() != world.serialize()) { return std::unexpected{evo::Error::replay_mismatch}; } } if (!options.save.empty()) { const auto bytes = world.serialize(); std::ofstream snapshot{options.save, std::ios::binary | std::ios::trunc}; snapshot.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); snapshot.close(); if (!snapshot) { return std::unexpected{evo::Error::io_failure}; } } if (!options.metrics.empty()) { if (const auto valid = validate_paths(options); !valid) { return valid; } std::ofstream metrics_file{options.metrics}; evo::PrometheusTextSink sink{metrics_file}; sink.observe({world.current_tick(), static_cast(world.entities().size())}); metrics_file.close(); if (!metrics_file) { return std::unexpected{evo::Error::io_failure}; } } std::ofstream output_file; if (!options.output.empty()) { if (const auto valid = validate_paths(options); !valid) { return valid; } output_file.open(options.output); if (!output_file) { return std::unexpected{evo::Error::io_failure}; } } auto& output = options.output.empty() ? std::cout : output_file; output << "{\"rules_version\":" << evo::rules_version << ",\"format_version\":" << evo::format_version << ",\"seed\":" << world.seed() << ",\"ticks\":" << world.current_tick().value << ",\"entities\":" << world.entities().size() << ",\"state_hash\":\"" << std::hex << std::setfill('0') << std::setw(16) << world.state_hash() << std::dec << "\",\"replay_verified\":" << (options.verify_replay ? "true" : "false") << "}\n"; output.flush(); if (!options.output.empty()) { output_file.close(); } if (!output) { return std::unexpected{evo::Error::io_failure}; } return {}; } } // namespace int main(int argc, char** argv) try { try { const auto options = parse(argc, argv); if (!options) { evo::log_error(std::cerr, options.error()); return 2; } if (options->help) { std::cout << "evo-sim [--seed N --entities N | --load FILE] --ticks N\n" " [--verify-replay] [--save FILE] [--output JSON] [--metrics FILE]\n" "evo-sim --ecosystem [--seed N] [--episodes N] [--tick-limit N]\n" " [--output JSON]\n" "evo-sim --ensemble [--seed N] [--seeds-per-cell N] [--strategies N]\n" " [--tick-limit N] [--output JSON]\n" "Synthetic proof. When loading, ticks are additional.\n" "Ecosystem mode measures seeded bounded episodes; it shares no state,\n" "snapshot or particle metric with the proof run.\n" "Ensemble mode runs genome-derived strategies over a resource and\n" "temperature gradient, reporting each cell's two seed halves\n" "separately. Its numbers describe that fixture and nothing wider.\n"; return 0; } const auto result = run(*options); if (!result) { evo::log_error(std::cerr, result.error()); return 1; } return 0; } catch (const std::exception&) { evo::log_error(std::cerr, evo::Error::unhandled_exception); return 1; } } catch (...) { // Last-resort process boundary, including failure of error reporting itself. return 1; }