#include "evo/biology/mutation.hpp" #include "evo/core/random.hpp" #include #include #include #include namespace evo::biology { namespace { // Four effects over seven capabilities. IDs are stable and carry no ranking; // 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 schema 1 lineage keeps its steps. constexpr std::uint32_t adjustment_step(const std::array& table, Capability kind) noexcept { const auto& limits = table[static_cast(kind)]; const auto span = limits.maximum - limits.minimum; return span / 100 == 0 ? 1 : span / 100; } 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()); 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); // 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); if (carried->parameter < limits.minimum + step) { return std::nullopt; } carried->parameter -= step; break; } case MutationEffect::acquire: if (present) { return std::nullopt; } draft.capabilities.push_back({entry.target, 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; } } // namespace evo::biology