From 86ee800f32b181e8c8c6ffd5814e07a3223ee212 Mon Sep 17 00:00:00 2001 From: dingo Date: Fri, 16 Oct 2026 22:41:55 -0400 Subject: [PATCH] Cellular rules 7: percentage mutations, skilled budding, hunting wildlife (ADR-0137) The region 6 playtest found a speed mutation adding 6,667 um/s (1/300 of the range, 33x a founder), so buds seemed to teleport; reproduction made buds bigger and dearer; and wildlife never hunted. Rules 7: - genome schema 4: a step is a tenth of the current value (at least 1); an acquired capability starts at the founder's value instead of a minimum it could never grow from; - development 4: a bud is always half the body, and reproduction takes value/2000 off its construction energy (founders save a quarter; matter is never discounted); - twins: a seeded roll (reproduction/2 per thousand) splits one affordable bud's investment into two quarter-size buds; - wildlife engulfs a touching cell the region step lets it take, players' included. Founder 3, owner format 6 (no new state), bundle v8 and schema v42; the cellular-v6 opening provisions it. The client's mutation callout shrinks to a "Mutation [E]" pill and its candidate texts describe the new steps. Co-Authored-By: Claude Opus 5.5 --- apps/evo-client/panels.cpp | 16 +- apps/evo-world-clone/main.cpp | 14 +- .../region/dev-session-route/listener.yaml | 2 +- ...37-percentage-mutations-skilled-budding.md | 96 +++++++++++ docs/adr/README.md | 1 + include/evo/biology/budding.hpp | 5 +- include/evo/biology/development.hpp | 4 +- include/evo/biology/founder.hpp | 2 + include/evo/biology/genome.hpp | 14 +- include/evo/biology/metabolism.hpp | 2 + include/evo/persistence/region_checkpoint.hpp | 4 +- .../evo/server/lifecycle/cellular_lives.hpp | 23 ++- .../0042_cellular_v8_reproduction_bundle.sql | 129 +++++++++++++++ migrations/apply.sql | 31 +++- schemas/cellular-lives-v1.md | 7 + src/biology/budding.cpp | 12 +- src/biology/development.cpp | 4 +- src/biology/metabolism.cpp | 18 +- src/biology/mutation.cpp | 31 +++- src/persistence/cellular_checkpoint_store.cpp | 5 + src/persistence/region_checkpoint.cpp | 6 +- src/server/lifecycle/cellular_lives.cpp | 155 +++++++++++------- src/server/lifecycle/wildlife_controller.cpp | 46 +++++- tests/cellular_lives_tests.cpp | 91 ++++++++++ tests/cellular_publication_tests.cpp | 80 ++++++--- tests/development_tests.cpp | 4 +- tests/genome_tests.cpp | 4 +- tests/metabolism_tests.cpp | 41 ++++- tests/mutation_tests.cpp | 43 ++++- tests/region_migration_tests.cpp | 2 +- tests/region_store_tests.cpp | 18 ++ tools/ci/postgres-check.sh | 10 +- tools/migrate-postgres.sh | 3 + 33 files changed, 786 insertions(+), 137 deletions(-) create mode 100644 docs/adr/0137-percentage-mutations-skilled-budding.md create mode 100644 migrations/0042_cellular_v8_reproduction_bundle.sql diff --git a/apps/evo-client/panels.cpp b/apps/evo-client/panels.cpp index 00556a6..8abd595 100644 --- a/apps/evo-client/panels.cpp +++ b/apps/evo-client/panels.cpp @@ -1144,10 +1144,12 @@ void hud_callout(const PanelView& v, FormBuffers& form) { ImGui::PushStyleColor(ImGuiCol_Button, ImVec4{0.165F, 0.133F, 0.075F, 1.0F}); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4{0.24F, 0.19F, 0.10F, 1.0F}); ImGui::PushStyleColor(ImGuiCol_Text, ImVec4{0.97F, 0.91F, 0.80F, 1.0F}); - const std::string label = - "Mutation ready - " + std::to_string(offer->candidates.size()) + " choices [E]"; - if (ImGui::Button(label.c_str(), {0, px(40)})) + // 2026-10-16: offers come often, so the callout is a small pill (E or a click opens it). + const std::string label = "Mutation [E]"; + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {px(10), px(3)}); + if (ImGui::Button(label.c_str(), {0, px(24)})) form.evolution_open = true; + ImGui::PopStyleVar(); ImGui::PopStyleColor(3); ImGui::End(); } @@ -1159,16 +1161,16 @@ constexpr std::array capability_kinds{"Metabolism", "Defense", "Movement", " constexpr std::array effect_names{"Increase", "Decrease", "Acquire", "Shed"}; constexpr std::array increase_text{"Convert more of what you eat into usable energy.", "A thicker wall: prey must be much larger to engulf you.", - "Swim faster; each movement costs a little more.", + "Swim 10% faster; each movement costs a little more.", "Take food faster from every patch you touch.", - "Invest more of your body in each bud.", + "Better at budding: cheaper buds, more twins (+10%).", "Grow toward a larger body: harder to engulf, slower to fill.", "Tolerate a wider range of temperatures."}; constexpr std::array decrease_text{"Convert less of what you eat into energy.", "A thinner, cheaper wall that is easier to breach.", - "Swim slower and spend less on movement.", + "Swim 10% slower and spend less on movement.", "Take food more slowly from each patch.", - "Each bud takes less of your body: cheaper, smaller buds.", + "Worse at budding: dearer buds, fewer twins (-10%).", "Grow toward a smaller body that is cheaper to keep.", "Tolerate a narrower range of temperatures."}; // A small before/after drawing of the cell for one candidate. diff --git a/apps/evo-world-clone/main.cpp b/apps/evo-world-clone/main.cpp index 75ce08d..a98f1b3 100644 --- a/apps/evo-world-clone/main.cpp +++ b/apps/evo-world-clone/main.cpp @@ -10,16 +10,17 @@ // evo-world-clone check-store --world W --region R --pg-* ... --objects DIR // [--reserve-mib N] // evo-world-clone provision --world W --region R --opening -// development-v1|primitive-v1|cellular-v1|cellular-v2|cellular-v3|cellular-v4|cellular-v5 +// development-v1|primitive-v1|cellular-v1 to cellular-v6 // --pg-* ... --objects DIR --build HEX [--commit HEX32] [--retain-build] // primitive-v1 also requires --frame N --source-id N, every --funding-*-* channel, // and one or more ordered --site X,Y values. -// cellular-v1 to cellular-v5 also require --width-um N --height-um N +// cellular-v1 to cellular-v6 also require --width-um N --height-um N // --ambient-temperature-mk N and one or more ordered --patch X,Y,SOURCE,ENERGY,C,N,P,O values // plus a stable --commit HEX32. cellular-v2 is the same opening on rules 3 (ADR-0124: // engulfment, detritus); cellular-v3 is it on rules 4 (ADR-0125: budding wildlife); // cellular-v4 on rules 5 (ADR-0128: offline freeze and resume). // cellular-v5 on rules 6 (2026-10-15 balance: finer mutations, cheaper construction). +// cellular-v6 on rules 7 (ADR-0137: percentage mutations, skilled budding, twins). // primitive-v1 and cellular-v1/v2/v3 accept --life-allocator-start N // (ADR-0123): the world's life-identity allocator is created once at the operator-audited // start N; a later run leaves it untouched and refuses one that is below N. @@ -277,7 +278,7 @@ std::optional parse(int argc, char** argv) { else if (o.command == "provision" && flag == "--opening" && (value == "development-v1" || value == "primitive-v1" || value == "cellular-v1" || value == "cellular-v2" || value == "cellular-v3" || value == "cellular-v4" || - value == "cellular-v5")) + value == "cellular-v5" || value == "cellular-v6")) o.opening = value; else if (o.command == "provision" && flag == "--frame" && n) o.primitive_frame = n; @@ -353,7 +354,7 @@ std::optional parse(int argc, char** argv) { return std::nullopt; } else if (o.opening == "cellular-v1" || o.opening == "cellular-v2" || o.opening == "cellular-v3" || o.opening == "cellular-v4" || - o.opening == "cellular-v5") { + o.opening == "cellular-v5" || o.opening == "cellular-v6") { const bool has_stock = std::ranges::any_of(o.cellular_patches, [](const auto& patch) { return patch.stock.energy.value != 0 || std::ranges::any_of(patch.stock.matter, @@ -464,7 +465,7 @@ int provision(const Options& o) { const bool primitive = o.opening == "primitive-v1"; const bool cellular = o.opening == "cellular-v1" || o.opening == "cellular-v2" || o.opening == "cellular-v3" || o.opening == "cellular-v4" || - o.opening == "cellular-v5"; + o.opening == "cellular-v5" || o.opening == "cellular-v6"; const auto primitive_frame = o.primitive_frame.value_or(0); if ((primitive || cellular) && primitive_frame == 0) return 2; @@ -567,7 +568,8 @@ int provision(const Options& o) { auto opening = server::CellularLives::create( *primitive_opening, std::move(*habitat), {{cellular_width_um, cellular_height_um}, 0, cellular_temperature_mk}, - o.opening == "cellular-v5" ? server::CellularLivesProfile::balance + o.opening == "cellular-v6" ? server::CellularLivesProfile::reproduction + : o.opening == "cellular-v5" ? server::CellularLivesProfile::balance : o.opening == "cellular-v4" ? server::CellularLivesProfile::presence : o.opening == "cellular-v3" ? server::CellularLivesProfile::budding : o.opening == "cellular-v2" ? server::CellularLivesProfile::engulf diff --git a/deploy/kubernetes/region/dev-session-route/listener.yaml b/deploy/kubernetes/region/dev-session-route/listener.yaml index 82104c5..c62ebd3 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-20261017T020216-38024:1792213336"} + - {name: REGION_SESSION_WINDOW, value: "dev-20261017T024155-69196:1792215715"} - {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"} ports: # QUIC (ADR-0090): UDP only; nothing listens on TCP 7400. diff --git a/docs/adr/0137-percentage-mutations-skilled-budding.md b/docs/adr/0137-percentage-mutations-skilled-budding.md new file mode 100644 index 0000000..8621dbf --- /dev/null +++ b/docs/adr/0137-percentage-mutations-skilled-budding.md @@ -0,0 +1,96 @@ +# ADR-0137: Percentage mutations, skilled budding and hunting wildlife (rules 7) + +## Status + +Accepted (2026-10-16) by the maintainer after the region 6 playtest. Implemented as +cellular rules 7: owner format 6, version bundle v8 and schema v42. The opening is +`cellular-v6`, served as DEV region 7. ADR-0135's proposed rules move up to the next +free numbers. + +## Context + +The region 6 playtest surfaced three problems. + +**Mutation steps.** A step is a fixed slice of a trait's whole range: 1/300 under +ADR-0132's genome schema 3. For movement (range 0–2,000,000 µm/s) that is +6,667 µm/s, +33 times a founder's 200 µm/s. A single speed mutation turned a cell, and every bud it +made, into something that seemed to teleport between food patches. Steps never felt +like a percentage. + +**Reproduction.** The trait was the share of the body invested in a bud. Raising it +made buds *bigger and dearer*. The maintainer wants the opposite: a reproductive lineage +should bud more cheaply and make more offspring. + +**Wildlife.** Wildlife never engulfed anything, so a field full of buds posed no danger. + +## Decision + +### Genome schema 4: percentage steps + +- **Steps:** a mutation step is a tenth of the trait's current value, at least 1, up or + down. Speed 200 → 220 or 180 µm/s. A lineage compounds. +- **Range:** steps that would leave the schema's range are refused, as before. +- **Gaining a trait:** an acquired capability starts at the founder's value for + movement (200 µm/s), ingestion and reproduction. Ten percent of a zero minimum would + never grow. Other capabilities still start at their minimum. +- **Units:** the table and units are schema 2's. +- **Existing lineages:** schema 1–3 lineages keep their own steps (ADR-0099). + +### Development version 4: reproduction is skill + +- **Bud size:** always half the parent's body. Development 3's rules and rates are + unchanged. +- **Cost:** reproduction takes `value / 2000` off the bud's construction energy, at most + half at value 1000. Founders (500) save a quarter. Matter is never discounted + (ADR-0118); the bud's body still has to come from the parent. + +### Twins + +On a bud action a seeded roll, unique to the parent and tick, allows twins with +probability `reproduction / 2` per thousand: 25% for a founder, at most 50%. + +- **Affordability:** twins happen only when the parent could pay for one whole bud. +- **Split:** the bud investment is then divided between two buds, each about a quarter + of the parent's body. Twins are more offspring for the same cost, never extra matter. +- **Results:** the parent's reported result is the first bud's. A twin with no room is + simply not made. + +### Wildlife engulfs + +The rules-7 wildlife controller asks to engulf when it touches a cell the region step +would let it take: mass at least 1.5 times the prey's per micrometre of the prey's +membrane (ADR-0124). That includes players' cells. Otherwise it buds, feeds or wanders +as before. Its intents are recorded in the trace as always, so replay never runs the +controller. + +### Rules 7 and region 7 + +- **Rules:** rules 7 are rules 6 plus founder 3 (schema 4, development 4), twins and + hunting wildlife. +- **State:** none new, so they keep owner format 6. +- **Bundle:** v8 = {rules 7, envelope 6, habitat 1, coordinate 1, genome 1, + development 4, founder 3, archive 2, mutation state 1}. +- **Schema v42:** admits the v8 bundle (manifest normalization and the birth-trace + binding). +- **Region 7:** the `cellular-v6` DEV opening, 30 × 30 mm, three times region 6 per + side. Food keeps region 6's density: 144 patches in a 12 × 12 grid. 64 founders are + funded at 9 spawn sites. + +### Client + +- **Callout:** the mutation callout is a small "Mutation [E]" pill, because offers come + often. +- **Descriptions:** candidate texts name the ±10% steps and the new meaning of + reproduction. + +## Consequences + +- Speed mutations change a cell visibly but sanely. Buds no longer outrun the eye. +- Reproduction becomes a reason to specialize in budding. +- Wildlife can kill, so a crowd of buds is both an army and a hazard. Your own cell can + be eaten by a larger descendant. +- **Region 6:** its cells stay in region 6, which is no longer served. Accounts with a + living region-6 cell are released with `tools/ops/retire-region-lives.sql` before + playing region 7. +- **Not decided here:** the client cannot yet tell which rules a region runs, so its + candidate texts describe rules 7. diff --git a/docs/adr/README.md b/docs/adr/README.md index 941adc0..1c63893 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -39,6 +39,7 @@ - [ADR-0132: Cellular balance, rules 6](0132-cellular-balance-rules-6.md) - genome schema 3 (a third of the mutation step) and development version 3 (a third of the construction energy) for founders of rules-6 regions; opening `cellular-v5`, bundle v7, schema v41; existing lineages and history unchanged. - [ADR-0135: Behaviour-driven evolution and budding colonies](0135-behaviour-driven-evolution-and-colonies.md) - proposed: offers weighted by each life's behaviour and by accept/decline history (never ruled out), per-candidate decline (rules 7); buds that attach to a steered colony or detach as anchored wildlife (rules 8); colony motion and a funded Coalesce transition into M14 multicellularity (rules 9). - [ADR-0136: Open energy, scattered nutrients and photosynthesis](0136-open-energy-and-scattered-nutrients.md) - proposed: an audited region boundary for sunlight and rare infall; scattered single-nutrient bubbles and puddle pools fed by contact instead of square patches; detritus to bubbles; a photosynthesis trait (genome schema 4); session v11 perception. +- [ADR-0137: Percentage mutations, skilled budding and hunting wildlife (rules 7)](0137-percentage-mutations-skilled-budding.md) - accepted: genome schema 4 steps by a tenth of the current value; development 4 makes reproduction cheapen buds; seeded twin buds split one investment; wildlife engulfs what the step allows; bundle v8, schema v42, DEV region 7 at 30 x 30 mm. - [ADR-0058: Region durability contract](0058-region-durability-contract.md) - accepted M7.1 full checkpoint batches and explicit state closure; storage implementation follows. diff --git a/include/evo/biology/budding.hpp b/include/evo/biology/budding.hpp index 1680db2..85669ed 100644 --- a/include/evo/biology/budding.hpp +++ b/include/evo/biology/budding.hpp @@ -31,9 +31,12 @@ enum class BuddingError : std::uint8_t { // Pure and deterministic. On every channel the parent's reserve before equals its reserve // after plus the bud's body and reserve, plus heat in energy. A refusal spends nothing. +// `share` > 1 (ADR-0137 twins) funds one of that many buds from the same investment: each +// gets the investment divided by `share`, so twins are smaller, not extra. [[nodiscard]] std::expected fund_bud(const Genome& genome, GrowthState parent_growth, - const accounting::Inventory& parent_reserve, std::uint32_t temperature_millikelvin); + const accounting::Inventory& parent_reserve, std::uint32_t temperature_millikelvin, + std::uint32_t share = 1); // What one bud takes from a fully grown, undamaged parent of this genome at this temperature // (ADR-0129 amendment): investment matter per channel, and construction energy plus the // bud's provision; exactly what `fund_bud` charges such a parent. Nullopt when the genome diff --git a/include/evo/biology/development.hpp b/include/evo/biology/development.hpp index da11845..42bc36e 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 == 3 - ? development_v2_rate_microseconds // Version 3 keeps version 2's rates. + : development_version >= 2 && development_version <= 4 + ? development_v2_rate_microseconds // Versions 3 and 4 keep version 2's rates. : 0; } // Chosen constants, reviewable as a unit and selected by the genome's diff --git a/include/evo/biology/founder.hpp b/include/evo/biology/founder.hpp index 5f70b07..52327b3 100644 --- a/include/evo/biology/founder.hpp +++ b/include/evo/biology/founder.hpp @@ -32,6 +32,8 @@ struct FounderVersion { }; 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}; 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 3a6e899..fe14f5f 100644 --- a/include/evo/biology/genome.hpp +++ b/include/evo/biology/genome.hpp @@ -111,14 +111,18 @@ inline constexpr std::uint32_t genome_schema_v2 = 2; // Schema 3 (rules 6, 2026-10-15 balance): schema 2's capability table and units, with // mutation steps a third as large (mutation.cpp). Founded only by rules-6 regions. 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; // The newest schema. Older records stay valid and are never rewritten (ADR-0099). -inline constexpr std::uint32_t genome_schema_version = genome_schema_v3; -// The capability table of a supported schema (1, 2 or 3); nullptr otherwise. +inline constexpr std::uint32_t genome_schema_version = genome_schema_v4; +// The capability table of a supported schema (1 to 4); 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 ? &capability_schema_v2 - : nullptr; + return schema == genome_schema_v1 ? &capability_schema_v1 + : schema == genome_schema_v2 || schema == genome_schema_v3 || schema == genome_schema_v4 + ? &capability_schema_v2 + : nullptr; } inline constexpr std::size_t max_parents = 2; inline constexpr std::size_t max_genome_bytes = 256; diff --git a/include/evo/biology/metabolism.hpp b/include/evo/biology/metabolism.hpp index cc4b885..9dd2638 100644 --- a/include/evo/biology/metabolism.hpp +++ b/include/evo/biology/metabolism.hpp @@ -6,6 +6,8 @@ #include namespace evo::biology { +// Development version 4 (rules 7, ADR-0137): a bud is always this share of the parent's body. +inline constexpr std::uint32_t bud_body_per_thousand_v4 = 500; // Shares in thousandths over the ledger's C/N/P/other channels, summing to 1000. // The last channel absorbs the rounding remainder, so a split conserves mass. using Composition = std::array; diff --git a/include/evo/persistence/region_checkpoint.hpp b/include/evo/persistence/region_checkpoint.hpp index 6131fcd..bf69ab9 100644 --- a/include/evo/persistence/region_checkpoint.hpp +++ b/include/evo/persistence/region_checkpoint.hpp @@ -61,10 +61,12 @@ inline constexpr CellularVersionBundle cellular_v5_versions{4, 5, 1, 1, 1, 2, 1, inline constexpr CellularVersionBundle cellular_v6_versions{5, 6, 1, 1, 1, 2, 1, 2, 1}; // 2026-10-15 balance: rules 6 on owner envelope 6, with development 3 and founder 2. inline constexpr CellularVersionBundle cellular_v7_versions{6, 6, 1, 1, 1, 3, 2, 2, 1}; +// ADR-0137: rules 7 on owner envelope 6, with development 4 and founder 3. +inline constexpr CellularVersionBundle cellular_v8_versions{7, 6, 1, 1, 1, 4, 3, 2, 1}; // Bundles with genome revisions: the revision history profile and format-3 traces. [[nodiscard]] constexpr bool cellular_revision_bundle(const CellularVersionBundle& b) noexcept { return b == cellular_v3_versions || b == cellular_v4_versions || b == cellular_v5_versions || - b == cellular_v6_versions || b == cellular_v7_versions; + b == cellular_v6_versions || b == cellular_v7_versions || b == cellular_v8_versions; } // Batch evidence bound by manifest v2 (ADR-0063); all zero at genesis. diff --git a/include/evo/server/lifecycle/cellular_lives.hpp b/include/evo/server/lifecycle/cellular_lives.hpp index a82041a..ed01c34 100644 --- a/include/evo/server/lifecycle/cellular_lives.hpp +++ b/include/evo/server/lifecycle/cellular_lives.hpp @@ -34,12 +34,22 @@ inline constexpr std::uint32_t cellular_lives_presence_rules = 5; // 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; // The founder a region of these rules creates. [[nodiscard]] constexpr biology::FounderVersion cellular_founder_version(std::uint32_t rules) noexcept { - return rules >= cellular_lives_balance_rules ? biology::primitive_founder_v2 - : biology::primitive_founder_v1; + return 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; @@ -158,7 +168,14 @@ struct CellularLifeTickFeedback { // 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 }; +enum class CellularLivesProfile : std::uint8_t { + offers, + engulf, + budding, + presence, + balance, + reproduction +}; struct CellularLivesConfig { biology::CellularArea area{}; std::uint64_t tick{}; diff --git a/migrations/0042_cellular_v8_reproduction_bundle.sql b/migrations/0042_cellular_v8_reproduction_bundle.sql new file mode 100644 index 0000000..fd77df0 --- /dev/null +++ b/migrations/0042_cellular_v8_reproduction_bundle.sql @@ -0,0 +1,129 @@ +-- ADR-0137: admit the cellular-v8 bundle (rules 7 on owner envelope 6, development 4, +-- founder 3: percentage mutation steps, skilled budding with twins, wildlife that +-- engulfs). It has no new trace or state layout; earlier bundles and committed rows keep +-- their meaning. + +-- The v8 bundle shares v3's revision history profile and format-3 traces. Normalize it +-- to v3 for the existing parser chain, then report the real bundle. +ALTER FUNCTION evolution.parse_checkpoint_manifest(bytea) + RENAME TO parse_checkpoint_manifest_v41; + +CREATE FUNCTION evolution.parse_checkpoint_manifest(m bytea) +RETURNS evolution.checkpoint_manifest LANGUAGE plpgsql IMMUTABLE +SET search_path = pg_catalog, pg_temp AS $$ +DECLARE + r evolution.checkpoint_manifest; + v3_bundle constant bytea := '\x020000000300000001000000010000000100000002000000010000000200000001000000'; + v8_bundle constant bytea := '\x070000000600000001000000010000000100000004000000030000000200000001000000'; +BEGIN + IF m IS NOT NULL AND octet_length(m) = 360 + AND evolution.manifest_uint(m, 12, 4) = 4 + AND substring(m FROM 161 FOR 36) = v8_bundle + AND evolution.manifest_uint(m, 228, 4) = 0 + AND evolution.manifest_uint(m, 232, 4) = 4 + AND evolution.manifest_uint(m, 236, 4) = 1 THEN + r := evolution.parse_checkpoint_manifest_v41(overlay(m PLACING v3_bundle FROM 161 FOR 36)); + r.versions := v8_bundle; + RETURN r; + END IF; + RETURN evolution.parse_checkpoint_manifest_v41(m); +END $$; +REVOKE ALL ON FUNCTION evolution.parse_checkpoint_manifest(bytea) FROM PUBLIC; + +-- Birth binding: v3 to v8 publications carry format-3 traces. Otherwise unchanged from +-- schema v41. +CREATE OR REPLACE FUNCTION evolution.cellular_births(p_trace bytea, p_manifest bytea) +RETURNS TABLE(account_id uuid, request_id evolution.u64, generation evolution.u64, + identity evolution.u64, born evolution.u64) +LANGUAGE plpgsql IMMUTABLE SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE + c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(p_manifest); + revision boolean; + ticks numeric; + tick_index integer; + trace_format numeric; + tick_header_size integer; + intent_count numeric; + birth_count numeric; + mutation_count numeric; + off integer := 112; + account bytea; + previous_account bytea; + previous_request numeric; +BEGIN + revision := c.versions IN ( + '\x020000000300000001000000010000000100000002000000010000000200000001000000'::bytea, + '\x030000000400000001000000010000000100000002000000010000000200000001000000'::bytea, + '\x040000000500000001000000010000000100000002000000010000000200000001000000'::bytea, + '\x050000000600000001000000010000000100000002000000010000000200000001000000'::bytea, + '\x060000000600000001000000010000000100000003000000020000000200000001000000'::bytea, + '\x070000000600000001000000010000000100000004000000030000000200000001000000'::bytea); + trace_format := evolution.manifest_uint(p_trace, 8, 4); + tick_header_size := CASE trace_format WHEN 2 THEN 8 WHEN 3 THEN 16 ELSE 0 END; + IF c.profile <> 4 OR c.commit_sequence = 0 OR p_trace IS NULL + OR octet_length(p_trace) <> c.trace_bytes OR sha256(p_trace) <> c.trace_sha256 + OR substring(p_trace FROM 1 FOR 8) <> '\x45564c4342543031' + OR tick_header_size = 0 + OR (revision AND trace_format <> 3) + OR (NOT revision AND trace_format <> 2) + OR evolution.manifest_uint(p_trace, 12, 4) <> 4 + OR evolution.manifest_uint(p_trace, 16, 8) <> c.world_id + OR evolution.manifest_uint(p_trace, 24, 8) <> c.region_id + OR evolution.manifest_uint(p_trace, 32, 8) <> c.frame_id + OR encode(substring(p_trace FROM 41 FOR 16), 'hex')::uuid <> c.predecessor_commit + OR substring(p_trace FROM 57 FOR 32) <> c.predecessor_digest + OR evolution.manifest_uint(p_trace, 88, 8) <> c.begin_tick + OR evolution.manifest_uint(p_trace, 96, 8) <> c.end_tick THEN + RAISE EXCEPTION 'invalid cellular birth trace binding' USING ERRCODE = '22023'; + END IF; + ticks := c.end_tick - c.begin_tick; + IF ticks < 1 OR ticks > 64 OR evolution.manifest_uint(p_trace, 104, 4) <> ticks + OR evolution.manifest_uint(p_trace, 108, 4) <> 0 THEN + RAISE EXCEPTION 'invalid cellular birth trace range' USING ERRCODE = '22023'; + END IF; + FOR tick_index IN 0 .. ticks::integer - 1 LOOP + IF off + tick_header_size > octet_length(p_trace) THEN + RAISE EXCEPTION 'truncated cellular tick header' USING ERRCODE = '22023'; + END IF; + intent_count := evolution.manifest_uint(p_trace, off, 4); + birth_count := evolution.manifest_uint(p_trace, off + 4, 4); + mutation_count := 0; + IF trace_format = 3 THEN + mutation_count := evolution.manifest_uint(p_trace, off + 8, 4); + IF evolution.manifest_uint(p_trace, off + 12, 4) <> 0 THEN + RAISE EXCEPTION 'invalid cellular tick reserved word' USING ERRCODE = '22023'; + END IF; + END IF; + IF intent_count > 256 OR birth_count > 256 OR mutation_count > 256 + OR off + tick_header_size + intent_count * 24 + birth_count * 40 + + mutation_count * 40 > octet_length(p_trace) THEN + RAISE EXCEPTION 'invalid cellular tick counts' USING ERRCODE = '22023'; + END IF; + off := off + tick_header_size + intent_count::integer * 24; + previous_account := ''::bytea; + previous_request := -1; + FOR birth_index IN 0 .. birth_count::integer - 1 LOOP + account := substring(p_trace FROM off + 1 FOR 16); + account_id := encode(account, 'hex')::uuid; + request_id := evolution.manifest_uint(p_trace, off + 16, 8); + generation := evolution.manifest_uint(p_trace, off + 24, 8); + identity := evolution.manifest_uint(p_trace, off + 32, 8); + born := c.begin_tick + tick_index + 1; + IF account_id = '00000000-0000-0000-0000-000000000000' OR request_id = 0 + OR generation = 0 OR identity = 0 + OR (account, request_id) <= (previous_account, previous_request) THEN + RAISE EXCEPTION 'invalid cellular birth record' USING ERRCODE = '22023'; + END IF; + previous_account := account; + previous_request := request_id; + off := off + 40; + RETURN NEXT; + END LOOP; + off := off + mutation_count::integer * 40; + END LOOP; + IF off <> octet_length(p_trace) THEN + RAISE EXCEPTION 'trailing cellular trace bytes' USING ERRCODE = '22023'; + END IF; +END $$; + +INSERT INTO evolution.schema_migrations(version, sha256) VALUES (42, :'migration_sha_42'); diff --git a/migrations/apply.sql b/migrations/apply.sql index ca669c6..8fe2f5a 100644 --- a/migrations/apply.sql +++ b/migrations/apply.sql @@ -117,6 +117,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') SELECT :'history_v38' || ',39:' || :'migration_sha_39' AS history_v39 \gset SELECT :'history_v39' || ',40:' || :'migration_sha_40' AS history_v40 \gset SELECT :'history_v40' || ',41:' || :'migration_sha_41' AS history_v41 \gset + SELECT :'history_v41' || ',42:' || :'migration_sha_42' AS history_v42 \gset SELECT :'history' = :'history_v22' AS at_v22, :'history' = :'history_v23' AS at_v23, :'history' = :'history_v24' AS at_v24, @@ -136,8 +137,10 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') :'history' = :'history_v38' AS at_v38, :'history' = :'history_v39' AS at_v39, :'history' = :'history_v40' AS at_v40, - :'history' = :'history_v41' AS at_v41 \gset - \if :at_v41 + :'history' = :'history_v41' AS at_v41, + :'history' = :'history_v42' AS at_v42 \gset + \if :at_v42 + \elif :at_v41 \elif :at_v40 \elif :at_v39 \elif :at_v38 @@ -513,7 +516,8 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, coalesce(max(version), 0) = 38 AS at_v38, coalesce(max(version), 0) = 39 AS at_v39, coalesce(max(version), 0) = 40 AS at_v40, - coalesce(max(version), 0) = 41 AS at_v41 + coalesce(max(version), 0) = 41 AS at_v41, + coalesce(max(version), 0) = 42 AS at_v42 FROM evolution.schema_migrations \gset \if :at_v24 \ir 0025_cellular_v2_bundle.sql @@ -533,6 +537,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v25 \ir 0026_cellular_profile_migration.sql \ir 0027_cellular_v3_migration.sql @@ -550,6 +555,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v26 \ir 0027_cellular_v3_migration.sql \ir 0028_cellular_v3_trace_bounds.sql @@ -566,6 +572,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v27 \ir 0028_cellular_v3_trace_bounds.sql \ir 0029_cellular_mutation_reservations.sql @@ -581,6 +588,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v28 \ir 0029_cellular_mutation_reservations.sql \ir 0030_cellular_birth_publication_binding.sql @@ -595,6 +603,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v29 \ir 0030_cellular_birth_publication_binding.sql \ir 0031_fix_cellular_birth_publication_record.sql @@ -608,6 +617,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v30 \ir 0031_fix_cellular_birth_publication_record.sql \ir 0032_fix_cellular_v3_manifest_normalization.sql @@ -620,6 +630,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v31 \ir 0032_fix_cellular_v3_manifest_normalization.sql \ir 0033_fix_cellular_action_tick_offset.sql @@ -631,6 +642,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v32 \ir 0033_fix_cellular_action_tick_offset.sql \ir 0034_cellular_v4_engulf_bundle.sql @@ -641,6 +653,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v33 \ir 0034_cellular_v4_engulf_bundle.sql \ir 0035_cellular_mutation_publication.sql @@ -650,6 +663,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v34 \ir 0035_cellular_mutation_publication.sql \ir 0036_cellular_v5_budding_bundle.sql @@ -658,6 +672,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v35 \ir 0036_cellular_v5_budding_bundle.sql \ir 0037_cellular_life_endings.sql @@ -665,29 +680,37 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v36 \ir 0037_cellular_life_endings.sql \ir 0038_cellular_v6_presence_bundle.sql \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v37 \ir 0038_cellular_v6_presence_bundle.sql \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v38 \ir 0039_account_identities.sql \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v39 \ir 0040_cellular_mutation_decline.sql \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v40 \ir 0041_cellular_v7_balance_bundle.sql + \ir 0042_cellular_v8_reproduction_bundle.sql \elif :at_v41 + \ir 0042_cellular_v8_reproduction_bundle.sql +\elif :at_v42 \else - \echo 'Unknown or changed migration history after v41' + \echo 'Unknown or changed migration history after v42' DO $$ BEGIN RAISE EXCEPTION 'unknown or changed migration history'; END $$; \endif -- Effective-privilege audit on every run, including no-ops (ADR-0060). Attributes diff --git a/schemas/cellular-lives-v1.md b/schemas/cellular-lives-v1.md index 3ce66e8..1995ef9 100644 --- a/schemas/cellular-lives-v1.md +++ b/schemas/cellular-lives-v1.md @@ -116,3 +116,10 @@ Format 6 also carries rules 6, byte for byte the same layout. Rules 6 differ onl what they found: new lives are founder 2 (genome schema 3, development version 3). Restore accepts format 6 with rules 5 or 6, and the version bundle (v6 or v7) must name the same rules. + +### Format 6, rules 7 (ADR-0137) + +Rules 7 keep the same layout again. New lives are founder 3 (genome schema 4, +development version 4). A bud action can make twins, and wildlife can engulf, but +neither adds any state. Restore accepts format 6 with rules 5, 6 or 7, on the v8 bundle +for rules 7. diff --git a/src/biology/budding.cpp b/src/biology/budding.cpp index ce18218..246ca1d 100644 --- a/src/biology/budding.cpp +++ b/src/biology/budding.cpp @@ -16,7 +16,10 @@ bool fits(const accounting::Inventory& part, const accounting::Inventory& whole) std::expected fund_bud(const Genome& genome, GrowthState parent_growth, const accounting::Inventory& parent_reserve, - std::uint32_t temperature_millikelvin) { + std::uint32_t temperature_millikelvin, + std::uint32_t share) { + if (share == 0) + return std::unexpected{BuddingError::no_capability}; if (!genome.carries(Capability::reproduction)) return std::unexpected{BuddingError::no_capability}; if (parent_growth.realized_per_thousand != 1000 || parent_growth.damage_per_thousand != 0) @@ -24,7 +27,12 @@ std::expected fund_bud(const Genome& genome, Growth const auto parent = metabolic_budget(genome, parent_growth, {temperature_millikelvin, {}}); if (!parent) return std::unexpected{BuddingError::development}; - const auto& investment = parent->reproduction_investment; + // ADR-0137 twins: each of `share` buds is funded from that fraction of the investment + // (rounded down; the remainder stays with the parent). + auto investment = parent->reproduction_investment; + investment.energy.value /= share; + for (auto& mass : investment.matter) + mass.value /= share; std::uint64_t invested_matter = 0; for (const auto& mass : investment.matter) invested_matter += mass.value; diff --git a/src/biology/development.cpp b/src/biology/development.cpp index c340dd1..43b2b2b 100644 --- a/src/biology/development.cpp +++ b/src/biology/development.cpp @@ -67,7 +67,9 @@ std::expected rules_for(std::uint32_t develo // Version 3 (rules 6, 2026-10-15 balance): version 2 with a third of the construction // energy (13 pJ per 1000 fg built instead of 40). Construction is overhead paid into // heat, so this changes no matter balance. - if (development_version == 3) { + // 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) { return DevelopmentRules{1000, 1200, 10, 15, 13, 60'000, 293'150, 50}; } return std::unexpected{DevelopmentError::unsupported_rules}; diff --git a/src/biology/metabolism.cpp b/src/biology/metabolism.cpp index bd77e85..332defc 100644 --- a/src/biology/metabolism.cpp +++ b/src/biology/metabolism.cpp @@ -2,6 +2,7 @@ #include "evo/accounting/rates.hpp" +#include #include namespace evo::biology { @@ -108,7 +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). - if (development_version == 2 || development_version == 3) { // Version 3: same metabolism. + // Versions 3 and 4: the same metabolism. + if (development_version >= 2 && development_version <= 4) { return MetabolicRules{structure_shares, membrane_shares, 50, 50'000}; } return std::unexpected{DevelopmentError::unsupported_rules}; @@ -201,12 +203,22 @@ metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState envi break; } if (genome.carries(Capability::reproduction)) { - const auto fraction = *genome.parameter(Capability::reproduction); + const auto value = *genome.parameter(Capability::reproduction); + // 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 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); // Offspring tissue is priced at what the parent's own tissue costs. - budget.reproduction_investment.energy.value = + const auto construction = scaled(matter_total(budget.reproduction_investment), shape->construction_per_kilogram); + // Discount = construction * skill / 2000, split to stay within 64 bits. + const std::uint64_t level = std::min(value, 1000); + const auto discount = construction / 2000 * level + construction % 2000 * level / 2000; + budget.reproduction_investment.energy.value = + skill ? construction - discount : construction; } return budget; } diff --git a/src/biology/mutation.cpp b/src/biology/mutation.cpp index e27824e..2de4cf6 100644 --- a/src/biology/mutation.cpp +++ b/src/biology/mutation.cpp @@ -1,5 +1,6 @@ #include "evo/biology/mutation.hpp" +#include "evo/biology/founder.hpp" #include "evo/core/random.hpp" #include @@ -32,14 +33,28 @@ constexpr std::array catalog = [] { // (rules 6, 2026-10-15 balance) takes a third of that step: successor bodies differ a // third as much, so the matter a mutation needs falls with them (ADR-0118: the cost is // the body difference, never a discount). +// Schema 4 (rules 7, ADR-0137) steps by a tenth of the current value instead (at least 1), +// so a trait changes by a percentage and a lineage compounds. constexpr std::uint32_t adjustment_step(const std::array& table, - Capability kind, std::uint32_t schema) noexcept { + Capability kind, std::uint32_t schema, + std::uint32_t current) noexcept { + if (schema == genome_schema_v4) + return current / 10 == 0 ? 1 : current / 10; const auto& limits = table[static_cast(kind)]; const auto span = limits.maximum - limits.minimum; const std::uint32_t divisor = schema == genome_schema_v3 ? 300 : 100; return span / divisor == 0 ? 1 : span / divisor; } +std::uint32_t acquired_start(Capability kind, const CapabilitySpec& limits) noexcept { + const auto& p = primitive_founder_parameters; + const auto value = kind == Capability::movement ? p.movement + : kind == Capability::ingestion ? p.ingestion + : kind == Capability::reproduction ? p.reproduction + : limits.minimum; + return std::clamp(value, limits.minimum, limits.maximum); +} + std::uint64_t mix(std::uint64_t hash, std::uint64_t value) noexcept { // Non-cryptographic combiner. No wall clock and no std::hash enters this. return hash ^ (value + 0x9e3779b97f4a7c15ULL + (hash << 6U) + (hash >> 2U)); @@ -96,7 +111,8 @@ std::optional apply(const Genome& genome, const MutationOperator& e if (!present) { return std::nullopt; } - const auto step = adjustment_step(table, entry.target, genome.schema_version()); + const auto step = + adjustment_step(table, entry.target, genome.schema_version(), carried->parameter); // Refused rather than clamped: a clamp would make two operators agree // and would offer a no-op as a real choice. if (carried->parameter > limits.maximum - step) { @@ -109,7 +125,8 @@ std::optional apply(const Genome& genome, const MutationOperator& e if (!present) { return std::nullopt; } - const auto step = adjustment_step(table, entry.target, genome.schema_version()); + const auto step = + adjustment_step(table, entry.target, genome.schema_version(), carried->parameter); if (carried->parameter < limits.minimum + step) { return std::nullopt; } @@ -120,7 +137,13 @@ std::optional apply(const Genome& genome, const MutationOperator& e if (present) { return std::nullopt; } - draft.capabilities.push_back({entry.target, limits.minimum, 0}); + // 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 + ? acquired_start(entry.target, limits) + : limits.minimum, + 0}); break; case MutationEffect::shed: if (!present) { diff --git a/src/persistence/cellular_checkpoint_store.cpp b/src/persistence/cellular_checkpoint_store.cpp index bd94cd5..fabc23f 100644 --- a/src/persistence/cellular_checkpoint_store.cpp +++ b/src/persistence/cellular_checkpoint_store.cpp @@ -168,6 +168,11 @@ provision_cellular_region(Postgres& owner, const FilesystemObjectStore& objects, // ADR-0128: a rules-5 region starts on the v6 bundle with genome revisions. manifest->cellular_versions = cellular_v6_versions; manifest->history_profile = cellular_revision_history_profile; + } else if (manifest && opening.format_version() == server::cellular_lives_presence_format && + opening.rules_version() == server::cellular_lives_reproduction_rules) { + // ADR-0137: a rules-7 region starts on the v8 bundle with genome revisions. + manifest->cellular_versions = cellular_v8_versions; + manifest->history_profile = cellular_revision_history_profile; } else if (manifest && opening.format_version() == server::cellular_lives_presence_format && opening.rules_version() == server::cellular_lives_balance_rules) { // 2026-10-15 balance: a rules-6 region starts on the v7 bundle with genome revisions. diff --git a/src/persistence/region_checkpoint.cpp b/src/persistence/region_checkpoint.cpp index 69d1390..9d8d62c 100644 --- a/src/persistence/region_checkpoint.cpp +++ b/src/persistence/region_checkpoint.cpp @@ -73,7 +73,8 @@ bool structural(const CheckpointManifest& m) noexcept { m.cellular_versions != cellular_v4_versions && m.cellular_versions != cellular_v5_versions && m.cellular_versions != cellular_v6_versions && - m.cellular_versions != cellular_v7_versions) || + m.cellular_versions != cellular_v7_versions && + m.cellular_versions != cellular_v8_versions) || (cellular && m.versions != environmental_v1_versions)) return false; if (primitive && (m.manifest_version != 2 || m.tick_microseconds != 50000 || @@ -169,7 +170,8 @@ bool supported(const CheckpointManifest& m) noexcept { m.cellular_versions == cellular_v4_versions || m.cellular_versions == cellular_v5_versions || m.cellular_versions == cellular_v6_versions || - m.cellular_versions == cellular_v7_versions) && + m.cellular_versions == cellular_v7_versions || + m.cellular_versions == cellular_v8_versions) && m.versions == environmental_v1_versions && m.tick_microseconds == 50000 && m.rng_streams == 0 && m.durability == DurabilityPolicy::single_volume_development; } diff --git a/src/server/lifecycle/cellular_lives.cpp b/src/server/lifecycle/cellular_lives.cpp index e9b8d80..9e8827e 100644 --- a/src/server/lifecycle/cellular_lives.cpp +++ b/src/server/lifecycle/cellular_lives.cpp @@ -535,7 +535,8 @@ CellularLives::create(const PrimitiveLives& opening, const auto world = nursery_config.world; const auto region = nursery_config.region; const auto frame = nursery_config.frame; - const bool balance = profile == CellularLivesProfile::balance; // Rules 6: presence plus. + const bool reproduction = profile == CellularLivesProfile::reproduction; // Rules 7. + const bool balance = profile == CellularLivesProfile::balance || reproduction; // Rules 6+. const bool presence = profile == CellularLivesProfile::presence || balance; const bool budding = profile == CellularLivesProfile::budding || presence; const bool engulf = profile == CellularLivesProfile::engulf || budding; @@ -549,14 +550,23 @@ CellularLives::create(const PrimitiveLives& opening, : budding ? cellular_lives_bud_format : engulf ? cellular_lives_engulf_format : cellular_lives_format, - balance ? cellular_lives_balance_rules - : presence ? cellular_lives_presence_rules - : budding ? cellular_lives_bud_rules - : engulf ? cellular_lives_engulf_rules - : cellular_lives_rules); + reproduction ? cellular_lives_reproduction_rules + : balance ? cellular_lives_balance_rules + : presence ? cellular_lives_presence_rules + : budding ? cellular_lives_bud_rules + : engulf ? cellular_lives_engulf_rules + : cellular_lives_rules); return std::unique_ptr{new CellularLives{std::move(state)}}; } +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 { + // Its own stream: the parent and tick hashed with a twin-only salt ("twin"). + constexpr std::uint64_t twin_stream = 0x7477696eULL; + const auto roll = mutation_seed(world, region, parent_life, tick ^ (twin_stream << 32U)); + return roll % 1000 < std::min(reproduction, 1000) / 2; +} + std::uint64_t CellularLives::world() const noexcept { return state_->world; } @@ -969,11 +979,12 @@ CellularLives::restore(std::span bytes, std::uint64_t world, const bool offer_version = magic == cellular_lives_v2_magic && format_version == cellular_lives_format && rules_version == cellular_lives_rules; - // Format 6 carries rules 5 or rules 6 (founder 2, no new state). + // Format 6 carries rules 5, 6 (founder 2) or 7 (founder 3, ADR-0137); no new state. const bool presence_version = magic == cellular_lives_v6_magic && format_version == cellular_lives_presence_format && (rules_version == cellular_lives_presence_rules || - rules_version == cellular_lives_balance_rules); + rules_version == cellular_lives_balance_rules || + rules_version == cellular_lives_reproduction_rules); // Formats 5 and 6 carry the bud sequence and parent lives (rules 4 and 5). const bool bud_version = presence_version || (magic == cellular_lives_v5_magic && format_version == cellular_lives_bud_format && @@ -1448,7 +1459,7 @@ CellularLives::advance_tick_with_mutations(std::span i for (const auto& request : ordered) { if (!bud_rules || !request.intent.bud) continue; - const auto parent = std::ranges::lower_bound( + auto parent = std::ranges::lower_bound( next_lives, request.life_id, {}, [](const CellularOwnedLife& value) { return value.identity.life; }); if (parent == next_lives.end() || parent->identity.life != request.life_id) { @@ -1459,55 +1470,87 @@ CellularLives::advance_tick_with_mutations(std::span i bud_results.push_back({request.life_id, 0, CellularBudResult::not_able}); continue; // Out of the world (ADR-0128). } - const auto temperature = state_->config.ambient_temperature_millikelvin; - const auto genome = next_archive.find(parent->identity.genome); - const auto parent_budget = budget_for(next_archive, *parent, temperature); - if (!genome || !parent_budget) - return std::unexpected{CellularLivesError::archive}; - const auto transition = - biology::fund_bud(*genome, parent->growth, parent->reserve, temperature); - if (!transition) { - if (transition.error() == biology::BuddingError::development) + // ADR-0137 (rules 7): on a twin roll the bud investment is split between two buds + // (each a quarter of the parent's body). The parent's reported result is the + // first bud's; a twin that finds no room is simply not made. + const bool twins = [&] { + if (state_->rules_version < cellular_lives_reproduction_rules) + return false; + const auto parent_genome = next_archive.find(parent->identity.genome); + if (!parent_genome) + return false; + const auto skill = parent_genome->parameter(biology::Capability::reproduction); + // Twins split one whole bud: the parent must afford that whole bud first. + return skill && + cellular_twin_bud(state_->world, state_->region, request.life_id, + proposal->end_tick, *skill) && + biology::fund_bud(*parent_genome, parent->growth, parent->reserve, + state_->config.ambient_temperature_millikelvin) + .has_value(); + }(); + for (int copy = 0; copy < (twins ? 2 : 1); ++copy) { + if (copy == 1) + // Appending the first bud may have moved the parent; find it again (buds + // sort after every existing life, so the order still holds). + parent = std::ranges::lower_bound( + next_lives, request.life_id, {}, + [](const CellularOwnedLife& value) { return value.identity.life; }); + const bool twin = copy == 1; + const auto temperature = state_->config.ambient_temperature_millikelvin; + const auto genome = next_archive.find(parent->identity.genome); + const auto parent_budget = budget_for(next_archive, *parent, temperature); + if (!genome || !parent_budget) + return std::unexpected{CellularLivesError::archive}; + const auto transition = biology::fund_bud(*genome, parent->growth, parent->reserve, + temperature, twins ? 2U : 1U); + if (!transition) { + if (transition.error() == biology::BuddingError::development) + return std::unexpected{CellularLivesError::biology}; + if (!twin) + bud_results.push_back( + {request.life_id, 0, + transition.error() == biology::BuddingError::insufficient_funding + ? CellularBudResult::insufficient_funding + : CellularBudResult::not_able}); + break; + } + const auto bud_budget = + biology::metabolic_budget(*genome, transition->growth, {temperature, {}}); + if (!bud_budget || bud_budget->body.matter != transition->body.matter) return std::unexpected{CellularLivesError::biology}; - bud_results.push_back({request.life_id, 0, - transition.error() == biology::BuddingError::insufficient_funding - ? CellularBudResult::insufficient_funding - : CellularBudResult::not_able}); - continue; + const auto identity = cellular_bud_identity(state_->region, next_bud_sequence); + const auto position = + bud_position(*parent, parent_budget->phenotype.extent, bud_budget->phenotype.extent, + next_lives, next_archive, state_->config); + if (!position) + return std::unexpected{position.error()}; + if (identity == 0 || !*position || + next_lives.size() >= biology::max_cellular_tick_lives || + next_archive.organism(identity)) { + if (!twin) + bud_results.push_back({request.life_id, 0, CellularBudResult::no_placement}); + break; + } + if (!add_inventory(next_heat, accounting::Inventory{transition->heat, {}}) || + !next_archive.record_birth(identity, parent->identity.genome, {proposal->end_tick})) + return std::unexpected{CellularLivesError::archive}; + parent->reserve = transition->parent_reserve; + CellularOwnedLife bud{}; + bud.identity = { + identity, identity, parent->identity.genome, identity, {proposal->end_tick}}; + bud.source = parent->source; + bud.growth = transition->growth; + bud.position = **position; + bud.body = transition->body; + bud.reserve = transition->reserve; + bud.parent_life = parent->identity.life; + // Bud identities increase within the region and exceed every allocated identity, + // so the new life sorts after all existing ones. + next_lives.push_back(bud); + ++next_bud_sequence; + if (!twin) + bud_results.push_back({request.life_id, identity, CellularBudResult::budded}); } - const auto bud_budget = - biology::metabolic_budget(*genome, transition->growth, {temperature, {}}); - if (!bud_budget || bud_budget->body.matter != transition->body.matter) - return std::unexpected{CellularLivesError::biology}; - const auto identity = cellular_bud_identity(state_->region, next_bud_sequence); - const auto position = - bud_position(*parent, parent_budget->phenotype.extent, bud_budget->phenotype.extent, - next_lives, next_archive, state_->config); - if (!position) - return std::unexpected{position.error()}; - if (identity == 0 || !*position || next_lives.size() >= biology::max_cellular_tick_lives || - next_archive.organism(identity)) { - bud_results.push_back({request.life_id, 0, CellularBudResult::no_placement}); - continue; - } - if (!add_inventory(next_heat, accounting::Inventory{transition->heat, {}}) || - !next_archive.record_birth(identity, parent->identity.genome, {proposal->end_tick})) - return std::unexpected{CellularLivesError::archive}; - parent->reserve = transition->parent_reserve; - CellularOwnedLife bud{}; - bud.identity = { - identity, identity, parent->identity.genome, identity, {proposal->end_tick}}; - bud.source = parent->source; - bud.growth = transition->growth; - bud.position = **position; - bud.body = transition->body; - bud.reserve = transition->reserve; - bud.parent_life = parent->identity.life; - // Bud identities increase within the region and exceed every allocated identity, - // so the new life sorts after all existing ones and `parent` stays valid. - next_lives.push_back(bud); - ++next_bud_sequence; - bud_results.push_back({request.life_id, identity, CellularBudResult::budded}); } std::ranges::sort(next_lives, {}, [](const CellularOwnedLife& life) { return life.identity.life; }); diff --git a/src/server/lifecycle/wildlife_controller.cpp b/src/server/lifecycle/wildlife_controller.cpp index d703505..1535a91 100644 --- a/src/server/lifecycle/wildlife_controller.cpp +++ b/src/server/lifecycle/wildlife_controller.cpp @@ -1,11 +1,13 @@ #include "evo/server/lifecycle/wildlife_controller.hpp" #include "evo/biology/budding.hpp" +#include "evo/biology/cellular_motion.hpp" #include #include #include #include +#include #include namespace evo::server { @@ -20,6 +22,16 @@ std::uint64_t mix(std::uint64_t life, std::uint64_t phase) noexcept { return value; } +// The region step's engulf test (ADR-0124), without overflow: hunter * 1000 must reach +// prey * 1500 per micrometre of the prey's membrane. +bool can_engulf(std::uint64_t hunter, std::uint64_t prey, std::uint32_t membrane_um) noexcept { + const auto factor = biology::cellular_engulf_ratio_milli_per_membrane_um * membrane_um; + constexpr auto most = std::numeric_limits::max(); + if (factor != 0 && prey > most / factor) + return false; + return hunter <= most / 1000 ? hunter * 1000 >= prey * factor : true; +} + bool overlaps(std::uint64_t start, std::uint32_t extent, std::uint32_t patch) noexcept { return start < std::uint64_t{patch} + biology::cellular_patch_pitch_um && start + extent > patch; @@ -72,10 +84,42 @@ wildlife_intents(const CellularLives& state, std::uint64_t tick) { intents.push_back({life.identity.life, intent}); continue; } + const auto extent = budget->phenotype.extent; + // Rules 7 (ADR-0137): engulf a touching cell the region step would let it take + // (ADR-0124: mass at least 1.5 x the prey's per micrometre of prey membrane), + // players' cells included; otherwise feed. + if (state.rules_version() >= cellular_lives_reproduction_rules) { + bool prey = false; + for (const auto& other : state.lives()) { + if (other.identity.life == life.identity.life || + other.presence == CellularPresence::suspended) + continue; + const auto other_genome = state.archive().find(other.identity.genome); + if (!other_genome) + return std::unexpected{CellularLivesError::archive}; + const auto other_budget = + biology::metabolic_budget(*other_genome, other.growth, {temperature, {}}); + const auto membrane = other_genome->parameter(biology::Capability::membrane); + if (!other_budget || !membrane) + return std::unexpected{CellularLivesError::biology}; + if (!biology::cellular_footprints_contact(life.position, extent, other.position, + other_budget->phenotype.extent)) + continue; + if (can_engulf(budget->phenotype.total_mass, other_budget->phenotype.total_mass, + *membrane)) { + prey = true; + break; + } + } + if (prey) { + intent.engulf = true; + intents.push_back({life.identity.life, intent}); + continue; + } + } const auto perceived = state.perceive(life.identity.life); if (!perceived) return std::unexpected{perceived.error()}; - const auto extent = budget->phenotype.extent; const auto centre_x = static_cast(life.position.x_um) + extent / 2; const auto centre_y = static_cast(life.position.y_um) + extent / 2; std::optional nearest; diff --git a/tests/cellular_lives_tests.cpp b/tests/cellular_lives_tests.cpp index 2dc527e..5ee9edd 100644 --- a/tests/cellular_lives_tests.cpp +++ b/tests/cellular_lives_tests.cpp @@ -1032,6 +1032,95 @@ void wildlife_steering_stays_within_the_intent_limit() { CHECK((x == 0 || (x > 0) == (dx > 0)) && (y == 0 || (y > 0) == (dy > 0))); } } +// ADR-0137: a rules-7 opening founds founder-3 cells, whose bud action sometimes yields a +// twin (reproduction 500: a quarter of the time); wildlife intents, engulfing included, +// are always accepted, and the region's totals never change. +void rules_seven_bud_twins_and_wildlife_hunts() { + auto primitive = PrimitiveLives::create({97, 1, 7, 17, founder_price(3), {{0, 0}, {1'500, 0}}}); + CHECK(primitive); + constexpr std::uint64_t rich = 10'000'000'000; + auto habitat = evo::biology::CellularHabitat::create( + {97, 1, 7, 6'000, 6'000, {{{0, 0}, 29, {{rich}, {{{rich}, {rich}, {rich}, {rich}}}}}}}); + CHECK(habitat); + auto created = + CellularLives::create(**primitive, std::move(*habitat), {{6'000, 6'000}, 0, 293'150}, + CellularLivesProfile::reproduction); + CHECK(created); + auto owner = std::move(*created); + CHECK(owner->rules_version() == cellular_lives_reproduction_rules && + owner->format_version() == cellular_lives_presence_format); + const std::span no_lives{}; + CHECK(owner->advance_tick(no_lives)); + LifeRequest request{}; + request.account.back() = 9; + request.action = 1; + auto born = owner->birth_candidate(request, {701, 701, 701, 701, {owner->tick()}}); + CHECK(born); + owner = std::move(*born); + const auto genome = owner->archive().find(owner->lives().front().identity.genome); + CHECK(genome && genome->schema_version() == evo::biology::genome_schema_v4 && + genome->development_version() == 4); + evo::biology::CellularStepIntent feed{}; + feed.intake_target = evo::biology::CellularPatchAddress{0, 0}; + evo::biology::CellularStepIntent bud{}; + bud.bud = true; + const auto all = [&](CellularLifeIntent mine) { + std::vector intents{mine}; + const auto wild = wildlife_intents(*owner, owner->tick() + 1); + if (!wild) + throw std::runtime_error{"wildlife intents"}; + intents.insert(intents.end(), wild->begin(), wild->end()); + std::ranges::sort(intents, {}, &CellularLifeIntent::life_id); + return intents; + }; + const auto offspring = [&] { + return std::ranges::count(owner->lives(), std::uint64_t{701}, + &CellularOwnedLife::parent_life); + }; + std::size_t twins = 0, singles = 0; + for (std::size_t round = 0; round < 1'500 && twins == 0; ++round) { + // Feed, and ask to bud only on a tick whose seeded roll allows twins. + for (int tick = 0; tick < 19 || !cellular_twin_bud(97, 1, 701, owner->tick() + 1, 500); + ++tick) + CHECK(owner->advance_tick(all({701, feed}))); + if (owner->lives().empty() || owner->lives().front().identity.life != 701) + break; // Engulfed by its own wildlife: still a valid, conserved outcome. + const auto before = offspring(); + const auto tick = owner->tick() + 1; + const auto stepped = owner->advance_tick_with_mutations( + all({701, bud}), std::span{}); + CHECK(stepped.has_value()); + const auto mine = std::ranges::find(stepped->buds, std::uint64_t{701}, + &CellularBudExecution::parent_life); + if (mine != stepped->buds.end() && mine->result == CellularBudResult::budded) { + const auto added = offspring() - before; + CHECK(added == 1 || added == 2); + // A twin only where the seeded roll allows one (it may still lack funds or room). + CHECK(added == 1 || cellular_twin_bud(97, 1, 701, tick, 500)); + (added == 2 ? twins : singles) += 1; + } + CHECK(owner->current_total() == owner->opening_total()); + } + CHECK(twins > 0); // Every bud here is on a twin roll; this seeded run makes a pair. + CHECK(owner->current_total() == owner->opening_total()); + const auto saved = owner->snapshot(); + const auto recovered = CellularLives::restore(saved, 97, 1, 7, owner->tick()); + CHECK(recovered && (*recovered)->rules_version() == cellular_lives_reproduction_rules && + (*recovered)->snapshot() == saved); +} +// The twin roll: seeded per parent and tick, never at zero skill, about skill / 2 per +// thousand, and a quarter of the time for a founder. +void twin_roll_follows_reproduction() { + std::size_t founder = 0, full = 0; + for (std::uint64_t tick = 1; tick <= 4'000; ++tick) { + CHECK(!cellular_twin_bud(1, 2, 3, tick, 0)); + CHECK(cellular_twin_bud(1, 2, 3, tick, 500) == cellular_twin_bud(1, 2, 3, tick, 500)); + founder += cellular_twin_bud(1, 2, 3, tick, 500) ? 1 : 0; + full += cellular_twin_bud(1, 2, 3, tick, 1'000) ? 1 : 0; + } + CHECK(founder > 800 && founder < 1'200); // About 1,000 of 4,000. + CHECK(full > 1'800 && full < 2'200 && full > founder); +} } // namespace int main() { @@ -1046,6 +1135,8 @@ int main() { rules_six_found_cheaper_cells_with_finer_mutations(); suspended_parent_of_a_bud_resumes(); wildlife_steering_stays_within_the_intent_limit(); + rules_seven_bud_twins_and_wildlife_hunts(); + twin_roll_follows_reproduction(); std::puts( "PASS cellular lives: feeding, tick ownership, terminal closure, rules 3, budding"); } catch (const std::exception& error) { diff --git a/tests/cellular_publication_tests.cpp b/tests/cellular_publication_tests.cpp index 9484174..837b1ca 100644 --- a/tests/cellular_publication_tests.cpp +++ b/tests/cellular_publication_tests.cpp @@ -11,6 +11,8 @@ #include #include #include +#include +#include void run_cellular_publication_tests(); namespace { @@ -711,17 +713,35 @@ void cellular_host_admits_mutation_choices() { // ADR-0125 (schema v36): a rules-4 region publishes a bud with its tick; the wildlife // descendant, its identity and the parent's debit recover after a restart. // 2026-10-15 balance (schema v41): a rules-6 region publishes a founder of genome schema 3 -// and development 3 on the v7 bundle, and a restarted host recovers it. -void cellular_balance_region_founds_and_recovers() { +// and development 3 on the v7 bundle, and a restarted host recovers it. ADR-0137 (schema +// v42): likewise a rules-7 region, founder 3 (schema 4, development 4) on the v8 bundle. +struct FoundingCase { + RegionKey key; + CellularLivesProfile profile; + evo::biology::FounderVersion founder; + std::uint32_t rules; + evo::persistence::CellularVersionBundle bundle; + std::uint8_t build_byte, commit_byte, account_byte; +}; +void cellular_balance_region_founds_and_recovers(const FoundingCase& c) { using namespace evo::biology; - constexpr RegionKey key{9771, 1}; + const RegionKey key = c.key; auto owner = connect_as(env("PGUSER")); auto runtime = connect_as(env("EVO_PG_RUNTIME_USER")); - const auto build = filled<32>(0xDC); - CHECK(owner->query("INSERT INTO evolution.retained_builds(build_identity) VALUES " - "(decode(repeat('dc',32),'hex')) ON CONFLICT DO NOTHING", - {}, 5s)); - auto endowed = primitive_endowment(primitive_founder_v2); + const auto build = filled<32>(c.build_byte); + { + std::string hex; + for (const auto byte : build) { + constexpr std::string_view digits = "0123456789abcdef"; + hex += digits[byte >> 4U]; + hex += digits[byte & 15U]; + } + CHECK(owner->query("INSERT INTO evolution.retained_builds(build_identity) VALUES " + "(decode('" + + hex + "','hex')) ON CONFLICT DO NOTHING", + {}, 5s)); + } + auto endowed = primitive_endowment(c.founder); CHECK(endowed); auto funding = endowed->body; funding.energy.value = endowed->reserve.energy.value + endowed->construction.value; @@ -736,16 +756,15 @@ void cellular_balance_region_founds_and_recovers() { 2'000, {{{0, 0}, 29, {{stock}, {{{stock}, {stock}, {stock}, {stock}}}}}}}); CHECK(habitat); - auto opening = - CellularLives::create(**primitive, std::move(*habitat), {{3'000, 2'000}, 0, 293'150}, - CellularLivesProfile::balance); + auto opening = CellularLives::create(**primitive, std::move(*habitat), + {{3'000, 2'000}, 0, 293'150}, c.profile); CHECK(opening); auto objects = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); CHECK(objects); - CHECK(provision_cellular_region(*owner, **objects, key, 1, **opening, distinct_commit(0xA7), - build, 5s)); - CHECK(owner->query("INSERT INTO evolution.life_allocators VALUES(9771,1000) " - "ON CONFLICT DO NOTHING", + CHECK(provision_cellular_region(*owner, **objects, key, 1, **opening, + distinct_commit(c.commit_byte), build, 5s)); + CHECK(owner->query("INSERT INTO evolution.life_allocators VALUES(" + std::to_string(key.world) + + ",1000) ON CONFLICT DO NOTHING", {}, 5s)); const auto connect = [&]() -> std::expected, PgFailure> { return Postgres::connect({env("PGHOST"), @@ -762,8 +781,8 @@ void cellular_balance_region_founds_and_recovers() { auto made = CellularRegionHost::create(config(), connect, std::move(*objects)); CHECK(made); auto host = std::move(*made); - CHECK(host->step().ready && host->state()->rules_version() == cellular_lives_balance_rules); - const auto account = filled<16>(0x85); + CHECK(host->step().ready && host->state()->rules_version() == c.rules); + const auto account = filled<16>(c.account_byte); const auto control = claim_account_control(*runtime, key, checked_value(host->authority()), account, 1, 1, 60'000ms, 5s); CHECK(control); @@ -784,12 +803,12 @@ void cellular_balance_region_founds_and_recovers() { CHECK(host->publish(birth)); const auto life = host->state()->lives().front(); const auto genome = host->state()->archive().find(life.identity.genome); - CHECK(genome && genome->schema_version() == genome_schema_v3 && - genome->development_version() == 3); + CHECK(genome && genome->schema_version() == c.founder.genome_schema && + genome->development_version() == c.founder.development_version); const auto manifest = decode_manifest(checked_value(host->committed()).manifest); - CHECK(manifest && manifest->cellular_versions == cellular_v7_versions); + CHECK(manifest && manifest->cellular_versions == c.bundle); - // A restarted host recovers the rules-6 state from the v7 checkpoint. + // A restarted host recovers the state from its checkpoint. host->drain(); host.reset(); auto reopened = FilesystemObjectStore::open(env("PGHOST"), key, max_cellular_lives_bytes); @@ -797,7 +816,7 @@ void cellular_balance_region_founds_and_recovers() { auto restarted = CellularRegionHost::create(config(), connect, std::move(*reopened)); CHECK(restarted); host = std::move(*restarted); - CHECK(host->step().ready && host->state()->rules_version() == cellular_lives_balance_rules && + CHECK(host->step().ready && host->state()->rules_version() == c.rules && host->state()->lives().size() == 1 && host->state()->lives().front().identity == life.identity); host->drain(); @@ -1059,7 +1078,22 @@ void run_cellular_publication_tests() { cellular_mutation_publication_binds_results(); cellular_host_admits_mutation_choices(); cellular_bud_publishes_and_recovers(); - cellular_balance_region_founds_and_recovers(); + cellular_balance_region_founds_and_recovers({{9771, 1}, + CellularLivesProfile::balance, + evo::biology::primitive_founder_v2, + cellular_lives_balance_rules, + cellular_v7_versions, + 0xDC, + 0xA7, + 0x85}); + cellular_balance_region_founds_and_recovers({{9772, 1}, + CellularLivesProfile::reproduction, + evo::biology::primitive_founder_v3, + cellular_lives_reproduction_rules, + cellular_v8_versions, + 0xDE, + 0xB3, + 0x87}); cellular_death_is_final_and_account_restarts(); auto owner = connect_as(env("PGUSER")); const auto build = filled<32>(0xD9); diff --git a/tests/development_tests.cpp b/tests/development_tests.cpp index b7ca120..792e991 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, 4U, 99U}) { + for (const auto version : {0U, 5U, 99U}) { const auto missing = rules_for(version); CHECK(!missing && missing.error() == DevelopmentError::unsupported_rules); } auto source = draft(); - source.development_version = 4; + source.development_version = 5; 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 ba0fbfc..6acc986 100644 --- a/tests/genome_tests.cpp +++ b/tests/genome_tests.cpp @@ -351,10 +351,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 = 4; // Schema 3 exists since rules 6. + unknown.schema_version = 5; // Schema 4 exists since rules 7 (ADR-0137). reject(unknown, GenomeError::unsupported_version); auto bytes = Genome::create(founder())->encode(); - bytes[8] = 4; // Schema field; decode refuses before the checksum matters. + bytes[8] = 5; // 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 341db14..26beea3 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, 4U, 99U}) { + for (const auto version : {0U, 5U, 99U}) { const auto missing = metabolic_rules_for(version); CHECK(!missing && missing.error() == DevelopmentError::unsupported_rules); } auto source = draft(); - source.development_version = 4; + source.development_version = 5; const auto future = build(source); const auto refused = metabolic_budget(future, {1000, 0}, temperate); CHECK(!refused && refused.error() == DevelopmentError::unsupported_rules); @@ -534,6 +534,42 @@ void founder_v2_builds_the_same_cell_for_less_energy() { CHECK(*primitive_endowment() == *e1); // The default stays founder 1. } +// ADR-0137 (development 4): a bud is always half the body, and reproduction takes value / +// 2000 off its construction energy; the matter is never discounted. +void founder_v3_buds_more_cheaply_with_skill() { + const auto v2 = primitive_founder(1, 1, primitive_founder_v2); + const auto v3 = primitive_founder(1, 1, primitive_founder_v3); + CHECK(v2 && v3 && v3->schema_version() == 4 && v3->development_version() == 4); + const auto b2 = metabolic_budget(*v2, {1000, 0}, temperate); + const auto b3 = metabolic_budget(*v3, {1000, 0}, temperate); + CHECK(b2 && b3 && b2->body == b3->body && b2->phenotype == b3->phenotype); + const auto full = b2->reproduction_investment.energy.value; // Founders invest 500. + CHECK(b3->reproduction_investment.matter == b2->reproduction_investment.matter); + CHECK(b3->reproduction_investment.energy.value == full - full / 4); + const auto with_skill = [&](std::uint32_t reproduction) { + GenomeDraft draft; + draft.schema_version = genome_schema_v4; + draft.id = 2; + draft.origin_event = 1; + draft.development_version = 4; + for (const auto& record : v3->capabilities()) + draft.capabilities.push_back(record); + for (auto& record : draft.capabilities) + if (record.kind == Capability::reproduction) + record.parameter = reproduction; + const auto genome = Genome::create(draft); + CHECK(genome.has_value()); + const auto budget = metabolic_budget(genome.value_or(*v3), {1000, 0}, temperate); + CHECK(budget.has_value()); + return budget.value_or(*b3).reproduction_investment; + }; + // The bud stays half the body at any skill; full skill halves its energy. + CHECK(with_skill(100).matter == b3->reproduction_investment.matter); + CHECK(with_skill(1000).matter == b3->reproduction_investment.matter); + CHECK(with_skill(1000).energy.value == full - full / 2); + CHECK(with_skill(1).energy.value > with_skill(1000).energy.value); +} + int main() try { hand_calculated_budget(); construction_composes_each_compartment(); @@ -551,6 +587,7 @@ int main() try { a_genome_drives_a_feeding_tick(); development_v2_and_the_first_bud(); founder_v2_builds_the_same_cell_for_less_energy(); + founder_v3_buds_more_cheaply_with_skill(); std::cout << "PASS metabolic budgets, composition splits and genome-driven feeding\n"; return 0; } catch (...) { diff --git a/tests/mutation_tests.cpp b/tests/mutation_tests.cpp index 2bb806d..8d27943 100644 --- a/tests/mutation_tests.cpp +++ b/tests/mutation_tests.cpp @@ -1,3 +1,4 @@ +#include "evo/biology/founder.hpp" #include "evo/biology/mutation.hpp" #include @@ -314,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 = 4; + source.development_version = 5; const auto future = build(source); const auto empty = mutation_candidates(future, context(1)); CHECK(!empty && empty.error() == MutationError::no_candidates); @@ -325,7 +326,8 @@ void invalid_contexts_are_refused() { // a schema 1 lineage is never migrated by mutating, and a schema 2 one steps per second. // Schema 3 (rules 6) steps a third as far: 1/300 of the range. void successors_keep_their_parents_schema() { - 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_v4}) { auto source = draft(); source.schema_version = schema; source.capabilities.push_back( @@ -333,7 +335,8 @@ void successors_keep_their_parents_schema() { const auto parent = build(source); const auto step = schema == genome_schema_v1 ? 1'000U // 1/100 of the range. : schema == genome_schema_v2 ? 20'000U - : 6'666U; // 2,000,000 / 300. + : schema == genome_schema_v3 ? 6'666U // 2,000,000 / 300. + : 100'000U; // A tenth of 1,000,000. bool adjusted = false; // Offers are seeded; search seeds (deterministically) for the movement adjustment. @@ -356,6 +359,39 @@ void successors_keep_their_parents_schema() { } } +// ADR-0137 (schema 4): a step is a tenth of the current value, down as well as up, and an +// acquired capability starts at the founder's value instead of the schema minimum. +void schema_four_steps_by_percentage() { + const auto find = [](const Genome& parent, Capability target, MutationEffect effect) { + for (std::uint64_t seed = 1; seed <= 400; ++seed) { + const auto offered = mutation_candidates(parent, context(seed, 8)); + CHECK(offered); + for (const auto& candidate : offered->candidates) + if (candidate.target == target && candidate.effect == effect) { + const auto successor = select_mutation(parent, context(seed, 8), *offered, + candidate.operator_id, 99, 42); + CHECK(successor.has_value()); + return successor.value_or(parent); + } + } + throw std::runtime_error("no such candidate"); + }; + auto source = draft(); + source.schema_version = genome_schema_v4; + source.capabilities.push_back({Capability::movement, 200, 0}); + const auto swimmer = build(source); + CHECK(*find(swimmer, Capability::movement, MutationEffect::adjust_up) + .parameter(Capability::movement) == 220); + CHECK(*find(swimmer, Capability::movement, MutationEffect::adjust_down) + .parameter(Capability::movement) == 180); + source.capabilities.back().parameter = 5; // Below ten, a step is still 1. + CHECK(*find(build(source), Capability::movement, MutationEffect::adjust_up) + .parameter(Capability::movement) == 6); + source.capabilities.pop_back(); + const auto still = build(source); + CHECK(*find(still, Capability::movement, MutationEffect::acquire) + .parameter(Capability::movement) == primitive_founder_parameters.movement); +} void mutation_funding_is_exact_and_atomic() { const auto parent = build(draft()); const auto context_value = context(33, 8); @@ -415,6 +451,7 @@ int main() try { invalid_contexts_are_refused(); every_eligible_operator_is_offered_and_none_is_favoured(); successors_keep_their_parents_schema(); + schema_four_steps_by_percentage(); mutation_funding_is_exact_and_atomic(); std::cout << "PASS mutation catalog, uniform seeded offers and guarded selection\n"; return 0; diff --git a/tests/region_migration_tests.cpp b/tests/region_migration_tests.cpp index beb7c53..15d6cab 100644 --- a/tests/region_migration_tests.cpp +++ b/tests/region_migration_tests.cpp @@ -212,7 +212,7 @@ void upgrade_across_migration_and_barrier() { " EVO_PG_RUNTIME_ROLE=evo_runtime_test bash \"$EVO_SOURCE_ROOT/" "tools/migrate-postgres.sh\" > /dev/null") == 0); CHECK(history(*owner_db) == "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24," - "25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41"); + "25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42"); CHECK(scalar(*owner_db, "SELECT (c.condeferrable AND c.condeferred AND " "c.confrelid = 'evolution.region_commits'::regclass)::text " "FROM pg_catalog.pg_constraint c WHERE c.conrelid = " diff --git a/tests/region_store_tests.cpp b/tests/region_store_tests.cpp index 103bb68..0ca1952 100644 --- a/tests/region_store_tests.cpp +++ b/tests/region_store_tests.cpp @@ -586,6 +586,23 @@ void cellular_v5_provisioning_uses_the_balance_bundle() { manifest->history_profile == cellular_revision_history_profile); } +// ADR-0137: cellular-v6 is the rules-7 opening on the v8 bundle (schema v42). +void cellular_v6_provisioning_uses_the_reproduction_bundle() { + const ServerRegion r{{9773, 1}, fresh("cellular-v6-provision-9773")}; + const std::string build(64, 'e'); + const std::string commit = "b0d5ce5c0f7e1d2ba1a0ce5c0f7e1d2b"; // Unique to this test. + const std::string patch = "3000,3000,2,1000,1000,1000,1000,1000"; + int code = -1; + const auto first = provision_cellular(r, "9773", "cellular-v6", build, commit, patch, code); + CHECK(code == 0 && has(first, "provisioned world=9773 region=1 sequence=0 tick=0")); + auto db = owner(); + const auto head = load_region_checkpoint(*db, r.key, 5s); + CHECK(head); + const auto manifest = decode_manifest(head->manifest); + CHECK(manifest && manifest->cellular_versions == cellular_v8_versions && + manifest->history_profile == cellular_revision_history_profile); +} + void cellular_provisioning_survives_a_build_promotion() { const ServerRegion r{{9761, 1}, fresh("cellular-provision-9761")}; const auto run = [&](const std::string& build, const std::string& commit, @@ -620,6 +637,7 @@ void run_region_store_tests() { cellular_v3_provisioning_uses_the_budding_bundle(); cellular_v4_provisioning_uses_the_presence_bundle(); cellular_v5_provisioning_uses_the_balance_bundle(); + cellular_v6_provisioning_uses_the_reproduction_bundle(); full_volumes_publish_nothing(); failing_writes_leave_nothing(); check_store_qualifies_the_stores(); diff --git a/tools/ci/postgres-check.sh b/tools/ci/postgres-check.sh index 6657d4b..860be0a 100644 --- a/tools/ci/postgres-check.sh +++ b/tools/ci/postgres-check.sh @@ -122,7 +122,7 @@ PGDATABASE=upgrade_path psql -X -v ON_ERROR_STOP=1 -1 -v "migration_sha=$v1_sha" -f "$root/migrations/0001_region_bootstrap.sql" > /dev/null test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',') FROM evolution.schema_migrations")" = 1 PGDATABASE=upgrade_path bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41 +test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42 # v2 heads have no payload binding: v2->v3 fails closed and leaves history at v2. v2_sha="$(sha256sum "$root/migrations/0002_region_fencing.sql")" v2_sha="${v2_sha%% *}" @@ -143,7 +143,7 @@ PGDATABASE=v3_commits psql -X -v ON_ERROR_STOP=1 \ -c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \ -c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '01000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32), 'hex'))" > /dev/null PGDATABASE=v3_commits bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 41:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41 +test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 42:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42 test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) FROM evolution.region_commits")" = 1 # Review P1: a v4 database holding a published (possibly terminal) checkpoint has # no durable decisions for it. The v5 upgrade must refuse before changing anything. @@ -197,7 +197,7 @@ PGDATABASE=v6_populated psql -X -v ON_ERROR_STOP=1 \ -c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \ -c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '02000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32) || repeat('00', 80), 'hex'))" > /dev/null PGDATABASE=v6_populated bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41 +test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42 test "$(PGDATABASE=v6_populated psql -XAtc "SELECT count(*) FROM evolution.region_commits c, LATERAL evolution.parse_checkpoint_manifest(c.manifest) m WHERE m.commit_sequence = 0 AND m.predecessor_commit IS NULL")" = 1 test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(conname, ',') FROM pg_constraint WHERE conrelid = 'evolution.region_heads'::regclass AND contype = 'c' AND pg_get_constraintdef(oid) LIKE '%end_tick%'")" = region_heads_published_tick phase permission-audit @@ -250,9 +250,9 @@ expect_audit_failure 'REVOKE EXECUTE ON FUNCTION evolution.claim_account_control bash "$root/tools/migrate-postgres.sh" # Restored configuration passes the audit again. phase checksum-drift # Unknown future versions and checksum drift must not be repaired silently. -psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=42 WHERE version=41' +psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=43 WHERE version=42' if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi -psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=41 WHERE version=42" +psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=42 WHERE version=43" psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=14" if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=13" diff --git a/tools/migrate-postgres.sh b/tools/migrate-postgres.sh index cd95532..bacf671 100644 --- a/tools/migrate-postgres.sh +++ b/tools/migrate-postgres.sh @@ -94,6 +94,8 @@ digest_40="$(sha256sum "$root/migrations/0040_cellular_mutation_decline.sql")" digest_40="${digest_40%% *}" digest_41="$(sha256sum "$root/migrations/0041_cellular_v7_balance_bundle.sql")" digest_41="${digest_41%% *}" +digest_42="$(sha256sum "$root/migrations/0042_cellular_v8_reproduction_bundle.sql")" +digest_42="${digest_42%% *}" psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \ --set="migration_sha_2=$digest_2" --set="migration_sha_3=$digest_3" \ --set="migration_sha_4=$digest_4" --set="migration_sha_5=$digest_5" \ @@ -128,5 +130,6 @@ psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \ --set="migration_sha_39=$digest_39" \ --set="migration_sha_40=$digest_40" \ --set="migration_sha_41=$digest_41" \ + --set="migration_sha_42=$digest_42" \ --set="runtime_role=$runtime_role" \ --file="$root/migrations/apply.sql"