Resolve cellular engulfment and detritus in the region step
Foundation / checks (ecs) (push) Successful in 2m17s
Foundation / checks (deploy) (push) Successful in 3m57s
Foundation / postgres-tools (push) Canceled after 0s
Foundation / server-image (push) Canceled after 0s
Foundation / image (push) Canceled after 0s
Foundation / checks (postgres) (push) Canceled after 6m13s
Foundation / checks (checks) (push) Canceled after 6m19s
Foundation / checks (tsan) (push) Canceled after 3m58s
Foundation / checks (client) (push) Canceled after 6m17s
Foundation / checks (network) (push) Canceled after 6m18s

ADR-0124 implements ADR-0098's predation and corpse rules for the
cellular trial. Under rules 3 the pure region step adds an engulf phase
after every life's step: in ascending life id, a predator takes the
lowest-id contacted survivor whose total mass, times 1.5 per micrometre
of its membrane, is at most the predator's. The prey's whole inventory
moves once; the predator keeps what its remaining per-tick intake allows
and the rest, like every starvation corpse, becomes detritus in the
patch at the dead cell's 1 mm cell. Corpse candidates report their cause.
Rules 2 is unchanged and ignores engulf intents.

Owner, protocol v11, persistence and recovery wiring follow in the next
11.3f steps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dingo
2026-10-13 18:47:48 -04:00
co-authored by Claude Opus 5.5
parent 4751b23857
commit 0fb67c3257
9 changed files with 502 additions and 9 deletions
@@ -12,7 +12,7 @@ spec:
env:
- {name: REGION_SESSION, value: "dev"}
- {name: REGION_SESSION_LISTEN, value: "0.0.0.0:7400"}
- {name: REGION_SESSION_WINDOW, value: "dev-20261013T224028-49591:1791942028"}
- {name: REGION_SESSION_WINDOW, value: "dev-20261013T224748-73224:1791942468"}
- {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"}
ports:
# QUIC (ADR-0090): UDP only; nothing listens on TCP 7400.
@@ -0,0 +1,104 @@
# ADR-0124: Cellular engulfment and detritus
## Status
Accepted M11.3 engineering contract (2026-10-13), under the maintainer's standing
direction to proceed through M11 with recommendations. It implements the
predation and corpse rules already ratified in
[ADR-0098](0098-m11-first-cellular-loop-decisions.md) §6. Values marked
**tunable** are versioned trial inputs for the 11.9 playtests, not final rules.
## Context
The cellular trial resolves movement, maintenance, patch intake and starvation
(ADR-0101 to ADR-0107). ADR-0098 also requires engulfment of a sufficiently
smaller contacted cell, contested by the prey's membrane, with the prey's whole
inventory moving to the predator once and any excess left as detritus, and it
requires that a corpse can be absorbed by any cell. ADR-0107 kept starvation
corpses as inert records, and nothing can engulf yet.
The 2026-10-13 probe showed that a player's only feedback is patch intake and
reserve, and that founders are identical in size. Engulfment therefore becomes
possible only once mutation or later growth changes relative size; until then it
must still be resolved correctly.
## Decision
### Intent
- A cellular action names one target **kind**, replacing the intake flag in
byte 12 of the 24-byte canonical input: 0 none, 1 patch intake at the given
patch address, 2 engulf. An engulf intent carries zero coordinates; the server
chooses the prey. Clients still send only intentions.
- Kind 2 is accepted only on session protocol v11, which otherwise equals v10.
Earlier sessions keep refusing it, and their bytes are unchanged.
### Tick order (rules 3)
Each tick keeps the ADR-0104 single-life order and ADR-0106 patch arbitration,
then adds two phases, all in ascending stable life id:
1. **Step:** movement, maintenance and patch intake exactly as under rules 2.
A life that cannot pay maintenance starves (ADR-0107).
2. **Engulf:** each life that survived step 1 and holds an engulf intent takes at
most one prey: the lowest-id surviving life in contact (ADR-0102 footprint
contact) for which
`predator_total_mass × 1000 ≥ required × prey_total_mass`, where
`required = 1500 × prey_membrane_um` (**tunable**; 1.5 for the 1 µm founder
membrane, per ADR-0098). Total mass is the phenotype's structural plus
membrane mass. A life engulfed earlier in the phase can neither act nor be
taken twice. A predator cannot engulf itself.
3. **Death and detritus:** every life that died this tick (starved or engulfed)
becomes a corpse record. Its accumulated heat goes to the world heat owner.
### Transfer
- The prey's body and reserve, every channel, move out exactly once.
- The predator's reserve receives at most its per-tick intake limit in each
channel (the same capacity that bounds absorption). The remainder is detritus.
- Detritus, and the whole inventory of a starved cell, is deposited into the
habitat at the 1 mm patch cell containing the corpse's position:
- If a patch exists there, the inventory is added to its stock. The patch keeps
its provenance; the corpse record and lineage archive keep the dead organism's.
- Otherwise a new patch is created there with the dead life's source as
provenance.
- If the habitat is at its 4,096-patch bound, the nearest existing patch
(lowest address on a tie) receives it.
- Corpse records keep identity, position, growth, extent, death tick and a new
**cause** (starved or engulfed). Their inventory is zero under rules 3.
- Any cell absorbs detritus with ordinary patch intake. Nothing decays or
replenishes; every channel is conserved region-wide.
### Versions and persistence
- Cellular rules 3 and owner envelope 4 (the corpse cause) form a new version
bundle `{rules 3, envelope 4, habitat 1, coordinate 1, genome 1, development 2,
founder 1, archive 2, mutation_state 1}`.
- New regions are provisioned on it. Existing v2 and v3 regions keep rules 2 and
replay byte-for-byte; no in-place migration is provided in this step.
- Schema migration 34 admits the new bundle and canonical input kind 2 with
zero coordinates. Batch traces record the kind with each intent.
- Client presentation of an engulf control and of corpse causes belongs to
11.8 (maintainer-owned client UI).
## Alternatives
- **Explicit prey id in the action:** rejected for this step. It needs a new
message layout and lets a client name an unseen cell; contact already bounds
the choice, and the server picks deterministically.
- **Engulf without a capacity bound:** rejected. ADR-0098 bounds the transfer by
the predator's capacity, and per-tick intake is the only capacity cells have.
- **Keep corpses as separate food objects:** rejected for now. A second food
type needs its own perception, contact and client view; depositing into the
patch grid reuses all three.
- **Migrate existing regions in place:** deferred. Only DEV regions exist, and a
fresh region is cheaper to qualify than a no-tick rules migration.
## Consequences
- Biology gains a pure engulf/detritus resolution; the cellular owner, snapshot,
manifest bundle, SQL admission, protocol v11, batch trace and recovery change.
- Founders are equal in size, so live engulfment needs mutation (11.4) or
later growth before it is observable in play.
- Size may dominate predation (ADR-0098 risk); 11.9 watches for it, and the
required ratio stays tunable.
+1
View File
@@ -24,6 +24,7 @@
- [ADR-0121: Durable cellular mutation selection](0121-durable-cellular-mutation-selection.md) - specifies a distinct reliable action, allocator identity, tick-bound replay and atomic publication for M11.4c.
- [ADR-0122: Append-only cellular genome revisions](0122-append-only-cellular-genome-revisions.md) - preserves immutable birth-genome links while adding a versioned revision chain and no-tick cellular-v3 migration.
- [ADR-0123: Dev cellular region and life-allocator provisioning](0123-dev-cellular-region-and-life-allocator-provisioning.md) - moves DEV to cellular region 100/2 at schema v33 and has the owner provisioner create a world's life allocator once at an audited start.
- [ADR-0124: Cellular engulfment and detritus](0124-cellular-engulfment-and-detritus.md) - resolves engulfment of a sufficiently smaller contacted cell and deposits every corpse's inventory into the patch grid as absorbable detritus, under cellular rules 3.
- [ADR-0058: Region durability contract](0058-region-durability-contract.md) - accepted M7.1 full checkpoint batches and explicit state closure; storage implementation follows.
+12
View File
@@ -408,6 +408,18 @@ scoped change before starting the next segment.
evidence is green for the pushed M11.3 implementation. Only the live human
probe remains before 11.3 closes and 11.4 can begin.
- 11.3e probe (2026-10-13): the exploratory playtest ran in DEV region 100/3;
steering and feeding work end to end. Notes:
[probe notes](../playtests/M11_3_PROBE_NOTES_2026-10-13.md); session and
deployment fixes are recorded in ADR-0123.
- 11.3f-1 (ADR-0124): the pure region step gains rules 3. An engulf intent
takes the lowest-id contacted survivor at least 1.5x lighter per micrometre
of prey membrane; the prey's whole inventory moves once, bounded by the
predator's remaining per-tick intake, and the rest, like every starvation
corpse, is deposited as patch detritus (a new patch at an empty cell). Rules 2
is unchanged and ignores engulf. Owner, protocol, persistence and recovery
wiring remain.
## Exit boundary
11.3 closes only when the documented segments have evidence and the player-facing
+16 -1
View File
@@ -7206,4 +7206,19 @@ an identity only with `born`. The session layer now clears identity and commit
on every other result. `quic_sessions` adds an `existing_life` refusal that
must arrive valid while the session stays established. Locally (MSVC, client
preset) the case failed with the same 33-byte decode error before the fix and
passed after it.
passed after it.
## 2026-10-13 — M11.3f-1 cellular engulfment and detritus resolver (CI pending)
ADR-0124. `propose_cellular_region_step` takes `CellularRegionRules`; rules 3
adds an engulf phase after every life's step (ascending life id, one prey per
predator, contact plus `predator_mass × 1000 ≥ 1500 × prey_membrane_um ×
prey_mass`), bounds the predator's gain by its remaining per-tick intake, and
deposits detritus and starvation corpses into the patch at the dead cell's
1 mm cell (a new patch at an empty cell, the nearest patch when full). Corpse
candidates report a cause and predator. Rules 2 results are unchanged.
Executed locally: MSVC Debug full build and `ctest -R cellular` (6/6, with five
new region-step cases: capacity split and region-wide conservation, size,
membrane and contact refusal, one prey per predator per tick, empty-cell
detritus, rules-2 no-op and invalid rules-3 intents); g++-14 `-Werror`,
clang-tidy-19 and clang-format 19.1.5 on the changed files.
+36 -3
View File
@@ -12,6 +12,18 @@
namespace evo::biology {
inline constexpr std::size_t max_cellular_tick_lives = 256;
// ADR-0124 (rules 3): a predator needs total mass >= ratio x prey total mass, with the
// ratio in thousandths per micrometre of prey membrane (tunable; 1.5 for 1 um).
inline constexpr std::uint64_t cellular_engulf_ratio_milli_per_membrane_um = 1'500;
struct CellularRegionRules {
// Rules 3: engulfment, and every corpse's inventory deposited as patch detritus.
// Rules 2 (false) is the original trial: engulf intents are ignored and starvation
// corpses keep their inventory.
bool engulf_and_detritus{};
auto operator<=>(const CellularRegionRules&) const = default;
};
struct CellularLifeStepInput {
std::uint64_t life_id{}; // Stable world identity; arbitrates same-tick patch contention.
CellularPosition position;
@@ -21,11 +33,21 @@ struct CellularLifeStepInput {
accounting::Inventory reserve;
accounting::Inventory heat; // Energy-only owner; matter channels must be zero.
MetabolicBudget budget;
std::uint32_t membrane_um{}; // Genome membrane thickness; contests engulfment (rules 3).
std::uint64_t source{}; // Provenance for a detritus patch this life creates (rules 3).
auto operator<=>(const CellularLifeStepInput&) const = default;
};
enum class CellularEngulfStatus : std::uint8_t {
not_requested,
engulfed, // Took the reported prey.
no_eligible_prey, // Nothing in contact was small enough.
unsupported // Rules 2 region: the intent had no effect.
};
struct CellularLifeStepResult {
std::uint64_t life_id{};
CellularStepCandidate candidate;
CellularEngulfStatus engulf{CellularEngulfStatus::not_requested};
std::uint64_t prey_id{};
auto operator<=>(const CellularLifeStepResult&) const = default;
};
struct CellularPatchStockUpdate {
@@ -33,10 +55,15 @@ struct CellularPatchStockUpdate {
accounting::Inventory stock;
auto operator<=>(const CellularPatchStockUpdate&) const = default;
};
enum class CellularDeathCause : std::uint8_t { starved = 1, engulfed = 2 };
struct CellularCorpseCandidate {
std::uint64_t life_id{};
CellularPosition position;
accounting::Inventory inventory; // Body and reserve; accumulated heat is transferred out.
// Rules 2: body and reserve. Rules 3: empty, because the inventory moved to the
// predator and detritus. Accumulated heat is transferred out in both.
accounting::Inventory inventory;
CellularDeathCause cause{CellularDeathCause::starved};
std::uint64_t predator_id{}; // Engulfed only.
auto operator<=>(const CellularCorpseCandidate&) const = default;
};
struct CellularRegionStepCandidate {
@@ -44,7 +71,10 @@ struct CellularRegionStepCandidate {
// Sorted by stable life_id, independent of connection or input order.
std::vector<CellularLifeStepResult> lives;
std::vector<CellularPatchStockUpdate> patches;
// Dead this tick (starved or engulfed), sorted by life_id.
std::vector<CellularCorpseCandidate> starved;
// Rules 3 detritus patches created at empty cells, sorted by address.
std::vector<CellularPatch> new_patches;
accounting::Picojoules heat_released{};
auto operator<=>(const CellularRegionStepCandidate&) const = default;
};
@@ -57,7 +87,8 @@ enum class CellularRegionStepError : std::uint8_t {
invalid_heat,
overflow,
life_step,
habitat
habitat,
invalid_intent
};
// Detached shared-habitat candidate. Same-tick claims resolve by ascending stable life id;
@@ -65,8 +96,10 @@ enum class CellularRegionStepError : std::uint8_t {
// life step rejects the complete candidate; the caller publishes nothing. If maintenance
// cannot be paid, the life dies in this tick: body and reserve move to one corpse candidate,
// and its accumulated heat is reported separately for transfer to the world heat owner.
// Under rules 3 (ADR-0124) an engulf phase follows, and every dead life's inventory is
// deposited into the patch at its cell (a new patch when the cell is empty).
[[nodiscard]] std::expected<CellularRegionStepCandidate, CellularRegionStepError>
propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
std::span<const CellularLifeStepInput> lives,
const CellularHabitat& habitat);
const CellularHabitat& habitat, CellularRegionRules rules = {});
} // namespace evo::biology
+3
View File
@@ -9,6 +9,9 @@ namespace evo::biology {
struct CellularStepIntent {
CellularIntent movement{};
std::optional<CellularPatchAddress> intake_target;
// ADR-0124: take one smaller contacted cell after every life's step (rules 3 only).
// Exclusive with an intake target; the server chooses the prey.
bool engulf{};
auto operator<=>(const CellularStepIntent&) const = default;
};
+190 -3
View File
@@ -1,14 +1,59 @@
#include "evo/biology/cellular_region_step.hpp"
#include "evo/accounting/rates.hpp"
#include <algorithm>
#include <limits>
#include <utility>
namespace evo::biology {
namespace {
constexpr auto u64_max = std::numeric_limits<std::uint64_t>::max();
bool add(std::uint64_t& to, std::uint64_t amount) noexcept {
if (amount > u64_max - to)
return false;
to += amount;
return true;
}
bool add(accounting::Inventory& to, const accounting::Inventory& from) noexcept {
if (!add(to.energy.value, from.energy.value))
return false;
for (std::size_t channel = 0; channel < to.matter.size(); ++channel)
if (!add(to.matter[channel].value, from.matter[channel].value))
return false;
return true;
}
// a * ka >= b * kb without overflow: compares the exact 128-bit products.
bool product_at_least(std::uint64_t a, std::uint64_t ka, std::uint64_t b, std::uint64_t kb) {
const auto wide = [](std::uint64_t x, std::uint64_t y) {
const std::uint64_t x0 = x & 0xFFFFFFFFU, x1 = x >> 32U;
const std::uint64_t y0 = y & 0xFFFFFFFFU, y1 = y >> 32U;
const std::uint64_t p00 = x0 * y0, p01 = x0 * y1, p10 = x1 * y0, p11 = x1 * y1;
const std::uint64_t middle = (p00 >> 32U) + (p01 & 0xFFFFFFFFU) + (p10 & 0xFFFFFFFFU);
const std::uint64_t high = p11 + (p01 >> 32U) + (p10 >> 32U) + (middle >> 32U);
const std::uint64_t low = (middle << 32U) | (p00 & 0xFFFFFFFFU);
return std::pair{high, low};
};
return wide(a, ka) >= wide(b, kb);
}
CellularPatchAddress cell_of(CellularPosition position) noexcept {
return {static_cast<std::uint32_t>(position.x_um / cellular_patch_pitch_um *
cellular_patch_pitch_um),
static_cast<std::uint32_t>(position.y_um / cellular_patch_pitch_um *
cellular_patch_pitch_um)};
}
struct Deposit {
std::uint64_t life_id{}, source{};
CellularPosition position;
accounting::Inventory inventory;
};
} // namespace
std::expected<CellularRegionStepCandidate, CellularRegionStepError>
propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
std::span<const CellularLifeStepInput> lives,
const CellularHabitat& habitat) {
const CellularHabitat& habitat, CellularRegionRules rules) {
if (begin_tick == std::numeric_limits<std::uint64_t>::max())
return std::unexpected{CellularRegionStepError::invalid_tick};
if (lives.size() > max_cellular_tick_lives)
@@ -19,6 +64,9 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
for (const auto& life : lives) {
if (life.life_id == 0)
return std::unexpected{CellularRegionStepError::invalid_life_id};
if (rules.engulf_and_detritus && (life.membrane_um == 0 || life.source == 0 ||
(life.intent.engulf && life.intent.intake_target)))
return std::unexpected{CellularRegionStepError::invalid_intent};
ordered.push_back(&life);
}
std::ranges::sort(ordered, {}, [](const auto* life) { return life->life_id; });
@@ -26,13 +74,17 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
if (ordered[i - 1]->life_id == ordered[i]->life_id)
return std::unexpected{CellularRegionStepError::duplicate_life_id};
CellularRegionStepCandidate candidate{begin_tick, begin_tick + 1, {}, {}, {}, {}};
CellularRegionStepCandidate candidate{begin_tick, begin_tick + 1, {}, {}, {}, {}, {}};
candidate.lives.reserve(ordered.size());
candidate.starved.reserve(ordered.size());
std::vector<accounting::Inventory> patch_stock;
patch_stock.reserve(habitat.patches().size());
for (const auto& patch : habitat.patches())
patch_stock.push_back(patch.stock);
// Inputs of the lives still in candidate.lives, in the same order.
std::vector<const CellularLifeStepInput*> survivors;
survivors.reserve(ordered.size());
std::vector<Deposit> deposits;
for (const auto* life : ordered) {
if (life->body.energy.value != 0)
@@ -43,6 +95,7 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
auto intent = life->intent;
const auto target = intent.intake_target;
intent.intake_target.reset();
intent.engulf = false;
const auto step =
propose_cellular_step(begin_tick, area, life->position, life->extent_um, intent,
life->reserve, life->heat, life->budget, habitat);
@@ -59,6 +112,10 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
std::numeric_limits<std::uint64_t>::max() - candidate.heat_released.value)
return std::unexpected{CellularRegionStepError::overflow};
candidate.heat_released.value += life->heat.energy.value;
if (rules.engulf_and_detritus) {
deposits.push_back({life->life_id, life->source, life->position, corpse.inventory});
corpse.inventory = {};
}
candidate.starved.push_back(corpse);
continue;
}
@@ -87,7 +144,137 @@ propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area,
}
}
}
candidate.lives.push_back({life->life_id, result});
CellularLifeStepResult life_result{life->life_id, result};
if (life->intent.engulf)
life_result.engulf = rules.engulf_and_detritus ? CellularEngulfStatus::no_eligible_prey
: CellularEngulfStatus::unsupported;
candidate.lives.push_back(life_result);
survivors.push_back(life);
}
if (rules.engulf_and_detritus) {
// Engulf phase (ADR-0124): ascending predator id; each takes at most the lowest-id
// eligible survivor in contact. A taken life neither acts nor is taken again.
std::vector<bool> taken(candidate.lives.size(), false);
for (std::size_t p = 0; p < candidate.lives.size(); ++p) {
if (taken[p] || !survivors[p]->intent.engulf)
continue;
auto& predator = candidate.lives[p];
const auto* hunter = survivors[p];
for (std::size_t q = 0; q < candidate.lives.size(); ++q) {
if (q == p || taken[q])
continue;
const auto* prey = survivors[q];
const auto& prey_step = candidate.lives[q].candidate;
if (!cellular_footprints_contact(predator.candidate.position, hunter->extent_um,
prey_step.position, prey->extent_um) ||
!product_at_least(hunter->budget.phenotype.total_mass, 1'000,
prey->budget.phenotype.total_mass,
cellular_engulf_ratio_milli_per_membrane_um *
prey->membrane_um))
continue;
// The prey's whole inventory moves once: body matter and its post-step reserve.
accounting::Inventory whole = prey_step.reserve_after;
if (!add(whole, prey->body))
return std::unexpected{CellularRegionStepError::overflow};
if (!add(candidate.heat_released.value, prey_step.heat_after.energy.value))
return std::unexpected{CellularRegionStepError::overflow};
// Capacity: what is left of the predator's per-tick intake limit this tick.
const auto remaining = [&](std::uint64_t per_second,
std::uint64_t already) -> std::optional<std::uint64_t> {
const auto limit = accounting::per_tick(
per_second, cellular_motion_tick_microseconds, accounting::Rounding::down);
if (!limit)
return std::nullopt;
return *limit > already ? *limit - already : 0;
};
const auto acquired = predator.candidate.intake
? predator.candidate.intake->transfer.acquired
: accounting::Inventory{};
accounting::Inventory taken_in{};
const auto energy_room =
remaining(hunter->budget.intake_limit.energy.value, acquired.energy.value);
if (!energy_room)
return std::unexpected{CellularRegionStepError::overflow};
taken_in.energy.value = std::min(whole.energy.value, *energy_room);
for (std::size_t channel = 0; channel < whole.matter.size(); ++channel) {
const auto room = remaining(hunter->budget.intake_limit.matter[channel].value,
acquired.matter[channel].value);
if (!room)
return std::unexpected{CellularRegionStepError::overflow};
taken_in.matter[channel].value = std::min(whole.matter[channel].value, *room);
}
if (!add(predator.candidate.reserve_after, taken_in))
return std::unexpected{CellularRegionStepError::overflow};
accounting::Inventory detritus = whole;
detritus.energy.value -= taken_in.energy.value;
for (std::size_t channel = 0; channel < detritus.matter.size(); ++channel)
detritus.matter[channel].value -= taken_in.matter[channel].value;
deposits.push_back({prey->life_id, prey->source, prey_step.position, detritus});
CellularCorpseCandidate corpse{prey->life_id, prey_step.position, {}};
corpse.cause = CellularDeathCause::engulfed;
corpse.predator_id = hunter->life_id;
candidate.starved.push_back(corpse);
predator.engulf = CellularEngulfStatus::engulfed;
predator.prey_id = prey->life_id;
taken[q] = true;
break;
}
}
std::vector<CellularLifeStepResult> remaining_lives;
remaining_lives.reserve(candidate.lives.size());
for (std::size_t i = 0; i < candidate.lives.size(); ++i)
if (!taken[i])
remaining_lives.push_back(candidate.lives[i]);
candidate.lives = std::move(remaining_lives);
std::ranges::sort(candidate.starved, {}, &CellularCorpseCandidate::life_id);
// Detritus: each dead life's inventory goes to the patch at its cell, a new patch at
// an empty cell, or the nearest patch once the habitat is full.
std::ranges::sort(deposits, {}, &Deposit::life_id);
for (const auto& deposit : deposits) {
const auto address = cell_of(deposit.position);
if (const auto index = habitat.find(address)) {
if (!add(patch_stock[*index], deposit.inventory))
return std::unexpected{CellularRegionStepError::overflow};
continue;
}
const auto made = std::ranges::lower_bound(candidate.new_patches, address, {},
&CellularPatch::address);
if (made != candidate.new_patches.end() && made->address == address) {
if (!add(made->stock, deposit.inventory))
return std::unexpected{CellularRegionStepError::overflow};
continue;
}
if (habitat.patches().size() + candidate.new_patches.size() < max_cellular_patches) {
candidate.new_patches.insert(made, {address, deposit.source, deposit.inventory});
continue;
}
// Full habitat: nearest existing patch, lowest address on a tie.
const auto distance = [&](CellularPatchAddress other) {
const auto dx = static_cast<std::int64_t>(other.x_um) - address.x_um;
const auto dy = static_cast<std::int64_t>(other.y_um) - address.y_um;
return static_cast<std::uint64_t>(dx * dx) + static_cast<std::uint64_t>(dy * dy);
};
std::optional<std::pair<std::uint64_t, CellularPatchAddress>> best;
for (const auto& patch : habitat.patches())
if (!best || std::pair{distance(patch.address), patch.address} < *best)
best = std::pair{distance(patch.address), patch.address};
for (const auto& patch : candidate.new_patches)
if (!best || std::pair{distance(patch.address), patch.address} < *best)
best = std::pair{distance(patch.address), patch.address};
if (!best)
return std::unexpected{CellularRegionStepError::habitat};
if (const auto index = habitat.find(best->second)) {
if (!add(patch_stock[*index], deposit.inventory))
return std::unexpected{CellularRegionStepError::overflow};
} else {
const auto nearest = std::ranges::lower_bound(candidate.new_patches, best->second,
{}, &CellularPatch::address);
if (!add(nearest->stock, deposit.inventory))
return std::unexpected{CellularRegionStepError::overflow};
}
}
}
for (std::size_t i = 0; i < patch_stock.size(); ++i)
+139 -1
View File
@@ -95,13 +95,151 @@ void refusal_never_returns_partial_tick_state() {
CHECK(result->patches.empty());
CHECK(map->patches()[0].stock == Inventory{{5}, {{{2}, {2}, {2}, {2}}}});
}
// ADR-0124 (rules 3) helpers: a cell of the given total mass, membrane and engulf intent.
CellularLifeStepInput cell(std::uint64_t id, CellularPosition at, std::uint64_t mass,
std::uint32_t membrane, bool engulf) {
CellularLifeStepInput life{id, at, 20, {}, {{0}, {{{10}, {10}, {10}, {10}}}},
{{100}, {}}, {}, budget()};
life.budget.phenotype.total_mass = mass;
life.intent.engulf = engulf;
life.membrane_um = membrane;
life.source = 900 + id;
return life;
}
constexpr CellularRegionRules rules3{true};
Inventory total(const CellularRegionStepCandidate& c, const CellularHabitat& map) {
Inventory sum{};
const auto add = [&](const Inventory& v) {
sum.energy.value += v.energy.value;
for (std::size_t i = 0; i < v.matter.size(); ++i)
sum.matter[i].value += v.matter[i].value;
};
std::vector<bool> updated(map.patches().size(), false);
for (const auto& patch : c.patches) {
add(patch.stock);
const auto index = map.find(patch.address);
CHECK(index.has_value());
if (index)
updated[*index] = true;
}
for (std::size_t i = 0; i < updated.size(); ++i)
if (!updated[i])
add(map.patches()[i].stock);
for (const auto& patch : c.new_patches)
add(patch.stock);
for (const auto& corpse : c.starved)
add(corpse.inventory);
sum.energy.value += c.heat_released.value;
return sum;
}
void engulfment_moves_the_prey_once_bounded_by_capacity() {
const auto map = habitat();
// Predator 3x the prey's mass, prey with a 1 um membrane: 3 >= 1.5.
const std::array input{cell(2, {0, 0}, 1'000, 1, false), cell(1, {10, 0}, 3'000, 1, true)};
const auto result = propose_cellular_region_step(4, {3'000, 2'000}, input, *map, rules3);
CHECK(result);
CHECK(result->lives.size() == 1 && result->lives[0].life_id == 1);
CHECK(result->lives[0].engulf == CellularEngulfStatus::engulfed &&
result->lives[0].prey_id == 2);
CHECK(result->starved.size() == 1 && result->starved[0].life_id == 2 &&
result->starved[0].cause == CellularDeathCause::engulfed &&
result->starved[0].predator_id == 1 && result->starved[0].inventory == Inventory{});
// Capacity is the per-tick intake limit: 1,000 per second is 50 per 50 ms tick.
// The prey holds 100 pJ and 10 fg per channel; the predator takes 50 pJ and all matter.
const auto& predator = result->lives[0].candidate.reserve_after;
CHECK(predator.energy.value == 100 + 50);
CHECK(predator.matter[0].value == 10);
// The other 50 pJ is detritus in the patch at the prey's cell.
CHECK(result->patches.size() == 1 &&
result->patches[0] == CellularPatchStockUpdate{{0, 0}, {{55}, {{{2}, {2}, {2}, {2}}}}});
CHECK(result->new_patches.empty());
// Region-wide conservation: lives + patches + corpses + released heat.
auto after = total(*result, *map);
after.energy.value += predator.energy.value;
for (std::size_t i = 0; i < after.matter.size(); ++i)
after.matter[i].value += predator.matter[i].value + 10; // The predator's body.
CHECK(after == Inventory{{5 + 100 + 100}, {{{2 + 20}, {2 + 20}, {2 + 20}, {2 + 20}}}});
}
void size_and_membrane_contest_engulfment() {
const auto map = habitat();
const std::array equal{cell(1, {0, 0}, 1'000, 1, true), cell(2, {0, 0}, 1'000, 1, false)};
const auto same = propose_cellular_region_step(4, {3'000, 2'000}, equal, *map, rules3);
CHECK(same && same->lives.size() == 2 && same->starved.empty());
CHECK(same->lives[0].engulf == CellularEngulfStatus::no_eligible_prey);
// A 3 um membrane raises the required ratio to 4.5; a 3x predator fails.
const std::array armored{cell(1, {0, 0}, 3'000, 1, true), cell(2, {0, 0}, 1'000, 3, false)};
const auto defended = propose_cellular_region_step(4, {3'000, 2'000}, armored, *map, rules3);
CHECK(defended && defended->lives.size() == 2 && defended->starved.empty());
// Out of contact: no prey, whatever the size.
const std::array apart{cell(1, {0, 0}, 9'000, 1, true), cell(2, {2'000, 0}, 1'000, 1, false)};
const auto distant = propose_cellular_region_step(4, {3'000, 2'000}, apart, *map, rules3);
CHECK(distant && distant->lives.size() == 2 &&
distant->lives[0].engulf == CellularEngulfStatus::no_eligible_prey);
}
void a_taken_cell_neither_acts_nor_is_taken_twice() {
const auto map = habitat();
// 1 takes 2 first (ascending id), so 2's own engulf of 3 never happens and 4 cannot
// take 2 again; 4 takes 3 instead.
const std::array input{cell(1, {0, 0}, 9'000, 1, true), cell(2, {0, 0}, 3'000, 1, true),
cell(3, {0, 0}, 1'000, 1, false), cell(4, {0, 0}, 9'000, 1, true)};
const auto result = propose_cellular_region_step(4, {3'000, 2'000}, input, *map, rules3);
CHECK(result && result->lives.size() == 2);
CHECK(result->lives[0].life_id == 1 && result->lives[0].prey_id == 2);
CHECK(result->lives[1].life_id == 4 && result->lives[1].prey_id == 3);
CHECK(result->starved.size() == 2 && result->starved[0].predator_id == 1 &&
result->starved[1].predator_id == 4);
}
void starvation_detritus_creates_a_patch_at_an_empty_cell() {
const auto map = habitat();
auto starving = cell(5, {1'500, 1'500}, 1'000, 1, false);
starving.budget.maintenance = {1'000'000};
const std::array input{starving};
const auto result = propose_cellular_region_step(4, {3'000, 2'000}, input, *map, rules3);
CHECK(result && result->lives.empty() && result->starved.size() == 1);
CHECK(result->starved[0].cause == CellularDeathCause::starved &&
result->starved[0].inventory == Inventory{});
CHECK(result->new_patches.size() == 1);
CHECK(result->new_patches[0] ==
CellularPatch{{1'000, 1'000}, 905, {{100}, {{{10}, {10}, {10}, {10}}}}});
CHECK(result->patches.empty());
}
void rules_two_ignores_engulf_and_rules_three_refuses_bad_intents() {
const auto map = habitat();
const std::array input{cell(1, {0, 0}, 9'000, 1, true), cell(2, {0, 0}, 1'000, 1, false)};
const auto legacy = propose_cellular_region_step(4, {3'000, 2'000}, input, *map);
CHECK(legacy && legacy->lives.size() == 2 && legacy->starved.empty() &&
legacy->lives[0].engulf == CellularEngulfStatus::unsupported);
auto both = cell(1, {0, 0}, 9'000, 1, true);
both.intent.intake_target = CellularPatchAddress{0, 0};
const std::array conflicting{both};
const auto refused = propose_cellular_region_step(4, {3'000, 2'000}, conflicting, *map, rules3);
CHECK(!refused && refused.error() == CellularRegionStepError::invalid_intent);
const std::array bare{cell(1, {0, 0}, 9'000, 0, false)};
const auto unmembraned = propose_cellular_region_step(4, {3'000, 2'000}, bare, *map, rules3);
CHECK(!unmembraned && unmembraned.error() == CellularRegionStepError::invalid_intent);
}
} // namespace
int main() {
try {
shared_patch_claims_are_identity_ordered_and_conserved();
refusal_never_returns_partial_tick_state();
std::puts("PASS cellular region step: shared claims and starvation closure");
engulfment_moves_the_prey_once_bounded_by_capacity();
size_and_membrane_contest_engulfment();
a_taken_cell_neither_acts_nor_is_taken_twice();
starvation_detritus_creates_a_patch_at_an_empty_cell();
rules_two_ignores_engulf_and_rules_three_refuses_bad_intents();
std::puts("PASS cellular region step: shared claims, starvation, engulfment, detritus");
} catch (const std::exception& error) {
std::fprintf(stderr, "%s\n", error.what());
return 1;