From a5307c768bf11cc4f23e03ac8c6c04681445feec Mon Sep 17 00:00:00 2001 From: dingo Date: Sun, 18 Oct 2026 21:48:27 -0400 Subject: [PATCH] feat(lifecycle): add opt-in funded cellular maturation --- CMakeLists.txt | 10 + README.md | 6 +- docs/STATUS.md | 17 + docs/adr/0157-funded-cellular-maturation.md | 65 +++ docs/biology/REPRODUCTION_MODEL.md | 12 + .../M12_EXACT_BIOLOGICAL_TRANSFER.md | 4 + docs/engineering/M12_REMAINING_GATES.md | 12 + docs/engineering/VALIDATION.md | 75 +++ include/evo/biology/metabolism.hpp | 5 +- include/evo/biology/mutation.hpp | 7 + .../evo/server/lifecycle/cellular_lives.hpp | 17 +- .../server/lifecycle/cellular_population.hpp | 3 + schemas/cellular-lives-v7.md | 25 +- schemas/cellular-population-batch.md | 6 + schemas/cellular-population.md | 7 + src/biology/metabolism.cpp | 6 +- src/biology/mutation.cpp | 13 +- src/server/lifecycle/cellular_lives.cpp | 89 +++- src/server/lifecycle/cellular_population.cpp | 17 +- .../lifecycle/cellular_population_batch.cpp | 3 +- tests/cellular_maturation_tests.cpp | 490 ++++++++++++++++++ tests/population_checkpoint_tests.cpp | 19 + 22 files changed, 889 insertions(+), 19 deletions(-) create mode 100644 docs/adr/0157-funded-cellular-maturation.md create mode 100644 tests/cellular_maturation_tests.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 85e0699..9e56937 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -685,6 +685,16 @@ endif() if(BUILD_TESTING) add_executable(evo-cellular-population-tests tests/cellular_population_tests.cpp) + add_executable(evo-cellular-maturation-tests tests/cellular_maturation_tests.cpp) + target_link_libraries(evo-cellular-maturation-tests PRIVATE evo::lifecycle) + evo_owned_target(evo-cellular-maturation-tests) + add_test(NAME cellular-funded-maturation COMMAND evo-cellular-maturation-tests) + set_tests_properties(cellular-funded-maturation PROPERTIES TIMEOUT ${evo_cohort_timeout}) + add_test(NAME cellular-maturation-process-restart COMMAND "${CMAKE_COMMAND}" + "-DPOPULATION_TEST=$" + "-DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/maturation-restart" + -P "${CMAKE_CURRENT_SOURCE_DIR}/tests/cellular_population_restart.cmake") + set_tests_properties(cellular-maturation-process-restart PROPERTIES TIMEOUT ${evo_cohort_timeout}) target_link_libraries(evo-cellular-population-tests PRIVATE evo::lifecycle) evo_owned_target(evo-cellular-population-tests) add_test(NAME cellular-population-transitions COMMAND evo-cellular-population-tests) diff --git a/README.md b/README.md index 61218e2..64d90c4 100644 --- a/README.md +++ b/README.md @@ -165,7 +165,11 @@ preserve exact identity/history and regional boundary budgets. Their scoped durable preparation/staging, atomic paired publication and verified recovery are implemented; [TLS transport fault checks](docs/engineering/M12_MIGRATION_TRANSPORT_FAULTS.md) cover independent local path loss and owner replacement. Linked ecology and -deployment qualification remain open. The microscope client is the M11 playtest path. +deployment qualification remain open. Portable opt-in +[rules-9 maturation](docs/adr/0157-funded-cellular-maturation.md) now funds real +juveniles through adulthood and budding in the same raw/cohort kernel; durable +admission and autonomous ecological qualification remain separate gates. +The microscope client is the M11 playtest path. `evo::simulation` remains graphics-, network- and database-independent. diff --git a/docs/STATUS.md b/docs/STATUS.md index 3cc4b8e..0617085 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,22 @@ # Project status and next steps +## Portable M12 funded maturation prerequisite - 2026-10-18 + +[ADR-0157](adr/0157-funded-cellular-maturation.md) adds opt-in rules-9 funded +growth to the exact raw/cohort kernel. A genuine finite-food bud reaches adulthood +and produces its own bud; construction preserves every stock, damage and genome. +The documented trial rate, blocked-expansion refusal, saved-choice funding, +newborn/offline exclusion, conversion and exact replay/process continuation pass. +Rules 8, DEV defaults and durable bundle admission retain their existing meaning. + +Native and GCC Release pass **81/81** each. Affected ASan/UBSan, including the final +offline/process guards, clang-tidy and formatting pass; detailed evidence and +fixture limits are in [validation](engineering/VALIDATION.md). Small juveniles' +pool nutrient rounding and sibling placement still constrain ecology. Durable +rules-9 admission/migration/census, automated generations, joint environmental +budgets, target-host costs, actual days and product gates remain open. This is a +portable prerequisite, not completion of M12. + ## M12.7c registered census pending handoff evidence - 2026-10-18 Schema 52 captures active biological migration pointers with history domain, diff --git a/docs/adr/0157-funded-cellular-maturation.md b/docs/adr/0157-funded-cellular-maturation.md new file mode 100644 index 0000000..128bf1b --- /dev/null +++ b/docs/adr/0157-funded-cellular-maturation.md @@ -0,0 +1,65 @@ +# ADR-0157: Opt-in funded cellular maturation + +## Status + +Accepted for the portable M12 ecology prerequisite, 2026-10-18. Extends +ADR-0031/0032/0120/0125/0128/0137/0139/0144. Trial parameters remain revisable; +this does not accept gameplay balance, durable admission or product readiness. + +## Decision + +Rules 9 explicitly opt an existing rules-8, format-7 owner into maturation. +The detached no-tick upgrade preserves every organism, archive, inventory, +presence, boundary flow and cohort tag. Only the biology rules field changes. +Format 7 already stores growth and all affected inventories. Population envelope +2 and recorded input formats need no new fields. Older readers reject rules 9; +rules 8 and its goldens retain their meaning. No default/DEV or SQL bundle changes. + +After old-size movement, maintenance, contact feeding, engulfment/death, selected +mutation, budding and presence changes, surviving active cells can construct at +most **5 realized thousandths per 50,000 microsecond tick** (100 per second). +This is an experimental rate, distinct from the development version's per-plan +bound. A newborn takes no growth step in its birth tick; frozen, lingering and +suspended cells do not grow. A resuming suspended cell starts growth on its next +active tick. Wildlife and controlled cells use the same construction rule. +A juvenile reaching adulthood can first request an admitted bud next tick. + +Use the existing channelwise affordable construction transition, additionally +capped by that rate. Pay its gross intake from retained reserve; release body +rounding matter back to reserve and send construction energy to world heat. +Recompute the resulting body from unchanged genome and new growth. Preserve +damage exactly: construction is not repair. There is no new resource source, +reserve grant, automatic mutation or sampled replacement organism. Checked +arithmetic and full owner closure precede publication; failure changes no state. + +Expanded squares retain their lower corner and expand toward positive axes. +In ascending stable life-ID order, require the whole proposed extent inside the +region and separated from every other present life, including lingering cells +and newborns. Suspended lives occupy no space. Earlier admitted expansions block +later ones. Refuse the proposed expansion without spending, relocation or trying +a smaller spatial step when blocked. This simple directional/contention bias is +explicit trial behavior, not a claim of physical growth geometry. + +Mutation offers remain the original deterministic draw with their recorded +context and displayed budget forecast. Selection validates that exact offer; +rules 9 then prices the selected successor at **current growth**, using retained +reserve. It neither redraws the candidate nor restores an obsolete juvenile body. +The old pure funding API retains recorded-growth behavior; an explicit new API +supports current-growth funding. Insufficient funds retain the offer as before. + +Successful growth reports the exact before/after growth and intake/release. +Final tick feedback reports the surviving cell's final reserve under rules 9. +Both representations and recorded unattended intervals execute the same kernel. + +## Qualification and limits + +Require channel and energy starvation, partial affordability, rounding and damage +checks; real funded founder -> juvenile -> adult -> offspring evidence; newborn +and offline exclusion; obstructed expansion with no spending; saved-choice funding +at changed growth; raw/cohort equivalence, conversion and midpoint restore/replay. +Tests must preserve old goldens and run under NDEBUG, ASan/UBSan and analysis. + +Rules-9 durable checkpoint admission, migration, registered census, environmental +coupling and client presentation require their own contract/qualification. Current +durable bundle allowlists continue to reject this rule. No actual-days soak, +deployment, World0 operation, extinction or M12 completion is inferred. diff --git a/docs/biology/REPRODUCTION_MODEL.md b/docs/biology/REPRODUCTION_MODEL.md index cdbb177..c15e43e 100644 --- a/docs/biology/REPRODUCTION_MODEL.md +++ b/docs/biology/REPRODUCTION_MODEL.md @@ -96,6 +96,18 @@ The maintainer accepted these for the first playable loop (2026-10-09): Fission, eggs, cohorts, spores, NPC mutation, and how long suspension is retained stay open. The values marked tunable are playtest hypotheses, not locked rules. +## Portable M12 maturation + +The portable M12 ecology prerequisite in +[ADR-0157](../adr/0157-funded-cellular-maturation.md) adds opt-in rules-9 funded +maturation to the cellular owner and exact cohorts. Genuine buds can spend their +own acquired nutrients and energy to reach adulthood, then fund their own buds. +The trial cap is 5 realized thousandths per 50 ms active tick, subject to exact +channel funding and expansion space; damage is retained. Newborn/offline cells +do not advance growth in that tick. Rules 8, DEV defaults and durable admission +remain unchanged. A scripted finite-food family proof is not evidence of +autonomous sustainable ecology, environmental coupling or actual-days operation. + ## Implemented M2.5 fixture boundary [ADR-0028](../adr/0028-funded-reproduction.md) implements funded budding inside diff --git a/docs/engineering/M12_EXACT_BIOLOGICAL_TRANSFER.md b/docs/engineering/M12_EXACT_BIOLOGICAL_TRANSFER.md index 409a03b..1ead355 100644 --- a/docs/engineering/M12_EXACT_BIOLOGICAL_TRANSFER.md +++ b/docs/engineering/M12_EXACT_BIOLOGICAL_TRANSFER.md @@ -40,6 +40,10 @@ ordering regression uses a real fully grown local founder reproducing alongside imported higher-namespace residents. Self-sustaining wildlife generations still need an explicit versioned maturation contract and ecological qualification. +ADR-0157 subsequently supplies opt-in portable rules-9 maturation with a funded +multi-generation family proof. These transfer contracts and durable bundle 10 +remain rules 8; they refuse rules-9 migration until separately qualified. + This is not the durable escrow gate. No prepared candidate may become an active destination owner before a future fenced transaction commits both heads and immutable transfer evidence. The source remains the sole owner until that commit; diff --git a/docs/engineering/M12_REMAINING_GATES.md b/docs/engineering/M12_REMAINING_GATES.md index 3f0d156..7fa9c75 100644 --- a/docs/engineering/M12_REMAINING_GATES.md +++ b/docs/engineering/M12_REMAINING_GATES.md @@ -99,6 +99,18 @@ not apply it. It is a concrete basis for a separately versioned funded maturatio contract that also resolves expanded-body collision, tick ordering and offline freeze. Its existence alone does not admit a new growth rule. +[ADR-0157](../adr/0157-funded-cellular-maturation.md) now implements that **portable +opt-in rules-9** prerequisite, preserving rules 8 and all default/live admission. +The exact construction transfer, bounded rate, spatial refusal, offline exclusion +and saved-choice funding are explicit. A real finite-food founder/bud reaches +funded adulthood and produces another bud, with paid sibling movement; raw/cohort +growth, conversion, recorded replay and separate-process continuation agree. +This is scripted biological evidence, not autonomous multi-generation ecological +qualification. Small juveniles can receive zero phosphorus per tick from a pool +because the existing quarter-yield rounds down; finite nutrient motes/contact and +space still matter. Durable rules-9 publication/migration/census, linked resources, +automatic wildlife robustness, balance and actual-days qualification remain open. + M12.6a's [regional census projection](../../schemas/ecology/regional-cellular-census-v1.md) independently implements local current-genome and descendant-closure queries. It keeps suspended stock and retained zero-carrier ancestry, separates exact cohort diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 4540eff..67b3bce 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -1,5 +1,80 @@ # Validation report +## 2026-10-18 - Portable M12 funded maturation prerequisite + +[ADR-0157](../adr/0157-funded-cellular-maturation.md) adds an explicit detached +rules-8/owner-7 -> rules-9 maturation candidate, including exact population tags. +The old owner formats, rules, golden vectors, default/DEV admission, SQL schema +52 and durable bundle allowlists are unchanged. Construction spends exact gross +reserve intake, returns body rounding releases and puts energy into world heat. +The trial cap is 5 realized thousandths per 50 ms active tick. Existing-size +actions finish first; newborn/offline cells do not construct. Fixed-corner +expansion must fit boundaries and all present neighbors, in stable life order. +Saved mutation choices keep their original draw and fund current-size bodies. + +Executed locally: + +- MSVC default Release full CTest **81/81 passed, 15.33 s**, with NDEBUG. +- GCC 14 Release full portable CTest **81/81 passed, 12.68 s**, with NDEBUG. +- Clang 19 ASan/UBSan affected development, uptake, habitat, step/region, owner, + metabolism, mutation, budding, maturation/process continuation, populations and + checkpoint-admission contracts **13/13 passed, 56.43 s**, without reports. + After adding the final discriminating controlled-subadult offline guard, both + maturation/process contracts passed again **2/2, 28.56 s**, without reports. +- Earlier in this same scope, the unchanged implementation's raw owner, mutation, + maturation, populations, census and migration contracts passed ASan/UBSan + **6/6, 103.80 s**, including the legacy rules-8 regression paths. +- clang-tidy 19 passed on both changed biology sources, all three changed + lifecycle sources and both test files. The final offline fixture passed a + separate analysis recheck. Repository clang-format 19 and `git diff --check` + passed. No old golden or numbered migration was replaced. + +The family test starts from a genuinely funded adult founder and its real bud, +never a fabricated adult wildlife record. With finite retained food and paid +sibling movement, that juvenile reaches adulthood and produces another bud at +**tick 27,901**, after **939 reported funded growth steps across the family**. +Every tick checks complete five-channel owner closure and each growth report's +exact reserve spending. Newborns have no growth report in their birth tick; +midpoint canonical restoration preserves continuation. This is accelerated, +scripted biological evidence, not autonomous sustainability or elapsed-day proof. + +Raw and cohort execution share the unchanged wildlife controller and produce +identical complete biological bytes for 1,024 growing ticks, including conversion +and repeated restoration. Recorded raw inputs and a full 64-tick population +interval decode/replay identically. A second executable process restores a growing +cohort and produces byte-identical 64-tick continuation. Population upgrade +preserves policy, tags and sequence. Rules-8 juveniles retain their original +growth. Valid rules-8 raw/population manifests accept their original payloads +and reject rules-9 payloads; an unadmitted rules-9 manifest bundle is unsupported. + +Geometry fault fixtures only relocate genuine funded juveniles, preserving all +stocks/identity/history. A region boundary and a frozen lingering neighbor each +refuse an otherwise funded extent increase without growth spending or movement. +A separate controlled-subadult offline fixture returns already-owned body matter +to reserve, leaves paid heat intact and grants no resource. Current founders are +born adult, so this artificial fixture tests the guard only, not the family proof. +Its active control demonstrably grows; freeze/linger/suspend preserve body, +growth, reserves and mutation progress. Suspended resume grows only on the next +active tick. Pure budget tests cover rate/zero caps, damage retention, partial +funding, each absent nutrient/energy channel and exact composed-body closure; +saved-offer tests preserve the original choice at changed growth and reject a +changed recorded context. + +The qualification exposed an existing ecological constraint: the smallest +juveniles can receive zero pool phosphorus per tick when quarter-yield floors +to zero. Contact with finite nutrient motes, placement and sibling space matter; +no feeding/balance rule was changed to conceal it. The family deliberately moves +a sibling through paid intentions. Automated multi-generation wildlife, +larger-cohort contention/tail cost and comparative ecological regimes remain open. + +This gate changes no PostgreSQL adapter, migration or runtime admission, so the +full private database/TLS/storage/backup/DR matrix was not rerun. Durable rules-9 +upgrade/publication/recovery, migration, registered census and client presentation +require separate admission/qualification. TSan was not rerun: no shared-memory +concurrency or scheduler ownership changed. Joint environmental budgets, actual +days, deployment-host evidence and product readiness remain open. No deployment, +World0 operation or terminal extinction decision occurred. + ## 2026-10-18 - M12.7c registered census pending handoff evidence [ADR-0156](../adr/0156-census-pending-migration-evidence.md)/schema 52 captures diff --git a/include/evo/biology/metabolism.hpp b/include/evo/biology/metabolism.hpp index 9dd2638..fbf5f64 100644 --- a/include/evo/biology/metabolism.hpp +++ b/include/evo/biology/metabolism.hpp @@ -55,8 +55,11 @@ struct MetabolicBudget { metabolic_rules_for(std::uint32_t development_version); // The single place the genome's description of capability becomes ledger // quantities. The genome record itself stays free of accounting types. +// max_growth_per_thousand caps this proposal, not a time rate; the caller owns +// its versioned cadence. The default preserves earlier budget results exactly. [[nodiscard]] std::expected -metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState environment); +metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState environment, + std::uint32_t max_growth_per_thousand = 1000); // An analysis, not a rule (ADR-0098 decision 7): whole seconds until feeding funds the // budget's reproduction investment, channel by channel and in energy, when the organism // takes in its full intake limit for `feeding_per_thousand` of the time and pays its diff --git a/include/evo/biology/mutation.hpp b/include/evo/biology/mutation.hpp index 6583e6c..800f9a6 100644 --- a/include/evo/biology/mutation.hpp +++ b/include/evo/biology/mutation.hpp @@ -88,4 +88,11 @@ select_mutation(const Genome& genome, const MutationContext& context, const Muta fund_mutation(const Genome& genome, const MutationContext& context, const MutationOffer& offered, std::uint16_t chosen, std::uint64_t successor_id, std::uint64_t origin_event, const accounting::Inventory& reserve); +// ADR-0157: preserve and validate the original draw, but fund its selected genome +// at the organism's current growth. No redraw or reset to the offer's old body. +[[nodiscard]] std::expected +fund_mutation_at_growth(const Genome& genome, const MutationContext& context, + const MutationOffer& offered, std::uint16_t chosen, + std::uint64_t successor_id, std::uint64_t origin_event, + const accounting::Inventory& reserve, GrowthState current_growth); } // namespace evo::biology diff --git a/include/evo/server/lifecycle/cellular_lives.hpp b/include/evo/server/lifecycle/cellular_lives.hpp index 408029c..aa1574b 100644 --- a/include/evo/server/lifecycle/cellular_lives.hpp +++ b/include/evo/server/lifecycle/cellular_lives.hpp @@ -43,8 +43,11 @@ inline constexpr std::uint32_t cellular_lives_reproduction_rules = 7; // carries the new state, so they keep owner format 6. inline constexpr std::uint32_t cellular_lives_foraging_rules = 8; // ADR-0144: opt-in boundary accounting and retained nonresident history. Biology -// remains rules 8; every earlier envelope retains its original meaning. +// starts on rules 8; every earlier envelope retains its original meaning. inline constexpr std::uint32_t cellular_lives_migration_format = 7; +// ADR-0157: opt-in funded maturation, using the unchanged format-7 fields. +inline constexpr std::uint32_t cellular_lives_maturation_rules = 9; +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 { @@ -158,10 +161,17 @@ struct CellularBudExecution { CellularBudResult result{}; auto operator<=>(const CellularBudExecution&) const = default; }; +struct CellularGrowthExecution { + std::uint64_t life_id{}; + biology::GrowthState before{}, after{}; + accounting::Inventory intake{}, release{}; + auto operator<=>(const CellularGrowthExecution&) const = default; +}; struct CellularTickExecution { biology::CellularRegionStepCandidate step; std::vector mutations; - std::vector buds; // Rules 4, in parent life order. + std::vector buds; // Rules 4, in parent life order. + std::vector growth; // Rules 9: funded expansions only, life order. }; struct CellularLifeTickFeedback { std::uint64_t life_id{}, tick{}; @@ -253,6 +263,9 @@ class CellularLives { // Explicit detached format-6/rules-8 -> format-7 upgrade. No biology advances. [[nodiscard]] std::expected, CellularLivesError> migration_upgrade_candidate() const; + // ADR-0157: detached no-tick rules-8/format-7 -> rules-9 candidate. No grant. + [[nodiscard]] std::expected, CellularLivesError> + maturation_upgrade_candidate() const; // Latest successful in-memory step report; omitted from snapshots and empty after restore. [[nodiscard]] std::span last_tick_feedback() const noexcept; [[nodiscard]] std::vector snapshot() const; diff --git a/include/evo/server/lifecycle/cellular_population.hpp b/include/evo/server/lifecycle/cellular_population.hpp index 86f7043..ea6a4bf 100644 --- a/include/evo/server/lifecycle/cellular_population.hpp +++ b/include/evo/server/lifecycle/cellular_population.hpp @@ -53,6 +53,9 @@ class CellularPopulation { // Explicit no-tick envelope-1 -> envelope-2 upgrade, retaining all cohort tags. [[nodiscard]] std::expected, CellularPopulationError> migration_upgrade_candidate() const; + // ADR-0157: preserve exact membership while upgrading nested biology to rules 9. + [[nodiscard]] std::expected, CellularPopulationError> + maturation_upgrade_candidate() const; [[nodiscard]] std::vector snapshot() const; [[nodiscard]] static std::expected, CellularPopulationError> restore(std::span bytes, std::uint64_t world, std::uint64_t region, diff --git a/schemas/cellular-lives-v7.md b/schemas/cellular-lives-v7.md index 5672c43..932768b 100644 --- a/schemas/cellular-lives-v7.md +++ b/schemas/cellular-lives-v7.md @@ -1,13 +1,14 @@ # Cellular owner format 7: exact boundary accounting -Authority: ADR-0144. Portable opt-in representation only; no PostgreSQL manifest -bundle or live worker admission is introduced by this segment. Rules stay 8. +Authority: ADR-0144, with opt-in maturation in ADR-0157. Rules 8 retain their +meaning; the additional rules-9 interpretation is portable only. Durable bundle +10 still admits rules 8 exclusively; no live worker opts into maturation. Formats 1–6 and their canonical bytes remain unchanged. Explicit no-tick upgrade from rules-8 format 6 preserves biology and opening stock and adds zero flows and no nonresident references. No downgrade may discard a nonzero ledger. -Little-endian, no native padding. Magic `AEVCLV07`, format 7, rules 8. The first -220 bytes have the format-6 layout except magic/format. The additional fields are: +Little-endian, no native padding. Magic `AEVCLV07`, format 7, rules 8 or 9. The first +220 bytes have the format-6 layout except magic/format/rules. The additional fields are: | Offset | Bytes | Field | |---:|---:|---| @@ -56,3 +57,19 @@ automatic spatial crossings and linked environmental fields are unimplemented. Durability must bind both candidates to one fenced atomic pair publication. This format alone supplies no freeze, escrow, receipt, activation or retry guarantee. + +## Rules 9: funded maturation + +ADR-0157's explicit no-tick upgrade from rules 8 changes only the rules field and +checksum, preserving this entire layout and all stocks/flows/history. The retained +growth, body, reserve and world heat fields encode every maturation effect. At +most 5 realized thousandths per 50 ms active tick are constructed after old-size +actions, budding and presence changes. Newborn/frozen/suspended cells do not grow; +a suspended resume begins growth next tick. Expanded squares retain their corner +and must fit every present neighbor/boundary, in ascending life-ID order. A blocked +expansion spends nothing. Damage and immutable genomes are preserved. + +Saved mutation offers retain their original draw/context; rules 9 fund the chosen +successor at current growth. No context/body reset is encoded. Unknown rules fail +closed; rules 9 in owner format 6 are refused. Biological migration and durable +rules-9 admission remain unsupported pending their separate qualification. diff --git a/schemas/cellular-population-batch.md b/schemas/cellular-population-batch.md index 05b18a0..d3f6d32 100644 --- a/schemas/cellular-population-batch.md +++ b/schemas/cellular-population-batch.md @@ -64,6 +64,12 @@ validator and schema 45's SQL trace checker admit only batch 1. A new durable bundle/upgrade and exact history/recovery contract remain required before any publication, scheduling or transfer activation can use the new representation. +ADR-0157 also allows portable batch 2 replay against envelope 2/owner 7/rules 9. +Recorded intentions are unchanged; the bound predecessor's explicit rules field +selects maturation. Both raw and cohort replay perform the same funded growth +and preserve exact member tags and stocks. This is not durable rules-9 admission; +the rules-8 bundle allowlist remains unchanged. + M12.4g/schema 46 adds the dedicated bundle-9 to 10 upgrade and full recovery contract. Bundle 10 admits batch 2 for ordinary intervals and manual conversion; bundle 9 still refuses it and remains bound to batch 1. Actual SHA-256 and wire diff --git a/schemas/cellular-population.md b/schemas/cellular-population.md index 00db8fd..389b3f0 100644 --- a/schemas/cellular-population.md +++ b/schemas/cellular-population.md @@ -57,3 +57,10 @@ history 5 in schema 46. An explicit no-tick version upgrade retains membership, policy and conversion sequence through the immutable version-upgrade journal. Ordinary publication requires population batch 2; profile transitions preserve bundle 10. No worker upgrades automatically and no paired migration is published. + +ADR-0157 additionally permits **portable** envelope 2 to contain owner 7/rules 9. +The nested owner identifies the changed growth semantics; no membership, policy, +sequence or wire-layout change is needed. An explicit no-tick maturation candidate +preserves all tags and upgrades only the nested rules. Both representations use +the same funded-growth kernel. Envelope 1 remains rules 8. Durable bundle 10 +remains rules 8 and does not admit this portable maturation upgrade. diff --git a/src/biology/metabolism.cpp b/src/biology/metabolism.cpp index 332defc..75ce948 100644 --- a/src/biology/metabolism.cpp +++ b/src/biology/metabolism.cpp @@ -117,7 +117,8 @@ metabolic_rules_for(std::uint32_t development_version) { } std::expected -metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState environment) { +metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState environment, + std::uint32_t max_growth_per_thousand) { const auto phenotype = derive_phenotype(genome, growth, environment); if (!phenotype) { return std::unexpected{phenotype.error()}; @@ -164,7 +165,8 @@ metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState envi // intake fits channel by channel. budget.construction.after = growth; const auto proposed = plan->after.realized_per_thousand - growth.realized_per_thousand; - for (std::uint32_t attempt = proposed; attempt > 0; --attempt) { + for (std::uint32_t attempt = std::min(proposed, max_growth_per_thousand); attempt > 0; + --attempt) { const GrowthState candidate{growth.realized_per_thousand + attempt, growth.damage_per_thousand}; const auto grown = derive_phenotype(genome, candidate, environment); diff --git a/src/biology/mutation.cpp b/src/biology/mutation.cpp index 2de4cf6..656b7b4 100644 --- a/src/biology/mutation.cpp +++ b/src/biology/mutation.cpp @@ -249,13 +249,22 @@ std::expected fund_mutation(const Genome& genome, const MutationContext& context, const MutationOffer& offered, std::uint16_t chosen, std::uint64_t successor_id, std::uint64_t origin_event, const accounting::Inventory& reserve) { + return fund_mutation_at_growth(genome, context, offered, chosen, successor_id, origin_event, + reserve, context.growth); +} + +std::expected +fund_mutation_at_growth(const Genome& genome, const MutationContext& context, + const MutationOffer& offered, std::uint16_t chosen, + std::uint64_t successor_id, std::uint64_t origin_event, + const accounting::Inventory& reserve, GrowthState current_growth) { const auto successor = select_mutation(genome, context, offered, chosen, successor_id, origin_event); if (!successor) { return std::unexpected{successor.error()}; } - const auto before = metabolic_budget(genome, context.growth, context.environment); - const auto after = metabolic_budget(*successor, context.growth, context.environment); + const auto before = metabolic_budget(genome, current_growth, context.environment); + const auto after = metabolic_budget(*successor, current_growth, context.environment); const auto rules = rules_for(genome.development_version()); if (!before || !after || !rules) { return std::unexpected{MutationError::development}; diff --git a/src/server/lifecycle/cellular_lives.cpp b/src/server/lifecycle/cellular_lives.cpp index 72116b9..fc7ee5b 100644 --- a/src/server/lifecycle/cellular_lives.cpp +++ b/src/server/lifecycle/cellular_lives.cpp @@ -711,6 +711,17 @@ std::expected, CellularLivesError> CellularLives::migration_upgrade_candidate() const { return migration_replacement(state_->lives, state_->archive, state_->boundary); } +std::expected, CellularLivesError> +CellularLives::maturation_upgrade_candidate() const { + if (state_->format_version != cellular_lives_migration_format || + state_->rules_version != cellular_lives_foraging_rules) + return std::unexpected(CellularLivesError::version); + auto candidate = restore(snapshot(), world(), region(), frame(), tick()); + if (!candidate) + return std::unexpected(candidate.error()); + (*candidate)->state_->rules_version = cellular_lives_maturation_rules; + return candidate; +} std::span CellularLives::last_tick_feedback() const noexcept { return last_tick_feedback_; } @@ -1091,7 +1102,8 @@ CellularLives::restore(std::span bytes, std::uint64_t world, // Format 6 carries rules 5, 6 (founder 2) or 7 (founder 3, ADR-0137); no new state. const bool migration_version = magic == cellular_lives_v7_magic && format_version == cellular_lives_migration_format && - rules_version == cellular_lives_foraging_rules; + (rules_version == cellular_lives_foraging_rules || + rules_version == cellular_lives_maturation_rules); const bool presence_version = migration_version || (magic == cellular_lives_v6_magic && format_version == cellular_lives_presence_format && @@ -1564,9 +1576,11 @@ CellularLives::advance_tick_with_mutations(std::span i continue; } const auto offer = found->mutation.offer.value_or(biology::MutationOffer{}); - auto transition = - biology::fund_mutation(*parent, offer.context, offer, selection.operator_id, - selection.successor_id, selection.successor_id, found->reserve); + auto transition = biology::fund_mutation_at_growth( + *parent, offer.context, offer, selection.operator_id, selection.successor_id, + selection.successor_id, found->reserve, + state_->rules_version >= cellular_lives_maturation_rules ? found->growth + : offer.context.growth); if (!transition) { if (transition.error() == biology::MutationError::insufficient_funding) { mutation_results.push_back({selection.life_id, selection.successor_id, @@ -1732,6 +1746,69 @@ CellularLives::advance_tick_with_mutations(std::span i } } } + // ADR-0157: old-size actions finish first. A newborn, frozen life or a life + // resuming from suspension did not take an active step and cannot grow here. + // Expansion holds the existing lower corner fixed; earlier IDs claim space first. + std::vector growth_results; + if (state_->rules_version == cellular_lives_maturation_rules) { + for (auto& life : next_lives) { + const auto input = std::ranges::lower_bound(ordered, life.identity.life, {}, + &CellularLifeIntent::life_id); + const auto previous = + std::ranges::lower_bound(state_->lives, life.identity.life, {}, + [](const auto& old) { return old.identity.life; }); + if (input == ordered.end() || input->life_id != life.identity.life || + input->intent.frozen || life.presence != CellularPresence::active || + previous == state_->lives.end() || previous->identity.life != life.identity.life || + previous->presence == CellularPresence::suspended || + life.growth.realized_per_thousand == 1000) + continue; + const auto genome = next_archive.find(life.identity.genome); + if (!genome) + return std::unexpected(CellularLivesError::archive); + const auto budget = biology::metabolic_budget( + *genome, life.growth, + {state_->config.ambient_temperature_millikelvin, life.reserve}, + cellular_growth_per_tick); + if (!budget || budget->body != life.body) + return std::unexpected(CellularLivesError::biology); + const auto& move = budget->construction; + if (move.after == life.growth) + continue; + const auto grown = biology::metabolic_budget( + *genome, move.after, {state_->config.ambient_temperature_millikelvin, {}}); + if (!grown) + return std::unexpected(CellularLivesError::biology); + const auto extent = grown->phenotype.extent; + bool clear = extent <= state_->config.area.width_um && + extent <= state_->config.area.height_um && + life.position.x_um <= state_->config.area.width_um - extent && + life.position.y_um <= state_->config.area.height_um - extent; + for (const auto& other : next_lives) { + if (!clear || other.identity.life == life.identity.life || + other.presence == CellularPresence::suspended) + continue; + const auto obstacle = + budget_for(next_archive, other, state_->config.ambient_temperature_millikelvin); + if (!obstacle) + return std::unexpected(obstacle.error()); + clear = separated(life.position.x_um, other.position.x_um, extent, + obstacle->phenotype.extent) || + separated(life.position.y_um, other.position.y_um, extent, + obstacle->phenotype.extent); + } + if (!clear) + continue; // No partial spatial retry, relocation or spending. + if (!subtract_inventory(life.reserve, move.intake) || + !add_inventory(life.reserve, move.release) || + !add_inventory(next_heat, accounting::Inventory{move.intake.energy, {}})) + return std::unexpected(CellularLivesError::overflow); + growth_results.push_back( + {life.identity.life, life.growth, move.after, move.intake, move.release}); + life.growth = move.after; + life.body = grown->body; + } + } std::ranges::sort(next_corpses, {}, &CellularOwnedCorpse::organism); if (proposal->heat_released.value > std::numeric_limits::max() - next_heat.energy.value) @@ -1829,6 +1906,8 @@ CellularLives::advance_tick_with_mutations(std::span i entry = std::prev(feedback.end()); } entry->presence = life.presence; + if (state_->rules_version == cellular_lives_maturation_rules) + entry->reserve = life.reserve; // Includes funded growth/mutation/budding. entry->resume_blocked = std::ranges::find(resume_blocked, life.identity.life) != resume_blocked.end(); } @@ -1836,6 +1915,6 @@ CellularLives::advance_tick_with_mutations(std::span i state_.swap(next); last_tick_feedback_ = std::move(feedback); return CellularTickExecution{std::move(*proposal), std::move(mutation_results), - std::move(bud_results)}; + std::move(bud_results), std::move(growth_results)}; } } // namespace evo::server diff --git a/src/server/lifecycle/cellular_population.cpp b/src/server/lifecycle/cellular_population.cpp index 5605d56..c3d4046 100644 --- a/src/server/lifecycle/cellular_population.cpp +++ b/src/server/lifecycle/cellular_population.cpp @@ -14,7 +14,10 @@ CellularPopulation::CellularPopulation(std::unique_ptr state, std::expected, CellularPopulationError> CellularPopulation::create(std::unique_ptr state, CellularTierPolicy policy) { - if (!state || state->rules_version() != cellular_lives_foraging_rules || + if (!state || + (state->rules_version() != cellular_lives_foraging_rules && + !(state->rules_version() == cellular_lives_maturation_rules && + state->format_version() == cellular_lives_migration_format)) || (state->format_version() != cellular_lives_presence_format && state->format_version() != cellular_lives_migration_format) || policy.materialize_radius_um == 0 || @@ -53,6 +56,18 @@ CellularPopulation::migration_upgrade_candidate() const { (*candidate)->conversion_sequence_ = conversion_sequence_; return candidate; } +std::expected, CellularPopulationError> +CellularPopulation::maturation_upgrade_candidate() const { + auto biological = state_->maturation_upgrade_candidate(); + if (!biological) + return std::unexpected(CellularPopulationError::unsupported); + auto candidate = create(std::move(*biological), policy_); + if (!candidate) + return std::unexpected(candidate.error()); + (*candidate)->members_ = members_; + (*candidate)->conversion_sequence_ = conversion_sequence_; + return candidate; +} std::expected CellularPopulation::collapse(std::uint64_t genome) { auto candidate = members_; diff --git a/src/server/lifecycle/cellular_population_batch.cpp b/src/server/lifecycle/cellular_population_batch.cpp index 880dc2a..f525b2d 100644 --- a/src/server/lifecycle/cellular_population_batch.cpp +++ b/src/server/lifecycle/cellular_population_batch.cpp @@ -77,7 +77,8 @@ class Reader { } // namespace bool population_interval_safe(const CellularLives& state) noexcept { - return state.rules_version() == cellular_lives_foraging_rules && + return (state.rules_version() == cellular_lives_foraging_rules || + state.rules_version() == cellular_lives_maturation_rules) && std::ranges::all_of(state.lives(), [](const auto& life) { return life.account == LifeAccount{} || life.presence == CellularPresence::suspended; }); diff --git a/tests/cellular_maturation_tests.cpp b/tests/cellular_maturation_tests.cpp new file mode 100644 index 0000000..fb335e7 --- /dev/null +++ b/tests/cellular_maturation_tests.cpp @@ -0,0 +1,490 @@ +#include "evo/biology/budding.hpp" +#include "evo/server/lifecycle/cellular_population_batch.hpp" +#include "fixtures/cellular_ecology.hpp" + +#include +#include + +namespace { +using namespace evo; +using namespace evo::server; +using namespace evo::fixture; + +Inventory stocked(std::uint64_t amount = 1'000'000'000'000ULL) { + Inventory result{{amount}, {}}; + for (auto& channel : result.matter) + channel.value = amount; + return result; +} +void construction_and_saved_choices() { + const auto genome = + checked(biology::primitive_founder(1, 1, biology::primitive_founder_v3), "growth genome"); + const biology::GrowthState start{400, 37}; + const biology::EnvironmentState environment{293'150, stocked()}; + const auto budget = + checked(biology::metabolic_budget(genome, start, environment, 5), "growth cap"); + require(budget.construction.after == biology::GrowthState{405, 37}, + "growth cap/damage changed"); + require(checked(biology::metabolic_budget(genome, start, environment, 0), "zero cap") + .construction.after == start, + "zero cap grew"); + for (std::size_t channel = 0; channel < 5; ++channel) { + auto available = environment; + if (channel == 0) + available.available.energy.value = 0; + else + available.available.matter[channel - 1].value = 0; + require(checked(biology::metabolic_budget(genome, start, available, 5), "starved growth") + .construction.after == start, + "missing nutrient/energy still grew"); + } + const auto one = checked(biology::metabolic_budget(genome, start, environment, 1), "one step"); + auto limited = environment; + limited.available = one.construction.intake; + require(checked(biology::metabolic_budget(genome, start, limited, 5), "partial funds") + .construction.after == one.construction.after, + "partial funding did not choose largest affordable step"); + const auto grown = + checked(biology::metabolic_budget(genome, budget.construction.after, environment), + "derived grown body"); + for (std::size_t channel = 0; channel < 4; ++channel) + require(budget.body.matter[channel].value + + budget.construction.intake.matter[channel].value == + grown.body.matter[channel].value + + budget.construction.release.matter[channel].value, + "construction channel did not close"); + + const biology::MutationContext context{17, 2, 1, 8, start, environment}; + const auto offer = checked(biology::mutation_candidates(genome, context), "saved offer"); + const biology::GrowthState current{700, 37}; + for (const auto& choice : offer.candidates) { + const auto transition = + checked(biology::fund_mutation_at_growth(genome, context, offer, choice.operator_id, 2, + 2, stocked(), current), + "current-size choice"); + const auto expected = + checked(biology::metabolic_budget(transition.successor, current, environment), + "current-size body"); + require(transition.body == expected.body, "saved choice restored obsolete body"); + require(transition.successor == checked(biology::select_mutation(genome, context, offer, + choice.operator_id, 2, 2), + "original draw"), + "growth rerolled choice"); + const auto old = checked( + biology::fund_mutation(genome, context, offer, choice.operator_id, 2, 2, stocked()), + "legacy choice"); + require(old.body != transition.body, "current-growth fixture is not discriminating"); + auto changed = context; + changed.growth = current; + require(!biology::fund_mutation_at_growth(genome, changed, offer, choice.operator_id, 2, 2, + stocked(), current), + "changed offer context accepted"); + } +} + +std::vector idle(const CellularLives& state, bool freeze = false, + std::uint64_t bud = 0) { + std::vector result; + for (const auto& life : state.lives()) { + CellularLifeIntent intent{life.identity.life, {}}; + intent.intent.frozen = freeze && life.account != LifeAccount{}; + intent.intent.bud = life.identity.life == bud && !intent.intent.frozen; + result.push_back(intent); + } + return result; +} +Owner upgraded(Owner state) { + require(!state->maturation_upgrade_candidate(), "format 6 bypassed explicit boundary upgrade"); + auto boundary = checked(state->migration_upgrade_candidate(), "boundary upgrade"); + const auto before = boundary->snapshot(); + auto result = checked(boundary->maturation_upgrade_candidate(), "growth upgrade"); + require(boundary->snapshot() == before && result->tick() == boundary->tick() && + result->current_total() == boundary->current_total() && + std::ranges::equal(result->lives(), boundary->lives()), + "upgrade changed biology"); + require(!result->maturation_upgrade_candidate() && !result->migration_upgrade_candidate(), + "unsupported upgrade admitted"); + return result; +} +struct Family { + Owner state; + std::uint64_t child{}; +}; +Family first_bud(bool maturation) { + auto state = opening(7, true, 1); + if (maturation) + state = upgraded(std::move(state)); + for (unsigned tick = 0; tick < 12'000; ++tick) { + const auto executed = checked( + state->advance_tick_with_mutations(idle(*state, false, tick % 100 == 99 ? 100 : 0), {}), + "first funded bud tick"); + for (const auto& bud : executed.buds) { + if (bud.result != CellularBudResult::budded) + continue; + const auto child = std::ranges::find( + state->lives(), bud.bud_life, [](const auto& life) { return life.identity.life; }); + require(child != state->lives().end() && child->growth.realized_per_thousand < 1000 && + child->account == LifeAccount{}, + "bud is not a genuine juvenile"); + require(std::ranges::none_of( + executed.growth, + [&](const auto& growth) { return growth.life_id == bud.bud_life; }), + "newborn grew in birth tick"); + return {std::move(state), bud.bud_life}; + } + } + throw std::runtime_error("finite feeding never funded the first bud"); +} +// Geometry-only codec fixture: retain real funded biology, identities and all +// five stocks. This is a placement fault seam, never an adult/resource shortcut. +Owner relocated(const CellularLives& state, std::uint64_t id, biology::CellularPosition position) { + auto bytes = state.snapshot(); + const auto index = static_cast( + std::ranges::find(state.lives(), id, [](const auto& life) { return life.identity.life; }) - + state.lives().begin()); + require(index < state.lives().size() && state.format_version() == 7, "relocation fixture"); + const auto put = [&](std::size_t at, std::uint64_t value) { + for (unsigned shift = 0; shift < 8; ++shift) + bytes[at + shift] = static_cast(value >> (shift * 8U)); + }; + std::uint32_t sites = 0; + for (unsigned shift = 0; shift < 4; ++shift) + sites |= std::uint32_t{bytes[60 + shift]} << (shift * 8U); + const auto row = 308 + sites * 8 + index * 504; + put(row + 72, position.x_um); + put(row + 80, position.y_um); + std::uint64_t hash = 14695981039346656037ULL; + for (const auto byte : std::span{bytes}.first(bytes.size() - 8)) + hash = (hash ^ byte) * 1099511628211ULL; + put(bytes.size() - 8, hash); + return checked( + CellularLives::restore(bytes, state.world(), state.region(), state.frame(), state.tick()), + "geometry fixture restore"); +} +void frozen_construction() { + auto family = first_bud(false); + auto state = upgraded(std::move(family.state)); + const auto founder = state->lives().front(); + const auto genome = checked(state->archive().find(founder.identity.genome), "frozen genome"); + const biology::GrowthState juvenile{400, 0}; + const auto body = + checked(biology::metabolic_budget(genome, juvenile, {293150, {}}), "frozen body").body; + auto bytes = state->snapshot(); + const auto put = [&](std::size_t at, std::uint64_t value, unsigned width = 8) { + for (unsigned shift = 0; shift < width; ++shift) + bytes[at + shift] = static_cast(value >> (shift * 8U)); + }; + // Offline-guard fixture only: a controlled subadult is not produced by the + // current adult-founder flow. Return already-owned body matter to its reserve; + // grant no stock/energy and leave the paid construction heat in the world. + constexpr std::size_t row = 308 + 8; // One site, first life, format 7. + put(row + 64, juvenile.realized_per_thousand, 4); + for (std::size_t channel = 0; channel < 4; ++channel) { + put(row + 96 + channel * 8, body.matter[channel].value); + put(row + 136 + channel * 8, founder.reserve.matter[channel].value + + founder.body.matter[channel].value - + body.matter[channel].value); + } + std::uint64_t hash = 14695981039346656037ULL; + for (const auto byte : std::span{bytes}.first(bytes.size() - 8)) + hash = (hash ^ byte) * 1099511628211ULL; + put(bytes.size() - 8, hash); + state = checked(CellularLives::restore(bytes, state->world(), state->region(), state->frame(), + state->tick()), + "controlled subadult guard fixture"); + const auto held = state->lives().front(); + auto active = restore(*state); + const auto active_tick = + checked(active->advance_tick_with_mutations(idle(*active), {}), "active subadult"); + require(std::ranges::any_of(active_tick.growth, + [](const auto& value) { return value.life_id == 100; }), + "offline fixture could not otherwise grow"); + for (unsigned tick = 0; tick <= cellular_linger_ticks; ++tick) { + checked(state->advance_tick(idle(*state, true)), "frozen subadult"); + const auto& frozen = state->lives().front(); + require(frozen.growth == held.growth && frozen.body == held.body && + frozen.reserve == held.reserve && frozen.mutation == held.mutation, + "frozen subadult advanced biology"); + } + require(state->lives().front().presence == CellularPresence::suspended, + "subadult did not suspend"); + state = restore(*state); + const auto resumed = + checked(state->advance_tick_with_mutations(idle(*state), {}), "subadult resume"); + require(state->lives().front().presence == CellularPresence::active && + state->lives().front().growth == held.growth && + std::ranges::none_of(resumed.growth, + [](const auto& value) { return value.life_id == 100; }), + "suspended resume constructed in its first tick"); + const auto next = + checked(state->advance_tick_with_mutations(idle(*state), {}), "resumed growth"); + require( + std::ranges::any_of(next.growth, [](const auto& value) { return value.life_id == 100; }), + "resumed active life failed to grow"); +} +void obstructed_expansion() { + auto family = first_bud(false); + for (unsigned tick = 0; tick < 3000; ++tick) + checked(family.state->advance_tick(idle(*family.state)), "finite juvenile feeding"); + auto state = upgraded(std::move(family.state)); + state = relocated(*state, family.child, {2000, 2000}); + for (unsigned tick = 0; tick < 200; ++tick) { + auto clear = restore(*state); + const auto before = *std::ranges::find(state->lives(), family.child, + [](const auto& life) { return life.identity.life; }); + const auto genome = + checked(state->archive().find(before.identity.genome), "geometry genome"); + const auto old_extent = + checked(biology::derive_phenotype(genome, before.growth, {293150, {}}), "old geometry") + .extent; + const auto trial = + checked(clear->advance_tick_with_mutations(idle(*clear, true), {}), "clear growth"); + const auto grown = + std::ranges::find(trial.growth, family.child, &CellularGrowthExecution::life_id); + if (grown != trial.growth.end() && + checked(biology::derive_phenotype(genome, grown->after, {293150, {}}), + "expanded geometry") + .extent > old_extent) { + for (const auto position : {biology::CellularPosition{48000 - old_extent, 2000}, + biology::CellularPosition{1000 - old_extent, 1000}}) { + auto blocked = relocated(*state, family.child, position); + const auto executed = + checked(blocked->advance_tick_with_mutations(idle(*blocked, true), {}), + "obstructed growth"); + const auto after = + std::ranges::find(blocked->lives(), family.child, + [](const auto& life) { return life.identity.life; }); + const auto step = std::ranges::find(executed.step.lives, family.child, + &biology::CellularLifeStepResult::life_id); + require(after != blocked->lives().end() && after->growth == before.growth && + after->body == before.body && after->position == position && + step != executed.step.lives.end() && + after->reserve == step->candidate.reserve_after && + std::ranges::none_of( + executed.growth, + [&](const auto& value) { return value.life_id == family.child; }), + "blocked expansion spent, moved or grew"); + require(restore(*blocked)->snapshot() == blocked->snapshot(), + "blocked restore differs"); + } + return; + } + state = std::move(clear); + } + throw std::runtime_error("geometry fixture never exercised a funded extent increase"); +} +void funded_generations() { + auto family = first_bud(true); + auto& state = family.state; + const auto opening_total = state->opening_total(); + bool adult = false; + std::size_t growth_count = 0; + for (unsigned tick = 0; tick < 24'000; ++tick) { + auto intentions = idle(*state, true, tick % 100 == 99 ? family.child : 0); + // Separate the real bud from a possible twin using paid movement. + if (tick < 20) + for (auto& intent : intentions) + if (intent.life_id != family.child && intent.life_id != 100) + intent.intent.movement = {0, 1000}; + const auto executed = + checked(state->advance_tick_with_mutations(intentions, {}), "funded family tick"); + growth_count += executed.growth.size(); + require(state->current_total() == opening_total, "family stock did not close"); + for (const auto& growth : executed.growth) + require(growth.after.realized_per_thousand > growth.before.realized_per_thousand && + growth.after.realized_per_thousand - growth.before.realized_per_thousand <= + 5 && + growth.after.damage_per_thousand == growth.before.damage_per_thousand, + "growth rate or damage changed"); + for (const auto& growth : executed.growth) { + const auto step = std::ranges::find(executed.step.lives, growth.life_id, + &biology::CellularLifeStepResult::life_id); + const auto life = + std::ranges::find(state->lives(), growth.life_id, + [](const auto& value) { return value.identity.life; }); + require(step != executed.step.lives.end() && life != state->lives().end(), + "growth report identity"); + require(life->reserve.energy.value + growth.intake.energy.value == + step->candidate.reserve_after.energy.value, + "growth energy did not spend reserve"); + for (std::size_t channel = 0; channel < 4; ++channel) + require(life->reserve.matter[channel].value + growth.intake.matter[channel].value == + step->candidate.reserve_after.matter[channel].value + + growth.release.matter[channel].value, + "growth reserve channel did not close"); + } + for (const auto& life : state->lives()) { + if (life.identity.life == family.child) + adult |= life.growth.realized_per_thousand == 1000; + if (life.identity.life == 100) + require(life.growth == biology::GrowthState{1000, 0}, "offline founder changed"); + } + if (tick % 317 == 0) + state = restore(*state); + for (const auto& bud : executed.buds) { + if (bud.parent_life != family.child || bud.result != CellularBudResult::budded) + continue; + require(adult && growth_count > 0, "offspring reproduced without funded adulthood"); + std::cout << "funded juvenile reached adulthood and budded at tick " << state->tick() + << ", growth steps " << growth_count << '\n'; + return; + } + } + throw std::runtime_error("funded juvenile never reproduced"); +} +void legacy_and_population_replay() { + auto family = first_bud(false); + auto legacy = restore(*family.state); + const auto initial = std::ranges::find(legacy->lives(), family.child, [](const auto& life) { + return life.identity.life; + })->growth; + for (unsigned tick = 0; tick < 400; ++tick) { + const auto executed = checked(legacy->advance_tick_with_mutations(idle(*legacy, true), {}), + "legacy no growth"); + require(executed.growth.empty(), "rules 8 gained growth"); + } + require(std::ranges::find( + legacy->lives(), family.child, + [](const auto& life) { + return life.identity.life; + })->growth == initial, + "rules 8 juvenile changed growth"); + auto boundary = checked(family.state->migration_upgrade_candidate(), "population boundary"); + auto population = checked(CellularPopulation::create(std::move(boundary)), "population create"); + const auto genome = population->state().lives().front().identity.genome; + checked(population->collapse(genome), "juvenile collapse"); + const auto tags = std::vector{population->members().begin(), + population->members().end()}; + const auto sequence = population->conversion_sequence(); + population = checked(population->maturation_upgrade_candidate(), "population growth upgrade"); + require(std::ranges::equal(population->members(), tags) && + population->conversion_sequence() == sequence, + "upgrade lost cohort tags"); + auto raw = restore(population->state()); + bool grew = false; + for (unsigned tick = 0; tick < 1024; ++tick) { + auto all = checked(wildlife_intents(*raw, raw->tick() + 1), "raw wildlife intentions"); + std::vector controlled; + for (const auto& life : raw->lives()) + if (life.account != LifeAccount{}) { + CellularLifeIntent frozen{life.identity.life, {}}; + frozen.intent.frozen = true; + controlled.push_back(frozen); + all.push_back(frozen); + } + std::ranges::sort(all, {}, &CellularLifeIntent::life_id); + auto before = restore(*raw); + const auto executed = checked(raw->advance_tick_with_mutations(all, {}), "raw maturation"); + grew |= !executed.growth.empty(); + checked(population->advance_tick(controlled), "cohort maturation"); + require(raw->snapshot() == population->state().snapshot(), "cohort changed growth biology"); + CellularBatch batch; + batch.header = {raw->world(), raw->region(), raw->frame(), {}, + {}, before->tick(), raw->tick()}; + batch.header.predecessor[0] = 1; + batch.header.predecessor_digest[0] = 2; + batch.ticks.push_back({all, {}, {}}); + const auto bytes = checked(encode_cellular_batch(batch), "growth trace encode"); + const auto decoded = checked(decode_cellular_batch(bytes), "growth trace decode"); + require( + checked(replay_cellular_batch(*before, decoded), "growth trace replay")->snapshot() == + raw->snapshot(), + "recorded growth replay differs"); + if (tick % 127 == 0) { + population = + checked(CellularPopulation::restore(population->snapshot(), raw->world(), + raw->region(), raw->frame(), raw->tick()), + "growing cohort restore"); + raw = restore(*raw); + } + if (tick == 256) { + const auto biology = population->state().snapshot(); + checked(population->materialize(genome), "growing materialization"); + checked(population->collapse(genome), "growing recollapse"); + require(population->state().snapshot() == biology, "conversion reset growth"); + } + } + require(grew, "raw/cohort comparison never exercised growth"); + require(population_interval_safe(*raw), "suspended controlled owner refused rules 9 interval"); + CellularBatchHeader header{raw->world(), raw->region(), raw->frame(), {}, + {}, raw->tick(), raw->tick() + 64}; + header.predecessor[0] = 1; + header.predecessor_digest[0] = 2; + auto inputs = checked(unattended_population_inputs(*raw, header), "growth interval inputs"); + auto execution = + checked(prepare_population_batch(*population, std::move(inputs)), "growth interval"); + auto batch = checked(decode_population_batch(checked(encode_population_batch(execution.batch), + "population trace encode")), + "population trace decode"); + require(checked(replay_population_batch(*population, batch), "population interval replay") + ->snapshot() == execution.state->snapshot(), + "population interval growth replay differs"); +} +void save(const char* path, std::span bytes) { + std::ofstream file(path, std::ios::binary | std::ios::trunc); + file.write(reinterpret_cast(bytes.data()), + static_cast(bytes.size())); + require(file.good(), "maturation checkpoint write"); +} +void continue_population(CellularPopulation& population) { + bool grew = false; + for (unsigned tick = 0; tick < 64; ++tick) { + std::vector controlled; + for (const auto& life : population.state().lives()) + if (life.account != LifeAccount{}) { + CellularLifeIntent input{life.identity.life, {}}; + input.intent.frozen = true; + controlled.push_back(input); + } + const auto executed = checked(population.advance_tick(controlled), "restart continuation"); + grew |= !executed.growth.empty(); + } + require(grew, "restart continuation never grew"); +} +void checkpoint(const char* path, const char* expected) { + auto family = first_bud(false); + for (unsigned tick = 0; tick < 400; ++tick) + checked(family.state->advance_tick(idle(*family.state, true)), "restart suspension"); + auto population = checked(CellularPopulation::create(upgraded(std::move(family.state))), + "restart population"); + checked(population->collapse(population->state().lives().front().identity.genome), + "restart cohort"); + save(path, population->snapshot()); + continue_population(*population); + save(expected, population->snapshot()); +} +void resume(const char* path, const char* output) { + std::ifstream file(path, std::ios::binary); + require(file.good(), "restart checkpoint read"); + const std::vector bytes{std::istreambuf_iterator{file}, {}}; + require(bytes.size() >= cellular_population_header_bytes + 8, "restart checkpoint length"); + // Test-only trusted fixture context; production recovery binds a manifest. + std::uint64_t tick = 0; + for (unsigned shift = 0; shift < 8; ++shift) + tick |= std::uint64_t{bytes[56 + shift]} << (shift * 8U); + auto population = + checked(CellularPopulation::restore(bytes, 207, 1, 1, tick), "fresh-process restore"); + continue_population(*population); + save(output, population->snapshot()); +} +} // namespace +int main(int argc, char** argv) try { + if (argc == 4 && std::string_view{argv[1]} == "--checkpoint") { + checkpoint(argv[2], argv[3]); + return 0; + } + if (argc == 4 && std::string_view{argv[1]} == "--resume") { + resume(argv[2], argv[3]); + return 0; + } + require(argc == 1, "unknown maturation test arguments"); + construction_and_saved_choices(); + frozen_construction(); + obstructed_expansion(); + funded_generations(); + legacy_and_population_replay(); + return 0; +} catch (const std::exception& error) { + std::fprintf(stderr, "%s\n", error.what()); + return 1; +} diff --git a/tests/population_checkpoint_tests.cpp b/tests/population_checkpoint_tests.cpp index 5e8db8d..a8aca0e 100644 --- a/tests/population_checkpoint_tests.cpp +++ b/tests/population_checkpoint_tests.cpp @@ -179,6 +179,25 @@ void manifests() { raw_mislabeled.payload_bytes = future->state().snapshot().size(); require(!restore_cellular_payload(future->state().snapshot(), raw_mislabeled), "portable owner 7 bypassed raw durable bundle admission"); + // ADR-0157: portable maturation must not acquire durable rules-8 authority. + auto maturation = checked(future->maturation_upgrade_candidate(), "portable maturation"); + auto rules8_population = next; + rules8_population.cellular_versions = cellular_v10_versions; + rules8_population.payload_bytes = future->snapshot().size(); + require(restore_population_payload(future->snapshot(), rules8_population).has_value() && + !restore_population_payload(maturation->snapshot(), rules8_population), + "rules 9 bypassed durable population admission"); + auto rules8_raw = source; + rules8_raw.cellular_versions = cellular_v10_versions; + rules8_raw.payload_bytes = future->state().snapshot().size(); + require(restore_cellular_payload(future->state().snapshot(), rules8_raw).has_value() && + !restore_cellular_payload(maturation->state().snapshot(), rules8_raw), + "rules 9 bypassed durable raw admission"); + auto unsupported_rules = rules8_population; + unsupported_rules.cellular_versions.rules = cellular_lives_maturation_rules; + require(!supported(unsupported_rules) && !encode_manifest(unsupported_rules) && + population_envelope_version(unsupported_rules.cellular_versions) == 0, + "portable rules 9 silently entered a durable bundle"); auto back = checked(population_profile_transition_manifest( next, filled<32>(11), filled<16>(12), lease, source.build, state->snapshot().size(), filled<32>(13)),