#include "evo/biology/budding.hpp" #include "evo/biology/founder.hpp" #include "evo/server/lifecycle/cellular_batch.hpp" #include "evo/server/lifecycle/cellular_play_summary.hpp" #include "fixtures/cellular_ecology.hpp" #include #include #include #include // Rules 13 owner (Cellular_Revamp_Build_Plan.md phase 1, ADR-0179): the format 10 -> 11 upgrade, // founder 6 births, the declared revamp rules and exact restore and replay. namespace { using namespace evo; using namespace evo::server; using namespace evo::fixture; CellularLiquidRules liquid(std::uint32_t side = 48'000) { return {.currents = {5, side, side, 250, 2, 4, side / 16, side / 8, 60, 300}, .founder = {.thrust_q10 = 20'480, .reverse_thrust_q10 = 20'480, .forward_drag_ppm = 95'163, .lateral_drag_ppm = 95'163, .turn = 3'276}, .deposits = {.drift_radius_um = 200, .max_drift_q10 = 100 * 1'024, .drift_decay_ppm = 95'163, .merged_cap = 8, .bubble_radius_um = biology::cellular_mote_radius_um}}; } // The trial revamp rules (deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning). CellularRevampRules revamp(std::uint32_t essential = 250) { return {.body = {.essential_upkeep_per_thousand = essential}, .burn_pj_per_kfg = {2'000, 2'000, 2'000, 2'000}, .step = {.membrane_collection_per_mille_per_point = 2, .engulf_ratio_milli = 1'500, .engulf_reserve_percent = 100, .kill_bubble_per_thousand = 500}, .drip_interval_ticks = 20, .drip_bubble_pj = 20'000'000, .drip_bubble_fg = 1'000'000, .reserve_load_per_thousand = 1'000}; } // Reserve matter slows thrust and turning and raises thrust costs in proportion to the body. void carried_matter_is_load() { const biology::CellularHandling base{.thrust_q10 = 20'480, .reverse_thrust_q10 = 10'240, .forward_drag_ppm = 95'163, .lateral_drag_ppm = 95'163, .turn = 3'276, .thrust_cost = {1'000}, .reverse_cost = {500}}; require(cellular_loaded_handling(base, 8'000'000, 0, revamp()) == base, "an empty reserve changed the handling"); const auto heavy = cellular_loaded_handling(base, 8'000'000, 8'000'000, revamp()); require(heavy.thrust_q10 == 10'240 && heavy.reverse_thrust_q10 == 5'120 && heavy.turn == 1'638 && heavy.thrust_cost.value == 2'000 && heavy.reverse_cost.value == 1'000 && heavy.forward_drag_ppm == base.forward_drag_ppm, "carrying the body's mass again did not halve thrust and double its cost"); auto none = revamp(); none.reserve_load_per_thousand = 0; require(cellular_loaded_handling(base, 8'000'000, 8'000'000, none) == base, "a zero load share still loaded the cell"); } LifeAccount account(std::uint8_t last) { LifeAccount value{}; value.back() = last; return value; } // A rules-13 region with a founder 5 born before the upgrade and a founder 6 born after it. Owner revamp_region(std::uint32_t essential = 250, std::uint64_t fee_pj = 0) { auto rules = revamp(essential); rules.bud_fee.energy.value = fee_pj; rules.bud_fee_scale_percent = fee_pj == 0 ? 0 : 100; auto state = opening(7, true, 2, false); // Funds two founders. checked(state->advance_tick({}), "genesis tick"); state = checked(state->migration_upgrade_candidate(), "boundary upgrade"); state = checked(state->maturation_upgrade_candidate(), "maturation upgrade"); state = checked(state->inheritance_upgrade_candidate(), "inheritance upgrade"); state = checked(state->photosynthesis_upgrade_candidate({0, 1, {0}}), "light upgrade"); require(!state->revamp_upgrade_candidate(revamp()), "revamp upgrade skipped rules 12"); state = checked(state->liquid_upgrade_candidate(liquid()), "liquid upgrade"); state = checked(state->birth_candidate({account(1), 1}, {100, 100, 100, 100, {state->tick()}}), "founder 5 birth"); require(!state->revamp_upgrade_candidate(revamp(1'001)), "an invalid essential share accepted"); state = checked(state->revamp_upgrade_candidate(rules), "revamp upgrade"); require(state->format_version() == cellular_lives_revamp_format && state->rules_version() == cellular_lives_revamp_rules && state->revamp_rules() == rules && state->liquid_rules() == liquid() && state->flow_field() != nullptr && !state->revamp_upgrade_candidate(revamp()), "revamp upgrade repeated, wrong versions or lost rules"); state = checked(state->birth_candidate({account(2), 1}, {101, 101, 101, 101, {state->tick()}}), "founder 6 birth"); const auto old = state->archive().find(100); const auto fresh = state->archive().find(101); require(old && old->schema_version() == biology::genome_schema_v6, "the founder 5 life lost its genome in the upgrade"); require(fresh && fresh->schema_version() == biology::genome_schema_v7 && fresh->development_version() == 7 && fresh->cellular_traits() == biology::founder_cellular_traits, "a rules-13 founder is not founder 6"); return state; } std::vector swim(const CellularLives& state, biology::CellularIntent movement, std::uint8_t exclude = 0) { std::vector result; for (const auto& life : state.lives()) { CellularLifeIntent input{life.identity.life, {}}; input.intent.movement = movement; input.intent.exclude = exclude; result.push_back(input); } return result; } void closed(const CellularLives& state) { const auto& ledger = state.boundary_ledger(); auto expected = state.opening_total(); expected.energy.value += ledger.incoming.energy.value - ledger.outgoing.energy.value; for (std::size_t channel = 0; channel < expected.matter.size(); ++channel) expected.matter[channel].value += ledger.incoming.matter[channel].value - ledger.outgoing.matter[channel].value; require(state.current_total() == expected, "revamp region broke closure"); } void starting_wildlife_is_a_funded_opening() { auto source = opening(77, true, 64, false); checked(source->advance_tick({}), "opening tick"); source = checked(source->migration_upgrade_candidate(), "boundary"); source = checked(source->maturation_upgrade_candidate(), "maturation"); source = checked(source->inheritance_upgrade_candidate(), "inheritance"); source = checked(source->photosynthesis_upgrade_candidate({0, 1, {0}}), "light"); source = checked(source->liquid_upgrade_candidate(liquid()), "liquid"); const auto before = source->snapshot(); auto seeded = checked(source->revamp_upgrade_candidate(revamp(), 32, 900'000), "wildlife"); require(source->snapshot() == before && seeded->lives().size() == 32, "seeding changed source or count"); auto again = checked(source->revamp_upgrade_candidate(revamp(), 32, 900'000), "same seed"); require(again->snapshot() == seeded->snapshot(), "opening is not deterministic"); require(!seeded->revamp_upgrade_candidate(revamp(), 32, 900'000), "reseeded a region"); require(!source->revamp_upgrade_candidate(revamp(), 256, 900'000), "accepted excessive count"); require(!source->revamp_upgrade_candidate(revamp(), 1, 0), "accepted zero identity"); require(!source->revamp_upgrade_candidate(revamp(), 1, cellular_bud_namespace), "accepted bud namespace for a root"); require(!source->revamp_upgrade_candidate(revamp(), 0, 900'000), "accepted unused identity"); require(restore(*seeded)->snapshot() == seeded->snapshot(), "fixture restore diverged"); bool varied = false; for (const auto& life : seeded->lives()) { const auto genome = seeded->archive().find(life.identity.genome); require(genome && life.account == LifeAccount{} && life.parent_life == 0 && life.growth == biology::GrowthState{1000, 0} && life.reserve.matter == accounting::Inventory{}.matter, "fixture changed founder starting rules"); const auto budget = checked(biology::metabolic_budget(*genome, life.growth, {seeded->ambient_temperature_millikelvin(), {}}, 1000, seeded->revamp_rules().body), "wildlife budget"); require(life.reserve.energy.value == budget.demand.value * biology::founder_reserve_seconds && life.body == budget.body && life.offspring_genome == genome->id(), "wildlife endowment or inherited plan wrong"); varied = varied || genome->cellular_traits() != biology::founder_cellular_traits; } require(varied && seeded->nursery() != source->nursery(), "wildlife was free or unvaried"); closed(*seeded); for (int tick = 0; tick < 5; ++tick) { const auto intents = checked(wildlife_intents(*seeded, seeded->tick() + 1), "wildlife intents"); checked(seeded->advance_tick(intents), "wildlife tick"); closed(*seeded); } require(restore(*seeded)->snapshot() == seeded->snapshot(), "running fixture restore"); // A player is born into the seeded region from the nursery's remainder and plays on. seeded = checked(seeded->birth_candidate( {account(9), 1}, {800'000, 800'000, 800'000, 800'000, {seeded->tick()}}), "player birth after seeding"); for (int tick = 0; tick < 40; ++tick) { auto intents = checked(wildlife_intents(*seeded, seeded->tick() + 1), "wildlife intents"); CellularLifeIntent player{800'000, {}}; player.intent.movement = {500, 200}; intents.push_back(player); std::ranges::sort(intents, {}, &CellularLifeIntent::life_id); checked(seeded->advance_tick(intents), "tick with the player"); closed(*seeded); } auto poor = opening(77, true, 1, false); checked(poor->advance_tick({}), "poor tick"); poor = checked(poor->migration_upgrade_candidate(), "poor boundary"); poor = checked(poor->maturation_upgrade_candidate(), "poor maturation"); poor = checked(poor->inheritance_upgrade_candidate(), "poor inheritance"); poor = checked(poor->photosynthesis_upgrade_candidate({0, 1, {0}}), "poor light"); poor = checked(poor->liquid_upgrade_candidate(liquid()), "poor liquid"); const auto poor_before = poor->snapshot(); require(!poor->revamp_upgrade_candidate(revamp(), 32, 900'000) && poor->snapshot() == poor_before, "insufficient nursery was not atomic"); } void shown_bud_charge_includes_the_fee() { auto state = revamp_region(); const auto& life = state->lives().back(); const auto genome = state->archive().find(life.identity.genome); require(genome.has_value(), "founder genome"); require(state->budding_cost(life.identity.life) == biology::bud_cost(*genome, state->ambient_temperature_millikelvin()), "zero-fee founder charge changed"); require(!state->budding_cost(999'999), "cost for missing life"); auto paid = revamp_region(250, 250'000); const auto shown = state->budding_cost(life.identity.life); if (!shown) throw std::runtime_error("missing shown cost"); auto expected = shown.value(); expected.energy.value += 250'000; require(paid->budding_cost(life.identity.life) == expected, "shown charge omitted the fee"); } void upgrade_and_restore() { const auto state = revamp_region(400); const auto copy = restore(*state); require(copy->snapshot() == state->snapshot() && copy->revamp_rules() == revamp(400) && copy->liquid_rules() == liquid(), "format 11 did not restore exactly"); // A tampered rules block is refused rather than read as another share. auto bytes = state->snapshot(); require(bytes.size() > 8, "empty snapshot"); bytes[8] = 10; // Format field: format 10 bytes with the format 11 magic. require(!CellularLives::restore(bytes, state->world(), state->region(), state->frame(), state->tick()), "a format 11 checkpoint restored as format 10"); } // The feeding settings live in a formerly reserved word: zero there is the original 100% // per-nutrient collection, so earlier regions restore unchanged; new values round-trip. void feeding_settings_restore() { auto rules = revamp(); rules.step.collection_percent = 130; rules.step.split_evenly = true; auto state = opening(7, true, 2, false); checked(state->advance_tick({}), "genesis tick"); state = checked(state->migration_upgrade_candidate(), "boundary upgrade"); state = checked(state->maturation_upgrade_candidate(), "maturation upgrade"); state = checked(state->inheritance_upgrade_candidate(), "inheritance upgrade"); state = checked(state->photosynthesis_upgrade_candidate({0, 1, {0}}), "light upgrade"); state = checked(state->liquid_upgrade_candidate(liquid()), "liquid upgrade"); const auto plain = checked(state->revamp_upgrade_candidate(revamp()), "plain upgrade"); state = checked(state->revamp_upgrade_candidate(rules), "feeding upgrade"); const auto copy = restore(*state); require(copy->revamp_rules() == rules && copy->snapshot() == state->snapshot(), "feeding settings did not restore"); require(restore(*plain)->revamp_rules().step.collection_percent == 100 && !restore(*plain)->revamp_rules().step.split_evenly, "an original region changed its feeding"); auto too_much = revamp(); too_much.step.collection_percent = 1'001; require(!state->revamp_upgrade_candidate(too_much), "collection above 1000% accepted"); } // Both generations live and pay their way in one region, and restore continues exactly. void mixed_generations_tick_and_continue() { auto continuous = revamp_region(); for (int tick = 0; tick < 30; ++tick) checked(continuous->advance_tick(swim(*continuous, {600, 800})), "continuous tick"); require(continuous->lives().size() == 2, "a life died in thirty ticks"); closed(*continuous); auto resumed = restore(*continuous); for (int tick = 0; tick < 30; ++tick) { checked(continuous->advance_tick(swim(*continuous, {-700, 300})), "continuous tick"); checked(resumed->advance_tick(swim(*resumed, {-700, 300})), "resumed tick"); } require(continuous->snapshot() == resumed->snapshot(), "restore diverged from a live run"); closed(*continuous); } // The spent pool drips back one bubble per non-empty channel on every interval tick, at // seeded spots, without losing or creating anything; a full habitat keeps it waiting. void the_spent_pool_drips_back() { const auto rules = revamp(); biology::CellularHabitatConfig config{7, 9, 11, 48'000, 48'000, {}}; config.format = biology::cellular_habitat_liquid_format; config.next_deposit = 1; accounting::Inventory spent{{50'000'000}, {{{2'500'000}, {0}, {300}, {1'000'000}}}}; auto off = config; auto kept = spent; require(cellular_drip_spent(off, kept, rules, 1, 2, 19, 5) && off == config && kept == spent, "the pool dripped between intervals"); auto once = config; auto left = spent; require(cellular_drip_spent(once, left, rules, 1, 2, 20, 5), "drip refused"); require(once.patches.size() == 4 && once.next_deposit == 5, "a drip is one bubble per non-empty channel"); accounting::Inventory dripped{}; for (const auto& bubble : once.patches) { require(bubble.kind == biology::CellularDepositKind::mote && bubble.merged == 1 && bubble.source == 5 && bubble.address.x_um < 48'000 && bubble.address.y_um < 48'000, "a drip bubble is malformed"); dripped.energy.value += bubble.stock.energy.value; for (std::size_t c = 0; c < 4; ++c) dripped.matter[c].value += bubble.stock.matter[c].value; } require(dripped == accounting::Inventory{{20'000'000}, {{{1'000'000}, {0}, {300}, {1'000'000}}}} && left == accounting::Inventory{{30'000'000}, {{{1'500'000}, {0}, {0}, {0}}}}, "the drip did not move the capped amounts exactly"); auto again = config; auto same = spent; require(cellular_drip_spent(again, same, rules, 1, 2, 20, 5) && again == once, "the drip is not deterministic"); auto full = config; for (std::uint32_t i = 0; i < biology::max_cellular_liquid_deposits; ++i) { biology::CellularPatch filler{{i % 48'000, i / 48'000}, 5, {{1}, {}}, ++full.next_deposit, biology::cellular_mote_radius_um, biology::CellularDepositKind::mote}; filler.merged = 1; full.patches.push_back(filler); } const auto packed = full; auto waiting = spent; require(cellular_drip_spent(full, waiting, rules, 1, 2, 20, 5) && full == packed && waiting == spent, "a full habitat took a drip"); } // Exclusions belong to owned lives under rules 13 and travel in the trace. void exclusions_are_checked_and_replayed() { auto state = revamp_region(); require(state->advance_tick(swim(*state, {300, 0}, 0b0101)).has_value(), "an owned life's exclusions were refused"); require(!state->advance_tick(swim(*state, {}, 0x10)).has_value(), "an exclusion outside the four matter channels was accepted"); auto older = opening(7, true, 2, false); checked(older->advance_tick({}), "genesis tick"); older = checked(older->migration_upgrade_candidate(), "boundary upgrade"); older = checked(older->maturation_upgrade_candidate(), "maturation upgrade"); older = checked(older->inheritance_upgrade_candidate(), "inheritance upgrade"); older = checked(older->photosynthesis_upgrade_candidate({0, 1, {0}}), "light upgrade"); older = checked(older->liquid_upgrade_candidate(liquid()), "liquid upgrade"); older = checked(older->birth_candidate({account(1), 1}, {100, 100, 100, 100, {older->tick()}}), "founder 5 birth"); require(!older->advance_tick(swim(*older, {}, 0b0001)).has_value(), "a rules-12 owner accepted exclusions"); } // A rules-13 region runs long enough for founders to spend their endowment, keeping closure, // and restores with its rules and spent pool exactly. void a_long_run_keeps_closure_and_restores() { auto state = revamp_region(); for (int tick = 0; tick < 700; ++tick) { const auto x = static_cast((tick / 50) % 2 == 0 ? 900 : -900); checked(state->advance_tick(swim(*state, {x, 400}, 0b0010)), "long-run tick"); } closed(*state); const auto copy = restore(*state); require(copy->snapshot() == state->snapshot() && copy->revamp_rules() == revamp(), "format 11 did not restore the rules and spent pool exactly"); } // Rules 13 offers: active play earns them, behaviour moves affinity, and a choice edits the // plan (never the expressed body), pays and reclaims its cost, or keeps the offer when // unaffordable; a decline clears it; a pending offer restores exactly. const CellularOwnedLife& life_of(const CellularLives& state, std::uint64_t id) { const auto found = std::ranges::find( state.lives(), id, [](const CellularOwnedLife& l) { return l.identity.life; }); require(found != state.lives().end(), "life missing"); return *found; } Owner offering_region(std::uint64_t cost_pj, bool safety = false) { auto rules = revamp(); if (safety) { rules.safety_version = 1; rules.growth_reserve_seconds = 60; rules.split_launch_um_per_s = 800; rules.step.split_evenly = true; rules.split_share_per_thousand = 800; rules.split_min_growth = 500; } rules.offer_interval_ticks = 40; for (auto& m : rules.mutations) { m.cost.energy.value = cost_pj; m.cost_scale_percent = 100; } auto fresh = opening(7, true, 2, false); checked(fresh->advance_tick({}), "genesis tick"); fresh = checked(fresh->migration_upgrade_candidate(), "boundary upgrade"); fresh = checked(fresh->maturation_upgrade_candidate(), "maturation upgrade"); fresh = checked(fresh->inheritance_upgrade_candidate(), "inheritance upgrade"); fresh = checked(fresh->photosynthesis_upgrade_candidate({0, 1, {0}}), "light upgrade"); fresh = checked(fresh->liquid_upgrade_candidate(liquid()), "liquid upgrade"); fresh = checked(fresh->birth_candidate({account(1), 1}, {100, 100, 100, 100, {fresh->tick()}}), "founder 5 birth"); fresh = checked(fresh->revamp_upgrade_candidate(rules), "revamp upgrade"); fresh = checked(fresh->birth_candidate({account(2), 1}, {101, 101, 101, 101, {fresh->tick()}}), "founder 6 birth"); return fresh; } void offers_come_from_active_play() { auto state = offering_region(0); for (int tick = 0; tick < 40; ++tick) checked(state->advance_tick(swim(*state, {1'000, 0})), "swim tick"); const auto& founder6 = life_of(*state, 101).revamp; require(founder6.offer.count == 3 && founder6.offer.event_index == 1 && founder6.events == 1 && founder6.active_ticks == 0, "forty ticks of active play did not earn a founder 6 an offer"); for (std::size_t k = 0; k < 3; ++k) require(biology::cellular_mutation(founder6.offer.ids.at(k)) != nullptr && founder6.offer.chances.at(k) >= 10 && founder6.offer.chances.at(k) <= 700'000, "an offered mutation is unknown or its chance out of bounds"); // A founder 5 plan (no traits) has no catalog: its life counts but is never offered. require(life_of(*state, 100).revamp.offer.count == 0, "a founder 5 plan was offered"); // Thrust moved affinity: forty ticks is short of the ten seconds Strong Propulsion counts. require(founder6.affinity.score.at(0) == 0, "affinity moved too early"); const auto copy = restore(*state); require(copy->snapshot() == state->snapshot() && life_of(*copy, 101).revamp == founder6, "a pending offer did not restore exactly"); } std::vector choose(const CellularLives& state, std::uint64_t life_id, std::uint16_t id, std::uint64_t successor) { const auto& offer = life_of(state, life_id).revamp.offer; return {{life_id, offer.event_index, offer.offer_tick, successor, id}}; } // Rules 13 (reproduction plan section 4): a choice splits the cell. Both plans carry the mutation, // only the offspring expresses it, body and reserve divide, and the player stays or becomes. void a_choice_splits_the_cell(bool become) { auto state = offering_region(1'000); for (int tick = 0; tick < 40; ++tick) checked(state->advance_tick(swim(*state, {1'000, 0})), "swim tick"); const auto before = life_of(*state, 101); const auto id = before.revamp.offer.ids.at(0); const auto deposits = state->habitat().patches().size(); auto choice = choose(*state, 101, id, 9'000); choice.front().become = become; const auto execution = checked(state->advance_tick_with_mutations(swim(*state, {}), choice), "choice tick"); require(execution.mutations.size() == 1 && execution.mutations.front().result == CellularMutationResult::split_applied, "the choice did not split the cell"); const auto identity = cellular_bud_identity(state->region(), 1); const auto& founder = life_of(*state, 101); const auto& child = life_of(*state, identity); require(founder.identity.genome == before.identity.genome && founder.offspring_genome == 9'000 && child.identity.genome == 9'000 && child.offspring_genome == 9'000 && child.parent_life == 101 && founder.revamp.offer.count == 0, "the split did not give both plans the mutation and only the offspring its body"); require(founder.growth.realized_per_thousand < 1'000 && child.growth.realized_per_thousand < 1'000 && child.revamp.affinity.score == founder.revamp.affinity.score, "the split did not halve both cells or pass on the affinity"); require(become ? child.account == account(2) && founder.account == LifeAccount{} : child.account == LifeAccount{} && founder.account == account(2), "control did not follow the choice"); // The account's reservation names the founder it was born as, wherever control went. require(cellular_lineage_root(*state, identity) == 101 && cellular_lineage_root(*state, 101) == 101, "the lineage root is not the founder born from the reservation"); require(state->habitat().patches().size() >= deposits + 1, "the paid cost was not reclaimed"); closed(*state); // A half-grown founder cannot split again, so its next offer waits until it has regrown. if (!become) { for (int tick = 0; tick < 40; ++tick) checked(state->advance_tick(swim(*state, {1'000, 0})), "swim tick"); const auto& founder_now = life_of(*state, 101); require(founder_now.growth.realized_per_thousand < 1'000 && founder_now.revamp.offer.count == 0, "a half-grown founder was offered a split"); closed(*state); } // Rules 13 wildlife (the founder after become): its controller's intents are always // admissible, with matter as energy, fee-aware buds and the revamp engulf test. if (become) { for (int tick = 0; tick < 300; ++tick) { auto intents = checked(wildlife_intents(*state, state->tick() + 1), "wildlife intents"); for (const auto& life : state->lives()) if (life.account != LifeAccount{}) { CellularLifeIntent owned{life.identity.life, {}}; owned.intent.movement = {600, 300}; intents.push_back(owned); } std::ranges::sort(intents, {}, &CellularLifeIntent::life_id); checked(state->advance_tick(intents), "wildlife tick"); } closed(*state); } const auto copy = restore(*state); require(copy->snapshot() == state->snapshot(), "a split region did not restore exactly"); } void the_region_cap_refuses_splits() { auto rules = revamp(); rules.offer_interval_ticks = 40; rules.organism_cap = 2; auto fresh = opening(7, true, 2, false); checked(fresh->advance_tick({}), "genesis tick"); fresh = checked(fresh->migration_upgrade_candidate(), "boundary upgrade"); fresh = checked(fresh->maturation_upgrade_candidate(), "maturation upgrade"); fresh = checked(fresh->inheritance_upgrade_candidate(), "inheritance upgrade"); fresh = checked(fresh->photosynthesis_upgrade_candidate({0, 1, {0}}), "light upgrade"); fresh = checked(fresh->liquid_upgrade_candidate(liquid()), "liquid upgrade"); fresh = checked(fresh->birth_candidate({account(1), 1}, {100, 100, 100, 100, {fresh->tick()}}), "founder 5 birth"); fresh = checked(fresh->revamp_upgrade_candidate(rules), "revamp upgrade"); fresh = checked(fresh->birth_candidate({account(2), 1}, {101, 101, 101, 101, {fresh->tick()}}), "founder 6 birth"); for (int tick = 0; tick < 40; ++tick) checked(fresh->advance_tick(swim(*fresh, {1'000, 0})), "swim tick"); const auto offer = life_of(*fresh, 101).revamp.offer; const auto refused = checked(fresh->advance_tick_with_mutations( swim(*fresh, {}), choose(*fresh, 101, offer.ids.at(0), 9'020)), "capped split tick"); require(refused.mutations.front().result == CellularMutationResult::split_refused && fresh->lives().size() == 2, "a full region allowed a split"); } // Become needs a bud, an owned life and rules 13; litter counts whole and chance offspring. void become_and_litter() { auto state = revamp_region(); auto lone = swim(*state, {}); lone.back().intent.become = true; require(!state->advance_tick(lone), "become without a bud was accepted"); require(cellular_litter_count(0, 0, 900) == 1 && cellular_litter_count(100, 99, 900) == 2 && cellular_litter_count(150, 49, 900) == 3 && cellular_litter_count(150, 50, 900) == 2 && cellular_litter_count(9'900, 0, 900) == 10, "litter counted the wrong offspring"); } void unaffordable_choices_wait_and_declines_clear() { auto state = offering_region(1'000'000'000'000); for (int tick = 0; tick < 40; ++tick) checked(state->advance_tick(swim(*state, {1'000, 0})), "swim tick"); const auto offer = life_of(*state, 101).revamp.offer; const auto execution = checked(state->advance_tick_with_mutations(swim(*state, {}), choose(*state, 101, offer.ids.at(1), 9'001)), "unaffordable choice tick"); require(execution.mutations.front().result == CellularMutationResult::insufficient_funding && life_of(*state, 101).revamp.offer == offer && !state->archive().find(9'001), "an unaffordable choice did not leave the offer waiting"); const auto declined = checked(state->advance_tick_with_mutations(swim(*state, {}), choose(*state, 101, 0, 9'002)), "decline tick"); require(declined.mutations.front().result == CellularMutationResult::declined && life_of(*state, 101).revamp.offer.count == 0 && life_of(*state, 101).offspring_genome == life_of(*state, 101).identity.genome, "a decline did not clear the offer"); // A choice naming something not offered fails the tick. for (int tick = 0; tick < 40; ++tick) checked(state->advance_tick(swim(*state, {1'000, 0})), "swim tick"); const auto next = life_of(*state, 101).revamp.offer; std::uint16_t absent = 1; while (std::ranges::find(next.ids, absent) != next.ids.end()) ++absent; require( !state->advance_tick_with_mutations(swim(*state, {}), choose(*state, 101, absent, 9'003)), "a choice outside the offer was accepted"); closed(*state); } void thrust_moves_affinity() { auto state = offering_region(0); for (int tick = 0; tick < 200; ++tick) checked(state->advance_tick(swim(*state, {1'000, 0})), "swim tick"); const auto& scores = life_of(*state, 101).revamp.affinity.score; // Ten seconds of thrust: Strong Propulsion up, Light Propulsion down (catalog ids 1 and 7). require(scores.at(0) == 100 && scores.at(6) == -100, "ten seconds of thrust did not move propulsion affinity"); } // Rules 13 (reproduction plan sections 6-7): Adhesion turns the cell into a two-member organism // that holds its whole body and reserve; the organism expresses later mutations as a whole, // buds add internal members, and at the threshold it emerges as a recorded export. Owner adhesion_region(std::uint64_t carbon_fee = 0, bool safety = false, std::uint32_t growth_rate = 0) { auto rules = revamp(); if (safety) { rules.safety_version = 1; rules.growth_reserve_seconds = 60; rules.split_launch_um_per_s = 800; rules.step.split_evenly = true; rules.step.collection_percent = 1'000; } rules.bud_fee.matter[0].value = carbon_fee; rules.bud_fee_scale_percent = carbon_fee == 0 ? 0 : 100; rules.offer_interval_ticks = 40; rules.bounds.buds_for_adhesion = 0; rules.emerge_members = 3; rules.emerge_mass_fg = 0; rules.growth_per_tick_centi_mille = growth_rate; // Zero keeps collected matter for buds. for (auto& m : rules.mutations) m.enabled = false; // Adhesion and five movement mutations: three options capped at 70% each need five. rules.mutations.at(48).enabled = true; rules.mutations.at(48).base_weight = 10'000; for (std::size_t i = 0; i < 5; ++i) rules.mutations.at(i).enabled = true; auto fresh = opening(7, true, 4, false); // A 6 mm region, rich motes at four sites. if (safety) { // Put finite food within reach of any seeded founder position. The test // isolates funding/allocation, rather than depending on the forager's search. auto habitat_config = fresh->habitat().config(); for (auto& patch : habitat_config.patches) if (patch.kind == biology::CellularDepositKind::pool) patch.radius_um = biology::max_cellular_deposit_radius_um; auto habitat = checked(biology::CellularHabitat::create(std::move(habitat_config)), "safety funding habitat"); auto nursery = checked(PrimitiveLives::create( {fresh->world(), fresh->region(), fresh->frame(), 17, fresh->nursery(), {{1'000, 1'000}, {1'000, 4'000}, {4'000, 1'000}, {4'000, 4'000}}}), "safety funding nursery"); fresh = checked(CellularLives::create(*nursery, std::move(habitat), {{6'000, 6'000}, 0, 293'150}, CellularLivesProfile::foraging), "safety funding opening"); } checked(fresh->advance_tick({}), "genesis tick"); fresh = checked(fresh->migration_upgrade_candidate(), "boundary upgrade"); fresh = checked(fresh->maturation_upgrade_candidate(), "maturation upgrade"); fresh = checked(fresh->inheritance_upgrade_candidate(), "inheritance upgrade"); fresh = checked(fresh->photosynthesis_upgrade_candidate({0, 1, {0}}), "light upgrade"); fresh = checked(fresh->liquid_upgrade_candidate(liquid(6'000)), "liquid upgrade"); fresh = checked(fresh->revamp_upgrade_candidate(rules), "revamp upgrade"); fresh = checked(fresh->birth_candidate({account(2), 1}, {101, 101, 101, 101, {fresh->tick()}}), "founder 6 birth"); return fresh; } // One tick's intents steering `life_id` toward the richest bubble (the fixture's rich founding // motes), with matter excluded from burning so the reserve keeps it for growth and buds. std::vector forage(const CellularLives& state, std::uint64_t life_id) { const auto& life = life_of(state, life_id); const biology::CellularPatch* best = nullptr; double nearest{}; // Short of energy, it heads for energy; otherwise for whatever is richest. const bool hungry = life.reserve.energy.value < 3'000'000; for (const auto& patch : state.habitat().patches()) { auto richest = patch.stock.energy.value; if (!hungry) for (const auto& channel : patch.stock.matter) richest = std::max(richest, channel.value); const auto distance = std::hypot( static_cast(patch.address.x_um) - static_cast(life.position.x_um), static_cast(patch.address.y_um) - static_cast(life.position.y_um)); if (richest >= 1'000'000'000 && (best == nullptr || distance < nearest)) { nearest = distance; best = &patch; } } require(best != nullptr, "nothing left in the region"); auto input = swim(state, {}, 0x0F); const auto dx = static_cast(best->address.x_um) - static_cast(life.position.x_um); const auto dy = static_cast(best->address.y_um) - static_cast(life.position.y_um); // Inside the unit circle: scale by the Euclidean length, rounded toward zero. const auto span = std::max(1.0, std::hypot(dx, dy)); if (hungry && span < 80) return input; // On the energy: hold still and feed rather than spend on thrust. for (auto& entry : input) if (entry.life_id == life_id) entry.intent.movement = {static_cast(dx * 999.0 / span), static_cast(dy * 999.0 / span)}; return input; } // Forages in offer intervals, declining offers, until one names `id`. std::uint16_t await_offer(Owner& state, std::uint64_t life_id, std::uint16_t id) { for (std::uint64_t round = 0; round < 40; ++round) { for (int tick = 0; tick < 40; ++tick) checked(state->advance_tick(forage(*state, life_id)), "forage tick"); const auto& offer = life_of(*state, life_id).revamp.offer; const auto end = offer.ids.begin() + offer.count; if (std::ranges::find(offer.ids.begin(), end, id) != end) return id; if (offer.count != 0) checked(state->advance_tick_with_mutations(swim(*state, {}), choose(*state, life_id, 0, 8'000 + round)), "decline tick"); } require(false, "the expected mutation was never offered"); return 0; } // Forages, asking to bud every 50 ticks, until a bud is funded or `ticks` pass; returns the last // bud result (a single request when `ticks` is 0). CellularBudExecution bud_until_funded(Owner& state, std::uint64_t life_id, int ticks) { CellularBudExecution last{}; for (int tick = 0; tick <= ticks; ++tick) { auto input = forage(*state, life_id); const bool ask = tick % 50 == 0; if (ask) { for (auto& entry : input) if (entry.life_id == life_id) { entry.intent = {}; entry.intent.bud = true; } } const auto executed = checked(state->advance_tick_with_mutations(input, {}), "bud tick"); if (ask) { require(executed.buds.size() == 1, "a bud request went unanswered"); last = executed.buds.front(); if (last.result == CellularBudResult::budded) break; } } return last; } // The bud fee comes on top of the bud. Wildlife that can fund a bud but not the fee as well is // refused, never charged less than the fee the region reclaims (DEV region 14 stalled on that // conservation error at its first such bud). Seeded wildlife under the DEV fee, run until buds. void the_bud_fee_is_paid_in_full_or_refused() { auto rules = revamp(); rules.bud_fee = {{250'000}, {{{100'000}, {30'000}, {10'000}, {60'000}}}}; rules.bud_fee_scale_percent = 100; auto source = opening(77, true, 64, false); checked(source->advance_tick({}), "opening tick"); source = checked(source->migration_upgrade_candidate(), "boundary"); source = checked(source->maturation_upgrade_candidate(), "maturation"); source = checked(source->inheritance_upgrade_candidate(), "inheritance"); source = checked(source->photosynthesis_upgrade_candidate({0, 1, {0}}), "light"); source = checked(source->liquid_upgrade_candidate(liquid()), "liquid"); auto state = checked(source->revamp_upgrade_candidate(rules, 32, 900'000), "wildlife"); int tick = 0; for (; tick < 12'000 && state->next_bud_sequence() < 2; ++tick) { const auto intents = checked(wildlife_intents(*state, state->tick() + 1), "intents"); checked(state->advance_tick(intents), "wildlife tick under the bud fee"); } require(state->next_bud_sequence() >= 2, "no wildlife budded under the fee"); closed(*state); } void an_organism_forms_grows_and_emerges() { auto state = adhesion_region(); const auto adhesion = await_offer(state, 101, 49); const auto single = life_of(*state, 101); auto choice = choose(*state, 101, adhesion, 9'000); const auto formed = checked(state->advance_tick_with_mutations(swim(*state, {}), choice), "adhesion tick"); require(formed.mutations.front().result == CellularMutationResult::split_applied, "Adhesion did not form an organism"); const auto identity = cellular_bud_identity(state->region(), 1); require(state->lives().size() == 1, "Adhesion left the single cell alive"); const auto organism = life_of(*state, identity); require(organism.revamp.members == 2 && organism.account == account(2) && organism.identity.genome == 9'000 && organism.offspring_genome == 9'000 && organism.parent_life == 101 && organism.revamp.affinity.score == single.revamp.affinity.score, "the organism did not take the cell's place, plan and account"); const auto merged = std::ranges::find(state->corpses(), std::uint64_t{101}, [](const CellularOwnedCorpse& c) { return c.life_id; }); require(merged != state->corpses().end() && merged->cause == biology::CellularDeathCause::merged && merged->inventory == accounting::Inventory{}, "the single cell did not end as an empty merged corpse"); closed(*state); require(restore(*state)->snapshot() == state->snapshot(), "an organism did not restore"); // An organism cannot become its bud; its next mutation is expressed as a whole. auto become = swim(*state, {}); become.front().intent.bud = true; become.front().intent.become = true; require(!state->advance_tick(become), "an organism was allowed to become a bud"); const auto strong = await_offer(state, identity, 1); const auto whole = checked(state->advance_tick_with_mutations( swim(*state, {}), choose(*state, identity, strong, 9'001)), "organism mutation tick"); require(whole.mutations.front().result == CellularMutationResult::applied && life_of(*state, identity).identity.genome == 9'001 && life_of(*state, identity).offspring_genome == 9'001 && state->lives().size() == 1, "the organism did not express its mutation as a whole"); closed(*state); // A bud adds an internal member, not a new life, once the organism has fed enough. const auto refused = bud_until_funded(state, identity, 0); require(refused.result == CellularBudResult::insufficient_funding && life_of(*state, identity).revamp.members == 2, "an unfed organism's bud was not refused"); const auto budded = bud_until_funded(state, identity, 10'000); require(budded.result == CellularBudResult::budded && budded.bud_life == identity && life_of(*state, identity).revamp.members == 3 && state->lives().size() == 1, "an organism's bud did not add an internal member"); closed(*state); require(cellular_can_emerge(life_of(*state, identity), state->revamp_rules()), "a three-member organism could not emerge"); const auto summary = checked(summarize_cellular_play(*state), "play summary"); require(summary.organisms == 1 && summary.largest_organism == 3 && summary.merged == 1 && summary.offers_earned >= 1, "the play summary missed the organism"); // Emerge: the whole organism leaves as an export and the life ends as emerged. const auto outgoing = state->boundary_ledger().outgoing; const auto leaving = life_of(*state, identity); auto emerge = swim(*state, {}); emerge.front().intent = {}; emerge.front().intent.emerge = true; checked(state->advance_tick(emerge), "emerge tick"); require(state->lives().empty(), "the organism did not leave"); const auto emerged = std::ranges::find(state->corpses(), identity, [](const CellularOwnedCorpse& c) { return c.life_id; }); require(emerged != state->corpses().end() && emerged->cause == biology::CellularDeathCause::emerged, "the organism did not end as emerged"); // The tick's step still moved the reserve first; the body (no growth here) leaves whole, // and closure accounts for every femtogram exactly. const auto& exported = state->boundary_ledger().outgoing; for (std::size_t c = 0; c < exported.matter.size(); ++c) require(exported.matter[c].value - outgoing.matter[c].value >= leaving.body.matter[c].value, "the emerged body was not recorded as an export"); require(exported.energy.value > outgoing.energy.value, "the emerged reserve stayed behind"); closed(*state); require(restore(*state)->snapshot() == state->snapshot(), "an emerged region did not restore"); } // Emerge needs an owned life at the threshold; a single cell asking is ignored, wildlife refused. void emerge_needs_the_threshold() { auto state = adhesion_region(); auto ask = swim(*state, {}); ask.front().intent = {}; ask.front().intent.emerge = true; checked(state->advance_tick(ask), "single-cell emerge tick"); require(state->lives().size() == 1, "a single cell emerged"); auto mixed = swim(*state, {}); mixed.front().intent.emerge = true; mixed.front().intent.bud = true; require(!state->advance_tick(mixed), "emerge with a bud was accepted"); CellularOwnedLife wild = life_of(*state, 101); wild.revamp.members = 8; require(cellular_can_emerge(wild, state->revamp_rules()), "an owned organism at the threshold"); wild.account = {}; require(!cellular_can_emerge(wild, state->revamp_rules()), "wildlife could emerge"); } // A recorded trace replays to the exact live result under rules 13. void trace_replays() { auto live = revamp_region(); const auto base = restore(*live); CellularBatch batch; batch.format_version = cellular_batch_inheritance_format; batch.header = {live->world(), live->region(), live->frame(), {}, {}, live->tick(), 0}; batch.header.predecessor.fill(1); batch.header.predecessor_digest.fill(2); for (int tick = 0; tick < 24; ++tick) { auto intents = swim(*live, {static_cast(tick < 12 ? 1'000 : -400), 0}, static_cast(tick % 16)); // A single cell asking to emerge is below the threshold and stays. intents.front().intent.emerge = tick == 5; checked(live->advance_tick(intents), "recorded tick"); batch.ticks.push_back({intents, {}, {}}); } batch.header.end_tick = live->tick(); const auto bytes = checked(encode_cellular_batch(batch), "trace encodes"); const auto decoded = checked(decode_cellular_batch(bytes), "trace decodes"); const auto replayed = checked(replay_cellular_batch(*base, decoded), "trace replays"); require(replayed->snapshot() == live->snapshot(), "replay diverged from the live run"); require(decoded.ticks.back().lives.front().intent.exclude == 23 % 16, "exclusions did not survive the trace"); require(decoded.ticks.at(5).lives.front().intent.emerge && !decoded.ticks.at(6).lives.front().intent.emerge, "Emerge did not survive the trace"); } // ADR-0182: operator commands import through the boundary ledger, remove into the spent pool, // spawn funded wildlife, refuse what does not apply, and replay exactly from trace 5. void admin_commands_apply_and_replay() { using Kind = CellularAdminKind; auto live = revamp_region(); const auto base = restore(*live); accounting::Inventory pool{{5'000'000'000}, {}}; accounting::Inventory bubbles{{400'000'000}, {}}; bubbles.matter[0].value = 4'000; const std::vector commands{ {1, Kind::add_pool, 0, 0, pool}, {2, Kind::add_bubbles, 4, 0, bubbles}, {3, Kind::grant_reserve, 0, 100, {{1'000'000}, {}}}, {4, Kind::spawn_wildlife, 3, 900'000, {}}, {5, Kind::remove_cell, 0, 101, {}}, {6, Kind::release_pool, 2, 0, {{1'000'000'000}, {}}}, {7, Kind::remove_cell, 0, 424'242, {}}, // No such life: refused, nothing changes. }; for (const auto& bad : {CellularAdminCommand{8, Kind::add_pool, 0, 0, {}}, CellularAdminCommand{8, Kind::spawn_wildlife, 65, 900'000, {}}, CellularAdminCommand{8, Kind::add_bubbles, 0, 0, pool}, CellularAdminCommand{0, Kind::add_pool, 0, 0, pool}}) require(!cellular_admin_command_valid(bad), "an invalid command shape was accepted"); require(!live->admin_candidate(std::vector{commands[1], commands[0]}), "commands out of order were accepted"); // The live run: one tick, then the commands after it. const auto intents = swim(*live, {}); checked(live->advance_tick(intents), "tick before the commands"); const auto spent_before = live->spent(); const auto deposits_before = live->habitat().patches().size(); const auto removed_body = life_of(*live, 101).body; const auto removed_reserve = life_of(*live, 101).reserve; std::vector results; auto after = checked(live->admin_candidate(commands, &results), "commands apply"); require(results.size() == 7 && std::ranges::all_of(results.begin(), results.begin() + 6, [](const auto& r) { return r.applied; }) && !results.back().applied, "unexpected command results"); closed(*after); require(after->lives().size() == live->lives().size() - 1 + 3, "wrong cell count"); std::size_t wildlife = 0; for (const auto& life : after->lives()) if (life.account == LifeAccount{} && life.identity.life >= 900'000 && life.identity.life < 900'003) ++wildlife; require(wildlife == 3, "spawned wildlife missing"); require(life_of(*after, 100).reserve.energy.value == life_of(*live, 100).reserve.energy.value + 1'000'000, "the grant did not reach the reserve"); const auto corpse = std::ranges::find(after->corpses(), 101ULL, &CellularOwnedCorpse::life_id); require(corpse != after->corpses().end() && corpse->cause == biology::CellularDeathCause::removed, "the removed cell left no removed corpse"); auto expected_spent = spent_before; expected_spent.energy.value += pool.energy.value - 1'000'000'000; for (const auto& part : {removed_body, removed_reserve}) { expected_spent.energy.value += part.energy.value; for (std::size_t c = 0; c < 4; ++c) expected_spent.matter[c].value += part.matter[c].value; } require(after->spent() == expected_spent, "the spent pool is off"); require(after->habitat().patches().size() == deposits_before + 4 + 2, "bubbles were not added"); require(restore(*after)->snapshot() == after->snapshot(), "commands do not restore"); auto again = checked(live->admin_candidate(commands), "commands apply again"); require(again->snapshot() == after->snapshot(), "commands are not deterministic"); // The same tick and commands from trace 5 replay to the same state. CellularBatch batch; batch.format_version = cellular_batch_admin_format; batch.header = {base->world(), base->region(), base->frame(), {}, {}, base->tick(), 0}; batch.header.predecessor.fill(1); batch.header.predecessor_digest.fill(2); batch.ticks.push_back({intents, {}, {}, commands}); batch.header.end_tick = base->tick() + 1; const auto bytes = checked(encode_cellular_batch(batch), "trace 5 encodes"); const auto decoded = checked(decode_cellular_batch(bytes), "trace 5 decodes"); require(decoded == batch, "trace 5 did not round-trip"); std::vector outcomes; std::vector replayed_results; const auto replayed = checked(replay_cellular_batch(*base, decoded, outcomes, replayed_results), "trace 5 replays"); require(replayed->snapshot() == after->snapshot() && replayed_results == results, "trace 5 replay diverged"); // Trace 4 cannot carry commands, and older owners cannot replay trace 5. auto old_format = batch; old_format.format_version = cellular_batch_inheritance_format; require(!encode_cellular_batch(old_format), "trace 4 carried commands"); auto mangled = bytes; mangled[8] = 4; // The version byte: a trace-4 header with nonzero command counts. require(!decode_cellular_batch(mangled), "a trace 4 with commands decoded"); } // ADR-0182 tuning amendments: adopt_tuning swaps the rules at a recorded tick; whoever applies // or replays it must name the rules for its revision and digest, and the safety revision stays. void tuning_is_adopted_and_replayed() { auto live = revamp_region(); const auto base = restore(*live); const auto& before = live->revamp_rules(); auto changed = before; changed.drip_interval_ticks += 7; changed.drip_bubble_pj *= 2; changed.body.essential_upkeep_per_thousand = 200; require(cellular_revamp_valid(changed) && encode_cellular_revamp_rules(changed) != encode_cellular_revamp_rules(before), "the changed rules are not distinct valid rules"); std::array digest{}; for (std::size_t i = 0; i < digest.size(); ++i) digest.at(i) = static_cast(i * 7 + 1); const auto adopt = cellular_adopt_tuning_command(1, 5, digest); require(cellular_admin_command_valid(adopt) && cellular_admin_digest(adopt) == digest && adopt.target == 5, "the adoption command does not carry its revision and digest"); auto zero = cellular_adopt_tuning_command(1, 5, {}); auto counted = adopt; counted.count = 1; auto other = adopt; other.amount.matter[3].value = 1; for (const auto& bad : {zero, counted, other}) require(!cellular_admin_command_valid(bad), "an invalid adoption was accepted"); const CellularTuningResolver resolver = [&](std::uint64_t revision, const std::array& named) -> std::optional { if (revision != 5 || named != digest) return std::nullopt; return changed; }; const auto intents = swim(*live, {}); checked(live->advance_tick(intents), "tick before the adoption"); const std::vector commands{adopt}; // Nobody can name the rules: an error, not a refusal (replay would diverge). require(!live->admin_candidate(commands), "an unnamed revision was applied or refused"); std::vector results; auto after = checked(live->admin_candidate(commands, &results, resolver), "adoption applies"); require(results.size() == 1 && results.front().applied && after->revamp_rules() == changed, "the rules were not adopted"); require(restore(*after)->snapshot() == after->snapshot(), "adopted rules do not restore"); // The safety revision is a law of the opening: such a revision is refused, nothing changes. auto unsafe = changed; unsafe.safety_version = before.safety_version + 1; std::vector refused; const auto kept = checked(live->admin_candidate(commands, &refused, [&](std::uint64_t, const std::array&) { return std::optional{unsafe}; }), "an unsafe adoption is a refusal"); require(refused.size() == 1 && !refused.front().applied && kept->revamp_rules() == before, "a safety revision change was adopted"); // Trace 5 replays the adoption with the same resolver, and the successor state names it. CellularBatch batch; batch.format_version = cellular_batch_admin_format; batch.header = {base->world(), base->region(), base->frame(), {}, {}, base->tick(), 0}; batch.header.predecessor.fill(1); batch.header.predecessor_digest.fill(2); batch.ticks.push_back({intents, {}, {}, commands}); batch.header.end_tick = base->tick() + 1; const auto decoded = checked(decode_cellular_batch(checked(encode_cellular_batch(batch), "encodes")), "decodes"); std::vector outcomes; std::vector replayed_results; require(!replay_cellular_batch(*base, decoded, outcomes, replayed_results), "an adoption replayed without its rules"); const auto replayed = checked(replay_cellular_batch(*base, decoded, outcomes, replayed_results, resolver), "the adoption replays"); require(replayed->snapshot() == after->snapshot(), "the adoption replay diverged"); const auto encoded = encode_cellular_revamp_rules(changed); const auto successor = cellular_successor_tuning( *replayed, [&](std::span bytes, const std::array& d) { return d == digest && std::ranges::equal(bytes, encoded); }); const auto from_successor = checked(replay_cellular_batch(*base, decoded, outcomes, replayed_results, successor), "the successor names the adopted rules"); require(from_successor->snapshot() == after->snapshot(), "the successor's rules diverged"); // One adoption per batch: its successor can name only one set of rules. auto twice = batch; twice.ticks.front().admin.push_back(cellular_adopt_tuning_command(2, 6, digest)); require(!encode_cellular_batch(twice), "two adoptions shared a batch"); } // ADR-0182 section 14: adopted energy cycling returns the region's heat (what its cells used, // and what had built up before) to the spent pool before the drip. The fields sit in a reserved // word, so historical rules keep their bytes; adopted rules restore and replay. void heat_cycles_back() { auto live = revamp_region(); for (int tick = 0; tick < 30; ++tick) checked(live->advance_tick(swim(*live, {1'000, 0})), "cells use energy"); const auto heat = live->heat().energy.value; require(heat > 0, "the cells used no energy"); const auto before = live->revamp_rules(); auto cycling = before; cycling.heat_recycle_per_thousand = 1'000; cycling.drip_absorb = true; cycling.drip_interval_ticks = 0; // No drip: the whole recycled heat stays in the pool. const auto old_bytes = encode_cellular_revamp_rules(before); const auto new_bytes = encode_cellular_revamp_rules(cycling); require(cellular_revamp_valid(cycling) && old_bytes.size() == new_bytes.size() && old_bytes != new_bytes, "the energy cycle is not a same-size distinct encoding"); auto excessive = cycling; excessive.heat_recycle_per_thousand = 1'001; require(!cellular_revamp_valid(excessive), "more than all the heat was recycled"); std::array digest{}; digest.fill(9); const std::vector commands{cellular_adopt_tuning_command(1, 7, digest)}; std::vector results; auto after = checked(live->admin_candidate(commands, &results, [&](std::uint64_t, const std::array&) { return std::optional{cycling}; }), "the energy cycle is adopted"); require(results.size() == 1 && results.front().applied && after->revamp_rules() == cycling, "the energy cycle was not adopted"); require(restore(*after)->revamp_rules() == cycling && restore(*after)->snapshot() == after->snapshot(), "the energy cycle does not restore"); const auto spent = after->spent().energy.value; const auto twin = restore(*after); const auto intents = swim(*after, {1'000, 0}); checked(after->advance_tick(intents), "a cycling tick"); require(after->heat().energy.value == 0 && after->spent().energy.value > spent + heat, "the heat, old and new, did not reach the spent pool"); checked(twin->advance_tick(intents), "the cycling tick again"); require(twin->snapshot() == after->snapshot(), "the cycling tick is not deterministic"); // Without the cycle the heat keeps building. checked(live->advance_tick(intents), "a historical tick"); require(live->heat().energy.value > heat, "historical rules recycled heat"); } // A drip at the deposit limit waits, or with the absorbing drip joins an existing bubble. void full_drip_is_absorbed() { biology::CellularHabitatConfig full{}; full.world = full.region = full.frame = 1; full.width_um = full.height_um = 1'000; full.format = biology::cellular_habitat_liquid_format; for (std::uint32_t i = 0; i < biology::max_cellular_liquid_deposits; ++i) { biology::CellularPatch bubble{ {i % 128 * 7, i / 128 * 11}, 1, {}, i + 1, biology::cellular_mote_radius_um, biology::CellularDepositKind::mote}; bubble.merged = 1; bubble.stock.matter[0].value = 10; full.patches.push_back(bubble); } std::ranges::sort(full.patches, {}, &biology::CellularPatch::address); full.next_deposit = biology::max_cellular_liquid_deposits + 1; auto rules = revamp(); rules.drip_interval_ticks = 1; accounting::Inventory pool{}; pool.energy.value = 30'000'000; pool.matter[0].value = 5; const auto energy = [](const biology::CellularHabitatConfig& c) { std::uint64_t total = 0; for (const auto& patch : c.patches) total += patch.stock.energy.value; return total; }; auto waiting = full; auto kept = pool; require(cellular_drip_spent(waiting, kept, rules, 1, 1, 1, 1) && kept == pool && waiting == full, "a full habitat took a drip without absorbing"); rules.drip_absorb = true; auto absorbing = full; auto left = pool; require(cellular_drip_spent(absorbing, left, rules, 1, 1, 1, 1), "the absorbing drip"); require(absorbing.patches.size() == full.patches.size() && left.energy.value == pool.energy.value - rules.drip_bubble_pj && left.matter[0].value == 0 && energy(absorbing) == rules.drip_bubble_pj, "the drip did not join existing bubbles"); } // The safety revision preserves all five channels, follows both control choices, // separates eligible predator/prey siblings and replays their actual motion exactly. void safety_split(bool become) { auto state = offering_region(0, true); for (int tick = 0; tick < 40; ++tick) checked(state->advance_tick(swim(*state, {1'000, 0})), "earn safety offer"); auto base = restore(*state); require(base->revamp_rules() == state->revamp_rules(), "safety settings lost on restore"); auto invalid = state->revamp_rules(); invalid.safety_version = 2; require(!cellular_revamp_valid(invalid), "an unknown safety revision was admitted"); invalid.safety_version = 0; require(!cellular_revamp_valid(invalid), "historical rules accepted hidden safety amounts"); auto unsplit = restore(*state); const auto intents = swim(*state, {}); checked(unsplit->advance_tick(intents), "unsplit comparison"); const auto pre = life_of(*unsplit, 101); auto choice = choose(*state, 101, life_of(*state, 101).revamp.offer.ids.at(0), 9'000); choice.front().become = become; const auto execution = checked(state->advance_tick_with_mutations(intents, choice), "safe split"); require(execution.mutations.front().result == CellularMutationResult::split_applied, "safety split refused"); const auto identity = cellular_bud_identity(state->region(), 1); const auto parent = life_of(*state, 101); const auto child = life_of(*state, identity); const auto expressed = state->archive().find(pre.identity.genome); const auto successor = state->archive().find(9'000); const auto expected = checked(biology::split_cell(*expressed, *successor, pre.growth, pre.body, pre.reserve, 293'150, become ? 800 : 200, 500, state->revamp_rules().body), "expected safety shares"); require( parent.body == expected.parent_body && child.body == expected.child_body && parent.reserve == expected.parent_reserve && child.reserve == expected.child_reserve, "the controlled cell did not receive its 80 percent without growth spending the buffer"); require(become ? child.account == account(2) : parent.account == account(2), "safety control went to the wrong cell"); const auto parent_budget = checked(biology::metabolic_budget(*expressed, parent.growth, {293'150, {}}, 1000, state->revamp_rules().body), "parent budget"); const auto child_budget = checked(biology::metabolic_budget(*successor, child.growth, {293'150, {}}, 1000, state->revamp_rules().body), "child budget"); require(!biology::cellular_footprints_contact(parent.position, parent_budget.phenotype.extent, child.position, child_budget.phenotype.extent), "split siblings remained in engulf contact"); const auto dx = static_cast(child.position.x_um) - static_cast(parent.position.x_um); const auto dy = static_cast(child.position.y_um) - static_cast(parent.position.y_um); require(dx * (std::int64_t{child.motion.velocity_x_q10} - parent.motion.velocity_x_q10) + dy * (std::int64_t{child.motion.velocity_y_q10} - parent.motion.velocity_y_q10) > 0, "the newborn was not launched away"); auto hunters = swim(*state, {}); for (auto& input : hunters) input.intent.engulf = true; checked(state->advance_tick(hunters), "sibling engulf attempt"); require(state->lives().size() == base->lives().size() + 1, "a sibling was immediately reclaimed"); closed(*state); CellularBatch batch; batch.format_version = cellular_batch_inheritance_format; batch.header = {state->world(), state->region(), state->frame(), {}, {}, base->tick(), state->tick()}; batch.header.predecessor.fill(1); batch.header.predecessor_digest.fill(2); batch.ticks.push_back({intents, {}, choice}); batch.ticks.push_back({hunters, {}, {}}); const auto decoded = checked(decode_cellular_batch(checked(encode_cellular_batch(batch), "encode")), "decode"); const auto replayed = checked(replay_cellular_batch(*base, decoded), "safety replay"); require(replayed->snapshot() == state->snapshot() && restore(*state)->snapshot() == state->snapshot(), "safety restore/replay diverged"); } void safe_bud_provision(bool become) { auto state = adhesion_region(100'000, true, 625); for (int tick = 0; tick < 4'000; ++tick) { const auto cost = state->budding_cost(101); if (!cost) throw std::runtime_error("safety fixture has no bud requirement"); const auto& reserve = life_of(*state, 101).reserve; bool funded = reserve.energy.value >= cost->energy.value + cost->energy.value / 10; for (std::size_t c = 0; funded && c < reserve.matter.size(); ++c) funded = reserve.matter[c].value >= cost->matter[c].value + cost->matter[c].value / 10; if (funded) break; checked(state->advance_tick(swim(*state, {}, 0x0F)), "fund safe bud"); } auto baseline = restore(*state); auto inputs = swim(*state, {}); auto request = std::ranges::find(inputs, 101, &CellularLifeIntent::life_id); request->intent.bud = true; request->intent.become = become; auto idle = swim(*baseline, {}); checked(baseline->advance_tick(idle), "pre-bud comparison"); const auto pre = life_of(*baseline, 101); const auto genome = baseline->archive().find(pre.identity.genome); const auto expected = checked(biology::fund_offspring(*genome, *genome, pre.growth, pre.reserve, 293'150), "ordinary bud funding"); const auto result = checked(state->advance_tick_with_mutations(inputs, {}), "safe bud"); require(result.buds.size() == 1 && result.buds.front().result == CellularBudResult::budded, "safe bud not funded"); const auto& parent = life_of(*state, 101); const auto& child = life_of(*state, result.buds.front().bud_life); require(parent.body == pre.body && child.body == expected.body, "safe budding consumed parent tissue"); auto parent_reserve = expected.parent_reserve; auto child_reserve = expected.reserve; if (become) { parent_reserve.matter[0].value -= 100'000; child_reserve.matter[0].value += 100'000; } require(parent.reserve == parent_reserve && child.reserve == child_reserve && (become ? child.account == account(2) : parent.account == account(2)), "bud provision did not follow control or was reclaimed instead"); require(state->habitat().patches().size() == baseline->habitat().patches().size(), "the returned provision also became environmental bubbles"); closed(*state); require(restore(*state)->snapshot() == state->snapshot(), "safe bud restore diverged"); std::uint32_t growth_steps = 0; const auto child_id = child.identity.life; for (int tick = 0; tick < 800; ++tick) { checked(state->advance_tick(swim(*state, {})), "funded safe growth"); const auto& growing = life_of(*state, child_id); const auto report = std::ranges::find(state->last_tick_feedback(), child_id, &CellularLifeTickFeedback::life_id); if (report != state->last_tick_feedback().end() && report->into_growth != accounting::Inventory{}) { ++growth_steps; const auto body_genome = state->archive().find(growing.identity.genome); const auto budget = checked(biology::metabolic_budget(*body_genome, growing.growth, {293'150, {}}, 1000, state->revamp_rules().body), "growing budget"); const auto burn = biology::cellular_burn( state->revamp_rules().burn_pj_per_kfg, body_genome->cellular_traits().value_or(biology::founder_cellular_traits).burn, 0); require(biology::cellular_payable_energy(growing.reserve, burn, false) >= budget.demand.value * 60, "growth consumed the resulting body's protected fuel"); } if (growing.growth.realized_per_thousand == 1000 || growth_steps == 16) break; } require(growth_steps != 0, "a well-fed juvenile never resumed safe growth"); closed(*state); } } // namespace int main() try { admin_commands_apply_and_replay(); tuning_is_adopted_and_replayed(); heat_cycles_back(); full_drip_is_absorbed(); safety_split(false); safety_split(true); safe_bud_provision(false); safe_bud_provision(true); starting_wildlife_is_a_funded_opening(); shown_bud_charge_includes_the_fee(); the_bud_fee_is_paid_in_full_or_refused(); upgrade_and_restore(); feeding_settings_restore(); mixed_generations_tick_and_continue(); the_spent_pool_drips_back(); carried_matter_is_load(); exclusions_are_checked_and_replayed(); a_long_run_keeps_closure_and_restores(); offers_come_from_active_play(); a_choice_splits_the_cell(false); a_choice_splits_the_cell(true); the_region_cap_refuses_splits(); become_and_litter(); unaffordable_choices_wait_and_declines_clear(); thrust_moves_affinity(); an_organism_forms_grows_and_emerges(); emerge_needs_the_threshold(); trace_replays(); std::puts("PASS rules 13 owner: upgrade, founder 6, restore and replay"); return 0; } catch (const std::exception& error) { std::printf("FAIL rules 13 owner: %s\n", error.what()); return 1; } catch (...) { std::puts("FAIL rules 13 owner"); return 1; }