#include "evo/processes/ecosystem.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::filesystem::path load, save, output, metrics; bool verify_replay{}; bool ecosystem{}; 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; 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 (++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") { 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; } else if (key == "--tick-limit") { options.tick_limit = *parsed; } else { options.ticks = *parsed; } } 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}; } // Episode measurement shares no state, snapshot or particle metric with the proof run. if (options.ecosystem && (entities_option || options.verify_replay || !options.load.empty() || !options.save.empty() || !options.metrics.empty() || options.episodes == 0 || options.tick_limit == 0)) { 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()); } std::expected run(const Options& options) { if (options.ecosystem) { return run_ecosystem(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" "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"; 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; }