Drive the energy cycle with measured ecosystem episodes

Close M2 with a deterministic driver that owns one community and one
seeded stream, holds no inventory and emits only the terminal, feeding
and reproduction intents the earlier increments already accept. No
simulation contract changed to make the cycle run unattended.

Two limits shaped the design. Identities are never reused and slots are
capped, so one community supports a bounded number of consumer lifetimes
and is not a population. No maintenance cost exists, so a consumer that
is never eaten never dies, and inventing a starvation rule here would
settle a question ENERGY_MODEL leaves open inside a measurement harness.
The harness therefore measures many bounded episodes, taking mortality
from predation and from a configured lifespan delivered as an ADR-0027
host terminal fact. Lifespan bounds an episode; it is not senescence.

The driver must never submit a batch the community rejects, so it probes
a discarded copy each tick to size bites against the state feeding will
actually see, claims each target for one feeder, and excludes a bitten
consumer from acting. A rejected tick is reported as a driver defect
rather than absorbed as ecology.

Across 64 seeds the suite steps tick by tick, requiring exact conserved
totals at every tick and an identical report on replay, and covers both
mortality paths, slot exhaustion, tick-limit termination, lineage
attribution, episode independence and configuration rejection.
evo-sim --ecosystem reports seeded ensembles: 3,000 episodes advanced
1,093,007 ticks, all reaching extinction, with deaths reconciling exactly
against founders plus births. That demonstrates arithmetic and turnover,
not ecological plausibility; strategy constants are chosen inputs.

