Files
aevolution/include/evo/server/lifecycle/cellular_lives.hpp
T
dingoandClaude Opus 5.5 3f82795c18
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m23s
Foundation / postgres-tools (push) Successful in 29s
Foundation / server-image (push) Successful in 4m10s
Foundation / image (push) Successful in 4m31s
feat(lifecycle): rules 12 liquid owner on format 10 with brake traces
The cellular owner gains rules 12 on owner format 10: an explicit no-tick
format-9/rules-11 upgrade declares the region's liquid rules (current
configuration, founder handling and deposit motion, from the tuning file and a
seed when the region opens), converts the habitat to format 3 and starts lives at
rest. Founders born afterwards are founder 5 (genome schema 6).

Each tick derives every life's handling from its genome and the declared founder
handling, samples the current at its footprint and steps the shared liquid
motion; afterwards bubbles move with the current and the drift moving cells
induce, and touching bubbles merge. Format 10 persists the rules and each life's
motion state; restore regenerates the identical current field.

Brake is a new step intent, valid only under rules 12, carried in trace 4 as flag
bit 1 (SQL never parses that byte; player action records keep it zero). Tests
cover the upgrade, exact restore, swimming and braking, moving food with fixed
pools, restore continuing a live run, and brake traces replaying exactly. Genomes
from before schema 6 handle as founders. Refreshes the DEV session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 17:28:58 -04:00

387 lines
21 KiB
C++

