From 108f29eda5f64bed5a3089221f405dd448fb02ad Mon Sep 17 00:00:00 2001 From: dingo Date: Mon, 19 Oct 2026 18:06:02 -0400 Subject: [PATCH] feat(biology): evolve photosynthetic producers that capture light ADR-0175 implements ADR-0136 step C with trial costs to be balanced after playtesting. Genome schema 5 adds a photosynthesis efficiency (empty in schemas 1-4, so earlier offers and draws are unchanged; mutation operators 29-32 are appended). Development version 5 builds the organelles as internal membrane (p/4 of structure, upkept twice) and slows movement by p/2 per thousand. Founder 4 and cellular rules 11 let lineages earn the capability as an offspring plan that children express. Owner format 9 declares the region's light. Inside each tick's detached candidate, active unfrozen producers capture cross-section x irradiance x efficiency (a quarter while moving), credited to the reserve and boundary inflow together and replayed from recorded intentions. Well-lit wildlife producers hold still. The joint owner keeps infall, water and radiation and nests a rules-11 owner unchanged. Co-Authored-By: Claude Opus 5.5 --- CMakeLists.txt | 7 +- .../region/dev-session-route/listener.yaml | 2 +- docs/STATUS.md | 12 ++ docs/adr/0175-photosynthesis-producers.md | 64 ++++++++ docs/adr/README.md | 2 + docs/engineering/M12_REMAINING_GATES.md | 2 +- docs/engineering/VALIDATION.md | 36 ++++ include/evo/biology/development.hpp | 10 +- include/evo/biology/founder.hpp | 3 + include/evo/biology/genome.hpp | 35 +++- include/evo/biology/mutation.hpp | 2 + .../server/lifecycle/cellular_environment.hpp | 11 +- .../evo/server/lifecycle/cellular_light.hpp | 34 ++++ .../evo/server/lifecycle/cellular_lives.hpp | 25 ++- .../server/lifecycle/wildlife_controller.hpp | 4 +- schemas/cellular-lives-v9.md | 25 +++ src/biology/development.cpp | 17 +- src/biology/metabolism.cpp | 6 +- src/biology/mutation.cpp | 19 ++- src/server/lifecycle/cellular_batch.cpp | 4 +- src/server/lifecycle/cellular_census.cpp | 4 +- src/server/lifecycle/cellular_environment.cpp | 128 +++++++++------ .../lifecycle/cellular_environment_batch.cpp | 7 +- src/server/lifecycle/cellular_light.cpp | 35 ++++ src/server/lifecycle/cellular_lives.cpp | 154 +++++++++++++++--- src/server/lifecycle/cellular_population.cpp | 6 +- .../lifecycle/cellular_population_batch.cpp | 6 +- src/server/lifecycle/wildlife_controller.cpp | 9 + tests/cellular_environment_tests.cpp | 151 ++++++++++++++++- tests/development_tests.cpp | 4 +- tests/genome_tests.cpp | 17 +- tests/metabolism_tests.cpp | 4 +- tests/mutation_tests.cpp | 2 +- tests/photosynthesis_tests.cpp | 137 ++++++++++++++++ 34 files changed, 856 insertions(+), 128 deletions(-) create mode 100644 docs/adr/0175-photosynthesis-producers.md create mode 100644 include/evo/server/lifecycle/cellular_light.hpp create mode 100644 schemas/cellular-lives-v9.md create mode 100644 src/server/lifecycle/cellular_light.cpp create mode 100644 tests/photosynthesis_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index b7aa59f..caea94e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -95,7 +95,8 @@ add_library(evo_lifecycle STATIC src/server/lifecycle/primitive_lives.cpp src/server/lifecycle/cellular_play_summary.cpp src/server/lifecycle/cellular_population.cpp src/server/lifecycle/cellular_population_codec.cpp src/server/lifecycle/cellular_population_policy.cpp src/server/lifecycle/cellular_schedule.cpp src/server/lifecycle/cellular_population_batch.cpp - src/server/lifecycle/cellular_environment.cpp src/server/lifecycle/cellular_environment_batch.cpp) + src/server/lifecycle/cellular_environment.cpp src/server/lifecycle/cellular_environment_batch.cpp + src/server/lifecycle/cellular_light.cpp) add_library(evo::lifecycle ALIAS evo_lifecycle) target_link_libraries(evo_lifecycle PUBLIC evo::biology evo::world) evo_owned_target(evo_lifecycle) @@ -707,6 +708,10 @@ if(BUILD_TESTING) -P "${CMAKE_CURRENT_SOURCE_DIR}/tests/cellular_population_restart.cmake") set_tests_properties(cellular-retained-plan-population cellular-retained-plan-population-restart PROPERTIES TIMEOUT ${evo_cohort_timeout}) + add_executable(evo-photosynthesis-tests tests/photosynthesis_tests.cpp) + target_link_libraries(evo-photosynthesis-tests PRIVATE evo::lifecycle) + evo_owned_target(evo-photosynthesis-tests) + add_test(NAME photosynthesis-contracts COMMAND evo-photosynthesis-tests) add_executable(evo-cellular-environment-tests tests/cellular_environment_tests.cpp) target_link_libraries(evo-cellular-environment-tests PRIVATE evo::lifecycle) evo_owned_target(evo-cellular-environment-tests) diff --git a/deploy/kubernetes/region/dev-session-route/listener.yaml b/deploy/kubernetes/region/dev-session-route/listener.yaml index a05761a..c98b1ad 100644 --- a/deploy/kubernetes/region/dev-session-route/listener.yaml +++ b/deploy/kubernetes/region/dev-session-route/listener.yaml @@ -12,7 +12,7 @@ spec: env: - {name: REGION_SESSION, value: "dev"} - {name: REGION_SESSION_LISTEN, value: "0.0.0.0:7400"} - - {name: REGION_SESSION_WINDOW, value: "dev-20261019T210956-a2cdedf2:1792458596"} + - {name: REGION_SESSION_WINDOW, value: "dev-20261019T215818-e009abce:1792461498"} - {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"} ports: # QUIC (ADR-0090): UDP only; nothing listens on TCP 7400. diff --git a/docs/STATUS.md b/docs/STATUS.md index 752c9da..90f08d3 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,17 @@ # Project status and next steps +## Photosynthesis producers (ADR-0136 step C) - 2026-10-19 + +[ADR-0175](adr/0175-photosynthesis-producers.md) adds genome schema 5's photosynthesis +capability with trial costs (organelle membrane mass and slower movement), founder 4 +and cellular rules 11. A region declares light in owner format 9; each tick a still, +active producer captures cross-section x irradiance x efficiency (a quarter while +moving), booked as boundary inflow inside the same atomic tick. A founder earns the +capability as its offspring plan; its children express it and capture light. Every +earlier genome, offer, owner and environment byte keeps its meaning. Durable bundle, +session wire, client look and a DEV opening follow next. Numbers are trial values to +balance after playtesting. + ## Cellular environment ownership (M12.5a-b) - 2026-10-19 The maintainer accepted one owner per patch of space for cells and their local diff --git a/docs/adr/0175-photosynthesis-producers.md b/docs/adr/0175-photosynthesis-producers.md new file mode 100644 index 0000000..9d97b73 --- /dev/null +++ b/docs/adr/0175-photosynthesis-producers.md @@ -0,0 +1,64 @@ +# ADR-0175: Photosynthesis producers + +## Status and scope + +Accepted 2026-10-19, implementing ADR-0136 step C. The maintainer authorized choosing +trial costs, to be balanced after playtesting; every number below is **tunable**. This +segment is portable biology and owner state; the session wire/client and durable/host +admission are separate segments. No default/live opening changes. + +## Decision + +**Capability.** Genome schema 5 adds `photosynthesis`, an efficiency per thousand +(1..1000) that requires a membrane. Schemas 1-4 carry an empty range for it, so no +earlier record, offer or draw changes. Mutation operators 29-32 (adjust up/down, +acquire, shed) are appended; earlier operator IDs are unchanged. Schema 5 keeps schema +4's percentage steps; an acquired photosynthesis starts at **100** (10 %). + +**Costs (development version 5).** Version 4's rules, plus photosynthetic organelles +built as internal membrane: at efficiency p they add p/4 of the structural mass as +membrane mass (so they cost construction and are upkept twice, like membrane) and slow +movement by p/2 per thousand. Extent is unchanged. Light gives energy only; a producer +still needs C/N/P by contact to grow and bud. + +**Founders and rules.** Founder 4 (schema 5, development 5) is founder 3 with that +schema: identical phenotype, body and endowment, and no photosynthesis. Cellular rules +11 are rules 10 (offspring plans) with founder 4. Under rules 10+, a selected mutation +edits the offspring plan, so photosynthesis is expressed by children (ADR-0163). + +**Light is booked by the cell owner (owner format 9).** Incident light is not a stock and +has no other owner, so the region's cellular owner declares it: irradiance (pJ per square +micrometre of cross-section per tick, a rational; trial **40**), a cumulative entitlement +and the share a moving cell keeps (trial **250** per thousand), plus the energy captured +so far. An explicit no-tick format-8/rules-10 -> format-9/rules-11 upgrade declares the +light; existing lineages keep their schemas, and only founders born afterwards, and their +descendants, can evolve photosynthesis. Inside each tick's detached candidate, after the +step, every active, unfrozen photosynthetic survivor that had an intention captures +`extent^2 x irradiance x p / 1000`, a quarter of that if its intention moved, rounded down +and bounded by the remaining entitlement. Capture is credited to its reserve, the boundary +inflow and the current total together, so the tick commits or refuses as one unit. Light +nobody captures never enters the books. Capture depends only on recorded intentions and +state, so the existing raw trace replays it. A dark declaration captures nothing. + +The ADR-0172 joint owner keeps infall, water and radiation and may nest a rules-11 owner; +its own environmental imports stay separate from the nested owner's captured light. +Putting light in the cell owner keeps producers on the existing live path (profile-4 +publication, sessions and player actions) instead of requiring a second live trace. + +**Wildlife.** Under rules 11 with declared light, a photosynthetic wildlife cell that +would capture at least its maintenance by holding still holds still (it still feeds from +what it touches); otherwise it forages as before. + +Measured trial consequences (founder size, irradiance 40): at 10 % a still producer +captures 1,600 pJ/tick against 7,850 pJ/tick maintenance and moves 5 % slower; around +55 % it breaks even; at 100 % it captures 16,000 pJ/tick at half speed against +10,100 pJ/tick maintenance. + +## Consequences + +Plant-like lineages become possible without infinite energy: capture is bounded by +cross-section, efficiency, stillness and entitlement, and producers still compete for +matter. All earlier genome, mutation, development, cellular and environment bytes and +goldens keep their meaning. Durable admission of rules 11 (a new cellular bundle), the +session wire (capability 7 in offers, producer look) and a DEV opening remain before +playtesting. diff --git a/docs/adr/README.md b/docs/adr/README.md index e1083c2..698671d 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -1,5 +1,7 @@ # Architecture decision records +- [ADR-0175: Photosynthesis producers](0175-photosynthesis-producers.md) - genome schema 5 photosynthesis with trial organelle costs, founder 4/rules 11, light booked by the cell owner (format 9) from recorded intentions, light-aware wildlife; earlier bytes unchanged. + - [ADR-0174: Durable cellular environment profile](0174-durable-cellular-environment-profile.md) - schema 56 checkpoint profile 6 nesting population envelope 2; explicit one-way 5 -> 6 entry, fenced joint publication with owned intervals and SQL flow totals, exact replayed recovery. - [ADR-0173: Cellular environment joint batch](0173-cellular-environment-batch.md) - portable `AEVOEBT1` wraps the unchanged population batch with per-tick recorded environmental flows; unattended recording runs the controller after each exchange and replay re-derives every flow exactly. diff --git a/docs/engineering/M12_REMAINING_GATES.md b/docs/engineering/M12_REMAINING_GATES.md index 939a797..498d9cf 100644 --- a/docs/engineering/M12_REMAINING_GATES.md +++ b/docs/engineering/M12_REMAINING_GATES.md @@ -66,7 +66,7 @@ or authorize production enablement. | 12.2 | Exact cellular model and paired matrix; local samples through 256 lives; bounded four-generation rules-9 predation/twin matrix | Deployment-host tail costs including publication; larger wildlife cohorts and fuller contention coverage; useful compression remains unimplemented. | | 12.3 | Dedicated population profile/trace/store/owning host; exact recovery and private PostgreSQL fault tests | Population-specific executable/network fault drills and target-host publication/capacity qualification. | | 12.4 | Owned intervals; exact transfer/accounting; durable atomic pair/recovery; independent loopback TLS path loss and owner expiry/replacement/heal; local object sync/read-failure matrix | Multi-host/kernel-network, storage-host and orchestrator drills, linked-boundary contracts and integrated ownership/stock audits at scale. | -| 12.5 | ADR-0172 portable joint owner: one budget for cells and local environment, effective depth, tagged water/dissolved compartments, refused atmosphere, finite infall entitlements, radiative export; closed/source-off/open/exhaustion and raw/cohort comparisons; ADR-0173 joint batch with exact unattended replay; ADR-0174/schema 56 durable profile 6 with owned intervals and exact recovery | Producer process and coefficients (ADR-0136 step C), executable/network joint fault drills, worker/census/migration integration and escrowed cross-worker sources (12.5d), target-host qualification (12.5e). | +| 12.5 | ADR-0175 photosynthesis producers (portable rules 11/format 9); ADR-0172 portable joint owner: one budget for cells and local environment, effective depth, tagged water/dissolved compartments, refused atmosphere, finite infall entitlements, radiative export; closed/source-off/open/exhaustion and raw/cohort comparisons; ADR-0173 joint batch with exact unattended replay; ADR-0174/schema 56 durable profile 6 with owned intervals and exact recovery | Durable rules-11 bundle, producer session wire/client and DEV opening; joint fault drills (deferred by the maintainer), worker/census/migration integration and escrowed cross-worker sources (12.5d), target-host qualification (12.5e). | | 12.6 | Retained archive, regional census/lineage queries, replayed history, scoped multi-region queries and consistent database head snapshots (12.6a-d); registered coverage/history domains follow in 12.7a-b | Cross-domain clone provenance, retained historical coverage/other viable stores, target-host query/index qualification and client permission/presentation; no account power or invented precise statistical ancestry. | | 12.7 | Viability/unknown policy; consistent cuts, registered coverage, history domains/restore forks and verified pending handoff evidence (12.7a-c/schema 52) | Cross-domain clone provenance, other viable-store coverage and durable accepted global evidence records/freshness. Missing/stale/unsupported owners must prevent terminal extinction. | | 12.8 | Deterministic seed/regime drivers, separate-process exact continuation and bounded unscripted generations | Reproducible integrated worlds running for actual days, real restarts/clone comparisons and retained accounting/diversity/cost audits. Accelerated tests cannot supply elapsed days. | diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 60e4f2d..fcc1319 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -1,5 +1,41 @@ # Validation report +## 2026-10-19 - Photosynthesis producers (ADR-0175) + +[ADR-0175](../adr/0175-photosynthesis-producers.md) adds genome schema 5, development 5, +founder 4, cellular rules 11 and owner format 9 with declared light. + +Executed locally: + +- GCC 14.2 Release full CTest **96/96** and MSVC 19.44 Release full CTest **96/96, + 7.35 s**, with NDEBUG and no MSVC warnings. +- Clang 19.1 ASan/UBSan biology and cellular subset (36 tests): one failure, a + heap-use-after-free in the new producer test, which compared an iterator into a + mutation offer after the tick had replaced the state holding it. The test now decides + before the tick; the environment and photosynthesis tests then pass **3/3, 88.86 s** + with no sanitizer reports. No product code changed for it. +- clang-tidy 19 and clang-format 19 on every new and changed source and test. +- Private PostgreSQL population (35 s) and joint-environment suites still pass on the + changed biology. + +Evidence: earlier genome schemas reject photosynthesis at any value and their offers +never include it (catalog grows from 28 to 32 with IDs 29-32 appended); all existing +goldens and cellular suites are unchanged. Founder 4 has founder 3's phenotype, body, +maintenance, reproduction investment and endowment exactly. Organelle mass, maintenance +and speed match the declared rule at 100, 500 and 1000 (maintenance 7,850 / 8,850 / +10,100 pJ/tick vs the founder's 7,600; still capture 1,600 / 8,000 / 16,000; moving a +quarter). A founder in a rules-11 region took the offered photosynthesis plan at tick +159; its budded child captured 387,200 pJ over 400 ticks with exact closure (captured +light equals the boundary energy inflow). Format 9 restores and continues byte-identically; +a nested joint owner keeps its infall separate from the owner's light. Twenty times the +irradiance gives exactly twenty times the capture on the same history; a dark declaration +captures nothing. In this rich fixture producers always touch food, so the light-driven +hold-still branch of the wildlife controller is not exercised by these tests. + +The ADR-0175 design first placed light in the joint owner; it was moved into the cell +owner before commit so producers can use the existing live publication path. No durable +bundle, SQL schema, session wire, client, DEV opening or live upgrade changes here. + ## 2026-10-19 - Durable cellular environment profile (M12.5c) [ADR-0174](../adr/0174-durable-cellular-environment-profile.md)/schema 56 adds diff --git a/include/evo/biology/development.hpp b/include/evo/biology/development.hpp index 42bc36e..d6e4ede 100644 --- a/include/evo/biology/development.hpp +++ b/include/evo/biology/development.hpp @@ -32,8 +32,8 @@ inline constexpr std::uint64_t development_v2_rate_microseconds = 1'000'000; [[nodiscard]] constexpr std::uint64_t development_rate_microseconds(std::uint32_t development_version) noexcept { return development_version == 1 ? development_v1_tick_microseconds - : development_version >= 2 && development_version <= 4 - ? development_v2_rate_microseconds // Versions 3 and 4 keep version 2's rates. + : development_version >= 2 && development_version <= 5 + ? development_v2_rate_microseconds // Versions 3-5 keep version 2's rates. : 0; } // Chosen constants, reviewable as a unit and selected by the genome's @@ -64,6 +64,12 @@ struct Phenotype { std::uint32_t thermal_shortfall{}; auto operator<=>(const Phenotype&) const = default; }; +// Development version 5 (ADR-0175; trial values): photosynthetic organelles are membrane +// built inside the cell. At efficiency p per thousand they add p/4 of the structural mass +// as membrane mass (so they are upkept twice, like membrane) and slow movement by p/2 per +// thousand. Light itself is captured by the region's environment owner, never here. +inline constexpr std::uint32_t photosynthesis_organelle_quarter = 4; +inline constexpr std::uint32_t photosynthesis_speed_halving = 2; // A proposal. It reserves nothing, pays for nothing and commits nothing; the // matching transfer does not exist until M3.3. struct DevelopmentPlan { diff --git a/include/evo/biology/founder.hpp b/include/evo/biology/founder.hpp index 52327b3..19af537 100644 --- a/include/evo/biology/founder.hpp +++ b/include/evo/biology/founder.hpp @@ -34,6 +34,9 @@ inline constexpr FounderVersion primitive_founder_v1{genome_schema_v2, 2}; inline constexpr FounderVersion primitive_founder_v2{genome_schema_v3, 3}; // Founder 3 serves rules 7 (ADR-0137): percentage mutation steps and skilled reproduction. inline constexpr FounderVersion primitive_founder_v3{genome_schema_v4, 4}; +// Founder 4 serves rules 11 (ADR-0175): founder 3 that can evolve photosynthesis. Founders +// start without it; the capability is only ever earned through mutation. +inline constexpr FounderVersion primitive_founder_v4{genome_schema_v5, 5}; inline constexpr std::uint32_t primitive_founder_development_version = primitive_founder_v1.development_version; // The founder genome under a world-scoped identity and its origin event. Fails only on diff --git a/include/evo/biology/genome.hpp b/include/evo/biology/genome.hpp index fe14f5f..f0d3d43 100644 --- a/include/evo/biology/genome.hpp +++ b/include/evo/biology/genome.hpp @@ -17,9 +17,10 @@ enum class Capability : std::uint8_t { ingestion, reproduction, target_size, - thermal_tolerance + thermal_tolerance, + photosynthesis // Schema 5 (ADR-0175); unrepresentable in earlier schemas. }; -inline constexpr std::size_t capability_count = 7; +inline constexpr std::size_t capability_count = 8; // The unit is a schema fact per kind and is never encoded, so no record can // contradict its own units. enum class Unit : std::uint8_t { @@ -55,7 +56,9 @@ inline constexpr std::array capability_schema_ CapabilitySpec{Unit::per_thousand, 1, 1000, false, capability_bit(Capability::energy_conversion)}, CapabilitySpec{Unit::femtograms, 1, 1'000'000'000, true, 0}, - CapabilitySpec{Unit::millikelvin, 1, 100'000, false, 0}}; + CapabilitySpec{Unit::millikelvin, 1, 100'000, false, 0}, + // An empty range: no schema-1 record can carry photosynthesis. + CapabilitySpec{Unit::per_thousand, 1, 0, false, 0}}; // Schema 2 (ADR-0099): the same capabilities with rates per second. Each rate range is // schema 1's times 20, so every schema 1 value has an exact schema 2 equivalent. inline constexpr std::array capability_schema_v2{ @@ -68,7 +71,22 @@ inline constexpr std::array capability_schema_ CapabilitySpec{Unit::per_thousand, 1, 1000, false, capability_bit(Capability::energy_conversion)}, CapabilitySpec{Unit::femtograms, 1, 1'000'000'000, true, 0}, - CapabilitySpec{Unit::millikelvin, 1, 100'000, false, 0}}; + CapabilitySpec{Unit::millikelvin, 1, 100'000, false, 0}, + CapabilitySpec{Unit::per_thousand, 1, 0, false, 0}}; // Not in schemas 2-4. +// Schema 5 (ADR-0175): schema 2 plus photosynthesis, an efficiency per thousand that +// needs a membrane to hold its organelles. +inline constexpr std::array capability_schema_v5{ + CapabilitySpec{Unit::per_thousand, 1, 1000, true, 0}, + CapabilitySpec{Unit::micrometres, 1, 10'000, true, 0}, + CapabilitySpec{Unit::micrometres_per_second, 0, 2'000'000, false, + capability_bit(Capability::membrane)}, + CapabilitySpec{Unit::femtograms_per_second, 0, 20'000'000, false, + capability_bit(Capability::membrane)}, + CapabilitySpec{Unit::per_thousand, 1, 1000, false, + capability_bit(Capability::energy_conversion)}, + CapabilitySpec{Unit::femtograms, 1, 1'000'000'000, true, 0}, + CapabilitySpec{Unit::millikelvin, 1, 100'000, false, 0}, + CapabilitySpec{Unit::per_thousand, 1, 1000, false, capability_bit(Capability::membrane)}}; // The current schema's table. inline constexpr const auto& capability_schema = capability_schema_v2; // Schema 1 rates are per tick of this quantum. @@ -114,15 +132,18 @@ inline constexpr std::uint32_t genome_schema_v3 = 3; // Schema 4 (rules 7, ADR-0137): schema 2's table and units; a mutation step is a tenth of // the current value (at least 1), and an acquired capability starts at the founder's value. inline constexpr std::uint32_t genome_schema_v4 = 4; +// Schema 5 (rules 11, ADR-0175): schema 4's steps with the photosynthesis capability. +inline constexpr std::uint32_t genome_schema_v5 = 5; // The newest schema. Older records stay valid and are never rewritten (ADR-0099). -inline constexpr std::uint32_t genome_schema_version = genome_schema_v4; -// The capability table of a supported schema (1 to 4); nullptr otherwise. +inline constexpr std::uint32_t genome_schema_version = genome_schema_v5; +// The capability table of a supported schema (1 to 5); nullptr otherwise. [[nodiscard]] constexpr const std::array* capability_schema_for(std::uint32_t schema) noexcept { return schema == genome_schema_v1 ? &capability_schema_v1 : schema == genome_schema_v2 || schema == genome_schema_v3 || schema == genome_schema_v4 ? &capability_schema_v2 - : nullptr; + : schema == genome_schema_v5 ? &capability_schema_v5 + : nullptr; } inline constexpr std::size_t max_parents = 2; inline constexpr std::size_t max_genome_bytes = 256; diff --git a/include/evo/biology/mutation.hpp b/include/evo/biology/mutation.hpp index 800f9a6..fc62af9 100644 --- a/include/evo/biology/mutation.hpp +++ b/include/evo/biology/mutation.hpp @@ -68,6 +68,8 @@ enum class MutationError : std::uint8_t { development }; inline constexpr std::size_t max_candidates = 8; +// ADR-0175 trial value: an acquired photosynthesis starts at 10 % efficiency. +inline constexpr std::uint32_t photosynthesis_acquired_start = 100; [[nodiscard]] std::span mutation_catalog() noexcept; // Identical inputs always yield identical candidates, sorted by operator ID. diff --git a/include/evo/server/lifecycle/cellular_environment.hpp b/include/evo/server/lifecycle/cellular_environment.hpp index 0bdd431..07cc7e3 100644 --- a/include/evo/server/lifecycle/cellular_environment.hpp +++ b/include/evo/server/lifecycle/cellular_environment.hpp @@ -69,7 +69,7 @@ struct CellularEnvironmentConfig { }; struct CellularEnvironmentTickReport { std::uint64_t tick{}; - accounting::Inventory imported{}; + accounting::Inventory imported{}; // Infall only; a rules-11 owner books its own light. accounting::Picojoules exported{}; std::uint64_t events{}, credited_bubbles{}, skipped_bubbles{}; CellularTickExecution biology; @@ -114,7 +114,7 @@ class CellularEnvironment { [[nodiscard]] std::span sources() const noexcept; [[nodiscard]] std::span infall() const noexcept; [[nodiscard]] accounting::Picojoules radiation_cap() const noexcept; - [[nodiscard]] accounting::Inventory imported() const noexcept; // All sources, cumulative. + [[nodiscard]] accounting::Inventory imported() const noexcept; // Infall, cumulative. [[nodiscard]] accounting::Picojoules exported() const noexcept; [[nodiscard]] std::uint64_t tick() const noexcept; @@ -139,6 +139,13 @@ class CellularEnvironment { friend std::expected, CellularEnvironmentError> execute_environment_batch(const CellularEnvironment&, CellularEnvironmentBatch&, bool record); struct Exchange; + struct Step { + CellularEnvironmentTickReport report; + }; + enum class StepMode : std::uint8_t { live, record, replay }; + [[nodiscard]] std::expected + joint_step(std::vector& intents, + std::span selections, StepMode mode); CellularEnvironment(std::unique_ptr population, CellularEnvironmentConfig config); [[nodiscard]] std::expected diff --git a/include/evo/server/lifecycle/cellular_light.hpp b/include/evo/server/lifecycle/cellular_light.hpp new file mode 100644 index 0000000..4208c04 --- /dev/null +++ b/include/evo/server/lifecycle/cellular_light.hpp @@ -0,0 +1,34 @@ +#pragma once + +#include "evo/accounting/ledger.hpp" +#include "evo/biology/genome.hpp" + +#include +#include +#include + +namespace evo::server { +// ADR-0175 trial values: light on a region's habitat, as picojoules per square micrometre +// of a cell's cross-section per 50 ms tick (a rational), and the share a moving cell keeps. +inline constexpr std::uint64_t cellular_light_trial_irradiance = 40; +inline constexpr std::uint32_t cellular_light_trial_moving_per_thousand = 250; +// Declared light on one habitat. The entitlement bounds cumulative capture; light nobody +// captures is not modelled and never enters the books. +struct CellularLight { + std::uint64_t numerator{}, denominator{1}; + accounting::Picojoules entitlement{}; + std::uint32_t moving_per_thousand{cellular_light_trial_moving_per_thousand}; + auto operator<=>(const CellularLight&) const = default; +}; +[[nodiscard]] constexpr bool cellular_light_valid(const CellularLight& light) noexcept { + return light.denominator != 0 && light.moving_per_thousand <= 1000 && + (light.numerator == 0) == (light.entitlement.value == 0); +} +// Energy one cell captures in a tick: cross-section (extent squared) x irradiance x its +// photosynthesis efficiency, reduced while moving, rounded down. Nothing for a genome +// without the capability. Nothing on overflow (refused, never wrapped). +[[nodiscard]] std::optional cellular_light_capture(const biology::Genome& genome, + std::uint32_t extent_um, + const CellularLight& light, + bool moving) noexcept; +} // namespace evo::server diff --git a/include/evo/server/lifecycle/cellular_lives.hpp b/include/evo/server/lifecycle/cellular_lives.hpp index 45c4562..7d31845 100644 --- a/include/evo/server/lifecycle/cellular_lives.hpp +++ b/include/evo/server/lifecycle/cellular_lives.hpp @@ -2,6 +2,7 @@ #include "evo/biology/cellular_region_step.hpp" #include "evo/biology/mutation.hpp" +#include "evo/server/lifecycle/cellular_light.hpp" #include "evo/server/lifecycle/primitive_lives.hpp" #include @@ -50,13 +51,23 @@ 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 that retain offspring plans (formats 8 and 9): 10 and 11. +[[nodiscard]] constexpr bool cellular_retained_plans(std::uint32_t rules) noexcept { + return rules == cellular_lives_inheritance_rules || + rules == cellular_lives_photosynthesis_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_reproduction_rules ? biology::primitive_founder_v3 - : rules >= cellular_lives_balance_rules ? biology::primitive_founder_v2 - : biology::primitive_founder_v1; + return 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. @@ -283,6 +294,14 @@ class CellularLives { // ADR-0165: explicit no-tick format-7/rules-9 -> format-8/rules-10 upgrade. [[nodiscard]] std::expected, 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, CellularLivesError> + photosynthesis_upgrade_candidate(CellularLight light) const; + // 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 offspring_revisions() const noexcept; // Latest successful in-memory step report; omitted from snapshots and empty after restore. [[nodiscard]] std::span last_tick_feedback() const noexcept; diff --git a/include/evo/server/lifecycle/wildlife_controller.hpp b/include/evo/server/lifecycle/wildlife_controller.hpp index c27dd68..ad24abe 100644 --- a/include/evo/server/lifecycle/wildlife_controller.hpp +++ b/include/evo/server/lifecycle/wildlife_controller.hpp @@ -23,7 +23,9 @@ inline constexpr std::int16_t wildlife_full_speed = 1'000; // One intention per wildlife life (zero account), sorted by life id: bud when the reserve // funds one, else steer to and feed from the nearest perceived patch holding energy, -// else wander. Owned lives are left to their players. +// else wander. Owned lives are left to their players. ADR-0175: under rules 11 with +// the region's declared light, a photosynthetic cell that would capture at least its +// maintenance by holding still stays still (it still feeds from whatever it touches). [[nodiscard]] std::expected, CellularLivesError> wildlife_intents(const CellularLives& state, std::uint64_t tick); } // namespace evo::server diff --git a/schemas/cellular-lives-v9.md b/schemas/cellular-lives-v9.md new file mode 100644 index 0000000..db12661 --- /dev/null +++ b/schemas/cellular-lives-v9.md @@ -0,0 +1,25 @@ +# Cellular owner format 9: declared light + +Authority: [ADR-0175](../docs/adr/0175-photosynthesis-producers.md). Format 9 is exactly +rules 11. It is [format 8](cellular-lives-v8.md) with magic `AEVCLV09` and a 40-byte +light block after the offspring-plan count; every other record, length rule and +validation is format 8's. Format 8 is exactly rules 10. Earlier formats are unchanged. + +| Offset | Bytes | Field | +|---:|---:|---| +| 316 | 8 | Irradiance numerator, pJ per square micrometre of cross-section per tick | +| 324 | 8 | Irradiance denominator, nonzero | +| 332 | 8 | Light entitlement, pJ; zero exactly when the numerator is zero (dark) | +| 340 | 4 | Share a moving cell keeps, per thousand, at most 1000 | +| 344 | 4 | Reserved zero | +| 348 | 8 | Cumulative captured energy, at most the entitlement | +| 356 | 8 each | Sorted spawn sites, then lives, corpses and the rest as in format 8 | + +The exact length is format 8's plus 40. Captured light is part of the boundary inflow +(`incoming.energy`) and therefore of the closure `current = opening + incoming - +outgoing`; no other balance holds it. Replay re-derives every capture from recorded +intentions and the stored state; the raw trace format is unchanged (trace 4). + +Format 9 arises only from the explicit no-tick format-8/rules-10 upgrade, which keeps +every existing lineage, body and plan. No SQL schema, checkpoint bundle, population +profile or migration adapter admits it yet. diff --git a/src/biology/development.cpp b/src/biology/development.cpp index 43b2b2b..457ad0f 100644 --- a/src/biology/development.cpp +++ b/src/biology/development.cpp @@ -69,7 +69,8 @@ std::expected rules_for(std::uint32_t develo // heat, so this changes no matter balance. // Version 4 (rules 7, ADR-0137) keeps version 3's rules; only what reproduction // means changes (metabolism.cpp). - if (development_version == 3 || development_version == 4) { + // Version 5 (ADR-0175) keeps them too; it adds photosynthetic organelles below. + if (development_version >= 3 && development_version <= 5) { return DevelopmentRules{1000, 1200, 10, 15, 13, 60'000, 293'150, 50}; } return std::unexpected{DevelopmentError::unsupported_rules}; @@ -101,6 +102,16 @@ derive_phenotype(const Genome& genome, GrowthState growth, EnvironmentState envi !multiply(phenotype.membrane_mass, shell, rules->membrane_density)) { return std::unexpected{DevelopmentError::overflow}; } + const auto photosynthesis = + genome.development_version() >= 5 && genome.carries(Capability::photosynthesis) + ? *genome.parameter(Capability::photosynthesis) + : 0U; + if (photosynthesis != 0 && + !add( + phenotype.membrane_mass, phenotype.membrane_mass, + scaled(phenotype.structural_mass / photosynthesis_organelle_quarter, photosynthesis))) { + return std::unexpected{DevelopmentError::overflow}; + } if (!add(phenotype.total_mass, phenotype.structural_mass, phenotype.membrane_mass)) { return std::unexpected{DevelopmentError::overflow}; } @@ -124,7 +135,9 @@ derive_phenotype(const Genome& genome, GrowthState growth, EnvironmentState envi if (!speed || *speed > std::numeric_limits::max()) { return std::unexpected{DevelopmentError::overflow}; } - phenotype.movement_speed = static_cast(*speed); + // Organelles slow the cell: p/2 per thousand off its speed (version 5). + const auto kept = thousand - photosynthesis / photosynthesis_speed_halving; + phenotype.movement_speed = static_cast(scaled(*speed, kept)); } if (genome.carries(Capability::ingestion)) { const auto intake = rate_per_tick(*genome.per_second(Capability::ingestion)); diff --git a/src/biology/metabolism.cpp b/src/biology/metabolism.cpp index 75ce948..79da3ed 100644 --- a/src/biology/metabolism.cpp +++ b/src/biology/metabolism.cpp @@ -109,8 +109,8 @@ metabolic_rules_for(std::uint32_t development_version) { return MetabolicRules{structure_shares, membrane_shares, 20, 50'000}; } // Version 2: per second; movement at 1000 um/s costs 50 pJ/s per 1000 fg (tunable). - // Versions 3 and 4: the same metabolism. - if (development_version >= 2 && development_version <= 4) { + // Versions 3, 4 and 5: the same metabolism. + if (development_version >= 2 && development_version <= 5) { return MetabolicRules{structure_shares, membrane_shares, 50, 50'000}; } return std::unexpected{DevelopmentError::unsupported_rules}; @@ -209,7 +209,7 @@ metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState envi // Version 4 (ADR-0137): a bud is always half the body, and reproduction is skill: // it takes up to half off the bud's construction energy (value / 2000). Matter is // never discounted (ADR-0118). Earlier versions invest `value` per thousand. - const bool skill = genome.development_version() == 4; + const bool skill = genome.development_version() >= 4; // Versions 4 and 5. const auto fraction = skill ? bud_body_per_thousand_v4 : value; // A parent divides the body it has, so the investment keeps its composition. budget.reproduction_investment = fraction_of(budget.body, fraction); diff --git a/src/biology/mutation.cpp b/src/biology/mutation.cpp index 656b7b4..21b98ba 100644 --- a/src/biology/mutation.cpp +++ b/src/biology/mutation.cpp @@ -10,7 +10,8 @@ namespace evo::biology { namespace { -// Four effects over seven capabilities. IDs are stable and carry no ranking; +// Four effects over eight capabilities. IDs are stable and carry no ranking; +// photosynthesis (ADR-0175) appends IDs 29-32, so every earlier ID is unchanged; // they exist to order candidates canonically and to name one across calls. constexpr std::array catalog = [] { std::array entries{}; @@ -38,7 +39,7 @@ constexpr std::array catalog = [] { constexpr std::uint32_t adjustment_step(const std::array& table, Capability kind, std::uint32_t schema, std::uint32_t current) noexcept { - if (schema == genome_schema_v4) + if (schema == genome_schema_v4 || schema == genome_schema_v5) return current / 10 == 0 ? 1 : current / 10; const auto& limits = table[static_cast(kind)]; const auto span = limits.maximum - limits.minimum; @@ -48,10 +49,11 @@ constexpr std::uint32_t adjustment_step(const std::array apply(const Genome& genome, const MutationOperator& e break; } case MutationEffect::acquire: - if (present) { + // An empty range (photosynthesis before schema 5) is not acquirable at all. + if (present || limits.maximum < limits.minimum) { return std::nullopt; } // Schema 4 starts an acquired capability at the founder's value (a percentage of // the minimum, zero speed for instance, would never grow); otherwise the minimum. draft.capabilities.push_back({entry.target, - genome.schema_version() == genome_schema_v4 + genome.schema_version() >= genome_schema_v4 ? acquired_start(entry.target, limits) : limits.minimum, 0}); diff --git a/src/server/lifecycle/cellular_batch.cpp b/src/server/lifecycle/cellular_batch.cpp index 43f89ba..c960eb0 100644 --- a/src/server/lifecycle/cellular_batch.cpp +++ b/src/server/lifecycle/cellular_batch.cpp @@ -40,8 +40,8 @@ bool owner_version_matches(const CellularLives& owner, const CellularBatch& batc if (!known_format(batch.format_version)) return false; if (batch.format_version == cellular_batch_inheritance_format) - return owner.format_version() == cellular_lives_inheritance_format && - owner.rules_version() == cellular_lives_inheritance_rules; + return owner.format_version() >= cellular_lives_inheritance_format && + cellular_retained_plans(owner.rules_version()); return owner.format_version() < cellular_lives_inheritance_format; } bool payload_version_matches(const CellularBatch& batch) { diff --git a/src/server/lifecycle/cellular_census.cpp b/src/server/lifecycle/cellular_census.cpp index a145923..a9f5471 100644 --- a/src/server/lifecycle/cellular_census.cpp +++ b/src/server/lifecycle/cellular_census.cpp @@ -57,8 +57,8 @@ CellularCensus::observe(const CellularLives& state, std::span= cellular_lives_inheritance_format && (population == 0 || population == cellular_population_inheritance_format); if (!inherited && ((!maturing && state.rules_version() != cellular_lives_foraging_rules) || (state.format_version() != cellular_lives_presence_format && diff --git a/src/server/lifecycle/cellular_environment.cpp b/src/server/lifecycle/cellular_environment.cpp index 62ad911..0d909c9 100644 --- a/src/server/lifecycle/cellular_environment.cpp +++ b/src/server/lifecycle/cellular_environment.cpp @@ -97,8 +97,8 @@ bool supported(const CellularLives& state) noexcept { return (state.format_version() == cellular_lives_migration_format && (state.rules_version() == cellular_lives_foraging_rules || state.rules_version() == cellular_lives_maturation_rules)) || - (state.format_version() == cellular_lives_inheritance_format && - state.rules_version() == cellular_lives_inheritance_rules); + (state.format_version() >= cellular_lives_inheritance_format && + cellular_retained_plans(state.rules_version())); } std::expected validate(const CellularLives& state, const CellularEnvironmentConfig& config) { @@ -285,11 +285,20 @@ CellularEnvironment::plan_exchange(std::uint64_t tick) const { return exchange; } -std::expected -CellularEnvironment::advance_tick(std::span controlled, - std::span selections) { +// One joint tick, shared by live play, unattended recording and replay: the infall and +// heat exchange; the full intentions (live: the shared controller on the exchanged state +// plus the players'; record: the controller plus frozen players; replay: as recorded); +// then the unchanged biological step, which books a rules-11 owner's own light. Any +// refusal swaps the exchange back, so the owner is unchanged. +std::expected +CellularEnvironment::joint_step(std::vector& intents, + std::span selections, + StepMode mode) { if (tick() == std::numeric_limits::max()) return std::unexpected(CellularEnvironmentError::overflow); + if (population_->policy_.automatic && + population_->conversion_sequence_ == std::numeric_limits::max()) + return std::unexpected(CellularEnvironmentError::overflow); auto exchange = plan_exchange(tick() + 1); if (!exchange) return std::unexpected(exchange.error()); @@ -299,53 +308,57 @@ CellularEnvironment::advance_tick(std::span controlled return std::unexpected(savepoint.error() == CellularLivesError::habitat ? CellularEnvironmentError::habitat : CellularEnvironmentError::conservation); - auto executed = population_->advance_tick(controlled, selections); - if (!executed) { + const auto refuse = [&](CellularEnvironmentError error) { lives.restore_boundary(std::move(*savepoint)); - return std::unexpected(CellularEnvironmentError::biology); - } - progress_ = std::move(exchange->progress); - exported_.value += exchange->heat_export.value; - exchange->report.biology = std::move(*executed); - return std::move(exchange->report); -} - -std::expected -CellularEnvironment::advance_unattended(std::vector& intents, bool record) { - if (tick() == std::numeric_limits::max()) - return std::unexpected(CellularEnvironmentError::overflow); - auto exchange = plan_exchange(tick() + 1); - if (!exchange) - return std::unexpected(exchange.error()); - auto& lives = *population_->state_; - auto savepoint = lives.exchange_boundary(exchange->deposits, exchange->heat_export); - if (!savepoint) - return std::unexpected(savepoint.error() == CellularLivesError::habitat - ? CellularEnvironmentError::habitat - : CellularEnvironmentError::conservation); + return std::unexpected(error); + }; biology::CellularStepIntent frozen; frozen.frozen = true; - if (record) { + if (mode != StepMode::replay) { auto chosen = wildlife_intents(lives, lives.tick() + 1); if (!chosen) - return std::unexpected(CellularEnvironmentError::biology); - for (const auto& life : lives.lives()) - if (life.account != LifeAccount{}) + return refuse(CellularEnvironmentError::biology); + std::size_t player = 0; + for (const auto& life : lives.lives()) { + if (life.account == LifeAccount{}) + continue; + if (mode == StepMode::record) { chosen->push_back({life.identity.life, frozen}); + } else { + if (player == intents.size() || intents[player].life_id != life.identity.life) + return refuse(CellularEnvironmentError::biology); + chosen->push_back(intents[player++]); + } + } + if (mode == StepMode::live && player != intents.size()) + return refuse(CellularEnvironmentError::biology); std::ranges::sort(*chosen, {}, &CellularLifeIntent::life_id); intents = std::move(*chosen); } - for (const auto& life : lives.lives()) { - if (life.account == LifeAccount{}) - continue; - const auto found = - std::ranges::find(intents, life.identity.life, &CellularLifeIntent::life_id); - if (life.presence != CellularPresence::suspended || found == intents.end() || - found->intent != frozen) - return std::unexpected(CellularEnvironmentError::unsupported); + if (mode == StepMode::live) { + for (const auto& selection : selections) { + const auto life = + std::ranges::find(lives.lives(), selection.life_id, + [](const auto& owned) { return owned.identity.life; }); + if (life == lives.lives().end() || life->account == LifeAccount{}) + return refuse(CellularEnvironmentError::biology); + } + } else { + if (!selections.empty()) + return refuse(CellularEnvironmentError::unsupported); + for (const auto& life : lives.lives()) { + if (life.account == LifeAccount{}) + continue; + const auto found = + std::ranges::find(intents, life.identity.life, &CellularLifeIntent::life_id); + if (life.presence != CellularPresence::suspended || found == intents.end() || + found->intent != frozen) + return refuse(CellularEnvironmentError::unsupported); + } } - if (!lives.advance_tick(intents)) - return std::unexpected(CellularEnvironmentError::biology); + auto executed = lives.advance_tick_with_mutations(intents, selections); + if (!executed) + return refuse(CellularEnvironmentError::biology); auto& members = population_->members_; std::erase_if(members, [&lives](const auto& member) { return std::ranges::find(lives.lives(), member.life, [](const auto& life) { @@ -353,14 +366,30 @@ CellularEnvironment::advance_unattended(std::vector& intents }) == lives.lives().end(); }); // The persisted policy's exact result; no random materialization or resampling. - if (population_->policy_.automatic) { - if (population_->conversion_sequence_ == std::numeric_limits::max()) - return std::unexpected(CellularEnvironmentError::overflow); + if (population_->policy_.automatic) population_->apply_policy(); - } progress_ = std::move(exchange->progress); exported_.value += exchange->heat_export.value; - return CellularEnvironmentFlow{exchange->report.imported, exchange->heat_export}; + exchange->report.biology = std::move(*executed); + return Step{std::move(exchange->report)}; +} + +std::expected +CellularEnvironment::advance_tick(std::span controlled, + std::span selections) { + std::vector intents(controlled.begin(), controlled.end()); + auto step = joint_step(intents, selections, StepMode::live); + if (!step) + return std::unexpected(step.error()); + return std::move(step->report); +} + +std::expected +CellularEnvironment::advance_unattended(std::vector& intents, bool record) { + auto step = joint_step(intents, {}, record ? StepMode::record : StepMode::replay); + if (!step) + return std::unexpected(step.error()); + return CellularEnvironmentFlow{step->report.imported, step->report.exported}; } CellularPopulationBoundary CellularEnvironment::population_boundary() const { return {population_->conversion_sequence_, population_->members_}; @@ -502,8 +531,9 @@ CellularEnvironment::restore(std::span bytes, std::uint64_t return std::unexpected(candidate.error()); (*candidate)->progress_ = std::move(progress); (*candidate)->exported_ = exported; - // Environmental flows are part of the nested ledger, never in addition to it. - accounting::Inventory flows; + // Environmental flows are part of the nested ledger, never in addition to it; a + // rules-11 owner's light is booked there too. + accounting::Inventory flows{(*candidate)->state().captured_light(), {}}; for (const auto& done : (*candidate)->progress_) if (!add(flows, done.imported)) return std::unexpected(CellularEnvironmentError::conservation); diff --git a/src/server/lifecycle/cellular_environment_batch.cpp b/src/server/lifecycle/cellular_environment_batch.cpp index c4d01ec..b23fc77 100644 --- a/src/server/lifecycle/cellular_environment_batch.cpp +++ b/src/server/lifecycle/cellular_environment_batch.cpp @@ -73,10 +73,9 @@ execute_environment_batch(const CellularEnvironment& base, CellularEnvironmentBa if (record) { population.biology.header = h; population.biology.ticks.clear(); - population.biology.format_version = - state.rules_version() == cellular_lives_inheritance_rules - ? cellular_batch_inheritance_format - : cellular_batch_format; + population.biology.format_version = cellular_retained_plans(state.rules_version()) + ? cellular_batch_inheritance_format + : cellular_batch_format; } for (std::size_t index = 0; index < count; ++index) { std::vector intents; diff --git a/src/server/lifecycle/cellular_light.cpp b/src/server/lifecycle/cellular_light.cpp new file mode 100644 index 0000000..53a00b6 --- /dev/null +++ b/src/server/lifecycle/cellular_light.cpp @@ -0,0 +1,35 @@ +#include "evo/server/lifecycle/cellular_light.hpp" + +#include + +namespace evo::server { +namespace { +bool multiply(std::uint64_t& value, std::uint64_t factor) noexcept { + if (factor != 0 && value > std::numeric_limits::max() / factor) + return false; + value *= factor; + return true; +} +} // namespace + +std::optional cellular_light_capture(const biology::Genome& genome, + std::uint32_t extent_um, + const CellularLight& light, + bool moving) noexcept { + if (!genome.carries(biology::Capability::photosynthesis) || light.numerator == 0 || + light.denominator == 0) + return 0; + const auto efficiency = genome.parameter(biology::Capability::photosynthesis); + if (!efficiency) + return std::nullopt; + // Exact checked products before the single rounding; overflow is refused. + std::uint64_t energy = extent_um; + if (!multiply(energy, extent_um) || !multiply(energy, light.numerator) || + !multiply(energy, *efficiency) || (moving && !multiply(energy, light.moving_per_thousand))) + return std::nullopt; + std::uint64_t divisor = light.denominator; + if (!multiply(divisor, 1000) || (moving && !multiply(divisor, 1000))) + return std::nullopt; + return energy / divisor; +} +} // namespace evo::server diff --git a/src/server/lifecycle/cellular_lives.cpp b/src/server/lifecycle/cellular_lives.cpp index e1781df..5b93430 100644 --- a/src/server/lifecycle/cellular_lives.cpp +++ b/src/server/lifecycle/cellular_lives.cpp @@ -22,6 +22,7 @@ constexpr std::uint64_t cellular_lives_v5_magic = 0x3530564C43564541ULL; // AEVC constexpr std::uint64_t cellular_lives_v6_magic = 0x3630564C43564541ULL; // AEVCLV06 constexpr std::uint64_t cellular_lives_v7_magic = 0x3730564C43564541ULL; // AEVCLV07 constexpr std::uint64_t cellular_lives_v8_magic = 0x3830564C43564541ULL; // AEVCLV08 +constexpr std::uint64_t cellular_lives_v9_magic = 0x3930564C43564541ULL; // AEVCLV09 constexpr std::size_t cellular_lives_header_bytes = 212; constexpr std::size_t cellular_site_bytes = 8; constexpr std::size_t cellular_life_v1_bytes = 168; @@ -39,6 +40,9 @@ constexpr std::size_t cellular_life_v6_bytes = cellular_life_v5_bytes + 16; // Format 7: two boundary-flow inventories and nonresident count/reserved. constexpr std::size_t cellular_lives_v7_header_bytes = cellular_lives_v5_header_bytes + 88; constexpr std::size_t cellular_lives_v8_header_bytes = cellular_lives_v7_header_bytes + 8; +// Format 9 (ADR-0175): light numerator, denominator, entitlement, moving share and +// reserved (4 each for the last two), and the cumulative captured energy. +constexpr std::size_t cellular_lives_v9_header_bytes = cellular_lives_v8_header_bytes + 40; constexpr std::size_t cellular_offspring_revision_bytes = 32; std::uint64_t checksum(std::span bytes) noexcept { @@ -585,6 +589,8 @@ struct CellularLives::State { std::uint64_t next_bud_sequence{1}; // Format 5: the next bud identity's sequence. CellularBoundaryLedger boundary{}; std::vector offspring_revisions; + CellularLight light{}; // Format 9 (ADR-0175). + accounting::Picojoules captured{}; // Format 9: light credited to reserves so far. State(std::uint64_t world_id, std::uint64_t region_id, std::uint64_t frame_id, CellularLivesConfig cfg, NurseryConfig nursery_definition, @@ -803,8 +809,7 @@ CellularLives::migration_replacement(std::vector living, std::expected CellularLives::exchange_boundary(std::span deposits, accounting::Picojoules heat_export) { - if (state_->format_version != cellular_lives_migration_format && - state_->format_version != cellular_lives_inheritance_format) + if (state_->format_version < cellular_lives_migration_format) return std::unexpected(CellularLivesError::version); if (heat_export.value > state_->heat.energy.value) return std::unexpected(CellularLivesError::conservation); @@ -846,13 +851,13 @@ CellularLives::exchange_boundary(std::span deposit habitat = std::move(*created); } const auto rules = state_->rules_version; - const auto total = validate_state( - state_->world, state_->region, state_->frame, state_->config, state_->nursery_config, - *habitat, state_->lives, state_->corpses, state_->archive, state_->nursery, heat, - state_->opening_total, rules >= cellular_lives_engulf_rules, - rules >= cellular_lives_bud_rules, state_->next_bud_sequence, - rules >= cellular_lives_presence_rules, &boundary, - rules == cellular_lives_inheritance_rules ? &state_->offspring_revisions : nullptr); + const auto total = + validate_state(state_->world, state_->region, state_->frame, state_->config, + state_->nursery_config, *habitat, state_->lives, state_->corpses, + state_->archive, state_->nursery, heat, state_->opening_total, + rules >= cellular_lives_engulf_rules, rules >= cellular_lives_bud_rules, + state_->next_bud_sequence, rules >= cellular_lives_presence_rules, &boundary, + cellular_retained_plans(rules) ? &state_->offspring_revisions : nullptr); if (!total) return std::unexpected(total.error()); BoundarySavepoint savepoint{std::move(state_->habitat), state_->heat, state_->current_total, @@ -892,6 +897,27 @@ std::span CellularLives::last_tick_feedback() co return last_tick_feedback_; } +std::expected, CellularLivesError> +CellularLives::photosynthesis_upgrade_candidate(CellularLight light) const { + if (state_->format_version != cellular_lives_inheritance_format || + state_->rules_version != cellular_lives_inheritance_rules) + return std::unexpected{CellularLivesError::version}; + if (!cellular_light_valid(light)) + return std::unexpected{CellularLivesError::invalid_config}; + auto candidate = restore(snapshot(), world(), region(), frame(), tick()); + if (!candidate) + return std::unexpected(candidate.error()); + (*candidate)->state_->format_version = cellular_lives_light_format; + (*candidate)->state_->rules_version = cellular_lives_photosynthesis_rules; + (*candidate)->state_->light = light; + return candidate; +} +const CellularLight& CellularLives::light() const noexcept { + return state_->light; +} +accounting::Picojoules CellularLives::captured_light() const noexcept { + return state_->captured; +} std::span CellularLives::offspring_revisions() const noexcept { return state_->offspring_revisions; } @@ -925,7 +951,8 @@ std::vector CellularLives::snapshot() const { const auto corpse_count = state_->corpses.size(); const bool parents = state_->format_version >= cellular_lives_bud_format; const bool presence = state_->format_version >= cellular_lives_presence_format; - const bool inheritance = state_->format_version == cellular_lives_inheritance_format; + const bool inheritance = state_->format_version >= cellular_lives_inheritance_format; + const bool lit = state_->format_version == cellular_lives_light_format; const auto life_bytes = inheritance ? cellular_life_v6_bytes + 8 : state_->format_version == cellular_lives_legacy_format ? cellular_life_v1_bytes @@ -938,10 +965,11 @@ std::vector CellularLives::snapshot() const { : causes ? cellular_corpse_v4_bytes : cellular_corpse_bytes; const bool migration = state_->format_version >= cellular_lives_migration_format; - const auto header_bytes = inheritance ? cellular_lives_v8_header_bytes - : migration ? cellular_lives_v7_header_bytes - : parents ? cellular_lives_v5_header_bytes - : cellular_lives_header_bytes; + const auto header_bytes = lit ? cellular_lives_v9_header_bytes + : inheritance ? cellular_lives_v8_header_bytes + : migration ? cellular_lives_v7_header_bytes + : parents ? cellular_lives_v5_header_bytes + : cellular_lives_header_bytes; const auto external_count = migration ? state_->boundary.nonresident_organisms.size() : 0; const auto total_bytes = header_bytes + cellular_site_bytes * site_count + life_bytes * life_count + @@ -966,6 +994,7 @@ std::vector CellularLives::snapshot() const { : state_->format_version == cellular_lives_engulf_format ? cellular_lives_v4_magic : state_->format_version == cellular_lives_bud_format ? cellular_lives_v5_magic : state_->format_version == cellular_lives_presence_format ? cellular_lives_v6_magic + : lit ? cellular_lives_v9_magic : inheritance ? cellular_lives_v8_magic : migration ? cellular_lives_v7_magic : cellular_lives_v2_magic; @@ -1001,6 +1030,14 @@ std::vector CellularLives::snapshot() const { out.put(state_->offspring_revisions.size(), 4); out.put(0, 4); } + if (lit) { + out.put(state_->light.numerator); + out.put(state_->light.denominator); + out.put(state_->light.entitlement.value); + out.put(state_->light.moving_per_thousand, 4); + out.put(0, 4); + out.put(state_->captured.value); + } for (const auto site : state_->nursery_config.sites) out.site(site); for (const auto& life : state_->lives) { @@ -1267,7 +1304,7 @@ CellularLives::birth_candidate(LifeRequest request, LifeAllocation allocation) c auto lives = state_->lives; lives.push_back({request.account, allocation, state_->nursery_config.source, endowed->growth, *position, endowed->body, endowed->reserve}); - if (state_->format_version == cellular_lives_inheritance_format) + if (state_->format_version >= cellular_lives_inheritance_format) lives.back().offspring_genome = allocation.genome; std::ranges::sort(lives, {}, [](const CellularOwnedLife& life) { return life.identity.life; }); @@ -1284,7 +1321,7 @@ CellularLives::birth_candidate(LifeRequest request, LifeAllocation allocation) c state_->rules_version >= cellular_lives_bud_rules, state_->next_bud_sequence, state_->rules_version >= cellular_lives_presence_rules, state_->format_version >= cellular_lives_migration_format ? &state_->boundary : nullptr, - state_->format_version == cellular_lives_inheritance_format ? &state_->offspring_revisions + state_->format_version >= cellular_lives_inheritance_format ? &state_->offspring_revisions : nullptr); if (!current) return std::unexpected{current.error()}; @@ -1297,6 +1334,8 @@ CellularLives::birth_candidate(LifeRequest request, LifeAllocation allocation) c candidate->last_tick_feedback_ = last_tick_feedback_; candidate->state_->next_bud_sequence = state_->next_bud_sequence; candidate->state_->offspring_revisions = state_->offspring_revisions; + candidate->state_->light = state_->light; + candidate->state_->captured = state_->captured; return candidate; } @@ -1319,9 +1358,14 @@ CellularLives::restore(std::span bytes, std::uint64_t world, format_version == cellular_lives_format && rules_version == cellular_lives_rules; // Format 6 carries rules 5, 6 (founder 2) or 7 (founder 3, ADR-0137); no new state. - const bool inheritance_version = magic == cellular_lives_v8_magic && - format_version == cellular_lives_inheritance_format && - rules_version == cellular_lives_inheritance_rules; + // Format 9 is exactly rules 11; format 8 exactly rules 10. + const bool light_version = magic == cellular_lives_v9_magic && + format_version == cellular_lives_light_format && + rules_version == cellular_lives_photosynthesis_rules; + const bool inheritance_version = + light_version || + (magic == cellular_lives_v8_magic && format_version == cellular_lives_inheritance_format && + rules_version == cellular_lives_inheritance_rules); const bool migration_version = inheritance_version || (magic == cellular_lives_v7_magic && format_version == cellular_lives_migration_format && @@ -1353,6 +1397,8 @@ CellularLives::restore(std::span bytes, std::uint64_t world, return std::unexpected(CellularLivesError::format); if (inheritance_version && bytes.size() < cellular_lives_v8_header_bytes + 8) return std::unexpected(CellularLivesError::format); + if (light_version && bytes.size() < cellular_lives_v9_header_bytes + 8) + return std::unexpected(CellularLivesError::format); const auto saved_world = in.get(); const auto saved_region = in.get(); const auto saved_frame = in.get(); @@ -1398,6 +1444,19 @@ CellularLives::restore(std::span bytes, std::uint64_t world, if (in.get(4) != 0 || plan_count > biology::max_archived_genomes) return std::unexpected{CellularLivesError::format}; } + CellularLight light{}; + accounting::Picojoules captured{}; + if (light_version) { + light.numerator = in.get(); + light.denominator = in.get(); + light.entitlement.value = in.get(); + light.moving_per_thousand = static_cast(in.get(4)); + const auto reserved = in.get(4); + captured.value = in.get(); + if (reserved != 0 || !cellular_light_valid(light) || + captured.value > light.entitlement.value) + return std::unexpected{CellularLivesError::format}; + } const auto life_bytes = inheritance_version ? cellular_life_v6_bytes + 8 : legacy ? cellular_life_v1_bytes : presence_version ? cellular_life_v6_bytes @@ -1407,10 +1466,11 @@ CellularLives::restore(std::span bytes, std::uint64_t world, : bud_version ? cellular_corpse_v5_bytes : engulf_version ? cellular_corpse_v4_bytes : cellular_corpse_bytes; - const auto expected_size = (inheritance_version ? cellular_lives_v8_header_bytes - : migration_version ? cellular_lives_v7_header_bytes - : bud_version ? cellular_lives_v5_header_bytes - : cellular_lives_header_bytes) + + const auto expected_size = (light_version ? cellular_lives_v9_header_bytes + : inheritance_version ? cellular_lives_v8_header_bytes + : migration_version ? cellular_lives_v7_header_bytes + : bud_version ? cellular_lives_v5_header_bytes + : cellular_lives_header_bytes) + cellular_site_bytes * site_count + life_bytes * life_count + corpse_bytes * corpse_count + habitat_size + archive_size + nonresident_count * 8 + @@ -1610,6 +1670,8 @@ CellularLives::restore(std::span bytes, std::uint64_t world, opening_total, *current, format_version, rules_version, std::move(boundary))}}; restored->state_->next_bud_sequence = next_bud_sequence; restored->state_->offspring_revisions = std::move(plan_history); + restored->state_->light = light; + restored->state_->captured = captured; if (!std::ranges::equal(bytes, restored->snapshot())) return std::unexpected{CellularLivesError::noncanonical}; return restored; @@ -1645,7 +1707,7 @@ CellularLives::advance_tick_with_mutations(std::span i const bool contact_rules = state_->rules_version >= cellular_lives_foraging_rules; const bool bud_rules = state_->rules_version >= cellular_lives_bud_rules; const bool presence_rules = state_->rules_version >= cellular_lives_presence_rules; - const bool inheritance_rules = state_->rules_version == cellular_lives_inheritance_rules; + const bool inheritance_rules = cellular_retained_plans(state_->rules_version); for (std::size_t i = 0; i < ordered.size(); ++i) { const auto& intent = ordered[i].intent; // Below rules 4 a bud is ignored, as engulfment is below rules 3 (ADR-0124/0125). @@ -2136,6 +2198,50 @@ CellularLives::advance_tick_with_mutations(std::span i *total, state_->format_version, state_->rules_version, state_->boundary); next->next_bud_sequence = next_bud_sequence; next->offspring_revisions = std::move(next_offspring_revisions); + next->light = state_->light; + next->captured = state_->captured; + // ADR-0175: light, from this tick's own intentions, credited to every active, + // unfrozen photosynthetic survivor's reserve and to the boundary inflow together. + if (next->light.numerator != 0) { + for (auto& life : next->lives) { + const auto left = next->light.entitlement.value - next->captured.value; + if (left == 0) + break; + if (life.presence != CellularPresence::active) + continue; + const auto genome = next->archive.find(life.identity.genome); + if (!genome) + return std::unexpected{CellularLivesError::archive}; + if (!genome->carries(biology::Capability::photosynthesis)) + continue; + const auto input = std::ranges::lower_bound( + ordered, life.identity.life, {}, + [](const CellularLifeIntent& value) { return value.life_id; }); + // Newborn buds had no intention this tick and capture from the next one. + if (input == ordered.end() || input->life_id != life.identity.life || + input->intent.frozen) + continue; + const auto budget = + budget_for(next->archive, life, next->config.ambient_temperature_millikelvin); + if (!budget) + return std::unexpected{CellularLivesError::biology}; + const auto energy = + cellular_light_capture(*genome, budget->phenotype.extent, next->light, + input->intent.movement != biology::CellularIntent{}); + if (!energy) + return std::unexpected{CellularLivesError::overflow}; + const auto granted = std::min(*energy, left); + constexpr auto most = std::numeric_limits::max(); + if (granted > most - life.reserve.energy.value || + granted > most - next->boundary.incoming.energy.value || + granted > most - next->current_total.energy.value) + return std::unexpected{CellularLivesError::overflow}; + life.reserve.energy.value += granted; + next->boundary.incoming.energy.value += granted; + next->current_total.energy.value += granted; + next->captured.value += granted; + } + } std::vector feedback; feedback.reserve(proposal->lives.size()); for (const auto& result : proposal->lives) { diff --git a/src/server/lifecycle/cellular_population.cpp b/src/server/lifecycle/cellular_population.cpp index ccf9660..28ec482 100644 --- a/src/server/lifecycle/cellular_population.cpp +++ b/src/server/lifecycle/cellular_population.cpp @@ -20,8 +20,8 @@ CellularPopulation::create(std::unique_ptr state, CellularTierPol state->format_version() == cellular_lives_migration_format)) || (state->rules_version() == cellular_lives_maturation_rules && state->format_version() == cellular_lives_migration_format) || - (state->rules_version() == cellular_lives_inheritance_rules && - state->format_version() == cellular_lives_inheritance_format)); + (cellular_retained_plans(state->rules_version()) && + state->format_version() >= cellular_lives_inheritance_format)); if (!supported || policy.materialize_radius_um == 0 || policy.collapse_radius_um <= policy.materialize_radius_um || policy.collapse_radius_um > biology::cellular_motion_axis_limit_um) @@ -44,7 +44,7 @@ std::uint64_t CellularPopulation::conversion_sequence() const noexcept { return conversion_sequence_; } std::uint32_t CellularPopulation::format_version() const noexcept { - if (state_->format_version() == cellular_lives_inheritance_format) + if (state_->format_version() >= cellular_lives_inheritance_format) return cellular_population_inheritance_format; return state_->format_version() == cellular_lives_migration_format ? 2U : 1U; } diff --git a/src/server/lifecycle/cellular_population_batch.cpp b/src/server/lifecycle/cellular_population_batch.cpp index 066e594..4d92533 100644 --- a/src/server/lifecycle/cellular_population_batch.cpp +++ b/src/server/lifecycle/cellular_population_batch.cpp @@ -84,8 +84,8 @@ class Reader { bool population_interval_safe(const CellularLives& state) noexcept { return (state.rules_version() == cellular_lives_foraging_rules || state.rules_version() == cellular_lives_maturation_rules || - (state.rules_version() == cellular_lives_inheritance_rules && - state.format_version() == cellular_lives_inheritance_format)) && + (cellular_retained_plans(state.rules_version()) && + state.format_version() >= cellular_lives_inheritance_format)) && std::ranges::all_of(state.lives(), [](const auto& life) { return life.account == LifeAccount{} || life.presence == CellularPresence::suspended; }); @@ -103,7 +103,7 @@ unattended_population_inputs(const CellularLives& base, const CellularBatchHeade if (!working) return std::unexpected(CellularPopulationError::format); CellularBatch batch{header, {}}; - if (base.rules_version() == cellular_lives_inheritance_rules) + if (cellular_retained_plans(base.rules_version())) batch.format_version = cellular_batch_inheritance_format; while ((*working)->tick() < header.end_tick) { auto intents = wildlife_intents(**working, (*working)->tick() + 1); diff --git a/src/server/lifecycle/wildlife_controller.cpp b/src/server/lifecycle/wildlife_controller.cpp index 3f34e30..e5c5750 100644 --- a/src/server/lifecycle/wildlife_controller.cpp +++ b/src/server/lifecycle/wildlife_controller.cpp @@ -140,6 +140,15 @@ wildlife_intents(const CellularLives& state, std::uint64_t tick) { continue; } } + if (state.rules_version() >= cellular_lives_photosynthesis_rules && + state.light().numerator != 0 && genome->carries(biology::Capability::photosynthesis)) { + const auto still = cellular_light_capture(*genome, extent, state.light(), false); + const auto period = budget->rate_microseconds / 50'000; + if (still && period != 0 && *still >= budget->maintenance.value / period) { + intents.push_back({life.identity.life, intent}); + continue; + } + } const auto perceived = state.perceive(life.identity.life); if (!perceived) return std::unexpected{perceived.error()}; diff --git a/tests/cellular_environment_tests.cpp b/tests/cellular_environment_tests.cpp index 28761df..67d20a7 100644 --- a/tests/cellular_environment_tests.cpp +++ b/tests/cellular_environment_tests.cpp @@ -85,8 +85,9 @@ void audit(const CellularEnvironment& value) { expected.matter[channel].value += ledger.incoming.matter[channel].value - ledger.outgoing.matter[channel].value; require(state.current_total() == expected, "joint owner broke open-boundary closure"); - require(ledger.incoming == value.imported() && - ledger.outgoing == Inventory{value.exported(), {}}, + auto environmental = value.imported(); + environmental.energy.value += state.captured_light().value; // A rules-11 owner's light. + require(ledger.incoming == environmental && ledger.outgoing == Inventory{value.exported(), {}}, "environment flows differ from the nested boundary ledger"); for (std::size_t index = 0; index < value.sources().size(); ++index) { const auto& made = value.sources()[index]; @@ -238,6 +239,151 @@ void raw_and_cohort() { << raw->exported().value << " pJ at tick " << raw->tick() << '\n'; } +// ADR-0175: a rules-11 region whose founder is born after the upgrade (founder 4). +Owner producer_region(std::uint64_t irradiance) { + auto state = opening(7, true, 1, false); + checked(state->advance_tick({}), "producer 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"); + const CellularLight light{irradiance, 1, {irradiance == 0 ? 0 : 1ULL << 50}}; + require(!state->photosynthesis_upgrade_candidate({1, 0, {1}}) && + !state->photosynthesis_upgrade_candidate({1, 1, {0}}), + "invalid light declared"); + state = checked(state->photosynthesis_upgrade_candidate(light), "photosynthesis upgrade"); + require(state->rules_version() == cellular_lives_photosynthesis_rules && + state->format_version() == cellular_lives_light_format && state->light() == light && + !state->photosynthesis_upgrade_candidate(light), + "photosynthesis upgrade repeated, wrong versions or lost light"); + LifeAccount account{}; + account.back() = 1; + state = checked(state->birth_candidate({account, 1}, {100, 100, 100, 100, {state->tick()}}), + "founder 4 birth"); + const auto genome = state->archive().find(100); + require(genome && genome->schema_version() == biology::genome_schema_v5 && + !genome->carries(biology::Capability::photosynthesis), + "founder 4 is not schema 5 without photosynthesis"); + return state; +} +bool photosynthetic(const CellularLives& state, std::uint64_t genome) { + const auto found = state.archive().find(genome); + return found && found->carries(biology::Capability::photosynthesis); +} +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; + require(state.current_total() == expected && ledger.incoming.energy == state.captured_light(), + "lit region broke closure or booked light outside the ledger"); +} +struct Producers { + std::unique_ptr population; + std::uint64_t plan{}, child{}, captured{}, lit_ticks{}, still{}; +}; +// The founder earns photosynthesis as its offspring plan (rules 10+), buds a child that +// expresses it, and that child captures light inside the owner's own tick. +Producers grow_producers(std::uint64_t irradiance) { + Producers out; + out.population = checked( + CellularPopulation::create(producer_region(irradiance), {false, 900, 1'600}), "producers"); + auto& population = *out.population; + for (unsigned tick = 0; tick < 80'000 && out.plan == 0; ++tick) { + const auto& life = population.state().lives().front(); + if (!life.mutation.offer) { + checked(population.advance_tick(controlled(population.state())), "feed"); + continue; + } + const auto& offer = *life.mutation.offer; + const auto found = std::ranges::find_if(offer.candidates, [](const auto& candidate) { + return candidate.target == biology::Capability::photosynthesis && + candidate.effect == biology::MutationEffect::acquire; + }); + const auto successor = 2'000'000 + tick; + // Decided before the tick: the tick replaces the state the offer lives in. + const bool acquire = found != offer.candidates.end(); + const CellularMutationSelection selection{100, life.mutation.event_index, + life.mutation.offer_tick, successor, + acquire ? found->operator_id : std::uint16_t{0}}; + checked(population.advance_tick(controlled(population.state()), std::span{&selection, 1}), + "selection tick"); + if (acquire) + out.plan = successor; + } + require( + out.plan != 0 && photosynthetic(population.state(), out.plan) && + !photosynthetic(population.state(), population.state().lives().front().identity.genome), + "founder never planned photosynthesis or expressed it itself"); + for (unsigned tick = 0; tick < 40'000 && out.child == 0; ++tick) { + checked(population.advance_tick(controlled(population.state(), true)), "bud"); + for (const auto& life : population.state().lives()) + if (life.parent_life == 100 && photosynthetic(population.state(), life.identity.genome)) + out.child = life.identity.life; + } + require(out.child != 0, "no child expressed the photosynthesis plan"); + for (unsigned tick = 0; tick < 400; ++tick) { + const auto before = population.state().captured_light().value; + const auto intents = + checked(wildlife_intents(population.state(), population.state().tick() + 1), "intents"); + for (const auto& intent : intents) { + const auto life = std::ranges::find(population.state().lives(), intent.life_id, + [](const auto& l) { return l.identity.life; }); + if (photosynthetic(population.state(), life->identity.genome) && + intent.intent == biology::CellularStepIntent{}) + ++out.still; + } + checked(population.advance_tick(controlled(population.state())), "lit tick"); + const auto gained = population.state().captured_light().value - before; + out.captured += gained; + out.lit_ticks += gained > 0 ? 1 : 0; + closed(population.state()); + } + return out; +} +void producers() { + auto trial = grow_producers(cellular_light_trial_irradiance); + require(trial.captured > 0 && trial.lit_ticks > 0, "a photosynthetic child captured no light"); + const auto& state = trial.population->state(); + const auto bytes = state.snapshot(); + require(bytes.size() > 8 && bytes[7] == '9', "lit region not owner format 9"); + auto restored = + checked(CellularPopulation::restore(trial.population->snapshot(), state.world(), + state.region(), state.frame(), state.tick()), + "lit restore"); + for (unsigned tick = 0; tick < 200; ++tick) { + checked(trial.population->advance_tick(controlled(trial.population->state())), "a"); + checked(restored->advance_tick(controlled(restored->state())), "b"); + require(trial.population->snapshot() == restored->snapshot(), + "lit region diverged after restore"); + } + // A joint owner nests the lit owner: its own infall stays separate from the light. + const auto& lit_state = trial.population->state(); + auto joint_config = config({}, 9); + joint_config.geometry.box.width = {lit_state.area().width_um}; + joint_config.geometry.box.height = {lit_state.area().height_um}; + auto joint = checked(CellularEnvironment::create(std::move(restored), std::move(joint_config)), + "lit joint"); + for (unsigned tick = 0; tick < 200; ++tick) { + step(*joint); + audit(*joint); + } + require(joint->state().captured_light().value > 0, "nested owner stopped capturing"); + // Without light nothing is captured, and a producer forages as before. + auto dark = grow_producers(0); + require(dark.captured == 0 && dark.population->state().captured_light().value == 0, + "a dark region captured light"); + // Same history until the plan, then capture scales exactly with irradiance. (These + // producers always touch food, so they hold still in any light; the light-driven + // holding-still branch is not observable in this rich fixture.) + auto bright = grow_producers(cellular_light_trial_irradiance * 20); + require(bright.child == trial.child && bright.captured == 20 * trial.captured && + bright.still == trial.still && dark.still == trial.still, + "capture did not scale with irradiance or light changed the controller"); + std::cout << "producers: plan " << trial.plan << ", child " << trial.child << ", captured " + << trial.captured << " pJ over " << trial.lit_ticks << " lit ticks (bright " + << bright.captured << ", still intents " << bright.still << " vs dark " << dark.still + << ")\n"; +} + // A full habitat refuses new deposits: bubbles are counted skipped, never deferred. void capacity() { auto value = environment(founders(), @@ -517,6 +663,7 @@ int main(int argc, char** argv) { atomic_and_restore(); raw_and_cohort(); capacity(); + producers(); traces(); refusals(); auto value = restart_fixture(); diff --git a/tests/development_tests.cpp b/tests/development_tests.cpp index 792e991..c0579be 100644 --- a/tests/development_tests.cpp +++ b/tests/development_tests.cpp @@ -174,12 +174,12 @@ void rule_versions_and_invalid_growth() { v3->structure_density == v2->structure_density && v3->maintenance_per_kilogram == v2->maintenance_per_kilogram && development_rate_microseconds(3) == development_rate_microseconds(2)); - for (const auto version : {0U, 5U, 99U}) { + for (const auto version : {0U, 6U, 99U}) { const auto missing = rules_for(version); CHECK(!missing && missing.error() == DevelopmentError::unsupported_rules); } auto source = draft(); - source.development_version = 5; + source.development_version = 6; // Version 5 exists since rules 11 (ADR-0175). const auto future = build(source); const auto derived = derive_phenotype(future, {1000, 0}, temperate); CHECK(!derived && derived.error() == DevelopmentError::unsupported_rules); diff --git a/tests/genome_tests.cpp b/tests/genome_tests.cpp index 6acc986..636f46b 100644 --- a/tests/genome_tests.cpp +++ b/tests/genome_tests.cpp @@ -116,7 +116,8 @@ void capability_and_range_rules() { draft.capabilities.push_back({Capability::thermal_tolerance, 1, 1U << capability_count}); reject(draft, GenomeError::unknown_capability); // Every boundary of every declared range, from both sides, in each schema's own table. - for (const auto schema : {genome_schema_v1, genome_schema_v2, genome_schema_v3}) { + for (const auto schema : + {genome_schema_v1, genome_schema_v2, genome_schema_v3, genome_schema_v5}) { const auto& table = *capability_schema_for(schema); const auto fresh = [&] { auto d = founder(); @@ -126,6 +127,16 @@ void capability_and_range_rules() { for (std::size_t index = 0; index < capability_count; ++index) { const auto kind = static_cast(index); const auto& limits = table[index]; + // An empty range (photosynthesis before schema 5) admits no value at all. + if (limits.maximum < limits.minimum) { + CHECK(kind == Capability::photosynthesis && schema != genome_schema_v5); + for (const auto value : {0U, 1U, 100U, 1000U}) { + draft = fresh(); + draft.capabilities.push_back({kind, value, 0}); + reject(draft, GenomeError::parameter_out_of_range); + } + continue; + } for (const auto value : {limits.minimum, limits.maximum}) { draft = fresh(); std::erase_if(draft.capabilities, @@ -351,10 +362,10 @@ void schema_v2_rates() { v1.capabilities[4].parameter = 1'000'001; reject(v1, GenomeError::parameter_out_of_range); auto unknown = founder(); - unknown.schema_version = 5; // Schema 4 exists since rules 7 (ADR-0137). + unknown.schema_version = 6; // Schema 5 exists since rules 11 (ADR-0175). reject(unknown, GenomeError::unsupported_version); auto bytes = Genome::create(founder())->encode(); - bytes[8] = 5; // Schema field; decode refuses before the checksum matters. + bytes[8] = 6; // Schema field; decode refuses before the checksum matters. CHECK(!Genome::decode(bytes) && Genome::decode(bytes).error() == GenomeError::unsupported_version); } diff --git a/tests/metabolism_tests.cpp b/tests/metabolism_tests.cpp index 26beea3..32314fd 100644 --- a/tests/metabolism_tests.cpp +++ b/tests/metabolism_tests.cpp @@ -385,12 +385,12 @@ void rules_fail_closed() { const auto m3 = metabolic_rules_for(3); CHECK(m2 && m3 && m3->movement_per_kilogram == m2->movement_per_kilogram && m3->intake_energy_per_kilogram == m2->intake_energy_per_kilogram); - for (const auto version : {0U, 5U, 99U}) { + for (const auto version : {0U, 6U, 99U}) { const auto missing = metabolic_rules_for(version); CHECK(!missing && missing.error() == DevelopmentError::unsupported_rules); } auto source = draft(); - source.development_version = 5; + source.development_version = 6; const auto future = build(source); const auto refused = metabolic_budget(future, {1000, 0}, temperate); CHECK(!refused && refused.error() == DevelopmentError::unsupported_rules); diff --git a/tests/mutation_tests.cpp b/tests/mutation_tests.cpp index 8d27943..f0a51a9 100644 --- a/tests/mutation_tests.cpp +++ b/tests/mutation_tests.cpp @@ -315,7 +315,7 @@ void invalid_contexts_are_refused() { // An unsupported development version leaves no eligible operator at all, // because every successor fails to derive a budget. auto source = draft(); - source.development_version = 5; + source.development_version = 6; const auto future = build(source); const auto empty = mutation_candidates(future, context(1)); CHECK(!empty && empty.error() == MutationError::no_candidates); diff --git a/tests/photosynthesis_tests.cpp b/tests/photosynthesis_tests.cpp new file mode 100644 index 0000000..1c82107 --- /dev/null +++ b/tests/photosynthesis_tests.cpp @@ -0,0 +1,137 @@ +#include "evo/biology/founder.hpp" +#include "evo/biology/mutation.hpp" +#include "evo/server/lifecycle/cellular_light.hpp" + +#include +#include +#include +#include + +namespace { +using namespace evo; +using namespace evo::biology; +using namespace evo::server; +void require(bool condition, const char* message) { + if (!condition) + throw std::runtime_error(message); +} +template T checked(std::expected value, const char* message) { + if (!value) + throw std::runtime_error(std::string{message} + ": " + + std::to_string(static_cast(value.error()))); + return std::move(*value); +} +Genome with(const Genome& base, std::uint32_t efficiency) { + GenomeDraft draft{base.id() + 1, 2, base.development_version(), {base.id()}, {}, {}}; + draft.schema_version = base.schema_version(); + draft.capabilities.assign(base.capabilities().begin(), base.capabilities().end()); + draft.capabilities.push_back({Capability::photosynthesis, efficiency, 0}); + return checked(Genome::create(draft), "photosynthetic genome"); +} +constexpr EnvironmentState reference{293'150, {}}; + +// Founder 4 is founder 3 with a schema that can express photosynthesis; it starts without. +void founders() { + const auto three = checked(primitive_founder(5, 5, primitive_founder_v3), "founder 3"); + const auto four = checked(primitive_founder(5, 5, primitive_founder_v4), "founder 4"); + require(!four.carries(Capability::photosynthesis) && four.schema_version() == 5 && + four.development_version() == 5, + "founder 4 carries photosynthesis or wrong versions"); + const auto a = checked(metabolic_budget(three, {1000, 0}, reference), "founder 3 budget"); + const auto b = checked(metabolic_budget(four, {1000, 0}, reference), "founder 4 budget"); + require(a.phenotype == b.phenotype && a.body == b.body && a.maintenance == b.maintenance && + a.reproduction_investment == b.reproduction_investment, + "founder 4 differs from founder 3 without photosynthesis"); + require(checked(primitive_endowment(primitive_founder_v4), "endowment 4") == + checked(primitive_endowment(primitive_founder_v3), "endowment 3"), + "founder 4 endowment changed"); + // Earlier schemas cannot carry it at any efficiency. + GenomeDraft old{9, 9, 4, {}, {}, genome_schema_v4}; + old.capabilities.assign(three.capabilities().begin(), three.capabilities().end()); + old.capabilities.push_back({Capability::photosynthesis, 100, 0}); + require(Genome::create(old).error() == GenomeError::parameter_out_of_range, + "schema 4 accepted photosynthesis"); +} + +// Organelles: p/4 of structure as membrane mass (upkept twice), speed down by p/2. +void costs() { + const auto four = checked(primitive_founder(5, 5, primitive_founder_v4), "founder 4"); + const auto base = checked(metabolic_budget(four, {1000, 0}, reference), "base budget"); + for (const auto efficiency : {100U, 500U, 1000U}) { + const auto producer = with(four, efficiency); + const auto budget = checked(metabolic_budget(producer, {1000, 0}, reference), "producer"); + const auto organelles = base.phenotype.structural_mass / 4 * efficiency / 1000; + require(budget.phenotype.membrane_mass == base.phenotype.membrane_mass + organelles && + budget.phenotype.structural_mass == base.phenotype.structural_mass && + budget.phenotype.extent == base.phenotype.extent && + budget.maintenance.value > base.maintenance.value && + budget.phenotype.movement_speed == + base.phenotype.movement_speed * (1000 - efficiency / 2) / 1000, + "photosynthesis costs differ from the declared trial rule"); + const CellularLight light{cellular_light_trial_irradiance, 1, {1ULL << 50}}; + const auto captured_still = + cellular_light_capture(producer, budget.phenotype.extent, light, false); + const auto captured_moving = + cellular_light_capture(producer, budget.phenotype.extent, light, true); + require(captured_still.has_value() && captured_moving.has_value(), "capture overflowed"); + const auto still = captured_still.value_or(0), moving = captured_moving.value_or(0); + const auto section = std::uint64_t{budget.phenotype.extent} * budget.phenotype.extent; + require(still == section * cellular_light_trial_irradiance * efficiency / 1000 && + moving == still / 4, + "light capture differs from cross-section x irradiance x efficiency"); + std::cout << "photosynthesis " << efficiency << ": maintenance " + << budget.maintenance.value / 20 << " pJ/tick (founder " + << base.maintenance.value / 20 << "), capture still " << still << ", moving " + << moving << ", speed " << budget.phenotype.movement_speed << " um/s\n"; + } + require(cellular_light_capture(four, 20, {cellular_light_trial_irradiance, 1, {1}}, false) == 0, + "a genome without the capability captured light"); +} + +// Schema 5 offers photosynthesis through the appended operators; earlier schemas never do. +void offers() { + const auto catalog = mutation_catalog(); + require(catalog.size() == 32, "catalog size"); + for (std::uint16_t id = 29; id <= 32; ++id) + require(catalog[id - 1].target == Capability::photosynthesis, + "photosynthesis operators are not IDs 29-32"); + const auto four = checked(primitive_founder(5, 5, primitive_founder_v4), "founder 4"); + const auto three = checked(primitive_founder(5, 5, primitive_founder_v3), "founder 3"); + bool offered = false; + for (std::uint64_t event = 1; event <= 400 && !offered; ++event) { + const MutationContext context{0x5EED, 1, event, 8, {1000, 0}, reference}; + const auto old = checked(mutation_candidates(three, context), "schema 4 offer"); + require(std::ranges::none_of( + old.candidates, + [](const auto& c) { return c.target == Capability::photosynthesis; }), + "schema 4 lineage offered photosynthesis"); + const auto offer = checked(mutation_candidates(four, context), "schema 5 offer"); + const auto found = std::ranges::find_if(offer.candidates, [](const auto& c) { + return c.target == Capability::photosynthesis && c.effect == MutationEffect::acquire; + }); + if (found == offer.candidates.end()) + continue; + offered = true; + require(found->parameter == photosynthesis_acquired_start, + "acquired photosynthesis does not start at the trial value"); + const auto successor = + checked(select_mutation(four, context, offer, found->operator_id, 77, 77), "select"); + require(*successor.parameter(Capability::photosynthesis) == photosynthesis_acquired_start, + "selected successor lost photosynthesis"); + } + require(offered, "schema 5 never offered photosynthesis"); +} +} // namespace + +int main() { + try { + founders(); + costs(); + offers(); + std::cout << "photosynthesis contracts passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +}