Files
aevolution/src/biology/metabolism.cpp
T
dingoandClaude Opus 5.5 c183021fd5
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 4s
Foundation / checks (client) (push) Successful in 4s
Foundation / checks (postgres) (push) Successful in 4s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m27s
Foundation / postgres-tools (push) Successful in 33s
Foundation / server-image (push) Successful in 4m14s
Foundation / image (push) Successful in 4m41s
feat(biology): genome schema 7 traits, founder 6 and development 7
Phase 1 of the cellular revamp build plan (ADR-0179). Genome schema 7 carries
twenty 16-bit cellular traits after the movement arrangement: density, upkeep
efficiency, growth speed, collection per channel (E/C/N/P/O), burn efficiency
per matter channel, engulf capacity, kill absorption, litter, the body recipe
(C/N/P/O per thousand, summing to 1000) and adhesion. Its membrane is held in
nanometres so it can change in 5% steps of the founder's 1 um. The largest
record still fits the 256-byte bound.

Development 7 and founder 6 serve rules 13: density sets how large a body is
for its mass, the recipe sets the body's composition (intake keeps the founder
shares), upkeep is an essential share no trait reduces plus the rest over upkeep
efficiency (region-declared BodyTuning, trial 25%), the producer speed penalty
is dropped, and the reproduction value is the bud's share of the body with the
construction discount fixed at the founder's level. Founder 6 builds exactly
founder 5's cell. Earlier schemas and development versions are unchanged.

The development and metabolism test mains now print the failing line. Refreshes
the DEV session window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:09:06 -04:00

278 lines
13 KiB
C++

#include "evo/biology/metabolism.hpp"
#include "evo/accounting/rates.hpp"
#include <algorithm>
#include <limits>
namespace evo::biology {
namespace {
constexpr std::uint64_t thousand = 1000;
// Membrane is the more carbon-rich compartment, so a thicker one changes what a
// body is made of and not only how much of it there is.
constexpr Composition structure_shares{500, 150, 50, 300};
constexpr Composition membrane_shares{700, 50, 100, 150};
constexpr std::uint32_t total_share(const Composition& shares) noexcept {
std::uint32_t sum = 0;
for (const auto share : shares) {
sum += share;
}
return sum;
}
static_assert(total_share(structure_shares) == thousand);
static_assert(total_share(membrane_shares) == thousand);
bool multiply(std::uint64_t& result, std::uint64_t left, std::uint64_t right) noexcept {
if (left != 0 && right > std::numeric_limits<std::uint64_t>::max() / left) {
return false;
}
result = left * right;
return true;
}
bool add(std::uint64_t& result, std::uint64_t left, std::uint64_t right) noexcept {
if (right > std::numeric_limits<std::uint64_t>::max() - left) {
return false;
}
result = left + right;
return true;
}
// Declared flooring, matching ADR-0031's derivation.
std::uint64_t scaled(std::uint64_t value, std::uint64_t numerator) noexcept {
return value / thousand * numerator + value % thousand * numerator / thousand;
}
// Splits a mass across the ledger's channels. The last channel takes whatever the
// first three left, so the parts always sum back to the whole.
accounting::Inventory compose(std::uint64_t mass, const Composition& shares) noexcept {
accounting::Inventory parts{};
std::uint64_t assigned = 0;
for (std::size_t index = 0; index + 1 < shares.size(); ++index) {
const auto part = scaled(mass, shares[index]);
parts.matter[index].value = part;
assigned += part;
}
parts.matter[shares.size() - 1].value = mass - assigned;
return parts;
}
bool combine(accounting::Inventory& total, const accounting::Inventory& amount) noexcept {
if (!add(total.energy.value, total.energy.value, amount.energy.value)) {
return false;
}
for (std::size_t index = 0; index < total.matter.size(); ++index) {
if (!add(total.matter[index].value, total.matter[index].value,
amount.matter[index].value)) {
return false;
}
}
return true;
}
// Every channel and the energy must fit: a surplus of one element never pays for
// a shortfall of another.
bool fits(const accounting::Inventory& needed, const accounting::Inventory& available) noexcept {
if (needed.energy > available.energy) {
return false;
}
for (std::size_t index = 0; index < needed.matter.size(); ++index) {
if (needed.matter[index] > available.matter[index]) {
return false;
}
}
return true;
}
std::uint64_t matter_total(const accounting::Inventory& inventory) noexcept {
std::uint64_t sum = 0;
for (const auto& mass : inventory.matter) {
sum += mass.value;
}
return sum;
}
// Scales an inventory's matter while keeping its composition. The last channel
// again takes the remainder, so the parts sum to the scaled whole exactly.
accounting::Inventory fraction_of(const accounting::Inventory& source,
std::uint64_t numerator) noexcept {
accounting::Inventory parts{};
const auto whole = scaled(matter_total(source), numerator);
std::uint64_t assigned = 0;
for (std::size_t index = 0; index + 1 < source.matter.size(); ++index) {
const auto part = scaled(source.matter[index].value, numerator);
parts.matter[index].value = part;
assigned += part;
}
parts.matter[source.matter.size() - 1].value = whole - assigned;
return parts;
}
} // namespace
std::expected<MetabolicRules, DevelopmentError>
metabolic_rules_for(std::uint32_t development_version) {
if (development_version == 1) {
return MetabolicRules{structure_shares, membrane_shares, 20, 50'000};
}
// Version 2: per second; movement at 1000 um/s costs 50 pJ/s per 1000 fg (tunable).
// Versions 3 to 7: the same metabolism. Version 7 reads the body's structure recipe from
// the genome's cellular traits instead (ADR-0179); intake keeps these founder shares.
if (development_version >= 2 && development_version <= 7) {
return MetabolicRules{structure_shares, membrane_shares, 50, 50'000};
}
return std::unexpected{DevelopmentError::unsupported_rules};
}
std::expected<MetabolicBudget, DevelopmentError>
metabolic_budget(const Genome& genome, GrowthState growth, EnvironmentState environment,
std::uint32_t max_growth_per_thousand, const BodyTuning& tuning) {
const auto phenotype = derive_phenotype(genome, growth, environment, tuning);
if (!phenotype) {
return std::unexpected{phenotype.error()};
}
const auto rules = metabolic_rules_for(genome.development_version());
if (!rules) {
return std::unexpected{rules.error()};
}
const auto shape = rules_for(genome.development_version());
if (!shape) {
return std::unexpected{shape.error()};
}
// The heritable recipe (version 7) or the version's fixed structure shares.
const auto& traits = genome.cellular_traits();
const Composition structure = traits ? Composition{traits->recipe[0], traits->recipe[1],
traits->recipe[2], traits->recipe[3]}
: rules->structure;
MetabolicBudget budget;
budget.phenotype = *phenotype;
budget.rate_microseconds = development_rate_microseconds(genome.development_version());
budget.assimilation_per_thousand =
static_cast<std::uint16_t>(phenotype->conversion_per_thousand);
budget.body = compose(phenotype->structural_mass, structure);
if (!combine(budget.body, compose(phenotype->membrane_mass, rules->membrane))) {
return std::unexpected{DevelopmentError::overflow};
}
budget.maintenance.value = phenotype->maintenance;
// Moving a larger body costs more, so a thicker membrane is paid for twice.
std::uint64_t haulage{};
if (!multiply(haulage, scaled(phenotype->total_mass, rules->movement_per_kilogram),
phenotype->movement_speed)) {
return std::unexpected{DevelopmentError::overflow};
}
budget.movement.value = haulage / thousand;
if (!add(budget.demand.value, budget.maintenance.value, budget.movement.value)) {
return std::unexpected{DevelopmentError::overflow};
}
// Intake funds structure, so it arrives in the proportions structure needs.
budget.intake_limit = compose(phenotype->ingestion_rate, rules->structure);
budget.intake_limit.energy.value =
scaled(phenotype->ingestion_rate, rules->intake_energy_per_kilogram);
const auto plan = plan_development(genome, growth, environment, tuning);
if (!plan) {
return std::unexpected{plan.error()};
}
// A plan bounds by total mass, which cannot tell whether the elements a step
// consumes are actually there: released matter never substitutes for an
// element the step needs. Narrow the proposal to the largest step whose own
// 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 = 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, tuning);
if (!grown) {
return std::unexpected{grown.error()};
}
// Compose the grown body and difference it against the current one.
// Composing the mass difference instead would discard the rounding this
// body already carries, and the budget could not then reproduce the
// derived body channel by channel. Each compartment is still composed
// separately: the two differ in what they cost.
auto reached = compose(grown->structural_mass, structure);
if (!combine(reached, compose(grown->membrane_mass, rules->membrane))) {
return std::unexpected{DevelopmentError::overflow};
}
ConstructionTransition move{};
move.after = candidate;
std::uint64_t acquired = 0, freed = 0;
for (std::size_t index = 0; index < reached.matter.size(); ++index) {
const auto held = budget.body.matter[index].value;
const auto wanted = reached.matter[index].value;
if (wanted >= held) {
move.intake.matter[index].value = wanted - held;
acquired += wanted - held;
} else {
move.release.matter[index].value = held - wanted;
freed += held - wanted;
}
}
// Energy is priced on the net mass change, as the plan prices it.
move.intake.energy.value = scaled(acquired - freed, shape->construction_per_kilogram);
if (!fits(move.intake, environment.available)) {
continue;
}
budget.construction = move;
break;
}
if (genome.carries(Capability::reproduction)) {
const auto value = *genome.parameter(Capability::reproduction);
// Version 4 (ADR-0137): a bud is always half the body, and reproduction is skill:
// it takes up to half off the bud's construction energy (value / 2000). Matter is
// never discounted (ADR-0118). Earlier versions invest `value` per thousand.
// Version 7 (ADR-0179): `value` is again the bud's share of the body, and keeps the
// skill discount at the founder's 500.
const bool skill = genome.development_version() >= 4;
const bool share = genome.development_version() >= 7;
const auto fraction = share || !skill ? value : bud_body_per_thousand_v4;
// A parent divides the body it has, so the investment keeps its composition.
budget.reproduction_investment = fraction_of(budget.body, fraction);
// Offspring tissue is priced at what the parent's own tissue costs.
const auto construction =
scaled(matter_total(budget.reproduction_investment), shape->construction_per_kilogram);
// Discount = construction * skill / 2000, split to stay within 64 bits.
// Version 7 fixes the discount at the founder's level, so bigger buds are not cheaper.
const std::uint64_t level =
share ? primitive_bud_skill_v7 : std::min<std::uint32_t>(value, 1000);
const auto discount = construction / 2000 * level + construction % 2000 * level / 2000;
budget.reproduction_investment.energy.value =
skill ? construction - discount : construction;
}
return budget;
}
std::optional<std::uint64_t> bud_funding_seconds(const MetabolicBudget& budget,
std::uint32_t feeding_per_thousand) noexcept {
const auto period = budget.rate_microseconds;
if (period == 0 || accounting::microseconds_per_second % period != 0 ||
feeding_per_thousand == 0 || feeding_per_thousand > thousand ||
matter_total(budget.reproduction_investment) == 0)
return std::nullopt;
const auto periods_per_second = accounting::microseconds_per_second / period;
// Per-second amounts; ceil(need / rate) seconds for each.
const auto seconds = [&](std::uint64_t need,
std::uint64_t per_period) -> std::optional<std::uint64_t> {
if (need == 0)
return std::uint64_t{0};
std::uint64_t per_second{};
if (!multiply(per_second, scaled(per_period, feeding_per_thousand), periods_per_second) ||
per_second == 0)
return std::nullopt;
return need / per_second + (need % per_second != 0 ? 1 : 0);
};
std::uint64_t longest = 0;
for (std::size_t c = 0; c < budget.reproduction_investment.matter.size(); ++c) {
const auto t = seconds(budget.reproduction_investment.matter[c].value,
budget.intake_limit.matter[c].value);
if (!t)
return std::nullopt;
longest = std::max(longest, *t);
}
// Energy: the fed share of intake, less the whole demand, all per period.
const auto fed = scaled(budget.intake_limit.energy.value, feeding_per_thousand);
if (fed <= budget.demand.value)
return std::nullopt;
std::uint64_t surplus{};
if (!multiply(surplus, fed - budget.demand.value, periods_per_second) || surplus == 0)
return std::nullopt;
const auto need = budget.reproduction_investment.energy.value;
longest = std::max(longest, need / surplus + (need % surplus != 0 ? 1 : 0));
return longest;
}
} // namespace evo::biology