Files
aevolution/tests/cellular_lives_tests.cpp
T
dingoandClaude Opus 5.5 7929dea2fc
Foundation / checks (network) (push) Canceled after 0s
Foundation / checks (postgres) (push) Canceled after 0s
Foundation / checks (tsan) (push) Canceled after 0s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (checks) (push) Canceled after 5s
Foundation / checks (client) (push) Canceled after 5s
Foundation / checks (deploy) (push) Canceled after 5s
Foundation / checks (ecs) (push) Successful in 2m26s
M11-PT-001: log why a cellular tick cannot be built
A tick whose batch the builder refuses was dropped silently and retried every 50 ms,
so a region could stop advancing with nothing in its log: after a restart DEV region 6
stayed at tick 7144 while its owner was connected. The server now prints each distinct
refusal once ("cellular tick stalled tick=N at=create|append error=E") until a tick
builds again.

Also covers a founder that buds, is suspended while its wildlife bud lives on, and
resumes on its owner's return (rules 6); that path resumes correctly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 11:35:51 -04:00

1022 lines
55 KiB
C++

#include "evo/server/lifecycle/cellular_batch.hpp"
#include "evo/server/lifecycle/cellular_lives.hpp"
#include "evo/server/lifecycle/cellular_play_summary.hpp"
#include "evo/server/lifecycle/wildlife_controller.hpp"
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <limits>
#include <source_location>
#include <span>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
using namespace evo::server;
using evo::accounting::Inventory;
void check(bool value, std::source_location at = std::source_location::current()) {
if (!value)
throw std::runtime_error("cellular lives line " + std::to_string(at.line()));
}
#define CHECK(...) check(static_cast<bool>(__VA_ARGS__))
Inventory founder_price(std::uint64_t count) {
const auto endowment = evo::biology::primitive_endowment();
CHECK(endowment);
auto funding = endowment->body;
funding.energy.value = endowment->reserve.energy.value + endowment->construction.value;
funding.energy.value *= count;
for (auto& channel : funding.matter)
channel.value *= count;
return funding;
}
std::uint64_t checksum(std::span<const std::uint8_t> bytes) {
std::uint64_t value = 14695981039346656037ULL;
for (const auto byte : bytes)
value = (value ^ byte) * 1099511628211ULL;
return value;
}
void refresh_checksum(std::vector<std::uint8_t>& bytes) {
const auto value = checksum(std::span{bytes}.first(bytes.size() - 8));
for (unsigned i = 0; i < 8; ++i)
bytes[bytes.size() - 8 + i] = static_cast<std::uint8_t>(value >> (i * 8U));
}
std::unique_ptr<CellularLives> empty_cellular_owner(Inventory funding,
std::vector<SpawnSite> sites) {
auto primitive = PrimitiveLives::create({91, 1, 1, 17, funding, std::move(sites)});
CHECK(primitive);
auto habitat = evo::biology::CellularHabitat::create({91, 1, 1, 1'000, 1'000, {}});
CHECK(habitat);
auto owner =
CellularLives::create(**primitive, std::move(*habitat), {{1'000, 1'000}, 0, 293'150});
CHECK(owner);
CHECK((*owner)->ambient_temperature_millikelvin() == 293'150);
return std::move(*owner);
}
void reserved_birth_is_funded_and_detached() {
auto opening = empty_cellular_owner(founder_price(1), {{0, 0}, {20, 0}});
const std::span<const CellularLifeIntent> no_lives{};
CHECK(opening->advance_tick(no_lives));
const auto predecessor = opening->snapshot();
LifeRequest request{};
request.account.back() = 9;
request.action = 17;
const LifeAllocation allocation{501, 501, 501, 501, {1}};
auto born = opening->birth_candidate(request, allocation);
CHECK(born && opening->tick() == 1 && opening->lives().empty());
CHECK((*born)->tick() == opening->tick() && (*born)->lives().size() == 1 &&
(*born)->lives()[0].account == request.account &&
(*born)->lives()[0].identity == allocation && (*born)->lives()[0].source == 17 &&
(*born)->lives()[0].position == (evo::biology::CellularPosition{0, 0}));
const auto endowment = evo::biology::primitive_endowment();
CHECK(endowment);
CHECK((*born)->nursery().energy.value == opening->nursery().energy.value -
endowment->reserve.energy.value -
endowment->construction.value);
CHECK((*born)->heat().energy.value == endowment->construction.value &&
(*born)->current_total() == (*born)->opening_total() &&
(*born)->archive().recorded() == 1);
CHECK(opening->snapshot() == predecessor);
const auto recovered = CellularLives::restore((*born)->snapshot(), 91, 1, 1, 1);
CHECK(recovered && (*recovered)->snapshot() == (*born)->snapshot());
auto retry_account = request;
retry_account.action++;
CHECK((*born)->birth_candidate(retry_account, {502, 502, 502, 502, {1}}).error() ==
CellularLivesError::life_exists);
CHECK(opening->birth_candidate(request, {502, 503, 502, 502, {1}}).error() ==
CellularLivesError::identity);
CHECK(opening->birth_candidate(request, {502, 502, 502, 502, {2}}).error() ==
CellularLivesError::invalid_tick);
const std::array next_tick{CellularLifeIntent{allocation.life, {}}};
CHECK((*born)->advance_tick(next_tick) && (*born)->tick() == 2 && (*born)->lives().size() == 1);
auto trace_base = empty_cellular_owner(founder_price(1), {{0, 0}});
CellularBatch birth_batch;
birth_batch.format_version = cellular_batch_v2_format;
birth_batch.header = {trace_base->world(), trace_base->region(), trace_base->frame(), {}, {},
trace_base->tick(), trace_base->tick() + 1};
birth_batch.header.predecessor.fill(3);
birth_batch.header.predecessor_digest.fill(4);
CellularTickIntents birth_tick;
birth_tick.births.push_back({request.account, request.action, 1, 801});
birth_batch.ticks.push_back(birth_tick);
const auto birth_bytes = encode_cellular_batch(birth_batch);
CHECK(birth_bytes);
const auto decoded_births = decode_cellular_batch(*birth_bytes);
CHECK(decoded_births && *decoded_births == birth_batch);
const auto replayed_birth = replay_cellular_batch(*trace_base, *decoded_births);
CHECK(replayed_birth && (*replayed_birth)->tick() == 1 &&
(*replayed_birth)->lives().size() == 1 &&
(*replayed_birth)->lives()[0].identity.life == 801 &&
(*replayed_birth)->lives()[0].account == request.account &&
(*replayed_birth)->archive().recorded() == 1 &&
(*replayed_birth)->current_total() == (*replayed_birth)->opening_total());
auto legacy_batch = birth_batch;
legacy_batch.ticks[0].births.clear();
auto legacy_bytes = encode_cellular_batch(legacy_batch);
CHECK(legacy_bytes);
(*legacy_bytes)[8] = static_cast<std::uint8_t>(cellular_batch_legacy_format);
legacy_bytes->erase(legacy_bytes->begin() + 116, legacy_bytes->begin() + 120);
const auto decoded_legacy = decode_cellular_batch(*legacy_bytes);
CHECK(decoded_legacy && decoded_legacy->format_version == cellular_batch_legacy_format &&
decoded_legacy->ticks[0].births.empty());
auto v2_bytes = encode_cellular_batch(legacy_batch);
CHECK(v2_bytes);
const auto decoded_v2 = decode_cellular_batch(*v2_bytes);
CHECK(decoded_v2 && decoded_v2->format_version == cellular_batch_v2_format &&
decoded_v2->ticks[0].births.empty() &&
decoded_v2->ticks[0].lives == legacy_batch.ticks[0].lives);
auto invalid_birth_batch = birth_batch;
invalid_birth_batch.ticks[0].births[0].generation = 0;
CHECK(encode_cellular_batch(invalid_birth_batch).error() == CellularBatchError::format);
auto unfunded = empty_cellular_owner({}, {{0, 0}});
CHECK(unfunded->advance_tick(no_lives));
const auto unfunded_snapshot = unfunded->snapshot();
CHECK(unfunded->birth_candidate(request, {601, 601, 601, 601, {1}}).error() ==
CellularLivesError::insufficient_funding);
CHECK(unfunded->snapshot() == unfunded_snapshot && unfunded->lives().empty());
auto occupied_primitive = PrimitiveLives::create({92, 1, 1, 17, founder_price(2), {{0, 0}}});
CHECK(occupied_primitive);
LifeRequest existing{};
existing.account.back() = 11;
existing.action = 1;
CHECK((*occupied_primitive)->spawn(existing, {701, 701, 701, 701, {1}}));
auto occupied_habitat = evo::biology::CellularHabitat::create({92, 1, 1, 1'000, 1'000, {}});
CHECK(occupied_habitat);
auto occupied = CellularLives::create(**occupied_primitive, std::move(*occupied_habitat),
{{1'000, 1'000}, 1, 293'150});
CHECK(occupied);
LifeRequest arriving{};
arriving.account.back() = 12;
arriving.action = 2;
CHECK((*occupied)->birth_candidate(arriving, {702, 702, 702, 702, {1}}).error() ==
CellularLivesError::no_placement);
}
void cellular_profile_migration_is_explicit_and_no_tick() {
auto primitive = PrimitiveLives::create({91, 1, 1, 17, founder_price(1), {{0, 0}}});
CHECK(primitive);
LifeRequest request{};
request.account.back() = 5;
request.action = 1;
CHECK((*primitive)->spawn(request, {1, 101, 201, 301, {1}}));
auto habitat = evo::biology::CellularHabitat::create({91, 1, 1, 1'000, 1'000, {}});
CHECK(habitat);
auto created =
CellularLives::create(**primitive, std::move(*habitat), {{1'000, 1'000}, 1, 293'150});
CHECK(created && (*created)->lives().size() == 1);
auto current = std::move(*created);
auto legacy_bytes = current->snapshot();
legacy_bytes.erase(legacy_bytes.begin() + 220 + 168, legacy_bytes.begin() + 220 + 480);
constexpr std::uint64_t legacy_magic = 0x3130564C43564541ULL;
for (unsigned index = 0; index < 8; ++index)
legacy_bytes[index] = static_cast<std::uint8_t>(legacy_magic >> (index * 8U));
legacy_bytes[8] = 1;
legacy_bytes[9] = legacy_bytes[10] = legacy_bytes[11] = 0;
legacy_bytes[12] = 1;
legacy_bytes[13] = legacy_bytes[14] = legacy_bytes[15] = 0;
refresh_checksum(legacy_bytes);
const auto legacy = CellularLives::restore(legacy_bytes, current->world(), current->region(),
current->frame(), current->tick());
CHECK(legacy && (*legacy)->format_version() == cellular_lives_legacy_format &&
(*legacy)->rules_version() == 1 && (*legacy)->snapshot() == legacy_bytes &&
(*legacy)->lives().size() == 1);
const auto legacy_life_id = (*legacy)->lives()[0].identity.life;
const std::array legacy_idle{CellularLifeIntent{legacy_life_id, {}}};
CHECK((*legacy)->advance_tick(legacy_idle) &&
(*legacy)->format_version() == cellular_lives_legacy_format &&
(*legacy)->rules_version() == 1 && (*legacy)->tick() == 2);
const auto before = (*legacy)->snapshot();
const auto biological_state = (*legacy)->lives()[0];
const auto migrated = (*legacy)->migrate_to_v2();
CHECK(migrated && (*migrated)->format_version() == cellular_lives_format &&
(*migrated)->rules_version() == cellular_lives_rules &&
(*migrated)->tick() == (*legacy)->tick() &&
(*migrated)->current_total() == (*legacy)->current_total() &&
(*migrated)->lives().size() == 1 &&
(*migrated)->lives()[0].account == biological_state.account &&
(*migrated)->lives()[0].identity == biological_state.identity &&
(*migrated)->lives()[0].source == biological_state.source &&
(*migrated)->lives()[0].growth == biological_state.growth &&
(*migrated)->lives()[0].position == biological_state.position &&
(*migrated)->lives()[0].body == biological_state.body &&
(*migrated)->lives()[0].reserve == biological_state.reserve &&
(*migrated)->lives()[0].mutation == CellularMutationProgress{} &&
(*legacy)->snapshot() == before && (*migrated)->snapshot() != before);
const auto restored =
CellularLives::restore((*migrated)->snapshot(), current->world(), current->region(),
current->frame(), (*migrated)->tick());
CHECK(restored && (*restored)->snapshot() == (*migrated)->snapshot());
const auto migrated_life_id = (*migrated)->lives()[0].identity.life;
const std::array migrated_idle{CellularLifeIntent{migrated_life_id, {}}};
CHECK((*migrated)->advance_tick(migrated_idle) &&
(*migrated)->format_version() == cellular_lives_format &&
(*migrated)->rules_version() == cellular_lives_rules && (*migrated)->tick() == 3);
const auto v2_before = (*migrated)->snapshot();
const auto revision_profile = (*migrated)->migrate_to_v3();
CHECK(revision_profile &&
(*revision_profile)->format_version() == cellular_lives_revision_format &&
(*revision_profile)->rules_version() == cellular_lives_rules &&
(*revision_profile)->tick() == (*migrated)->tick() &&
(*revision_profile)->current_total() == (*migrated)->current_total() &&
std::ranges::equal((*revision_profile)->lives(), (*migrated)->lives()) &&
(*revision_profile)->archive().format_version() ==
evo::biology::lineage_archive_revision_format &&
(*revision_profile)->archive().revisions().empty() &&
(*migrated)->snapshot() == v2_before);
const auto v3_bytes = (*revision_profile)->snapshot();
const auto v3_restored =
CellularLives::restore(v3_bytes, 91, 1, 1, (*revision_profile)->tick());
CHECK(v3_restored && (*v3_restored)->snapshot() == v3_bytes &&
(*v3_restored)->format_version() == cellular_lives_revision_format);
}
void retained_feeding_earns_a_persistent_mutation_offer() {
auto primitive = PrimitiveLives::create({93, 1, 1, 17, founder_price(1), {{0, 0}}});
CHECK(primitive);
LifeRequest request{};
request.account.back() = 3;
request.action = 1;
CHECK((*primitive)->spawn(request, {1, 101, 201, 301, {1}}));
Inventory patch_stock{{1'000'000'000'000ULL},
{{{1'000'000'000'000ULL},
{1'000'000'000'000ULL},
{1'000'000'000'000ULL},
{1'000'000'000'000ULL}}}};
auto habitat = evo::biology::CellularHabitat::create(
{93, 1, 1, 1'000, 1'000, {{{0, 0}, 29, patch_stock}}});
CHECK(habitat);
auto created =
CellularLives::create(**primitive, std::move(*habitat), {{1'000, 1'000}, 1, 293'150});
CHECK(created && (*created)->lives().size() == 1 &&
(*created)->lives()[0].mutation.fed_energy_credit_pj == 0);
auto& owner = **created;
const auto life_id = owner.lives()[0].identity.life;
CHECK(owner.mutation_offer(life_id) && !*owner.mutation_offer(life_id));
const auto founder = owner.archive().find(owner.lives()[0].identity.genome);
CHECK(founder);
const auto founder_budget = evo::biology::metabolic_budget(
*founder, owner.lives()[0].growth, {owner.ambient_temperature_millikelvin(), {}});
CHECK(founder_budget &&
founder_budget->maintenance.value <=
std::numeric_limits<std::uint64_t>::max() / cellular_mutation_surplus_seconds);
const auto threshold = founder_budget->maintenance.value * cellular_mutation_surplus_seconds;
std::uint64_t total_acquired{};
bool offered = false;
for (std::size_t step = 0; step < 10'000 && !offered; ++step) {
const std::array intent{CellularLifeIntent{life_id, {{0, 0}, {{0, 0}}}}};
const auto advanced = owner.advance_tick(intent);
CHECK(advanced && advanced->lives.size() == 1 && advanced->lives[0].candidate.intake);
const auto intake = advanced->lives[0].candidate.intake.value_or(
evo::biology::CellularPatchUptakeProposal{});
total_acquired += intake.transfer.acquired.energy.value;
const auto offer = owner.mutation_offer(life_id);
CHECK(offer);
offered = offer->has_value();
}
CHECK(offered);
const auto earned = owner.mutation_offer(life_id);
const auto earned_data = earned.value_or(std::nullopt).value_or(evo::biology::MutationOffer{});
CHECK(earned && earned_data.candidates.size() <= cellular_mutation_candidate_count &&
!earned_data.candidates.empty() && owner.lives()[0].mutation.event_index == 1 &&
owner.lives()[0].mutation.offer_tick == owner.tick() &&
total_acquired == threshold + owner.lives()[0].mutation.fed_energy_credit_pj);
const auto saved = owner.snapshot();
const auto recovered = CellularLives::restore(saved, 93, 1, 1, owner.tick());
CHECK(recovered && (*recovered)->snapshot() == saved);
auto changed_seed = saved;
constexpr std::size_t v2_header_and_single_site = 220;
constexpr std::size_t v1_life_bytes = 168;
constexpr std::size_t mutation_seed_offset = 40;
changed_seed[v2_header_and_single_site + v1_life_bytes + mutation_seed_offset] ^= 1U;
refresh_checksum(changed_seed);
const auto noncanonical = CellularLives::restore(changed_seed, 93, 1, 1, owner.tick());
CHECK(!noncanonical && noncanonical.error() == CellularLivesError::noncanonical);
const auto replayed_offer = (*recovered)->mutation_offer(life_id);
CHECK(replayed_offer && replayed_offer == earned);
const std::array idle{CellularLifeIntent{life_id, {}}};
CHECK(owner.advance_tick(idle));
const auto after_tick = owner.mutation_offer(life_id);
CHECK(after_tick && after_tick == earned);
auto revision_owner = owner.migrate_to_v3();
CHECK(revision_owner && (*revision_owner)->format_version() == cellular_lives_revision_format);
const auto current_offer = (*revision_owner)->mutation_offer(life_id);
const auto current_offer_data =
current_offer.value_or(std::nullopt).value_or(evo::biology::MutationOffer{});
CHECK(current_offer && !current_offer_data.candidates.empty());
const CellularMutationSelection selection{life_id,
(*revision_owner)->lives()[0].mutation.event_index,
(*revision_owner)->lives()[0].mutation.offer_tick,
999, current_offer_data.candidates[0].operator_id};
CellularBatch mutation_batch;
mutation_batch.header = {(*revision_owner)->world(),
(*revision_owner)->region(),
(*revision_owner)->frame(),
{},
{},
(*revision_owner)->tick(),
(*revision_owner)->tick() + 1};
mutation_batch.header.predecessor.fill(0x31);
mutation_batch.header.predecessor_digest.fill(0x41);
CellularTickIntents mutation_tick;
mutation_tick.lives.push_back({life_id, {}});
mutation_tick.mutations.push_back(selection);
mutation_batch.ticks.push_back(mutation_tick);
const auto mutation_bytes = encode_cellular_batch(mutation_batch);
CHECK(mutation_bytes);
const auto decoded_mutation = decode_cellular_batch(*mutation_bytes);
CHECK(decoded_mutation && *decoded_mutation == mutation_batch);
const std::array mutation_actions{CellularMutationActionRecord{
(*revision_owner)->lives()[0].account,
44,
mutation_batch.header.end_tick,
{life_id, selection.event_index, selection.offer_tick, selection.operator_id}}};
const auto action_block = encode_cellular_mutation_action_block(
mutation_actions, mutation_batch.header.begin_tick, mutation_batch.header.end_tick);
CHECK(action_block);
const auto decoded_action_block = decode_cellular_mutation_action_block(
*action_block, mutation_batch.header.begin_tick, mutation_batch.header.end_tick);
CHECK(decoded_action_block &&
*decoded_action_block ==
std::vector<CellularMutationActionRecord>{mutation_actions.front()} &&
match_cellular_mutation_actions_to_trace(**revision_owner, *decoded_mutation,
*decoded_action_block));
const auto replayed_mutation = replay_cellular_batch(**revision_owner, *decoded_mutation);
CHECK(replayed_mutation && (*replayed_mutation)->tick() == mutation_batch.header.end_tick);
// ADR-0120 amendment: operator 0 declines the same offer. The trace, its action block and
// replay accept it; the offer is consumed, the genome and inventories are unchanged,
// and the reserved successor identity stays unused.
{
auto declined = selection;
declined.operator_id = 0;
auto decline_batch = mutation_batch;
decline_batch.ticks[0].mutations[0] = declined;
const auto decline_bytes = encode_cellular_batch(decline_batch);
CHECK(decline_bytes);
const auto decoded_decline = decode_cellular_batch(*decline_bytes);
CHECK(decoded_decline && *decoded_decline == decline_batch);
const std::array decline_actions{
CellularMutationActionRecord{(*revision_owner)->lives()[0].account,
45,
decline_batch.header.end_tick,
{life_id, declined.event_index, declined.offer_tick, 0}}};
const auto decline_block = encode_cellular_mutation_action_block(
decline_actions, decline_batch.header.begin_tick, decline_batch.header.end_tick);
CHECK(decline_block);
const auto decoded_block = decode_cellular_mutation_action_block(
*decline_block, decline_batch.header.begin_tick, decline_batch.header.end_tick);
CHECK(decoded_block && match_cellular_mutation_actions_to_trace(
**revision_owner, *decoded_decline, *decoded_block));
const auto replayed_decline = replay_cellular_batch(**revision_owner, *decoded_decline);
CHECK(replayed_decline);
const auto& after = **replayed_decline;
CHECK(!after.lives().empty() && !after.lives()[0].mutation.offer &&
after.lives()[0].mutation.offer_tick == 0 &&
after.lives()[0].identity.genome == (*revision_owner)->lives()[0].identity.genome &&
after.archive().revisions().empty() && !after.archive().find(declined.successor_id) &&
after.current_total() == after.opening_total());
// An operator that was not offered is still refused.
auto unknown = decline_batch;
unknown.ticks[0].mutations[0].operator_id = 0xFFFF;
CHECK(!replay_cellular_batch(**revision_owner, unknown));
}
const std::array idle_next{CellularLifeIntent{life_id, {}}};
const std::array selections{selection};
const auto direct_mutation =
(*revision_owner)->advance_tick_with_mutations(idle_next, selections);
CHECK(direct_mutation && direct_mutation->mutations.size() == 1 &&
(*replayed_mutation)->snapshot() == (*revision_owner)->snapshot() &&
(*revision_owner)->current_total() == (*revision_owner)->opening_total());
if (direct_mutation->mutations[0].result == CellularMutationResult::applied) {
CHECK(direct_mutation->mutations[0].successor_id == selection.successor_id &&
(*revision_owner)->lives()[0].identity.genome == selection.successor_id &&
(*revision_owner)
->archive()
.current_genome((*revision_owner)->lives()[0].identity.organism) ==
selection.successor_id &&
(*revision_owner)->archive().revisions().size() == 1 &&
!(*revision_owner)->lives()[0].mutation.offer);
} else if (direct_mutation->mutations[0].result ==
CellularMutationResult::insufficient_funding) {
CHECK(direct_mutation->mutations[0].result ==
CellularMutationResult::insufficient_funding &&
(*revision_owner)->lives()[0].identity.genome ==
(*revision_owner)
->archive()
.organism((*revision_owner)->lives()[0].identity.organism)
->genome &&
(*revision_owner)->archive().revisions().empty() &&
(*revision_owner)->lives()[0].mutation.offer.has_value());
} else {
CHECK(direct_mutation->mutations[0].result == CellularMutationResult::life_died &&
(*revision_owner)->lives().empty() && (*revision_owner)->corpses().size() == 1 &&
(*revision_owner)->archive().revisions().empty());
}
}
void owner_advances_and_closes_death_atomically() {
auto primitive = PrimitiveLives::create({90, 1, 7, 17, founder_price(2), {{0, 0}, {20, 0}}});
CHECK(primitive);
LifeRequest request{};
request.account.back() = 1;
request.action = 1;
CHECK((*primitive)->spawn(request, {1, 101, 201, 301, {1}}));
request.account.back() = 2;
CHECK((*primitive)->spawn(request, {2, 102, 202, 302, {1}}));
evo::biology::CellularHabitatConfig habitat_config{
90, 1, 7, 3'000, 2'000, {{{0, 0}, 29, {{10}, {{{10}, {10}, {10}, {10}}}}}}};
auto habitat = evo::biology::CellularHabitat::create(std::move(habitat_config));
CHECK(habitat);
auto created =
CellularLives::create(**primitive, std::move(*habitat), {{3'000, 2'000}, 1, 293'150});
CHECK(created);
auto& owner = **created;
CHECK(owner.world() == 90 && owner.region() == 1 && owner.frame() == 7);
CHECK(owner.lives().size() == 2 && owner.tick() == 1);
CHECK(owner.current_total() == owner.opening_total());
const std::array invalid{CellularLifeIntent{1, {}}, CellularLifeIntent{1, {}}};
const auto refused = owner.advance_tick(invalid);
CHECK(!refused && owner.tick() == 1 && owner.lives().size() == 2);
const auto first_life_id = owner.lives()[0].identity.life;
const auto second_life_id = owner.lives()[1].identity.life;
const auto visible_patches = owner.perceive(first_life_id);
CHECK(visible_patches && visible_patches->size() == 1 &&
visible_patches->front().address == (evo::biology::CellularPatchAddress{0, 0}) &&
visible_patches->front().available == owner.habitat().patches()[0].stock);
CHECK(owner.perceive(0).error() == CellularLivesError::invalid_life);
const std::array invalid_motion{CellularLifeIntent{first_life_id, {}},
CellularLifeIntent{second_life_id, {{1'001, 0}, std::nullopt}}};
const auto partial = owner.advance_tick(invalid_motion);
CHECK(!partial && partial.error() == CellularLivesError::region_step && owner.tick() == 1 &&
owner.lives().size() == 2);
const std::array feed{CellularLifeIntent{first_life_id, {{0, 0}, {{0, 0}}}},
CellularLifeIntent{second_life_id, {{0, 0}, {{0, 0}}}}};
const auto fed = owner.advance_tick(feed);
CHECK(fed && owner.tick() == 2 && owner.lives().size() == 2);
CHECK(fed->lives.size() == 2 &&
fed->lives[0].candidate.intake_status == evo::biology::CellularIntakeStatus::acquired);
CHECK(owner.format_version() == cellular_lives_format &&
owner.lives()[0].mutation.fed_energy_credit_pj > 0 &&
owner.mutation_offer(first_life_id) && !*owner.mutation_offer(first_life_id));
CHECK(owner.last_tick_feedback().size() == 2 &&
owner.last_tick_feedback()[0].tick == owner.tick() &&
owner.last_tick_feedback()[0].life_id == owner.lives()[0].identity.life &&
owner.last_tick_feedback()[0].reserve == fed->lives[0].candidate.reserve_after &&
owner.last_tick_feedback()[0].maintenance_cost ==
fed->lives[0].candidate.maintenance_cost &&
owner.last_tick_feedback()[0].movement ==
evo::biology::CellularMovementStatus::not_requested &&
owner.last_tick_feedback()[0].intake == evo::biology::CellularIntakeStatus::acquired);
CHECK(owner.habitat().patches()[0].stock == (Inventory{{0}, {}}));
CHECK(owner.current_total() == owner.opening_total());
const auto saved = owner.snapshot();
CHECK(saved.size() <= max_cellular_lives_bytes);
auto recovered = CellularLives::restore(saved, 90, 1, 7, owner.tick());
CHECK(recovered && (*recovered)->snapshot() == saved);
CHECK((*recovered)->last_tick_feedback().empty()); // Transient presentation is not restored.
CHECK(!CellularLives::restore(saved, 91, 1, 7, owner.tick()));
CHECK(!CellularLives::restore(saved, 90, 1, 7, owner.tick() + 1));
auto damaged = saved;
damaged[100] ^= 1;
const auto damaged_result = CellularLives::restore(damaged, 90, 1, 7, owner.tick());
CHECK(!damaged_result && damaged_result.error() == CellularLivesError::checksum);
auto unsupported = saved;
unsupported[8] = static_cast<std::uint8_t>(cellular_lives_format + 1);
refresh_checksum(unsupported);
const auto unsupported_result = CellularLives::restore(unsupported, 90, 1, 7, owner.tick());
CHECK(!unsupported_result && unsupported_result.error() == CellularLivesError::version);
auto outside = saved;
std::fill(outside.begin() + 300, outside.begin() + 308, uint8_t{0xff});
refresh_checksum(outside);
CHECK(!CellularLives::restore(outside, 90, 1, 7, owner.tick()));
CellularBatch replay_batch;
replay_batch.header = {owner.world(), owner.region(), owner.frame(), {}, {},
owner.tick(), owner.tick() + 2};
replay_batch.header.predecessor.fill(0x31);
replay_batch.header.predecessor_digest.fill(0x41);
for (int i = 0; i < 2; ++i) {
CellularTickIntents tick;
for (const auto& life : owner.lives())
tick.lives.push_back({life.identity.life, {}});
replay_batch.ticks.push_back(std::move(tick));
}
const auto batch_bytes = encode_cellular_batch(replay_batch);
CHECK(batch_bytes && batch_bytes->size() <= max_cellular_batch_bytes);
const auto decoded_batch = decode_cellular_batch(*batch_bytes);
CHECK(decoded_batch && *decoded_batch == replay_batch);
CellularActionRecord action;
action.account = owner.lives()[0].account;
action.action_id = 17;
action.input[0] = static_cast<std::uint8_t>(owner.tick() + 1);
const std::array actions{action};
const auto action_bytes = encode_cellular_action_block(actions, owner.tick(), owner.tick() + 2);
CHECK(action_bytes && action_bytes->size() == cellular_action_record_bytes);
const auto decoded_actions =
decode_cellular_action_block(*action_bytes, owner.tick(), owner.tick() + 2);
CHECK(decoded_actions && *decoded_actions == std::vector<CellularActionRecord>{action});
CHECK(match_cellular_actions_to_trace(owner, *decoded_batch, *decoded_actions));
auto changed_action = action;
changed_action.input[8] = 1;
const std::array changed_actions{changed_action};
CHECK(match_cellular_actions_to_trace(owner, *decoded_batch, changed_actions).error() ==
CellularActionBlockError::mismatch);
const auto replayed_batch = replay_cellular_batch(owner, *decoded_batch);
CHECK(replayed_batch && (*replayed_batch)->tick() == owner.tick() + 2);
CHECK((*replayed_batch)->last_tick_feedback().size() == owner.lives().size() &&
(*replayed_batch)->last_tick_feedback()[0].tick == (*replayed_batch)->tick());
CHECK((*replayed_batch)->current_total() == owner.opening_total());
auto short_batch = *batch_bytes;
short_batch.pop_back();
CHECK(!decode_cellular_batch(short_batch));
auto noncanonical_batch = *batch_bytes;
noncanonical_batch[noncanonical_batch.size() - 1] = 1;
CHECK(!decode_cellular_batch(noncanonical_batch));
auto wrong_scope = replay_batch;
wrong_scope.header.region++;
CHECK(replay_cellular_batch(owner, wrong_scope).error() == CellularBatchError::scope);
std::size_t steps{};
while (!owner.lives().empty() && steps < 2'000) {
std::vector<CellularLifeIntent> idle;
idle.reserve(owner.lives().size());
for (const auto& life : owner.lives())
idle.push_back({life.identity.life, {}});
const auto advanced = owner.advance_tick(idle);
const auto replayed = (*recovered)->advance_tick(idle);
CHECK(advanced && replayed && *advanced == *replayed);
CHECK(owner.snapshot() == (*recovered)->snapshot());
CHECK(owner.current_total() == owner.opening_total());
++steps;
}
CHECK(owner.lives().empty() && owner.corpses().size() == 2 && steps < 2'000);
CHECK(owner.corpses()[0].organism == 101 && owner.corpses()[0].died_tick <= owner.tick());
CHECK(owner.corpses()[1].organism == 102 && owner.corpses()[1].died_tick <= owner.tick());
CHECK(owner.corpses()[0].life_id == 1 && owner.corpses()[0].source == 17 &&
owner.corpses()[0].growth == (evo::biology::GrowthState{1000, 0}) &&
owner.corpses()[0].extent_um == 20);
const auto lineage = owner.archive().organism(101);
CHECK(lineage && !lineage->alive && lineage->died.value == owner.corpses()[0].died_tick);
const auto second_lineage = owner.archive().organism(102);
CHECK(second_lineage && !second_lineage->alive &&
second_lineage->died.value == owner.corpses()[1].died_tick);
CHECK(owner.heat().energy.value != 0);
CHECK(owner.current_total() == owner.opening_total());
const auto terminal_snapshot = owner.snapshot();
auto terminal_recovery = CellularLives::restore(terminal_snapshot, 90, 1, 7, owner.tick());
CHECK(terminal_recovery && (*terminal_recovery)->snapshot() == terminal_snapshot);
CHECK((*terminal_recovery)->lives().empty() &&
std::ranges::equal((*terminal_recovery)->corpses(), owner.corpses()));
CHECK((*terminal_recovery)->heat() == owner.heat());
CHECK((*terminal_recovery)->archive().organism(101) == owner.archive().organism(101));
}
// ADR-0124 rules 3: engulf intents resolve, starvation leaves detritus, corpses keep a cause.
void rules_three_owner_resolves_engulf_and_detritus() {
auto primitive = PrimitiveLives::create({92, 1, 7, 17, founder_price(2), {{0, 0}, {20, 0}}});
CHECK(primitive);
LifeRequest request{};
request.account.back() = 1;
request.action = 1;
CHECK((*primitive)->spawn(request, {1, 101, 201, 301, {1}}));
request.account.back() = 2;
CHECK((*primitive)->spawn(request, {2, 102, 202, 302, {1}}));
evo::biology::CellularHabitatConfig habitat_config{
92, 1, 7, 3'000, 2'000, {{{0, 0}, 29, {{10}, {{{10}, {10}, {10}, {10}}}}}}};
auto habitat = evo::biology::CellularHabitat::create(std::move(habitat_config));
CHECK(habitat);
auto created =
CellularLives::create(**primitive, std::move(*habitat), {{3'000, 2'000}, 1, 293'150},
CellularLivesProfile::engulf);
CHECK(created);
auto& owner = **created;
CHECK(owner.format_version() == cellular_lives_engulf_format &&
owner.rules_version() == cellular_lives_engulf_rules &&
owner.archive().format_version() == evo::biology::lineage_archive_revision_format);
// Equal founders touching at an edge: neither is 1.5x the other.
evo::biology::CellularStepIntent engulf{};
engulf.engulf = true;
const std::array hunt{CellularLifeIntent{1, engulf}, CellularLifeIntent{2, {}}};
const auto hunted = owner.advance_tick(hunt);
CHECK(hunted && owner.lives().size() == 2);
CHECK(owner.last_tick_feedback()[0].engulf ==
evo::biology::CellularEngulfStatus::prey_too_large &&
owner.last_tick_feedback()[1].engulf ==
evo::biology::CellularEngulfStatus::not_requested);
// An engulf intent with an intake target is refused as a whole tick.
auto both = engulf;
both.intake_target = evo::biology::CellularPatchAddress{0, 0};
const std::array conflicting{CellularLifeIntent{1, both}, CellularLifeIntent{2, {}}};
CHECK(!owner.advance_tick(conflicting) && owner.tick() == 2);
// Below rules 4 a bud intent is ignored: the tick advances and nothing buds.
evo::biology::CellularStepIntent bud{};
bud.bud = true;
CHECK(owner.advance_tick(std::array{CellularLifeIntent{1, bud}, CellularLifeIntent{2, {}}}));
CHECK(owner.lives().size() == 2 && !owner.last_tick_feedback()[0].bud &&
owner.current_total() == owner.opening_total());
const auto patch_before = owner.habitat().patches()[0].stock;
std::size_t steps{};
while (!owner.lives().empty() && steps < 2'000) {
std::vector<CellularLifeIntent> idle;
for (const auto& life : owner.lives())
idle.push_back({life.identity.life, {}});
const auto advanced = owner.advance_tick(idle);
if (!advanced)
std::fprintf(stderr, "rules 3 idle tick %zu refused: %d\n", steps,
static_cast<int>(advanced.error()));
CHECK(advanced);
CHECK(owner.current_total() == owner.opening_total());
++steps;
}
CHECK(owner.lives().empty() && owner.corpses().size() == 2);
// 11.9 telemetry (ADR-0130): account-free aggregates from the state alone.
const auto ended = summarize_cellular_play(owner);
CHECK(ended && ended->owned == 0 && ended->deaths == 2 && ended->starved == 2 &&
ended->engulfed == 0 && ended->owned_deaths == 2 && ended->lifespan_min > 0 &&
ended->lifespan_min <= ended->lifespan_median &&
ended->lifespan_median <= ended->lifespan_max && ended->buds == 0 &&
ended->living_genomes == 0);
for (const auto& corpse : owner.corpses())
CHECK(corpse.cause == evo::biology::CellularDeathCause::starved &&
corpse.predator_life == 0 && corpse.inventory == Inventory{});
// Both founders died inside the (0, 0) cell, so their whole inventories joined that patch.
CHECK(owner.habitat().patches().size() == 1);
CHECK(owner.habitat().patches()[0].stock.matter[0].value >
patch_before.matter[0].value + 2 * founder_price(1).matter[0].value / 2);
const auto saved = owner.snapshot();
auto recovered = CellularLives::restore(saved, 92, 1, 7, owner.tick());
CHECK(recovered && (*recovered)->snapshot() == saved &&
std::ranges::equal((*recovered)->corpses(), owner.corpses()));
// A corpse cause outside the closed set, or a predator on a starvation corpse, is refused.
const auto corpse_at = saved.size() - 8 - owner.habitat().snapshot().size() -
owner.archive().encode().size() - std::size_t{2} * 116;
auto bad_cause = saved;
bad_cause[corpse_at + 100] = 7;
refresh_checksum(bad_cause);
CHECK(CellularLives::restore(bad_cause, 92, 1, 7, owner.tick()).error() ==
CellularLivesError::noncanonical);
auto bad_predator = saved;
bad_predator[corpse_at + 108] = 1;
refresh_checksum(bad_predator);
CHECK(CellularLives::restore(bad_predator, 92, 1, 7, owner.tick()).error() ==
CellularLivesError::noncanonical);
}
// ADR-0125: a fed founder buds an unowned wildlife cell carrying its genome. The bud's
// identity is in the region namespace, funding is conserved, and restore is exact.
void rules_four_owner_buds_wildlife() {
auto primitive = PrimitiveLives::create({93, 1, 7, 17, founder_price(1), {{0, 0}}});
CHECK(primitive);
LifeRequest request{};
request.account.back() = 3;
request.action = 1;
CHECK((*primitive)->spawn(request, {1, 101, 201, 301, {1}}));
constexpr std::uint64_t rich = 10'000'000'000;
evo::biology::CellularHabitatConfig habitat_config{
93, 1, 7, 3'000, 2'000, {{{0, 0}, 29, {{rich}, {{{rich}, {rich}, {rich}, {rich}}}}}}};
auto habitat = evo::biology::CellularHabitat::create(std::move(habitat_config));
CHECK(habitat);
auto created =
CellularLives::create(**primitive, std::move(*habitat), {{3'000, 2'000}, 1, 293'150},
CellularLivesProfile::budding);
CHECK(created);
auto& owner = **created;
CHECK(owner.format_version() == cellular_lives_bud_format &&
owner.rules_version() == cellular_lives_bud_rules && owner.next_bud_sequence() == 1);
evo::biology::CellularStepIntent feed{};
feed.intake_target = evo::biology::CellularPatchAddress{0, 0};
evo::biology::CellularStepIntent bud{};
bud.bud = true;
// A bud is exclusive with feeding; below rules 4 it is ignored (the rules 3 test).
auto feeding_bud = feed;
feeding_bud.bud = true;
CHECK(owner.advance_tick(std::array{CellularLifeIntent{1, feeding_bud}}).error() ==
CellularLivesError::invalid_intents);
// Freezing is rules 5 (ADR-0128).
evo::biology::CellularStepIntent frozen{};
frozen.frozen = true;
CHECK(owner.advance_tick(std::array{CellularLifeIntent{1, frozen}}).error() ==
CellularLivesError::invalid_intents);
const auto parent_genome = owner.lives().front().identity.genome;
std::optional<CellularTickExecution> budded;
std::size_t refused{};
for (std::size_t round = 0; round < 400 && !budded; ++round) {
for (int tick = 0; tick < 19; ++tick)
CHECK(owner.advance_tick(std::array{CellularLifeIntent{1, feed}}));
const auto before = owner.lives().front().reserve;
auto attempt = owner.advance_tick_with_mutations(
std::array{CellularLifeIntent{1, bud}}, std::span<const CellularMutationSelection>{});
CHECK(attempt && attempt->buds.size() == 1 && attempt->buds.front().parent_life == 1);
CHECK(owner.current_total() == owner.opening_total());
if (attempt->buds.front().result == CellularBudResult::budded) {
budded = std::move(*attempt);
} else {
// A refusal spends nothing beyond the ordinary tick.
CHECK(attempt->buds.front().result == CellularBudResult::insufficient_funding);
CHECK(owner.lives().size() == 1 &&
owner.lives().front().reserve.matter == before.matter);
++refused;
}
}
CHECK(budded.has_value() && refused > 0);
const auto budding = budded.value_or(CellularTickExecution{});
CHECK(budding.buds.size() == 1);
const auto identity = cellular_bud_identity(1, 1);
CHECK(budding.buds.front().bud_life == identity && owner.next_bud_sequence() == 2);
CHECK(owner.lives().size() == 2);
const auto& parent = owner.lives()[0];
const auto& child = owner.lives()[1];
CHECK(parent.identity.life == 1 && child.identity.life == identity);
CHECK(child.account == LifeAccount{} && child.parent_life == 1 &&
child.identity.genome == parent_genome && child.identity.organism == identity &&
child.identity.born.value == owner.tick() &&
child.mutation == CellularMutationProgress{});
CHECK(child.growth.realized_per_thousand < 1000 && child.reserve.energy.value > 0);
CHECK(owner.archive().living_carriers(parent_genome).value_or(0) == 2);
const auto counted = summarize_cellular_play(owner);
CHECK(counted && counted->owned == 1 && counted->wildlife == 1 && counted->buds == 1 &&
counted->living_genomes == 1 && counted->deepest_lineage == 1 && counted->deaths == 0);
CHECK(owner.last_tick_feedback().front().bud == CellularBudResult::budded &&
owner.last_tick_feedback().front().bud_life == identity);
CHECK(owner.current_total() == owner.opening_total());
// The wildlife controller drives only the unowned bud: deterministically, and here by
// feeding from the stocked patch it already touches (no movement needed).
const auto controlled = wildlife_intents(owner, owner.tick() + 1);
CHECK(controlled && controlled->size() == 1 && controlled->front().life_id == identity);
CHECK(wildlife_intents(owner, owner.tick() + 1) == controlled);
const auto& wild = controlled->front().intent;
CHECK(!wild.engulf &&
(wild.bud || (wild.intake_target == evo::biology::CellularPatchAddress{0, 0} &&
wild.movement == evo::biology::CellularIntent{})));
CHECK(owner.advance_tick(std::array{CellularLifeIntent{1, feed}, controlled->front()}));
// Wildlife feeds like any cell but never earns a mutation offer.
// Read the bud from the current state: the tick above replaced the one `child` named.
const auto& wildlife = owner.lives()[1];
const auto child_x = wildlife.position.x_um / 1000 * 1000;
const auto child_y = wildlife.position.y_um / 1000 * 1000;
evo::biology::CellularStepIntent child_feed{};
child_feed.intake_target = evo::biology::CellularPatchAddress{
static_cast<std::uint32_t>(child_x), static_cast<std::uint32_t>(child_y)};
for (int tick = 0; tick < 40; ++tick)
CHECK(owner.advance_tick(
std::array{CellularLifeIntent{1, feed}, CellularLifeIntent{identity, child_feed}}));
CHECK(owner.lives().size() == 2 && owner.lives()[1].mutation == CellularMutationProgress{});
const auto saved = owner.snapshot();
auto recovered = CellularLives::restore(saved, 93, 1, 7, owner.tick());
CHECK(recovered && (*recovered)->snapshot() == saved &&
(*recovered)->next_bud_sequence() == 2 &&
std::ranges::equal((*recovered)->lives(), owner.lives()));
// A bud identity at or beyond the recorded sequence is refused on restore.
auto rewound = saved;
const auto sequence_at = std::size_t{212};
rewound[sequence_at] = 1;
refresh_checksum(rewound);
CHECK(!CellularLives::restore(rewound, 93, 1, 7, owner.tick()));
}
// 2026-10-15 balance: a rules-6 opening keeps owner format 6 and founds schema-3,
// development-3 cells, whose birth costs the nursery less construction energy; the
// snapshot restores as rules 6 and a rules-5 opening still founds founder-1 cells.
void rules_six_found_cheaper_cells_with_finer_mutations() {
auto primitive = PrimitiveLives::create({95, 1, 7, 17, founder_price(2), {{0, 0}, {1'500, 0}}});
CHECK(primitive);
auto habitat = evo::biology::CellularHabitat::create({95, 1, 7, 3'000, 2'000, {}});
CHECK(habitat);
auto created =
CellularLives::create(**primitive, std::move(*habitat), {{3'000, 2'000}, 0, 293'150},
CellularLivesProfile::balance);
CHECK(created);
auto owner = std::move(*created);
CHECK(owner->format_version() == cellular_lives_presence_format &&
owner->rules_version() == cellular_lives_balance_rules);
const std::span<const CellularLifeIntent> no_lives{};
CHECK(owner->advance_tick(no_lives));
LifeRequest request{};
request.account.back() = 7;
request.action = 1;
const LifeAllocation allocation{601, 601, 601, 601, {1}};
const auto born = owner->birth_candidate(request, allocation);
CHECK(born && (*born)->lives().size() == 1);
const auto genome = (*born)->archive().find(allocation.genome);
CHECK(genome && genome->schema_version() == evo::biology::genome_schema_v3 &&
genome->development_version() == 3);
const auto endowment = evo::biology::primitive_endowment(evo::biology::primitive_founder_v2);
const auto classic = evo::biology::primitive_endowment();
CHECK(endowment && classic && endowment->construction.value < classic->construction.value);
CHECK((*born)->nursery().energy.value == owner->nursery().energy.value -
endowment->reserve.energy.value -
endowment->construction.value);
CHECK((*born)->heat().energy.value == endowment->construction.value &&
(*born)->current_total() == (*born)->opening_total());
const auto recovered = CellularLives::restore((*born)->snapshot(), 95, 1, 7, (*born)->tick());
CHECK(recovered && (*recovered)->rules_version() == cellular_lives_balance_rules &&
(*recovered)->snapshot() == (*born)->snapshot());
CHECK(cellular_founder_version(cellular_lives_presence_rules) ==
evo::biology::primitive_founder_v1 &&
cellular_founder_version(cellular_lives_balance_rules) ==
evo::biology::primitive_founder_v2);
}
// ADR-0128: an offline owned life freezes, lingers 200 ticks, is suspended without aging,
// survives restore, and resumes; a newborn on its spot makes it resume nearby.
void rules_five_owner_freezes_lingers_suspends_and_resumes() {
auto primitive = PrimitiveLives::create({94, 1, 7, 17, founder_price(3), {{0, 0}, {1'500, 0}}});
CHECK(primitive);
LifeRequest request{};
request.account.back() = 1;
request.action = 1;
CHECK((*primitive)->spawn(request, {1, 101, 201, 301, {1}}));
request.account.back() = 2;
CHECK((*primitive)->spawn(request, {2, 102, 202, 302, {1}}));
auto habitat = evo::biology::CellularHabitat::create({94, 1, 7, 3'000, 2'000, {}});
CHECK(habitat);
auto created =
CellularLives::create(**primitive, std::move(*habitat), {{3'000, 2'000}, 1, 293'150},
CellularLivesProfile::presence);
CHECK(created);
auto owner = std::move(*created);
CHECK(owner->format_version() == cellular_lives_presence_format &&
owner->rules_version() == cellular_lives_presence_rules);
evo::biology::CellularStepIntent frozen{};
frozen.frozen = true;
// The trace keeps the flag (intent byte 13) and refuses it with anything else.
CellularBatch frozen_batch;
frozen_batch.header = {94, 1, 7, {}, {}, owner->tick(), owner->tick() + 1};
frozen_batch.header.predecessor.fill(1);
frozen_batch.header.predecessor_digest.fill(2);
frozen_batch.ticks.push_back({{{1, frozen}, {2, {}}}, {}, {}});
const auto frozen_bytes = encode_cellular_batch(frozen_batch);
CHECK(frozen_bytes);
CHECK(decode_cellular_batch(*frozen_bytes) == frozen_batch);
auto flag_two = *frozen_bytes;
flag_two[cellular_batch_header_bytes + cellular_batch_tick_header_bytes + 13] = 2;
CHECK(!decode_cellular_batch(flag_two));
// A frozen intent carries nothing else.
auto moving = frozen;
moving.movement = {100, 0};
CHECK(owner->advance_tick(std::array{CellularLifeIntent{1, moving}, CellularLifeIntent{2, {}}})
.error() == CellularLivesError::invalid_intents);
const auto before = owner->lives()[0];
CHECK(
owner->advance_tick(std::array{CellularLifeIntent{1, frozen}, CellularLifeIntent{2, {}}}));
const auto first_frozen = owner->tick();
CHECK(owner->lives()[0].presence == CellularPresence::lingering &&
owner->lives()[0].frozen_since == first_frozen &&
owner->lives()[0].reserve == before.reserve &&
owner->lives()[0].position == before.position &&
owner->lives()[1].reserve.energy.value < before.reserve.energy.value);
// Back within the linger: active again in place.
CHECK(owner->advance_tick(std::array{CellularLifeIntent{1, {}}, CellularLifeIntent{2, {}}}));
CHECK(owner->lives()[0].presence == CellularPresence::active &&
owner->lives()[0].frozen_since == 0);
// Frozen through the whole linger: suspended after 200 ticks, without aging.
CHECK(
owner->advance_tick(std::array{CellularLifeIntent{1, frozen}, CellularLifeIntent{2, {}}}));
const auto parked = owner->lives()[0];
for (std::uint64_t tick = 1; tick <= cellular_linger_ticks; ++tick) {
CHECK(owner->lives()[0].presence == CellularPresence::lingering);
CHECK(owner->advance_tick(
std::array{CellularLifeIntent{1, frozen}, CellularLifeIntent{2, {}}}));
CHECK(owner->current_total() == owner->opening_total());
}
CHECK(owner->lives()[0].presence == CellularPresence::suspended &&
owner->lives()[0].reserve == parked.reserve &&
owner->lives()[0].position == parked.position &&
owner->last_tick_feedback()[0].presence == CellularPresence::suspended);
// Suspended lives stay out of the step while frozen.
for (int tick = 0; tick < 5; ++tick)
CHECK(owner->advance_tick(
std::array{CellularLifeIntent{1, frozen}, CellularLifeIntent{2, {}}}));
CHECK(owner->lives()[0].reserve == parked.reserve);
const auto saved = owner->snapshot();
auto recovered = CellularLives::restore(saved, 94, 1, 7, owner->tick());
CHECK(recovered && (*recovered)->snapshot() == saved &&
std::ranges::equal((*recovered)->lives(), owner->lives()));
// A lingering presence older than the linger is refused on restore.
auto stale = saved;
const auto presence_at = std::size_t{220} + std::size_t{2} * 8 + 480 + 8;
stale[presence_at] = static_cast<std::uint8_t>(CellularPresence::lingering);
refresh_checksum(stale);
CHECK(!CellularLives::restore(stale, 94, 1, 7, owner->tick()));
// A newborn takes the suspended cell's spot (placement ignores suspended cells)...
LifeRequest third{};
third.account.back() = 3;
third.action = 1;
auto born = owner->birth_candidate(third, {50, 50, 50, 50, {owner->tick()}});
CHECK(born);
owner = std::move(*born);
CHECK(owner->lives().size() == 3 && owner->lives()[2].position == parked.position);
// ...so the resume relocates within three extents, clear of everyone.
CHECK(owner->advance_tick(std::array{CellularLifeIntent{1, {}}, CellularLifeIntent{2, {}},
CellularLifeIntent{50, {}}}));
const auto& resumed = owner->lives()[0];
CHECK(resumed.presence == CellularPresence::active && resumed.frozen_since == 0 &&
resumed.position != parked.position && !owner->last_tick_feedback()[0].resume_blocked);
CHECK(owner->current_total() == owner->opening_total());
}
// M11-PT-001: a founder buds, its owner leaves until it is suspended while the wildlife
// bud lives on, then returns. The first unfrozen tick must resume it, not fail the tick.
void suspended_parent_of_a_bud_resumes() {
auto primitive = PrimitiveLives::create({96, 1, 7, 17, founder_price(1), {{0, 0}}});
CHECK(primitive);
LifeRequest request{};
request.account.back() = 4;
request.action = 1;
CHECK((*primitive)->spawn(request, {1, 101, 201, 301, {1}}));
constexpr std::uint64_t rich = 10'000'000'000;
auto habitat = evo::biology::CellularHabitat::create(
{96, 1, 7, 3'000, 2'000, {{{0, 0}, 29, {{rich}, {{{rich}, {rich}, {rich}, {rich}}}}}}});
CHECK(habitat);
auto created =
CellularLives::create(**primitive, std::move(*habitat), {{3'000, 2'000}, 1, 293'150},
CellularLivesProfile::balance);
CHECK(created);
auto& owner = **created;
evo::biology::CellularStepIntent feed{};
feed.intake_target = evo::biology::CellularPatchAddress{0, 0};
evo::biology::CellularStepIntent bud{};
bud.bud = true;
evo::biology::CellularStepIntent frozen{};
frozen.frozen = true;
const auto with_wildlife = [&](CellularLifeIntent mine) {
std::vector<CellularLifeIntent> intents{mine};
if (const auto wild = wildlife_intents(owner, owner.tick() + 1); wild)
for (const auto& intent : *wild)
intents.push_back(intent);
else
throw std::runtime_error{"wildlife intents"};
std::ranges::sort(intents, {}, &CellularLifeIntent::life_id);
return intents;
};
for (std::size_t round = 0; round < 400 && owner.lives().size() == 1; ++round) {
for (int tick = 0; tick < 19; ++tick)
CHECK(owner.advance_tick(std::array{CellularLifeIntent{1, feed}}));
CHECK(owner.advance_tick(std::array{CellularLifeIntent{1, bud}}));
}
CHECK(owner.lives().size() == 2);
for (std::uint64_t tick = 0; tick <= cellular_linger_ticks + 1; ++tick) {
const auto stepped = owner.advance_tick(with_wildlife({1, frozen}));
if (!stepped)
std::fprintf(stderr, "linger tick %llu error %u\n",
static_cast<unsigned long long>(tick),
static_cast<unsigned>(stepped.error()));
CHECK(stepped.has_value());
}
CHECK(owner.lives()[0].presence == CellularPresence::suspended);
const auto resumed = owner.advance_tick(with_wildlife({1, {}}));
if (!resumed)
std::fprintf(stderr, "resume error %u\n", static_cast<unsigned>(resumed.error()));
CHECK(resumed && owner.lives()[0].presence == CellularPresence::active);
for (int tick = 0; tick < 20; ++tick)
CHECK(owner.advance_tick(with_wildlife({1, feed})));
CHECK(owner.current_total() == owner.opening_total());
}
} // namespace
int main() {
try {
reserved_birth_is_funded_and_detached();
cellular_profile_migration_is_explicit_and_no_tick();
retained_feeding_earns_a_persistent_mutation_offer();
owner_advances_and_closes_death_atomically();
rules_three_owner_resolves_engulf_and_detritus();
rules_four_owner_buds_wildlife();
rules_five_owner_freezes_lingers_suspends_and_resumes();
rules_six_found_cheaper_cells_with_finer_mutations();
suspended_parent_of_a_bud_resumes();
std::puts(
"PASS cellular lives: feeding, tick ownership, terminal closure, rules 3, budding");
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;
}
}