#include "evo/biology/mutation.hpp" #include "evo/biology/founder.hpp" #include "evo/core/random.hpp" #include #include #include #include namespace evo::biology { namespace { // Four effects over eight capabilities. IDs are stable and carry no ranking; // photosynthesis (ADR-0175) appends IDs 29-32, so every earlier ID is unchanged; // they exist to order candidates canonically and to name one across calls. constexpr std::array catalog = [] { std::array entries{}; std::uint16_t next = 1; for (std::size_t index = 0; index < capability_count; ++index) { const auto kind = static_cast(index); for (const auto effect : {MutationEffect::adjust_up, MutationEffect::adjust_down, MutationEffect::acquire, MutationEffect::shed}) { entries[static_cast(next - 1)] = {next, kind, effect}; ++next; } } return entries; }(); // One rule rather than a constant per capability: a hundredth of the declared // range, at least one. Granularity follows the range, which is a stated model // choice and not a claim about biology. // The step comes from the genome's own schema, so a lineage keeps its steps. Schema 3 // (rules 6, 2026-10-15 balance) takes a third of that step: successor bodies differ a // third as much, so the matter a mutation needs falls with them (ADR-0118: the cost is // the body difference, never a discount). // Schema 4 (rules 7, ADR-0137) steps by a tenth of the current value instead (at least 1), // so a trait changes by a percentage and a lineage compounds. constexpr std::uint32_t adjustment_step(const std::array& table, Capability kind, std::uint32_t schema, std::uint32_t current) noexcept { if (schema >= genome_schema_v4) return current / 10 == 0 ? 1 : current / 10; const auto& limits = table[static_cast(kind)]; const auto span = limits.maximum - limits.minimum; const std::uint32_t divisor = schema == genome_schema_v3 ? 300 : 100; return span / divisor == 0 ? 1 : span / divisor; } std::uint32_t acquired_start(Capability kind, const CapabilitySpec& limits) noexcept { const auto& p = primitive_founder_parameters; const auto value = kind == Capability::movement ? p.movement : kind == Capability::ingestion ? p.ingestion : kind == Capability::reproduction ? p.reproduction : kind == Capability::photosynthesis ? photosynthesis_acquired_start : limits.minimum; return std::clamp(value, limits.minimum, limits.maximum); } std::uint64_t mix(std::uint64_t hash, std::uint64_t value) noexcept { // Non-cryptographic combiner. No wall clock and no std::hash enters this. return hash ^ (value + 0x9e3779b97f4a7c15ULL + (hash << 6U) + (hash >> 2U)); } std::uint64_t context_digest(const Genome& genome, const MutationContext& context) noexcept { std::uint64_t hash = genome.content_digest(); for (const auto value : {context.seed, static_cast(context.stream), context.event_index, static_cast(context.candidate_count), static_cast(context.growth.realized_per_thousand), static_cast(context.growth.damage_per_thousand), static_cast(context.environment.temperature_millikelvin), context.environment.available.energy.value}) { hash = mix(hash, value); } for (const auto& mass : context.environment.available.matter) { hash = mix(hash, mass.value); } return hash; } // Exactly uniform below bound. Plain modulo would lean very slightly toward low // operator IDs, which is precisely the bias this increment must be able to deny. std::uint64_t bounded(Random& stream, std::uint64_t bound) noexcept { const auto limit = std::numeric_limits::max() - std::numeric_limits::max() % bound; auto draw = stream.next(); while (draw >= limit) { draw = stream.next(); } return draw % bound; } // Applies one operator, or reports that it does not apply at all. Validity is // left entirely to Genome::create: prerequisites, required capabilities, ranges // and the development graph are enforced once, where they were defined. std::optional apply(const Genome& genome, const MutationOperator& entry, std::uint64_t id, std::uint64_t origin_event) { GenomeDraft draft; // A successor keeps its parent's schema: its parameters are the parent's, in the // parent's units (ADR-0099), and a lineage's offers never shift by migration. draft.schema_version = genome.schema_version(); draft.id = id; draft.origin_event = origin_event; draft.development_version = genome.development_version(); draft.parents = {genome.id()}; draft.capabilities.assign(genome.capabilities().begin(), genome.capabilities().end()); draft.movement_arrangement = genome.movement_arrangement(); draft.cellular_traits = genome.cellular_traits(); const auto& table = *capability_schema_for(genome.schema_version()); const auto& limits = table[static_cast(entry.target)]; const auto carried = std::ranges::find(draft.capabilities, entry.target, &CapabilityRecord::kind); const auto present = carried != draft.capabilities.end(); switch (entry.effect) { case MutationEffect::adjust_up: { if (!present) { return std::nullopt; } const auto step = adjustment_step(table, entry.target, genome.schema_version(), carried->parameter); // Refused rather than clamped: a clamp would make two operators agree // and would offer a no-op as a real choice. if (carried->parameter > limits.maximum - step) { return std::nullopt; } carried->parameter += step; break; } case MutationEffect::adjust_down: { if (!present) { return std::nullopt; } const auto step = adjustment_step(table, entry.target, genome.schema_version(), carried->parameter); if (carried->parameter < limits.minimum + step) { return std::nullopt; } carried->parameter -= step; break; } case MutationEffect::acquire: // An empty range (photosynthesis before schema 5) is not acquirable at all. if (present || limits.maximum < limits.minimum) { return std::nullopt; } // Schema 4 starts an acquired capability at the founder's value (a percentage of // the minimum, zero speed for instance, would never grow); otherwise the minimum. draft.capabilities.push_back({entry.target, genome.schema_version() >= genome_schema_v4 ? acquired_start(entry.target, limits) : limits.minimum, 0}); break; case MutationEffect::shed: if (!present) { return std::nullopt; } draft.capabilities.erase(carried); break; } return draft; } } // namespace std::span mutation_catalog() noexcept { return catalog; } std::expected mutation_candidates(const Genome& genome, const MutationContext& context) { if (context.candidate_count == 0 || context.candidate_count > max_candidates) { return std::unexpected{MutationError::invalid_context}; } // Eligibility is whatever M3.1 accepts, so there is no second rulebook. std::vector eligible; for (const auto& entry : catalog) { // Any valid placeholder identity: eligibility and the reported budget // depend on capabilities, never on which ID a successor would be given. const auto draft = apply(genome, entry, genome.id() == 1 ? 2 : 1, 1); if (!draft) { continue; } const auto successor = Genome::create(*draft); if (!successor) { continue; } const auto budget = metabolic_budget(*successor, context.growth, context.environment); if (!budget) { continue; } const auto parameter = successor->parameter(entry.target); eligible.push_back({entry.id, entry.target, entry.effect, parameter ? *parameter : 0U, budget->maintenance.value, budget->phenotype.total_mass}); } if (eligible.empty()) { return std::unexpected{MutationError::no_candidates}; } // Draw without replacement. Every eligible operator is exactly as likely as // every other: nothing about the organism makes a helpful one more probable. Random stream{mix(context_digest(genome, context), context.stream)}; const auto wanted = std::min(context.candidate_count, eligible.size()); for (std::size_t index = 0; index < wanted; ++index) { const auto pick = index + bounded(stream, eligible.size() - index); std::swap(eligible[index], eligible[pick]); } eligible.resize(wanted); // Canonical order. Position carries no meaning; nothing here is ranked. std::ranges::sort(eligible, {}, &MutationCandidate::operator_id); // The offer records what produced it, so selection can check that directly. return MutationOffer{genome.id(), genome.content_digest(), context, std::move(eligible)}; } std::expected select_mutation(const Genome& genome, const MutationContext& context, const MutationOffer& offered, std::uint16_t chosen, std::uint64_t successor_id, std::uint64_t origin_event) { // Checked first and directly. A regenerated candidate list cannot establish // this: the catalog yields few distinct lists, so two different contexts draw // the same one often enough that a list comparison would accept a stale offer. // Answering a moved context with a still-valid but different mutation would // mutate an organism into something nobody was shown. if (offered.parent != genome.id() || offered.parent_digest != genome.content_digest() || offered.context != context) { return std::unexpected{MutationError::context_changed}; } const auto current = mutation_candidates(genome, context); if (!current) { return std::unexpected{current.error()}; } // The context and parent match, so the draw is determined. A difference here // means the offer itself was altered, which is not a context having moved. if (current->candidates != offered.candidates) { return std::unexpected{MutationError::altered_offer}; } const auto picked = std::ranges::find(current->candidates, chosen, &MutationCandidate::operator_id); if (picked == current->candidates.end()) { return std::unexpected{MutationError::unknown_candidate}; } const auto entry = std::ranges::find(catalog, chosen, &MutationOperator::id); if (entry == catalog.end()) { return std::unexpected{MutationError::unknown_candidate}; } const auto draft = apply(genome, *entry, successor_id, origin_event); if (!draft) { return std::unexpected{MutationError::invalid_successor}; } auto successor = Genome::create(*draft); if (!successor) { return std::unexpected{MutationError::invalid_successor}; } return *successor; } std::expected fund_mutation(const Genome& genome, const MutationContext& context, const MutationOffer& offered, std::uint16_t chosen, std::uint64_t successor_id, std::uint64_t origin_event, const accounting::Inventory& reserve) { return fund_mutation_at_growth(genome, context, offered, chosen, successor_id, origin_event, reserve, context.growth); } std::expected fund_mutation_at_growth(const Genome& genome, const MutationContext& context, const MutationOffer& offered, std::uint16_t chosen, std::uint64_t successor_id, std::uint64_t origin_event, const accounting::Inventory& reserve, GrowthState current_growth) { const auto successor = select_mutation(genome, context, offered, chosen, successor_id, origin_event); if (!successor) { return std::unexpected{successor.error()}; } const auto before = metabolic_budget(genome, current_growth, context.environment); const auto after = metabolic_budget(*successor, current_growth, context.environment); const auto rules = rules_for(genome.development_version()); if (!before || !after || !rules) { return std::unexpected{MutationError::development}; } MutationTransition transition{*successor, after->body, reserve, {}, {}}; std::uint64_t added_matter = 0; for (std::size_t channel = 0; channel < transition.body.matter.size(); ++channel) { const auto old_mass = before->body.matter[channel].value; const auto new_mass = after->body.matter[channel].value; if (new_mass > old_mass) { const auto amount = new_mass - old_mass; if (amount > std::numeric_limits::max() - added_matter) { return std::unexpected{MutationError::development}; } added_matter += amount; transition.intake.matter[channel].value = amount; } else { transition.release.matter[channel].value = old_mass - new_mass; } } // Construction energy is charged for each channel's added material. The // release from another channel cannot pay for construction or hide a missing // nutrient; this matches channel-specific affordability in M3.3. const auto per_thousand = rules->construction_per_kilogram; const auto whole = added_matter / 1000; const auto remainder = added_matter % 1000; if ((whole != 0 && per_thousand > std::numeric_limits::max() / whole) || (remainder != 0 && per_thousand > std::numeric_limits::max() / remainder)) { return std::unexpected{MutationError::development}; } const auto whole_energy = whole * per_thousand; const auto remainder_energy = remainder * per_thousand / 1000; if (remainder_energy > std::numeric_limits::max() - whole_energy) { return std::unexpected{MutationError::development}; } transition.intake.energy.value = whole_energy + remainder_energy; if (reserve.energy.value < transition.intake.energy.value) { return std::unexpected{MutationError::insufficient_funding}; } transition.reserve.energy.value -= transition.intake.energy.value; for (std::size_t channel = 0; channel < transition.body.matter.size(); ++channel) { const auto available = reserve.matter[channel].value; const auto required = transition.intake.matter[channel].value; const auto returned = transition.release.matter[channel].value; if (available < required) { return std::unexpected{MutationError::insufficient_funding}; } if (returned > std::numeric_limits::max() - (available - required)) { return std::unexpected{MutationError::development}; } transition.reserve.matter[channel].value = available - required + returned; } return transition; } } // namespace evo::biology