#pragma once
#include "evo/biology/cellular_region_step.hpp"
#include "evo/biology/mutation.hpp"
#include "evo/server/lifecycle/cellular_light.hpp"
#include "evo/server/lifecycle/cellular_liquid.hpp"
#include "evo/server/lifecycle/primitive_lives.hpp"
#include <compare>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <memory>
#include <optional>
#include <span>
#include <vector>
namespace evo::server {
inline constexpr std::uint32_t cellular_lives_legacy_format = 1;
inline constexpr std::uint32_t cellular_lives_format = 2;
inline constexpr std::uint32_t cellular_lives_revision_format = 3;
inline constexpr std::uint32_t cellular_lives_rules = 2;
// ADR-0124: format 4 adds each corpse's cause and predator; rules 3 add engulfment and
// corpse detritus. They are used together, with the revision-format archive.
inline constexpr std::uint32_t cellular_lives_engulf_format = 4;
inline constexpr std::uint32_t cellular_lives_engulf_rules = 3;
// ADR-0125: format 5 adds the region's bud sequence and each life's and corpse's parent
// life; rules 4 add funded budding of unowned wildlife on top of rules 3.
inline constexpr std::uint32_t cellular_lives_bud_format = 5;
inline constexpr std::uint32_t cellular_lives_bud_rules = 4;
// ADR-0128: format 6 adds each life's presence and freeze tick; rules 5 are rules 4 plus
// the offline freeze, linger, suspension and resume.
inline constexpr std::uint32_t cellular_lives_presence_format = 6;
inline constexpr std::uint32_t cellular_lives_presence_rules = 5;
// 2026-10-15 balance (ADR-0132): rules 6 are rules 5 with founders of genome schema
// 3 and development version 3 (founder 2): a third of the mutation step and a third of the
// construction energy. No new state, so they keep owner format 6.
inline constexpr std::uint32_t cellular_lives_balance_rules = 6;
// ADR-0137: rules 7 are rules 6 with founder 3 (genome schema 4: percentage mutation
// steps; development 4: reproduction cheapens buds), twin buds, and wildlife that engulfs.
// No new state, so they keep owner format 6.
inline constexpr std::uint32_t cellular_lives_reproduction_rules = 7;
// ADR-0136 step A: rules 8 are rules 7 on a format-2 habitat of pools and bubbles, fed by
// contact; detritus becomes bubbles and emptied deposits disappear. The habitat envelope
// carries the new state, so they keep owner format 6.
inline constexpr std::uint32_t cellular_lives_foraging_rules = 8;
// ADR-0144: opt-in boundary accounting and retained nonresident history. Biology
// starts on rules 8; every earlier envelope retains its original meaning.
inline constexpr std::uint32_t cellular_lives_migration_format = 7;
// ADR-0157: opt-in funded maturation, using the unchanged format-7 fields.
inline constexpr std::uint32_t cellular_lives_maturation_rules = 9;
// ADR-0165: explicit offspring-plan editing mode; expressed bodies retain their genomes.
inline constexpr std::uint32_t cellular_lives_inheritance_format = 8;
inline constexpr std::uint32_t cellular_lives_inheritance_rules = 10;
// ADR-0175: rules 10 with founder 4 (genome schema 5), which can evolve photosynthesis.
// Format 9 is format 8 with the region's declared light and cumulative capture.
inline constexpr std::uint32_t cellular_lives_light_format = 9;
inline constexpr std::uint32_t cellular_lives_photosynthesis_rules = 11;
// Rules 12 (Cellular_Region_Movement_Plan.md, ADR-0177): rules 11 with founder 5 (genome
// schema 6, movement arrangement) in a liquid region. Format 10 is format 9 with the declared
// liquid rules and each life's motion state, on a format-3 habitat whose food moves.
inline constexpr std::uint32_t cellular_lives_liquid_format = 10;
inline constexpr std::uint32_t cellular_lives_liquid_rules = 12;
// Rules that retain offspring plans (formats 8 to 10): 10 to 12.
[[nodiscard]] constexpr bool cellular_retained_plans(std::uint32_t rules) noexcept {
return rules == cellular_lives_inheritance_rules ||
rules == cellular_lives_photosynthesis_rules || rules == cellular_lives_liquid_rules;
}
inline constexpr std::uint32_t cellular_growth_per_tick = 5; // Per 50 ms; trial rate.
// The founder a region of these rules creates.
[[nodiscard]] constexpr biology::FounderVersion
cellular_founder_version(std::uint32_t rules) noexcept {
return rules >= cellular_lives_liquid_rules ? biology::primitive_founder_v5
: rules >= cellular_lives_photosynthesis_rules ? biology::primitive_founder_v4
: rules >= cellular_lives_reproduction_rules ? biology::primitive_founder_v3
: rules >= cellular_lives_balance_rules ? biology::primitive_founder_v2
: biology::primitive_founder_v1;
}
// ADR-0137: a bud action also yields a twin with probability reproduction / 2 per thousand
// (founders: 25 %), when the reserve funds it and there is room. Seeded per parent and tick.
[[nodiscard]] bool cellular_twin_bud(std::uint64_t world, std::uint64_t region,
std::uint64_t parent_life, std::uint64_t tick,
std::uint32_t reproduction) noexcept;
// Trial values (ADR-0128): ticks a frozen life lingers in the world (10 s at 50 ms), and
// how many of its own extents away a resume may look for a clear spot.
inline constexpr std::uint64_t cellular_linger_ticks = 200;
inline constexpr std::uint32_t cellular_resume_extents = 3;
enum class CellularPresence : std::uint8_t {
active,
lingering,
suspended
}; // A bud's life, organism and event identity: 2^63 + region * 2^32 + sequence. A rules-4
// owner refuses an allocated identity at or above 2^63, so the namespaces never meet.
inline constexpr std::uint64_t cellular_bud_namespace = std::uint64_t{1} << 63U;
inline constexpr std::uint64_t cellular_bud_max_region = (std::uint64_t{1} << 31U) - 1;
[[nodiscard]] constexpr std::uint64_t cellular_bud_identity(std::uint64_t region,
std::uint64_t sequence) noexcept {
return region == 0 || region > cellular_bud_max_region || sequence == 0 ||
sequence > 0xFFFF'FFFFULL
? 0
: cellular_bud_namespace + (region << 32U) + sequence;
}
inline constexpr std::size_t max_cellular_lives_bytes = std::size_t{16} * 1024 * 1024;
inline constexpr std::uint64_t cellular_mutation_surplus_seconds = 60;
inline constexpr std::uint16_t cellular_mutation_candidate_count = 3;
inline constexpr std::uint32_t cellular_mutation_stream = 0x4D555431U; // "MUT1"
struct CellularMutationProgress {
std::uint64_t fed_energy_credit_pj{};
std::uint64_t event_index{};
std::uint64_t offer_tick{};
std::optional<biology::MutationOffer> offer;
auto operator<=>(const CellularMutationProgress&) const = default;
};
struct CellularOwnedLife {
LifeAccount account{};
LifeAllocation identity{}; // genome always identifies the expressed body.
std::uint64_t source{};
biology::GrowthState growth{};
biology::CellularPosition position{};
accounting::Inventory body{};
accounting::Inventory reserve{};
CellularMutationProgress mutation{};
std::uint64_t parent_life{}; // Format 5: the budding parent; zero for a founder.
// Format 6 (ADR-0128): presence and the tick its freeze began (zero while active).
CellularPresence presence{CellularPresence::active};
std::uint64_t frozen_since{};
std::uint64_t offspring_genome{}; // Format 8; older formats retain zero.
biology::CellularMotionState motion{}; // Format 10; older formats retain zero.
auto operator<=>(const CellularOwnedLife&) const = default;
};
struct CellularOwnedCorpse {
std::uint64_t life_id{};
std::uint64_t organism{};
std::uint64_t source{};
std::uint64_t died_tick{};
biology::CellularPosition position{};
biology::GrowthState growth{};
std::uint32_t extent_um{};
accounting::Inventory inventory{}; // Empty under rules 3: it became detritus.
biology::CellularDeathCause cause{biology::CellularDeathCause::unrecorded};
std::uint64_t predator_life{}; // Engulfed only.
std::uint64_t parent_life{}; // Format 5: kept after death.
std::uint64_t offspring_genome{}; // Format 8: retained plan, not living stock.
auto operator<=>(const CellularOwnedCorpse&) const = default;
};
struct CellularBoundaryLedger {
accounting::Inventory incoming{}, outgoing{}; // Cumulative flows, never stock.
std::vector<std::uint64_t> nonresident_organisms; // Retained history, never activity.
bool operator==(const CellularBoundaryLedger&) const = default;
};
struct CellularOffspringRevision {
std::uint64_t life{}, previous{}, successor{}, tick{};
auto operator<=>(const CellularOffspringRevision&) const = default;
};
[[nodiscard]] constexpr std::uint64_t cellular_offspring_genome(const CellularOwnedLife& life) {
return life.offspring_genome == 0 ? life.identity.genome : life.offspring_genome;
}
class CellularMigration;
class CellularEnvironment;
struct CellularLifeIntent {
std::uint64_t life_id{};
biology::CellularStepIntent intent{};
auto operator<=>(const CellularLifeIntent&) const = default;
};
struct CellularMutationSelection {
std::uint64_t life_id{}, event_index{}, offer_tick{}, successor_id{};
std::uint16_t operator_id{};
auto operator<=>(const CellularMutationSelection&) const = default;
};
// declined (ADR-0120 amendment): operator 0 consumed the offer without changing the genome.
enum class CellularMutationResult : std::uint8_t {
applied,
life_died,
insufficient_funding,
declined,
offspring_plan_applied // Rules 10: inherited plan changed, expressed body did not.
};
struct CellularMutationExecution {
std::uint64_t life_id{}, successor_id{};
CellularMutationResult result{};
auto operator<=>(const CellularMutationExecution&) const = default;
};
enum class CellularBudResult : std::uint8_t {
budded,
life_died, // The parent died earlier in the tick.
not_able, // No reproduction capability, not fully grown, or damaged.
insufficient_funding, // Some channel of investment plus provision is missing.
no_placement // No free spot touching the parent, or no identity left.
};
struct CellularBudExecution {
std::uint64_t parent_life{}, bud_life{}; // bud_life is zero unless budded.
CellularBudResult result{};
auto operator<=>(const CellularBudExecution&) const = default;
};
struct CellularGrowthExecution {
std::uint64_t life_id{};
biology::GrowthState before{}, after{};
accounting::Inventory intake{}, release{};
auto operator<=>(const CellularGrowthExecution&) const = default;
};
struct CellularTickExecution {
biology::CellularRegionStepCandidate step;
std::vector<CellularMutationExecution> mutations;
std::vector<CellularBudExecution> buds; // Rules 4, in parent life order.
std::vector<CellularGrowthExecution> growth; // Rules 9: funded expansions only, life order.
};
struct CellularLifeTickFeedback {
std::uint64_t life_id{}, tick{};
accounting::Inventory reserve;
accounting::Picojoules maintenance_cost{}, movement_cost{};
biology::CellularMovementStatus movement{biology::CellularMovementStatus::not_requested};
biology::CellularIntakeStatus intake{biology::CellularIntakeStatus::not_requested};
biology::CellularEngulfStatus engulf{biology::CellularEngulfStatus::not_requested};
std::uint64_t prey_life{};
std::optional<CellularBudResult> bud; // Rules 4, when this life asked to bud.
std::uint64_t bud_life{};
// Rules 5: presence after the tick, and whether a requested resume found no clear spot.
CellularPresence presence{CellularPresence::active};
bool resume_blocked{};
accounting::Picojoules light{}; // Rules 11 (ADR-0175): light captured this tick.
auto operator<=>(const CellularLifeTickFeedback&) const = default;
};
// Which owner version a new region starts on. Offers: format 2, rules 2 (the M11.3/11.4
// trial, upgraded by the no-tick migrations). Engulf: format 4, rules 3 (ADR-0124).
// Budding: format 5, rules 4 (ADR-0125). Presence: format 6, rules 5 (ADR-0128).
enum class CellularLivesProfile : std::uint8_t {
offers,
engulf,
budding,
presence,
balance,
reproduction,
foraging
};
struct CellularLivesConfig {
biology::CellularArea area{};
std::uint64_t tick{};
std::uint32_t ambient_temperature_millikelvin{};
};
enum class CellularLivesError : std::uint8_t {
identity,
invalid_config,
invalid_life,
life_exists,
no_placement,
insufficient_funding,
duplicate_life,
invalid_tick,
invalid_intents,
biology,
region_step,
mutation,
archive,
habitat,
overflow,
conservation,
format,
version,
checksum,
noncanonical
};
// In-memory authoritative cellular owner. It consumes funded profile-3 opening
// state but never mutates or reinterprets that checkpoint. Each tick is applied
// to a detached candidate and swapped only after life, corpse, heat, habitat and
// archive closure all validate. Durable profile-4 publication remains external.
class CellularLives {
public:
[[nodiscard]] static std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
create(const PrimitiveLives& opening, std::unique_ptr<biology::CellularHabitat> habitat,
CellularLivesConfig config, CellularLivesProfile profile = CellularLivesProfile::offers);
CellularLives(const CellularLives&) = delete;
CellularLives& operator=(const CellularLives&) = delete;
~CellularLives();
[[nodiscard]] std::uint64_t world() const noexcept;
[[nodiscard]] std::uint64_t region() const noexcept;
[[nodiscard]] std::uint64_t frame() const noexcept;
[[nodiscard]] std::uint64_t tick() const noexcept;
[[nodiscard]] std::uint32_t format_version() const noexcept;
[[nodiscard]] std::uint32_t rules_version() const noexcept;
// Format 5: the sequence the next bud's identity will use (ADR-0125).
[[nodiscard]] std::uint64_t next_bud_sequence() const noexcept;
[[nodiscard]] std::uint32_t ambient_temperature_millikelvin() const noexcept;
[[nodiscard]] biology::CellularArea area() const noexcept;
[[nodiscard]] std::span<const CellularOwnedLife> lives() const noexcept;
[[nodiscard]] std::span<const CellularOwnedCorpse> corpses() const noexcept;
[[nodiscard]] const biology::CellularHabitat& habitat() const noexcept;
[[nodiscard]] const biology::LineageArchive& archive() const noexcept;
[[nodiscard]] accounting::Inventory nursery() const noexcept;
[[nodiscard]] accounting::Inventory heat() const noexcept;
[[nodiscard]] accounting::Inventory opening_total() const noexcept;
[[nodiscard]] accounting::Inventory current_total() const noexcept;
[[nodiscard]] const CellularBoundaryLedger& boundary_ledger() const noexcept;
// Explicit detached format-6/rules-8 -> format-7 upgrade. No biology advances.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
migration_upgrade_candidate() const;
// ADR-0157: detached no-tick rules-8/format-7 -> rules-9 candidate. No grant.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
maturation_upgrade_candidate() const;
// ADR-0165: explicit no-tick format-7/rules-9 -> format-8/rules-10 upgrade.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
inheritance_upgrade_candidate() const;
// ADR-0175: explicit no-tick format-8/rules-10 -> format-9/rules-11 upgrade declaring
// the region's light. Existing lineages keep their genome schemas; only founders born
// afterwards can evolve photosynthesis.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
photosynthesis_upgrade_candidate(CellularLight light) const;
// Rules 12: explicit no-tick format-9/rules-11 -> format-10/rules-12 upgrade declaring
// the region's liquid rules. The habitat becomes format 3 (every bubble counts one merged
// bubble) and lives start at rest. Founders born afterwards are founder 5.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
liquid_upgrade_candidate(const CellularLiquidRules& rules) const;
// Format 10: the declared liquid rules and the current field they generate (null before).
[[nodiscard]] const CellularLiquidRules& liquid_rules() const noexcept;
[[nodiscard]] const biology::CellularFlowField* flow_field() const noexcept;
// Format 9: declared light and the energy captured from it, cumulatively.
[[nodiscard]] const CellularLight& light() const noexcept;
[[nodiscard]] accounting::Picojoules captured_light() const noexcept;
[[nodiscard]] std::span<const CellularOffspringRevision> offspring_revisions() const noexcept;
// Latest successful in-memory step report; omitted from snapshots and empty after restore.
[[nodiscard]] std::span<const CellularLifeTickFeedback> last_tick_feedback() const noexcept;
[[nodiscard]] std::vector<std::uint8_t> snapshot() const;
// Exact stock view for one live cell, filtered by its authoritative footprint and the
// M11.3 perception radius. Patch provenance and out-of-range stock are never returned.
[[nodiscard]] std::expected<std::vector<biology::CellularPatchPerception>, CellularLivesError>
perceive(std::uint64_t life_id) const;
// Stable unranked offer for the owning life; an absent offer is legitimate.
[[nodiscard]] std::expected<std::optional<biology::MutationOffer>, CellularLivesError>
mutation_offer(std::uint64_t life_id) const;
// Detached no-tick representation upgrade. Only a fully restored v1 owner can migrate.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
migrate_to_v2() const;
// Detached no-tick v2-to-v3 profile upgrade enabling genome revisions.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
migrate_to_v3() const;
// Returns a detached post-birth candidate for an allocator-reserved request.
// The caller supplies the durable identity; the owner derives founder biology,
// funding, source and the first unoccupied provisioned site. Birth must occur
// at the current checkpoint tick, after that tick's existing-life step.
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
birth_candidate(LifeRequest request, LifeAllocation allocation) const;
[[nodiscard]] static std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
restore(std::span<const std::uint8_t> bytes, std::uint64_t world, std::uint64_t region,
std::uint64_t frame, std::uint64_t tick);
// Advances every living cell exactly one 50 ms tick. Intentions are keyed by
// stable life ID and must cover the living set exactly. Any refusal leaves
// this owner byte-for-byte unchanged.
[[nodiscard]] std::expected<biology::CellularRegionStepCandidate, CellularLivesError>
advance_tick(std::span<const CellularLifeIntent> intents);
// Mutation selections are validated against the predecessor offer, then applied
// after the normal life step and before births on the same advancing tick.
// Rules 10 edit only the retained offspring plan; parent tissue is unchanged.
[[nodiscard]] std::expected<CellularTickExecution, CellularLivesError>
advance_tick_with_mutations(std::span<const CellularLifeIntent> intents,
std::span<const CellularMutationSelection> selections);
private:
friend class CellularMigration;
friend class CellularEnvironment;
// ADR-0172: the exchanged-out values, so a refused joint tick can swap them back.
struct BoundarySavepoint {
std::unique_ptr<biology::CellularHabitat> habitat; // Null when no deposit changed.
accounting::Inventory heat{}, current_total{};
CellularBoundaryLedger boundary{};
};
// Validated no-tick exchange: imports the new deposits (ids assigned here) and exports
// retained heat, both through the boundary ledger. Refusal changes nothing.
[[nodiscard]] std::expected<BoundarySavepoint, CellularLivesError>
exchange_boundary(std::span<const biology::CellularPatch> deposits,
accounting::Picojoules heat_export);
void restore_boundary(BoundarySavepoint savepoint) noexcept;
[[nodiscard]] std::expected<std::unique_ptr<CellularLives>, CellularLivesError>
migration_replacement(std::vector<CellularOwnedLife>, const biology::LineageArchive&,
CellularBoundaryLedger) const;
struct State;
explicit CellularLives(std::unique_ptr<State> state);
std::unique_ptr<State> state_;
std::vector<CellularLifeTickFeedback> last_tick_feedback_;
};
} // namespace evo::server