Native Release, clang-tidy analysis, ASan and format checks pass 11/11;
golden d61ad5bf0c928c76 is unchanged. Linux CI has not run yet.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-09-22 17:38:34 -04:00
co-authored by Claude Opus 5
parent 67637ac14c
commit eaf58f2b85
13 changed files with 1009 additions and 11 deletions
+12 -2
View File
@@ -40,13 +40,13 @@ target_include_directories(evo_accounting PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/in
target_compile_features(evo_accounting PUBLIC cxx_std_23)
evo_owned_target(evo_accounting)
add_library(evo_processes STATIC src/processes/producer.cpp src/processes/feeding.cpp)
add_library(evo_processes STATIC src/processes/producer.cpp src/processes/feeding.cpp src/processes/ecosystem.cpp)
add_library(evo::processes ALIAS evo_processes)
target_link_libraries(evo_processes PUBLIC evo::accounting)
evo_owned_target(evo_processes)
add_executable(evo-sim apps/evo-sim/main.cpp)
target_link_libraries(evo-sim PRIVATE evo::simulation)
target_link_libraries(evo-sim PRIVATE evo::simulation evo::processes)
evo_owned_target(evo-sim)
include(CTest)
@@ -56,6 +56,11 @@ if(BUILD_TESTING)
evo_owned_target(evo-feeding-tests)
add_test(NAME feeding-contracts COMMAND evo-feeding-tests)
set_tests_properties(feeding-contracts PROPERTIES TIMEOUT 60)
add_executable(evo-ecosystem-tests tests/ecosystem_tests.cpp)
target_link_libraries(evo-ecosystem-tests PRIVATE evo::processes)
evo_owned_target(evo-ecosystem-tests)
add_test(NAME ecosystem-contracts COMMAND evo-ecosystem-tests)
set_tests_properties(ecosystem-contracts PROPERTIES TIMEOUT 300)
add_executable(evo-producer-tests tests/producer_tests.cpp)
target_link_libraries(evo-producer-tests PRIVATE evo::processes)
evo_owned_target(evo-producer-tests)
@@ -76,6 +81,11 @@ if(BUILD_TESTING)
set_tests_properties(cli-replay PROPERTIES PASS_REGULAR_EXPRESSION "d61ad5bf0c928c76")
add_test(NAME cli-invalid-number COMMAND evo-sim --ticks -1)
set_tests_properties(cli-invalid-number PROPERTIES WILL_FAIL TRUE)
add_test(NAME cli-ecosystem COMMAND evo-sim --ecosystem --seed 0 --episodes 32)
set_tests_properties(cli-ecosystem PROPERTIES TIMEOUT 120
PASS_REGULAR_EXPRESSION "2cd4a15f9fbe9949")
add_test(NAME cli-ecosystem-conflict COMMAND evo-sim --ecosystem --verify-replay)
set_tests_properties(cli-ecosystem-conflict PROPERTIES WILL_FAIL TRUE)
add_test(NAME cli-file-integration COMMAND "${CMAKE_COMMAND}"
"-DEVO_SIM=$<TARGET_FILE:evo-sim>" "-DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/cli-integration"
-P "${CMAKE_CURRENT_SOURCE_DIR}/tests/cli_integration.cmake")
+14 -1
View File
@@ -48,6 +48,16 @@ On Windows use a Visual Studio x64 developer shell, or the repository's
./build/debug/evo-sim --load state.evo --ticks 500 --output results.json
```
```sh
./build/release/evo-sim --ecosystem --seed 0 --episodes 3000
```
Ecosystem mode measures seeded bounded episodes of the synthetic feeding community
and reports ticks, births, both mortality paths, extinctions and a fingerprint. It
shares no state, snapshot or particle metric with the proof run, and its strategy
constants are measurement inputs rather than simulation rules. See
[ADR-0029](docs/adr/0029-ecosystem-driver-and-episodes.md) for scope.
The second command continues saved PRNG/component state. `--verify-replay`
compares an uninterrupted run to a midpoint serialization/restore run. JSON
reports the seed, ticks, active entities and canonical state hash. Snapshots
@@ -80,7 +90,10 @@ restore. See [testing strategy](docs/engineering/TEST_STRATEGY.md) and
`include/evo` exposes core values and the headless simulation API.
`src/simulation` implements component state, tick ordering and local snapshot
codec. `src/accounting` provides the independent finite-inventory ledger;
it is not yet part of particle snapshots. `apps/evo-sim` owns CLI/file I/O and reporting. `tests` holds contract,
it is not yet part of particle snapshots. `src/processes` holds the synthetic
producer, feeding, reproduction and episode fixtures built on that ledger; they
are bounded experiments, not organism biology. `apps/evo-sim` owns CLI/file I/O
and reporting. `tests` holds contract,
fuzz and measurement programs. Future biology, world, networking and persistence
modules are documented boundaries; they are added when they have real behavior.
+114 -2
View File
@@ -1,3 +1,4 @@
#include "evo/processes/ecosystem.hpp"
#include "evo/simulation/world.hpp"
#include "evo/telemetry/sinks.hpp"
@@ -10,6 +11,8 @@
#include <iostream>
#include <limits>
#include <optional>
#include <sstream>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
@@ -19,8 +22,11 @@ struct Options {
std::uint64_t seed{123456};
std::uint64_t ticks{1000};
std::uint64_t entities{8};
std::uint64_t episodes{1};
std::uint64_t tick_limit{2000};
std::filesystem::path load, save, output, metrics;
bool verify_replay{};
bool ecosystem{};
bool help{};
};
@@ -78,6 +84,7 @@ std::expected<void, evo::Error> validate_paths(const Options& options) {
std::expected<Options, evo::Error> parse(int argc, char** argv) {
Options options;
bool initial_state_option = false;
bool entities_option = false;
for (int index = 1; index < argc; ++index) {
const std::string_view key{argv[index]};
if (key == "--help") {
@@ -88,11 +95,16 @@ std::expected<Options, evo::Error> parse(int argc, char** argv) {
options.verify_replay = true;
continue;
}
if (key == "--ecosystem") {
options.ecosystem = true;
continue;
}
if (++index >= argc) {
return std::unexpected{evo::Error::invalid_arguments};
}
const std::string_view value{argv[index]};
if (key == "--seed" || key == "--ticks" || key == "--entities") {
if (key == "--seed" || key == "--ticks" || key == "--entities" || key == "--episodes" ||
key == "--tick-limit") {
const auto parsed = number(value);
if (!parsed) {
return std::unexpected{parsed.error()};
@@ -103,6 +115,11 @@ std::expected<Options, evo::Error> parse(int argc, char** argv) {
} else if (key == "--entities") {
options.entities = *parsed;
initial_state_option = true;
entities_option = true;
} else if (key == "--episodes") {
options.episodes = *parsed;
} else if (key == "--tick-limit") {
options.tick_limit = *parsed;
} else {
options.ticks = *parsed;
}
@@ -121,6 +138,12 @@ std::expected<Options, evo::Error> parse(int argc, char** argv) {
if (options.entities > evo::max_entities || (!options.load.empty() && initial_state_option)) {
return std::unexpected{evo::Error::invalid_arguments};
}
// Episode measurement shares no state, snapshot or particle metric with the proof run.
if (options.ecosystem && (entities_option || options.verify_replay || !options.load.empty() ||
!options.save.empty() || !options.metrics.empty() ||
options.episodes == 0 || options.tick_limit == 0)) {
return std::unexpected{evo::Error::invalid_arguments};
}
if (const auto valid = validate_paths(options); !valid) {
return std::unexpected{valid.error()};
}
@@ -167,7 +190,92 @@ std::expected<void, evo::Error> advance(evo::SimulationWorld& world, std::uint64
return {};
}
std::expected<void, evo::Error> write_report(const Options& options, const std::string& text) {
std::ofstream output_file;
if (!options.output.empty()) {
if (const auto valid = validate_paths(options); !valid) {
return valid;
}
output_file.open(options.output);
if (!output_file) {
return std::unexpected{evo::Error::io_failure};
}
}
auto& output = options.output.empty() ? std::cout : output_file;
output << text;
output.flush();
if (!options.output.empty()) {
output_file.close();
}
if (!output) {
return std::unexpected{evo::Error::io_failure};
}
return {};
}
// CLI-local fixture constants. They are measurement inputs, not simulation rules,
// and are deliberately not exported by the library. See ADR-0029.
evo::accounting::Inventory bundle(std::uint64_t value) {
using namespace evo::accounting;
return {{value}, {Femtograms{value}, Femtograms{value}, Femtograms{value}, Femtograms{value}}};
}
evo::processes::StrategyConfig grazer() {
return {bundle(20), bundle(3), 900, bundle(30), bundle(20), 50};
}
evo::processes::StrategyConfig forager() {
return {bundle(20), bundle(2), 1000, bundle(24), bundle(16), 70};
}
std::expected<void, evo::Error> run_ecosystem(const Options& options) {
using namespace evo::processes;
const ProducerConfig plants{{{10}, 1}, {2, 1}, 1000, {1}, bundle(1).matter};
const EcosystemConfig config{plants, {100'000}, bundle(200).matter, {bundle(4)},
800, 14, options.tick_limit};
const std::array founders{grazer(), forager()};
std::uint64_t ticks{}, births{}, predation{}, lifespan{}, extinctions{}, survivors{};
std::uint64_t shortest = std::numeric_limits<std::uint64_t>::max(), longest{}, fingerprint{};
for (std::uint64_t index = 0; index < options.episodes; ++index) {
if (options.seed > std::numeric_limits<std::uint64_t>::max() - index) {
return std::unexpected{evo::Error::invalid_arguments};
}
auto episode = EcosystemEpisode::create(config, founders, options.seed + index);
if (!episode) {
return std::unexpected{evo::Error::invalid_arguments};
}
const auto summary = episode->run();
if (!summary) {
return std::unexpected{evo::Error::replay_mismatch};
}
if (summary->ticks > std::numeric_limits<std::uint64_t>::max() - ticks) {
return std::unexpected{evo::Error::tick_exhausted};
}
ticks += summary->ticks;
births += summary->births;
predation += summary->predation_deaths;
lifespan += summary->lifespan_deaths;
extinctions += summary->extinction_tick != 0 ? 1 : 0;
survivors += summary->surviving_lineages;
shortest = std::min(shortest, summary->ticks);
longest = std::max(longest, summary->ticks);
fingerprint ^= summary->fingerprint + 0x9e3779b97f4a7c15ULL + (fingerprint << 6U) +
(fingerprint >> 2U);
}
std::ostringstream report;
report << "{\"rules_version\":" << evo::rules_version
<< ",\"mode\":\"ecosystem\",\"seed\":" << options.seed
<< ",\"episodes\":" << options.episodes << ",\"tick_limit\":" << options.tick_limit
<< ",\"ticks\":" << ticks << ",\"births\":" << births
<< ",\"predation_deaths\":" << predation << ",\"lifespan_deaths\":" << lifespan
<< ",\"extinctions\":" << extinctions << ",\"surviving_lineages\":" << survivors
<< ",\"shortest\":" << shortest << ",\"longest\":" << longest << ",\"fingerprint\":\""
<< std::hex << std::setfill('0') << std::setw(16) << fingerprint << std::dec << "\"}\n";
return write_report(options, report.str());
}
std::expected<void, evo::Error> run(const Options& options) {
if (options.ecosystem) {
return run_ecosystem(options);
}
auto loaded = initial_world(options);
if (!loaded) {
return std::unexpected{loaded.error()};
@@ -257,7 +365,11 @@ int main(int argc, char** argv) try {
std::cout
<< "evo-sim [--seed N --entities N | --load FILE] --ticks N\n"
" [--verify-replay] [--save FILE] [--output JSON] [--metrics FILE]\n"
"Synthetic proof. When loading, ticks are additional.\n";
"evo-sim --ecosystem [--seed N] [--episodes N] [--tick-limit N]\n"
" [--output JSON]\n"
"Synthetic proof. When loading, ticks are additional.\n"
"Ecosystem mode measures seeded bounded episodes; it shares no state,\n"
"snapshot or particle metric with the proof run.\n";
return 0;
}
const auto result = run(*options);
+7 -2
View File
@@ -65,8 +65,13 @@ flows, rather than relying on M2.3's zero-inventory depletion trigger.
M2.4 now implements that terminal-inventory and bounded-return contract. M2.5
now supplies funded budding, bounded pre-allocated slot capacity and retained
parent/origin identity (ADR-0028); offspring are paid for out of parent inventory
and no trait varies between generations. M2.6 must exercise the whole cycle over
seeded long runs; a closed conservation proof is not yet an interesting ecology.
and no trait varies between generations. M2.6 now drives the whole cycle without
a caller (ADR-0029). Two limits shape it: retained identities and capped slots
mean one community is not a population, and with no maintenance cost an uneaten
consumer never dies. It therefore measures many bounded episodes, with mortality
from predation and a configured lifespan, rather than one continuous run. Over a
million ticks conserve exactly, which demonstrates arithmetic, not ecology.
M3 replaces duplicated strategies with heritable developmental capabilities.
## M3 — Genome v0.1
+20 -4
View File
@@ -1,13 +1,13 @@
# Project status and next steps
Updated 2026-09-21. The repository contains an engineering foundation and a
Updated 2026-09-22. The repository contains an engineering foundation and a
deterministic headless proof. It does not yet contain cellular gameplay or a
persistent simulation server. The founding vision remains unchanged.
## Completed implementation
- Vision, architectural pillars, risks, open-question register, architecture
diagrams, biological contracts, engineering constitution and 28 ADRs.
diagrams, biological contracts, engineering constitution and 29 ADRs.
Proposed/deferred choices remain distinct from accepted proof decisions.
- M0–M4 task breakdowns with dependencies, acceptance evidence and risks,
plus M5–M14 gates in [ROADMAP.md](ROADMAP.md).
@@ -61,8 +61,8 @@ for the bounded proof; the general production ECS remains a later measured choic
| Priority | Work | Completion evidence |
|---|---|---|
| 1 | M2.6 headless energy-cycle fixture | Complete capture/feeding/reproduction/decomposition cycle, seeded million-tick ecosystem runs and diagnostics |
| 2 | M3.1 immutable genome schema and ancestry | Versioned developmental capability data replacing M2.5's duplicated configuration |
| 1 | M3.1 immutable genome schema and ancestry | Versioned developmental capability data replacing M2.6's duplicated founder strategies |
| 2 | M3.2 development pipeline | Same genome and environment yield the same explicit phenotype parameters |
| Delivery gate | Add/update the dev workload when a deployable increment needs it; Argo is ready | Observe Job/pod completion separately from image publication; no World0 changes |
M1.6 now implements [the sequential scheduler contract](architecture/SCHEDULER_CONTRACT.md):
@@ -143,6 +143,22 @@ the particle goldens unchanged. Native Release, analysis, ASan and formatting
passed; Linux CI for this increment has not run yet. This is not a reproductive
strategy, fecundity rule, mutation model or funded founder admission.
M2.6 closes M2 with a deterministic ecosystem driver (ADR-0029). It owns one
community and one seeded stream, holds no inventory and emits only the intents
the earlier increments already accept, so no simulation contract changed. Two
limits shaped it: retained identities and capped slots mean one community is not
a population, and with no maintenance cost an uneaten consumer never dies. The
harness therefore measures many bounded episodes, with mortality from predation
and a configured lifespan delivered as a host terminal fact. The driver probes a
discarded copy each tick so it never submits a batch the community rejects; a
rejected tick is reported as a driver defect rather than absorbed as ecology.
`evo-sim --ecosystem` reports seeded episode ensembles: 3,000 episodes advanced
1,093,007 ticks, all reaching extinction, with deaths reconciling exactly against
founders plus births and conserved totals identical at every tick. That
demonstrates arithmetic and turnover, not ecological plausibility; strategy
constants are chosen inputs and must not become gameplay by having been measured.
Native Release, analysis, ASan and formatting passed; Linux CI has not run yet.
Before biology, resolve the relevant heredity and energetic contracts rather
than treating proof particles as organisms. Exact game tick rate, NPC mutation,
logout treatment, species/extinction rules and multicellular transition remain
@@ -0,0 +1,114 @@
# ADR-0029: Deterministic ecosystem driver and bounded episodes
## Status
Adopted for the M2.6 headless measurement harness. No gameplay AI, perception,
behavior model, senescence biology, metabolic rate or population abstraction is
selected. The simulation contracts of ADR-0024 through ADR-0028 are unchanged.
## Context
M2.2 through M2.5 close the transfer cycle, but every intent is supplied by the
caller. Nothing decides what happens, so a long run needs a decision source before
extinction or diversity can be measured at all.
Two structural limits surfaced while scoping this increment. First, ADR-0028
retains identities permanently and caps slots at `max_consumers`, so one community
supports a bounded number of consumer lifetimes and is not a population: a single
million-tick community would spend almost all of those ticks after slot exhaustion
in a static state. Second, no maintenance cost exists, so a consumer that is never
eaten never dies and a run has no endogenous end. ENERGY_MODEL leaves baseline
metabolism and starvation rules open, so inventing them here would settle an open
biological question inside a measurement harness.
## Decision
Add `EcosystemEpisode`, which privately owns one `FeedingCommunity` and one seeded
`Random` stream. It holds no inventory, performs no transfers and calls no public
mutator other than `advance`. It reads committed public state and emits intents.
Measure many bounded episodes rather than one long community. Each episode ends at
extinction, defined here as no living consumer, or at a configured tick limit.
Because births consume permanent slots and every consumer has a finite lifespan,
extinction is reachable in every episode. The long-run figure is the total ticks
advanced across seeded episodes, and each episode reports its own outcome.
Mortality has exactly two sources, both already contracted. Predation: the driver
bites a target's entire remaining balance when that fits the intake cap, which
ADR-0026 already turns into terminal depletion. Lifespan: the driver emits an
ADR-0027 terminal fact once a consumer's age reaches its configured lifespan.
Lifespan is a host scheduling rule that bounds the episode, not senescence, aging
biology or a death cause. No maintenance, starvation or metabolic cost is added.
A founder strategy fixes opening inventory, intake cap, assimilation, an investment
bundle, a reproduction threshold and a lifespan. ADR-0028 makes a child duplicate
its parent, so a founder strategy identifies one lineage for the whole episode and
competing strategies are the only source of variation. Lineage membership is
recovered by walking retained parent references to a founder.
Per tick the driver emits, in this order: terminal facts for every active consumer
that has reached its lifespan; then feed intents; then reproduce intents. It must
never submit a batch the community rejects, so it applies three self-restrictions.
A consumer terminated this tick neither feeds nor is fed upon nor reproduces. Each
target is claimed by at most one feeder per tick, assigned in ascending consumer
ID, which removes contention rejection. A consumer that is a feeding target this
tick does not reproduce this tick, which removes the interaction between a reduced
balance and the later reproduction check. Reproduce intents are truncated to the
number of free slots in ascending parent ID. Bites are per-channel
`min(intake cap, target balance)` and targets with no inventory are skipped.
A rejected `advance` is therefore a driver defect, not an ecological outcome, and
is reported as `community_failure` rather than being retried or absorbed. Target
selection draws from the seeded stream; nothing else consults it.
Each episode reports seed, ticks advanced, births, predation and lifespan deaths,
extinction tick, founder and surviving lineage counts, cumulative decomposition,
conserved totals and a state fingerprint. Conserved totals must be identical at
every tick. The report is data for review, not a pass threshold.
## Alternatives Considered
A maintenance cost with a starvation rule would give endogenous mortality, but
ENERGY_MODEL leaves metabolism and starvation explicitly open and a measurement
harness is the wrong place to settle them. Reusing retired slots would destroy the
ancestry ADR-0028 just established. Raising `max_consumers` delays exhaustion
without removing it and would widen per-tick intent bounds with no evidence. One
continuous million-tick community measures a static post-exhaustion state. Letting
the driver retry a rejected batch would hide driver defects as ecology.
## Benefits
The full cycle runs unattended and deterministically: nutrients fund growth, growth
funds feeding, feeding funds offspring, lifespan and predation produce corpses, and
decomposition returns matter. Extinction and lineage survival become measurable
across seeds, conservation is checked every tick over long horizons, and the driver
is separable from the contracts it exercises.
## Costs
Episode length is bounded by slots times lifespan, so this measures many short
histories rather than one long one. Strategy constants, lifespans and the targeting
rule are chosen, not derived. One-feeder-per-target and the reproduction exclusion
are scheduling conveniences that bias contention away from the ordering ADR-0026
deliberately exposes. Whole-community copies per tick remain the baseline.
## Risks
Do not read episode statistics as population dynamics, life-history theory or
balance. Lifespan is not senescence, targeting is not perception, and a surviving
lineage count is not speciation or fitness. Conservation holding across a million
ticks demonstrates arithmetic, not ecological plausibility, and the explicit risk
of this increment is passing every invariant while modelling nothing interesting.
Strategy constants must not become gameplay by having been measured.
## Consequences
Test per-tick conservation and nonnegative balances across many seeds, identical
reports for one seed on repeated runs, independence of episodes, extinction
reached and recorded, lineage attribution through retained ancestry, both mortality
paths, slot exhaustion, tick-limit termination, a single-founder episode, an
episode whose founders cannot reproduce, and that the driver never provokes a
rejected batch. Cross-platform fingerprints must agree. No snapshot format,
database, renderer, deployment or simulation contract changes. Serialized recovery
of episode state is not provided; M4 aggregation remains the path to real
populations.
+1
View File
@@ -21,6 +21,7 @@ Each record has the eight required sections.
0026 adds shared community ownership and bounded synthetic feeding for M2.3.
0027 adds terminal inventory ownership and budgeted nutrient return for M2.4.
0028 adopts funded reproduction, bounded slot capacity and retained lineage IDs.
0029 scopes the deterministic ecosystem driver and bounded measured episodes.
Every dependency adoption records exact version/commit and integrity hash,
transitive license obligations, maintenance/security review, owner and removal
+20
View File
@@ -95,3 +95,23 @@ identity, deterministic replay, crashes at every conversion boundary, interval
uniqueness, mixed-genome diversity, repeated conversion attacks, extreme rates,
late migrations/censuses and suspended viability. Compare explicit individuals:
passing conservation alone is insufficient ecological evidence.
## Implemented M2.6 episode boundary
[ADR-0029](../adr/0029-ecosystem-driver-and-episodes.md) measures bounded episodes
of the synthetic community. It settles none of the contracts above. There is no
tier, no cohort, no conversion transaction, no representative materialization and
no habitat. Every process stays an identified individual for its whole life.
Extinction here is the narrow, local statement that an episode has no living
consumer, recorded with the tick it happened. It is not the globally reconciled
watermark this document requires: there are no suspended members, eggs, spores,
in-flight transfers or other viable stores to reconcile, and no policy acceptance.
Surviving lineage counts come from retained parent references, not from species
classification, and lineages differ only by founder strategy because no genome
exists yet.
The shared bounded controller proposal is exercised only as a measurement driver.
It has no perception, no learning and no evolving behavior, and its constants are
inputs rather than results. Population math, cohort collapse and resolution
equivalence remain M4 work.
+40
View File
@@ -236,3 +236,43 @@ A child duplicates the configuration of its parent because no genome exists yet.
This is duplication, not heredity, and no trait varies between generations.
Reproductive strategy, fecundity, juvenile viability, gestation, spatial placement
and account ownership are not defined here. No inventory is created on birth.
## Implemented M2.6 measured episodes
[ADR-0029](../adr/0029-ecosystem-driver-and-episodes.md) adds `EcosystemEpisode`,
a deterministic driver that owns one community and one seeded stream, holds no
inventory and performs no transfers. It reads committed state and emits the
terminal, feeding and reproduction intents the earlier increments already accept.
No simulation contract changed to make the cycle run unattended.
Two limits shape the harness. Identities are never reused and slots are capped,
so one community supports a bounded number of consumer lifetimes and is not a
population. No maintenance cost exists, so a consumer that is never eaten never
dies. The harness therefore measures many bounded episodes rather than one long
community, and mortality comes only from predation, where a bite takes a target's
whole remaining balance, and from a configured lifespan delivered as a host
terminal fact. Lifespan bounds the episode; it is not senescence or a death cause.
```mermaid
flowchart LR
N[Nutrients] --> P[Producer structure]
P -->|bite| C[Consumer reserve]
C -->|funded endowment| O[Offspring]
C -->|lifespan or predation| D[Corpse]
O --> C
D -->|bounded decay| N
C -->|assimilation loss| W[Waste and heat]
W --> N
```
The driver must never submit a batch the community rejects, so it probes a
discarded copy to size bites against the state feeding will actually see, claims
each target for one feeder, and excludes a bitten consumer from acting that tick.
A rejected tick is reported as a driver defect rather than absorbed as ecology.
Conservation is checked at every tick across seeded ensembles, and each episode
reports births, both mortality paths, extinction tick, surviving lineages and a
fingerprint. Conservation holding over a million ticks demonstrates arithmetic,
not ecological plausibility. Strategy constants, lifespans and the targeting rule
are chosen inputs, not derived biology, and must not become gameplay by having
been measured. Real populations still require M4 aggregation.
+37
View File
@@ -313,3 +313,40 @@ long-run ecosystem behavior were not exercised. This fixture defines no
reproductive strategy, fecundity, mutation, gestation, spatial placement or account
ownership, and no deployment manifest or image pin changed. Linux validation is
pending its first pushed run; no Gitea result is claimed for this increment yet.
## M2.6 measured ecosystem episodes (2026-09-22)
Native Release, analysis and MSVC ASan each passed 11/11 CTests; formatting passed.
Commands: `tools/windows-check.ps1 -Preset <release|analysis|asan> -Action check`
and debug `-Action format`. Formatting rejected 25 wrapped declarations on the
first run; clang-format 19.1.5 rewrote them and Release was rebuilt and rerun.
Three CTest cases are new: `ecosystem-contracts`, `cli-ecosystem` pinned to
fingerprint `2cd4a15f9fbe9949`, and `cli-ecosystem-conflict`, which requires the
CLI to reject `--ecosystem` combined with proof-run options.
The suite checks a solitary founder that only ages, a hand-checked predation
retirement, births exhausting exactly the reserved slots, tick-limit termination
with survivors, configuration rejection, and two episodes interleaved without
observing each other. Across 64 seeds it steps tick by tick, requiring that the
driver never provokes a rejected batch and that conserved totals are identical at
every tick, then replays each seed and requires an identical report. That ensemble
advanced 22,804 ticks with 879 births, 730 predation deaths, 277 lifespan deaths
and extinction in all 64 episodes, episode length 73 to 463 ticks.
`build/release/evo-sim.exe --ecosystem --seed 0 --episodes 3000` advanced
**1,093,007 ticks** in 1.34 s, with 41,138 births, 33,984 predation deaths, 13,154
lifespan deaths, extinction in all 3,000 episodes, episode length 50 to 497 ticks
and fingerprint `130d7725c0dc8b16`. Deaths equal founders plus births exactly
(6,000 + 41,138 = 47,138), so every process died once and no producer was grazed
out: the producer always retains captured energy, so its whole inventory never
reaches zero. The elapsed time is one uncontrolled wall-clock observation, not a
performance threshold.
This measures arithmetic conservation and turnover, not ecological plausibility.
Strategy constants, lifespans and the targeting rule are chosen inputs. There is
no maintenance cost, starvation rule, perception, spatial gate, genome or
heritable variation, so lineages differ only by founder strategy. Episode state is
not serialized, allocation failure is not injected, and no population abstraction
exists. Golden `d61ad5bf0c928c76` and every earlier suite are unchanged. No
deployment manifest or image pin changed. Linux validation is pending its first
pushed run; no Gitea result or cross-platform fingerprint agreement is claimed yet.
+79
View File
@@ -0,0 +1,79 @@
#pragma once
#include "evo/core/random.hpp"
#include "evo/processes/feeding.hpp"
namespace evo::processes {
// One founder strategy. ADR-0028 makes a child duplicate its parent, so a founder
// strategy identifies one lineage for the whole episode.
struct StrategyConfig {
accounting::Inventory opening;
accounting::Inventory intake_limit;
std::uint16_t assimilation_per_thousand;
accounting::Inventory reproduction_threshold;
accounting::Inventory investment;
// Ticks of life before a host terminal fact. Bounds the episode; not senescence.
std::uint32_t lifespan;
};
struct EcosystemConfig {
ProducerConfig producer;
accounting::Picojoules source;
std::array<accounting::Femtograms, 4> nutrients;
DecompositionConfig decomposition;
std::uint16_t construction_per_thousand;
std::uint32_t capacity;
std::uint64_t tick_limit;
};
struct EcosystemReport {
std::uint64_t seed;
std::uint64_t ticks;
std::uint64_t births;
std::uint64_t predation_deaths;
std::uint64_t lifespan_deaths;
// Zero when living consumers remained when the episode stopped.
std::uint64_t extinction_tick;
std::uint32_t founders;
std::uint32_t surviving_lineages;
accounting::Inventory decomposed;
accounting::Inventory conserved;
std::uint64_t fingerprint;
auto operator<=>(const EcosystemReport&) const = default;
};
enum class EcosystemError : std::uint8_t {
invalid_config,
// The community rejected a driver batch. This is a driver defect, not ecology.
community_failure
};
inline constexpr std::size_t max_strategies = 4;
class EcosystemEpisode {
public:
[[nodiscard]] static std::expected<EcosystemEpisode, EcosystemError>
create(EcosystemConfig config, std::span<const StrategyConfig> founders, std::uint64_t seed);
// One driven tick. False once the episode has ended; the report is then final.
[[nodiscard]] std::expected<bool, EcosystemError> step();
[[nodiscard]] std::expected<EcosystemReport, EcosystemError> run();
[[nodiscard]] EcosystemReport report() const noexcept;
[[nodiscard]] const FeedingCommunity& community() const noexcept {
return community_;
}
// Founder ID whose retained ancestry this process descends from; zero if unborn.
[[nodiscard]] std::uint32_t lineage(std::uint32_t id) const noexcept;
private:
EcosystemEpisode(FeedingCommunity community, std::vector<StrategyConfig> founders,
EcosystemConfig config, std::uint64_t seed);
[[nodiscard]] const StrategyConfig& strategy(std::uint32_t id) const noexcept;
FeedingCommunity community_;
std::vector<StrategyConfig> founders_;
EcosystemConfig config_;
Random random_;
std::uint64_t seed_;
std::uint64_t births_{};
std::uint64_t predation_deaths_{};
std::uint64_t lifespan_deaths_{};
std::uint64_t extinction_tick_{};
accounting::Inventory decomposed_{};
bool finished_{};
};
} // namespace evo::processes
+308
View File
@@ -0,0 +1,308 @@
#include "evo/processes/ecosystem.hpp"
#include <algorithm>
#include <limits>
#include <utility>
namespace evo::processes {
namespace {
constexpr std::size_t slot_limit = max_consumers + 2;
std::size_t balance_index(std::uint32_t actor) noexcept {
return actor == 1 ? 2 : static_cast<std::size_t>(actor) + 2;
}
bool covers(const accounting::Inventory& need, const accounting::Inventory& have) noexcept {
if (need.energy > have.energy) {
return false;
}
for (std::size_t index = 0; index < 4; ++index) {
if (need.matter[index] > have.matter[index]) {
return false;
}
}
return true;
}
// Cumulative diagnostics saturate; they are reported totals, not owned inventory.
void accumulate(accounting::Inventory& total, const accounting::Inventory& amount) noexcept {
constexpr auto maximum = std::numeric_limits<std::uint64_t>::max();
total.energy.value = amount.energy.value > maximum - total.energy.value
? maximum
: total.energy.value + amount.energy.value;
for (std::size_t index = 0; index < 4; ++index) {
total.matter[index].value = amount.matter[index].value > maximum - total.matter[index].value
? maximum
: total.matter[index].value + amount.matter[index].value;
}
}
// Non-cryptographic combiner, used only to compare results across platforms.
std::uint64_t mix(std::uint64_t hash, std::uint64_t value) noexcept {
return hash ^ (value + 0x9e3779b97f4a7c15ULL + (hash << 6U) + (hash >> 2U));
}
} // namespace
EcosystemEpisode::EcosystemEpisode(FeedingCommunity community, std::vector<StrategyConfig> founders,
EcosystemConfig config, std::uint64_t seed)
: community_{std::move(community)}, founders_{std::move(founders)}, config_{config},
random_{seed}, seed_{seed} {}
std::expected<EcosystemEpisode, EcosystemError>
EcosystemEpisode::create(EcosystemConfig config, std::span<const StrategyConfig> founders,
std::uint64_t seed) {
if (founders.empty() || founders.size() > max_strategies || config.tick_limit == 0) {
return std::unexpected{EcosystemError::invalid_config};
}
for (const auto& founder : founders) {
// A zero lifespan would retire a founder before it ever acted; a zero
// investment would request a birth the community rejects outright.
if (founder.lifespan == 0 || founder.investment == accounting::Inventory{} ||
founder.assimilation_per_thousand > 1000) {
return std::unexpected{EcosystemError::invalid_config};
}
}
std::vector<ConsumerConfig> consumers;
consumers.reserve(founders.size());
for (const auto& founder : founders) {
consumers.push_back(
{founder.opening, founder.intake_limit, founder.assimilation_per_thousand});
}
auto community = FeedingCommunity::create(
config.producer, config.source, config.nutrients, consumers, config.decomposition,
{config.capacity, config.construction_per_thousand, {}});
if (!community) {
return std::unexpected{EcosystemError::invalid_config};
}
return EcosystemEpisode{
std::move(*community), {founders.begin(), founders.end()}, config, seed};
}
std::uint32_t EcosystemEpisode::lineage(std::uint32_t id) const noexcept {
if (id < 2) {
return 0;
}
// A child always occupies a higher slot than its parent, so this terminates.
auto current = id;
while (true) {
const auto exists = community_.born(current);
if (!exists || !*exists) {
return 0;
}
const auto ancestor = community_.parent(current);
if (!ancestor) {
return 0;
}
if (*ancestor == 0) {
return current;
}
current = *ancestor;
}
}
const StrategyConfig& EcosystemEpisode::strategy(std::uint32_t id) const noexcept {
const auto root = lineage(id);
// Every born consumer descends from a founder; index zero is a safe fallback.
const auto offset = root >= 2 && static_cast<std::size_t>(root - 2) < founders_.size()
? static_cast<std::size_t>(root - 2)
: 0U;
return founders_[offset];
}
std::expected<bool, EcosystemError> EcosystemEpisode::step() {
if (finished_) {
return false;
}
const auto slots = static_cast<std::uint32_t>(founders_.size() + config_.capacity + 1);
const auto tick = community_.progress().tick.value + 1;
// Lifespan retirement is decided from age alone, before any activity this tick.
std::vector<TerminalEvent> terminal;
for (std::uint32_t id = 2; id <= slots; ++id) {
const auto alive = community_.active(id);
const auto born = community_.origin(id);
if (!alive || !*alive || !born) {
continue;
}
if (tick - born->value >= strategy(id).lifespan) {
terminal.push_back({id});
}
}
// Probe a discarded copy so bites are sized against the state feeding will see:
// terminal facts and producer capture/growth both land before any feeding.
auto probe = community_;
if (!probe.advance(Tick{tick}, {}, terminal)) {
return std::unexpected{EcosystemError::community_failure};
}
std::array<std::uint32_t, slot_limit> target{};
std::array<bool, slot_limit> claimed{};
for (std::uint32_t consumer = 2; consumer <= slots; ++consumer) {
const auto alive = probe.active(consumer);
// A consumer that cannot bite must not claim a target away from one that can.
if (!alive || !*alive || strategy(consumer).intake_limit == accounting::Inventory{}) {
continue;
}
std::array<std::uint32_t, slot_limit> available{};
std::size_t count = 0;
for (std::uint32_t candidate = 1; candidate <= slots; ++candidate) {
const auto living = probe.active(candidate);
if (candidate == consumer || claimed[candidate] || !living || !*living) {
continue;
}
if (probe.balances()[balance_index(candidate)] == accounting::Inventory{}) {
continue;
}
available[count++] = candidate;
}
if (count == 0) {
continue;
}
// One feeder per target removes contention rejection from the batch.
const auto chosen = available[random_.next() % count];
target[consumer] = chosen;
claimed[chosen] = true;
}
// A consumer bitten this tick may be retired by that bite, so it does not act.
for (std::uint32_t consumer = 2; consumer <= slots; ++consumer) {
if (target[consumer] != 0 && claimed[consumer]) {
target[consumer] = 0;
}
}
claimed.fill(false);
std::vector<FeedIntent> meals;
for (std::uint32_t consumer = 2; consumer <= slots; ++consumer) {
if (target[consumer] == 0) {
continue;
}
const auto& cap = strategy(consumer).intake_limit;
const auto& balance = probe.balances()[balance_index(target[consumer])];
accounting::Inventory bite{};
bite.energy.value = std::min(cap.energy.value, balance.energy.value);
for (std::size_t channel = 0; channel < 4; ++channel) {
bite.matter[channel].value =
std::min(cap.matter[channel].value, balance.matter[channel].value);
}
if (bite == accounting::Inventory{}) {
continue;
}
claimed[target[consumer]] = true;
meals.push_back(
{static_cast<std::uint64_t>(meals.size()) + 1, consumer, target[consumer], bite});
}
std::size_t free_slots = 0;
for (std::uint32_t id = 2; id <= slots; ++id) {
const auto exists = probe.born(id);
if (exists && !*exists) {
++free_slots;
}
}
std::vector<ReproduceIntent> newborn;
for (std::uint32_t parent = 2; parent <= slots && newborn.size() < free_slots; ++parent) {
const auto alive = probe.active(parent);
if (!alive || !*alive || claimed[parent]) {
continue;
}
const auto& plan = strategy(parent);
const auto& balance = probe.balances()[balance_index(parent)];
// Feeding only adds to an unbitten parent, so this bound stays valid.
if (!covers(plan.reproduction_threshold, balance) || !covers(plan.investment, balance)) {
continue;
}
newborn.push_back(
{static_cast<std::uint64_t>(newborn.size()) + 1, parent, plan.investment});
}
const auto receipts = community_.advance(Tick{tick}, meals, terminal, newborn);
if (!receipts) {
return std::unexpected{EcosystemError::community_failure};
}
lifespan_deaths_ += terminal.size();
for (const auto& receipt : *receipts) {
if (receipt.target_depleted) {
++predation_deaths_;
}
}
births_ += community_.last_births().size();
accumulate(decomposed_, community_.last_decomposed());
bool surviving = false;
for (std::uint32_t id = 2; id <= slots; ++id) {
const auto alive = community_.active(id);
if (alive && *alive) {
surviving = true;
break;
}
}
if (!surviving) {
extinction_tick_ = tick;
finished_ = true;
} else if (tick >= config_.tick_limit) {
finished_ = true;
}
return true;
}
std::expected<EcosystemReport, EcosystemError> EcosystemEpisode::run() {
while (true) {
const auto stepped = step();
if (!stepped) {
return std::unexpected{stepped.error()};
}
if (!*stepped) {
return report();
}
}
}
EcosystemReport EcosystemEpisode::report() const noexcept {
const auto slots = static_cast<std::uint32_t>(founders_.size() + config_.capacity + 1);
EcosystemReport summary{};
summary.seed = seed_;
summary.ticks = community_.progress().tick.value;
summary.births = births_;
summary.predation_deaths = predation_deaths_;
summary.lifespan_deaths = lifespan_deaths_;
summary.extinction_tick = extinction_tick_;
summary.founders = static_cast<std::uint32_t>(founders_.size());
std::array<bool, slot_limit> represented{};
for (std::uint32_t id = 2; id <= slots; ++id) {
const auto alive = community_.active(id);
if (!alive || !*alive) {
continue;
}
const auto root = lineage(id);
if (root != 0 && !represented[root]) {
represented[root] = true;
++summary.surviving_lineages;
}
}
summary.decomposed = decomposed_;
// The ledger validated at creation that every channel total fits u64.
for (const auto& balance : community_.balances()) {
summary.conserved.energy.value += balance.energy.value;
for (std::size_t channel = 0; channel < 4; ++channel) {
summary.conserved.matter[channel].value += balance.matter[channel].value;
}
}
std::uint64_t hash = 0;
for (const auto value : {summary.ticks, summary.births, summary.predation_deaths,
summary.lifespan_deaths, summary.extinction_tick}) {
hash = mix(hash, value);
}
for (const auto& balance : community_.balances()) {
hash = mix(hash, balance.energy.value);
for (const auto& mass : balance.matter) {
hash = mix(hash, mass.value);
}
}
for (std::uint32_t id = 1; id <= slots; ++id) {
const auto exists = community_.born(id);
const auto alive = community_.active(id);
hash = mix(hash, (exists && *exists ? 2U : 0U) + (alive && *alive ? 1U : 0U));
hash = mix(hash, lineage(id));
}
summary.fingerprint = hash;
return summary;
}
} // namespace evo::processes
+243
View File
@@ -0,0 +1,243 @@
#include "evo/processes/ecosystem.hpp"
#include <algorithm>
#include <iostream>
#include <limits>
#include <source_location>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
using namespace evo::processes;
using namespace evo::accounting;
void check(bool condition, std::source_location location = std::source_location::current()) {
if (!condition) {
throw std::runtime_error("ecosystem line " + std::to_string(location.line()));
}
}
#define CHECK(expression) check(static_cast<bool>(expression))
Inventory bundle(std::uint64_t value) {
return {{value}, {Femtograms{value}, Femtograms{value}, Femtograms{value}, Femtograms{value}}};
}
// Captures 10 energy and grows two whole recipe units each tick while funded.
ProducerConfig producer() {
return {{{10}, 1}, {2, 1}, 1000, {1}, bundle(1).matter};
}
Inventory sum(const FeedingCommunity& community) {
Inventory total{};
for (const auto& inventory : community.balances()) {
CHECK(inventory.energy.value <=
std::numeric_limits<std::uint64_t>::max() - total.energy.value);
total.energy.value += inventory.energy.value;
for (std::size_t index = 0; index < 4; ++index) {
CHECK(inventory.matter[index].value <=
std::numeric_limits<std::uint64_t>::max() - total.matter[index].value);
total.matter[index].value += inventory.matter[index].value;
}
}
return total;
}
EcosystemConfig grazing_world() {
return {producer(), {100'000}, bundle(200).matter, {bundle(4)}, 800, 14, 2000};
}
StrategyConfig grazer() {
return {bundle(20), bundle(3), 900, bundle(30), bundle(20), 50};
}
StrategyConfig forager() {
return {bundle(20), bundle(2), 1000, bundle(24), bundle(16), 70};
}
void solitary_founder_retires() {
// No source, no nutrients and no intake: nothing happens but ageing.
const EcosystemConfig config{producer(), {}, {}, {}, 1000, 0, 100};
const std::array founders{StrategyConfig{bundle(7), {}, 1000, bundle(1), bundle(1), 5}};
auto episode = EcosystemEpisode::create(config, founders, 1);
CHECK(episode);
const auto opening = sum(episode->community());
const auto summary = episode->run();
CHECK(summary);
CHECK(summary->ticks == 5 && summary->extinction_tick == 5);
CHECK(summary->lifespan_deaths == 1 && summary->predation_deaths == 0);
CHECK(summary->births == 0 && summary->surviving_lineages == 0);
CHECK(summary->founders == 1 && summary->conserved == opening);
// A retired founder keeps its identity and its founder ancestry.
CHECK(!*episode->community().active(2) && episode->lineage(2) == 2);
CHECK(episode->community().parent(2) && *episode->community().parent(2) == 0);
CHECK(episode->lineage(1) == 0); // The producer is not a consumer lineage.
// The episode is over; further steps do nothing.
const auto exhausted = episode->step();
CHECK(exhausted && !*exhausted && episode->report() == *summary);
}
void predation_retires_a_target() {
// The producer holds nothing, so the only target with inventory is the prey.
const EcosystemConfig config{producer(), {}, {}, {bundle(1)}, 1000, 0, 40};
const std::array founders{StrategyConfig{{}, bundle(100), 1000, bundle(10'000), bundle(1), 9},
StrategyConfig{bundle(5), {}, 1000, bundle(10'000), bundle(1), 30}};
auto episode = EcosystemEpisode::create(config, founders, 2);
CHECK(episode);
const auto opening = sum(episode->community());
const auto stepped = episode->step();
CHECK(stepped && *stepped);
CHECK(!*episode->community().active(3)); // Bitten for its whole inventory.
CHECK(episode->report().predation_deaths == 1);
CHECK(episode->report().lifespan_deaths == 0);
const auto summary = episode->run();
CHECK(summary);
// The predator outlives its prey and then reaches its own lifespan.
CHECK(summary->predation_deaths == 1 && summary->lifespan_deaths == 1);
CHECK(summary->extinction_tick == 9 && summary->ticks == 9);
CHECK(summary->births == 0 && summary->conserved == opening);
CHECK(episode->lineage(3) == 3); // Ancestry survives a predation death.
}
void births_exhaust_capacity() {
// Each parent funds one child per tick; children inherit the same strategy.
const EcosystemConfig config{producer(), {}, {}, {}, 1000, 6, 200};
const std::array founders{StrategyConfig{bundle(64), {}, 1000, bundle(2), bundle(2), 120}};
auto episode = EcosystemEpisode::create(config, founders, 3);
CHECK(episode);
const auto opening = sum(episode->community());
const auto summary = episode->run();
CHECK(summary);
CHECK(summary->births == 6); // Exactly the reserved slots, never more.
CHECK(summary->predation_deaths == 0 && summary->lifespan_deaths == 7);
CHECK(summary->extinction_tick == summary->ticks && summary->conserved == opening);
CHECK(summary->surviving_lineages == 0);
for (std::uint32_t id = 2; id <= 8; ++id) {
CHECK(*episode->community().born(id) && episode->lineage(id) == 2);
}
}
void tick_limit_stops_a_living_community() {
auto config = grazing_world();
config.tick_limit = 25;
const std::array founders{grazer(), forager()};
auto episode = EcosystemEpisode::create(config, founders, 4);
CHECK(episode);
const auto summary = episode->run();
CHECK(summary);
CHECK(summary->ticks == 25 && summary->extinction_tick == 0);
CHECK(summary->surviving_lineages >= 1 && summary->conserved == sum(episode->community()));
}
void seeded_episodes_conserve_and_end() {
const auto config = grazing_world();
const std::array founders{grazer(), forager()};
std::uint64_t total_ticks{}, extinctions{}, births{}, predation{}, lifespan{};
std::uint64_t shortest = std::numeric_limits<std::uint64_t>::max(), longest{};
std::uint64_t both_lineages{};
for (std::uint64_t seed = 0; seed < 64; ++seed) {
auto episode = EcosystemEpisode::create(config, founders, seed);
CHECK(episode);
const auto opening = sum(episode->community());
std::uint32_t peak_lineages{};
while (true) {
const auto stepped = episode->step();
CHECK(stepped); // The driver must never provoke a rejected batch.
if (!*stepped) {
break;
}
// Conservation is exact at every tick, not only at the end.
CHECK(sum(episode->community()) == opening);
peak_lineages = std::max(peak_lineages, episode->report().surviving_lineages);
}
const auto summary = episode->report();
CHECK(summary.conserved == opening && summary.seed == seed);
CHECK(summary.ticks > 0 && summary.ticks <= config.tick_limit);
CHECK(summary.births <= config.capacity);
// Every process dies at most once; the producer may also be grazed out.
CHECK(summary.predation_deaths + summary.lifespan_deaths <=
summary.founders + summary.births + 1);
if (summary.extinction_tick != 0) {
CHECK(summary.extinction_tick == summary.ticks);
CHECK(summary.surviving_lineages == 0);
++extinctions;
} else {
CHECK(summary.ticks == config.tick_limit && summary.surviving_lineages >= 1);
}
// Repeating one seed reproduces the whole episode exactly.
auto replay = EcosystemEpisode::create(config, founders, seed);
CHECK(replay);
const auto repeated = replay->run();
CHECK(repeated && *repeated == summary);
total_ticks += summary.ticks;
births += summary.births;
predation += summary.predation_deaths;
lifespan += summary.lifespan_deaths;
shortest = std::min(shortest, summary.ticks);
longest = std::max(longest, summary.ticks);
both_lineages += peak_lineages == 2 ? 1 : 0;
}
// Both mortality paths and reproduction must actually occur across the ensemble.
CHECK(births > 0 && predation > 0 && lifespan > 0);
CHECK(extinctions > 0 && both_lineages > 0 && shortest <= longest);
std::cout << "ecosystem ensemble: seeds=64 ticks=" << total_ticks << " births=" << births
<< " predation=" << predation << " lifespan=" << lifespan
<< " extinctions=" << extinctions << " shortest=" << shortest
<< " longest=" << longest << '\n';
}
void episodes_are_independent() {
const auto config = grazing_world();
const std::array founders{grazer(), forager()};
auto first = EcosystemEpisode::create(config, founders, 11);
auto second = EcosystemEpisode::create(config, founders, 11);
auto other = EcosystemEpisode::create(config, founders, 12);
CHECK(first && second && other);
// Interleaving two episodes cannot let one observe the other.
while (true) {
const auto left = first->step();
const auto right = second->step();
const auto unrelated = other->step();
CHECK(left && right && unrelated);
CHECK(first->report() == second->report());
if (!*left) {
CHECK(!*right);
break;
}
}
CHECK(first->report() == second->report());
CHECK(other->report().seed == 12 && other->report() != first->report());
}
void invalid_configuration_is_rejected() {
const auto config = grazing_world();
const std::array founders{grazer()};
CHECK(!EcosystemEpisode::create(config, {}, 1));
const std::vector<StrategyConfig> crowded(max_strategies + 1, grazer());
CHECK(!EcosystemEpisode::create(config, crowded, 1));
auto no_ticks = config;
no_ticks.tick_limit = 0;
CHECK(!EcosystemEpisode::create(no_ticks, founders, 1));
auto oversized = config;
oversized.capacity = static_cast<std::uint32_t>(max_consumers);
CHECK(!EcosystemEpisode::create(oversized, founders, 1));
for (auto broken : {0U, 1U, 2U}) {
auto invalid = founders[0];
if (broken == 0) {
invalid.lifespan = 0;
} else if (broken == 1) {
invalid.investment = {};
} else {
invalid.assimilation_per_thousand = 1001;
}
const std::array rejected{invalid};
CHECK(!EcosystemEpisode::create(config, rejected, 1));
}
}
} // namespace
int main() try {
solitary_founder_retires();
predation_retires_a_target();
births_exhaust_capacity();
tick_limit_stops_a_living_community();
episodes_are_independent();
invalid_configuration_is_rejected();
seeded_episodes_conserve_and_end();
std::cout << "PASS ecosystem episodes, mortality, lineage and conservation\n";
return 0;
} catch (...) {
return 1;
}