diff --git a/Cellular_Revamp_Build_Plan.md b/Cellular_Revamp_Build_Plan.md index 3f4e3d2..1a5b264 100644 --- a/Cellular_Revamp_Build_Plan.md +++ b/Cellular_Revamp_Build_Plan.md @@ -148,17 +148,33 @@ Client: organism drawn as its member cells; Emerge button at the threshold. Verify: one reserve and one genome across members; whole engulfment conserves; the Emerge action only at the threshold. -### Session v14 and the client +### Session v14 and the client - done - Session v14: the phase 1 body values in perception; payable energy; the exclusion control; named offers with pro, con, chance, cost and Stay / Become; the bud choice; organisms and the Emerge action. - Client screens for all of the above. +As built ([schema](schemas/network/session-v14-cellular-revamp.md)): a 64-byte body block +(members, threshold, exclusions, Emerge open, payable energy, mass, the 20 traits); become, +emerge and exclusions on actions; become on choices; catalog offers (id, chance, cost) named +by the client from the shared catalog; the emerged ending. The client shows Stay / Become +offspring on each offer (one Choose for an organism or Adhesion), "Continue as the bud", +the organism's size and the Emerge button, the channels kept from burning, the body, and the +emerged end screen. + +### Durable plumbing - done + +Bundle 15, schema 60 and the `cellular-v10` opening (ADR-0179 "Durable form"): the +14 -> 15 revamp profile migration with recovery, become stored as bit 15 of the durable +choice's operator, the action input's new bits, and mutation results 0-6. + ### Phase 6: wildlife, instrumentation and the playtest - Wildlife controller: matter-as-energy aware, budding with litter, engulfing with the - new eligibility. + new eligibility. Done: hunger counts payable energy, buds wait for the bud fee (litter is + the owner's), an organism adds members until one short of the threshold, and hunting uses + the region step's rules-13 engulf test (reserve share, capacity, membrane in nanometres). - Play summary: first-birth time, time to Adhesion, deaths by cause, energy share paid by matter, offers seen and chosen, mutations held per lineage. - Mount `tuning/cellular-revamp.tuning` into the provision Job beside `cellular.tuning` @@ -174,7 +190,6 @@ Emerge action only at the threshold. | Retuning bubble energy or founder `energy_conversion` (keep 40% vs today's 100%) | 2 | | Organism pace: in tests a two-member organism at half growth swims about 7.5 µm per tick and needed about 5,000 ticks on a rich mote to fund one internal member | 6 | | Region migration does not carry rules-13 per-life state (affinity, members); an organism's move would be refused | 6 | -| The life-ended message has no `emerged` reason yet (reported as unrecorded) | v14 | ## Risks diff --git a/apps/evo-client/cellular_controls.hpp b/apps/evo-client/cellular_controls.hpp index 36be1fa..20767f8 100644 --- a/apps/evo-client/cellular_controls.hpp +++ b/apps/evo-client/cellular_controls.hpp @@ -12,6 +12,9 @@ namespace evo::client_app { struct CellularControls { bool auto_feed{true}, slow_near_food{true}, precision{}; int speed_percent{100}; + // Rules 13 (v14): matter channels kept from burning as energy (bit 0 carbon .. bit 3 + // other). Upkeep still burns them when nothing else can pay. + std::uint8_t exclude{}; }; struct CellularSteering { client::Intention intention; diff --git a/apps/evo-client/cellular_play.hpp b/apps/evo-client/cellular_play.hpp index 1231167..522e351 100644 --- a/apps/evo-client/cellular_play.hpp +++ b/apps/evo-client/cellular_play.hpp @@ -14,9 +14,10 @@ namespace evo::client_app { struct MutationChoice { std::uint64_t life{}, event{}, offer_tick{}; std::uint16_t operator_id{}; + bool become{}; // Rules 13 (v14): continue as the offspring the choice splits off. friend bool operator==(const MutationChoice&, const MutationChoice&) = default; }; -enum class CellAction : std::uint8_t { engulf, bud, mutation }; +enum class CellAction : std::uint8_t { engulf, bud, mutation, emerge }; enum class CellActionState : std::uint8_t { queued, sent, @@ -35,6 +36,7 @@ struct CellActionRecord { // The region's reported effect of this engulf or bud, once a view carries it. std::optional engulf; std::optional bud; + bool become{}; // A bud the player continues as (v14). }; struct CellEnergyChange { std::uint64_t from_tick{}, to_tick{}, amount{}; @@ -149,7 +151,8 @@ class CellularPlay { [[nodiscard]] bool can_act() const { return connected_ && fresh_ && life_ != 0 && !ended_ && !pending_ && !birth_pending_; } - [[nodiscard]] bool queue(CellAction kind, std::uint64_t tick, MutationChoice choice = {}) { + [[nodiscard]] bool queue(CellAction kind, std::uint64_t tick, MutationChoice choice = {}, + bool become = false) { if (!can_act() || tick == 0) return false; if (kind == CellAction::mutation && @@ -163,9 +166,16 @@ class CellularPlay { const auto id = allocate_id(); if (id == 0) return false; - pending_ = CellActionRecord{ - kind, CellActionState::queued, id, life_, tick, - choice, network::AdmitStatus::admitted, std::nullopt, std::nullopt}; + pending_ = CellActionRecord{kind, + CellActionState::queued, + id, + life_, + tick, + choice, + network::AdmitStatus::admitted, + std::nullopt, + std::nullopt, + kind == CellAction::bud && become}; return true; } void sent() { diff --git a/apps/evo-client/main.cpp b/apps/evo-client/main.cpp index 31b47ec..4a56ac3 100644 --- a/apps/evo-client/main.cpp +++ b/apps/evo-client/main.cpp @@ -573,7 +573,8 @@ int main(int argc, char** argv) try { buffers.cellular_controls.auto_feed = false; } if (auto* remote = host.session(); remote && mode() == Mode::remote) { - if (actions.cell_action && remote->request_cellular(*actions.cell_action)) + if (actions.cell_action && + remote->request_cellular(*actions.cell_action, {}, actions.cell_become)) cellular_feed_target.reset(); if (actions.mutation) static_cast(remote->request_cellular(evo::client_app::CellAction::mutation, diff --git a/apps/evo-client/panels.cpp b/apps/evo-client/panels.cpp index 28f5d1d..2af89fd 100644 --- a/apps/evo-client/panels.cpp +++ b/apps/evo-client/panels.cpp @@ -1,4 +1,5 @@ #include "panels.hpp" +#include "evo/biology/cellular_catalog.hpp" #include "evo/client/labels.hpp" #include #include @@ -565,6 +566,8 @@ const char* cell_action_name(CellAction kind) { return "Bud"; case CellAction::mutation: return "Mutation"; + case CellAction::emerge: + return "Emerge"; } return "Action"; } @@ -1275,9 +1278,28 @@ void hud_dock(const PanelView& v, FormBuffers& form, PanelActions& a, bool compa if (action_button("Engulf", {each, px(44)}, {0.38F, 0.68F, 1.0F, 1})) a.cell_action = CellAction::engulf; ImGui::SameLine(); - if (action_button("Bud", {each, px(44)}, {0.82F, 0.53F, 0.96F, 1})) + if (action_button("Bud", {each, px(44)}, {0.82F, 0.53F, 0.96F, 1})) { a.cell_action = CellAction::bud; + a.cell_become = form.bud_become && d && d->members == 1; + } ImGui::EndDisabled(); + // Rules 13 (v14): continue as the bud, or grow the organism toward Emerge. + if (d && d->members != 0 && play && play->life() != 0) { + if (d->members == 1) { + ImGui::Checkbox("Continue as the bud", &form.bud_become); + } else { + ImGui::TextColored(lavender, "Organism of %u cells (Emerge at %u)", + static_cast(d->members), + static_cast(d->emerge_members)); + ImGui::BeginDisabled(!play->can_act() || !d->can_emerge); + if (action_button("Emerge", {-1, px(40)}, {0.98F, 0.82F, 0.35F, 1})) + a.cell_action = CellAction::emerge; + ImGui::EndDisabled(); + if (!d->can_emerge) + disabled_wrapped("Emerge opens at the threshold of cells, mass and reserve. Buds " + "add cells to the organism."); + } + } // What a bud needs, by nutrient (ADR-0129 amendment). if (d && play && play->life() != 0) { if (!bud_known(*d)) { @@ -1386,6 +1408,35 @@ void hud_notes(const PanelView& v, FormBuffers& form, PanelActions& a, bool comp } ImGui::EndDisabled(); } + // Rules 13 (v14): which reserve matter may stand in for energy, and the heritable body. + if (const auto* d = diagnostics(v); d && d->members != 0) { + if (ImGui::CollapsingHeader("Burning reserve matter")) { + for (std::size_t c = 0; c < 4; ++c) { + const auto bit = static_cast(1U << c); + bool keep = (form.cellular_controls.exclude & bit) != 0; + const std::string label = std::string{"Keep "} + nutrient_names.at(c + 1); + if (ImGui::Checkbox(label.c_str(), &keep)) + form.cellular_controls.exclude = + static_cast(keep ? form.cellular_controls.exclude | bit + : form.cellular_controls.exclude & ~bit); + } + ImGui::TextDisabled("Can pay %s now", energy_text(d->payable_energy_pj).c_str()); + disabled_wrapped("Matter you keep is never burned for movement or mutations; upkeep " + "still burns it when nothing else can pay."); + } + if (ImGui::CollapsingHeader("Body")) { + const auto& t = d->traits; + ImGui::Text("Mass %s", mass_text(d->total_mass_fg).c_str()); + ImGui::TextDisabled("Density %u Upkeep efficiency %u Growth %u", unsigned{t[0]}, + unsigned{t[1]}, unsigned{t[2]}); + ImGui::TextDisabled("Engulf capacity %u Kill absorption %u", unsigned{t[12]}, + unsigned{t[13]}); + ImGui::TextDisabled("Litter %u Recipe C%u N%u P%u O%u", unsigned{t[14]}, + unsigned{t[15]}, unsigned{t[16]}, unsigned{t[17]}, unsigned{t[18]}); + if (t[19] != 0) + ImGui::TextColored(lavender, "Adhesive: a multicellular organism"); + } + } if (ImGui::CollapsingHeader("Steering")) { ImGui::Checkbox("Slow near food", &form.cellular_controls.slow_near_food); ImGui::Checkbox("Precision steering (20%)", &form.cellular_controls.precision); @@ -1494,10 +1545,83 @@ void candidate_glyph(const network::CellularOfferedCandidate& c, float width) { IM_COL32(173, 164, 184, 255), "->"); ImGui::Dummy({width, height}); } +// Rules 13 (v14): a named catalog mutation, with its pro, con, chance and tuned cost. The +// choice splits a single cell (stay as the founder or become the offspring that expresses it); +// an organism expresses it as a whole. +const biology::CellularMutationSpec* named_mutation(const network::CellularLifeDiagnostics* d, + const network::CellularOfferedCandidate& c) { + if (!d || d->members == 0 || c.capability != 0 || c.effect != 0) + return nullptr; + return biology::cellular_mutation(c.operator_id); +} +void named_offer_card(const PanelView& v, const network::CellularMutationOffer& offer, + const network::CellularOfferedCandidate& c, + const biology::CellularMutationSpec& spec, PanelActions& a) { + const auto* play = v.cellular_play; + const auto* d = diagnostics(v); + ImGui::TextDisabled("%.1f%% chance", static_cast(c.parameter) / 10'000.0); + ImGui::PushFont(nullptr, px(18)); + ImGui::TextWrapped("%.*s", static_cast(spec.name.size()), spec.name.data()); + ImGui::PopFont(); + ImGui::TextColored({0.32F, 0.90F, 0.73F, 1}, "+ %.*s", static_cast(spec.pro.size()), + spec.pro.data()); + ImGui::TextColored(amber, "- %.*s", static_cast(spec.con.size()), spec.con.data()); + bool affordable = d != nullptr; + const bool table = begin_nutrient_table("cost"); + for (std::size_t channel = 0; channel < 5; ++channel) { + const auto need = channel == 0 ? c.cost_energy_pj : c.cost_matter_fg.at(channel - 1); + if (need == 0) + continue; + // Energy may be paid with burnable matter standing in. + const auto have = + d ? (channel == 0 ? d->payable_energy_pj : d->reserve_matter_fg.at(channel - 1)) : 0; + affordable = affordable && have >= need; + if (table) + nutrient_row(channel, nutrient_names.at(channel), + static_cast(static_cast(have) / static_cast(need)), + channel == 0 ? energy_text(need) : mass_text(need)); + } + if (table) + ImGui::EndTable(); + const bool organism = d && d->members > 1; + const bool adhesion = spec.effect == biology::CellularEffect::acquire_adhesion; + if (adhesion) + disabled_wrapped("Your cell and its split-off offspring stay joined: one organism with " + "one genome and one reserve, growing toward Emerge."); + else if (organism) + disabled_wrapped("Your whole organism changes, paid from its reserve."); + else + disabled_wrapped("Your cell splits: both keep the change in their plan; only the " + "offspring expresses it."); + const bool ready = + play && play->can_act() && v.remote && v.remote->server_tick > offer.offer_tick; + ImGui::BeginDisabled(!affordable || !ready); + const MutationChoice stay{offer.life_identity, offer.event_index, offer.offer_tick, + c.operator_id, false}; + if (organism || adhesion) { + if (ImGui::Button(affordable ? "Choose" : "Feed first", {-1, px(40)})) + a.mutation = stay; + } else { + const float half = (ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) / 2; + if (ImGui::Button(affordable ? "Stay" : "Feed first", {half, px(40)})) + a.mutation = stay; + ImGui::SameLine(); + if (ImGui::Button("Become offspring", {half, px(40)})) { + auto become = stay; + become.become = true; + a.mutation = become; + } + } + ImGui::EndDisabled(); +} void offer_card(const PanelView& v, const network::CellularMutationOffer& offer, const network::CellularOfferedCandidate& c, PanelActions& a) { const auto* play = v.cellular_play; const auto* d = diagnostics(v); + if (const auto* spec = named_mutation(d, c)) { + named_offer_card(v, offer, c, *spec, a); + return; + } ImGui::TextDisabled("%s", capability_kinds.at(c.capability)); const float width = ImGui::GetContentRegionAvail().x; candidate_glyph(c, width); @@ -1573,10 +1697,14 @@ void evolution_window(const PanelView& v, FormBuffers& form, PanelActions& a, bo ImGui::TextWrapped( "%s", cause == network::CellularDeathReason::starved ? "Your cell starved" : cause == network::CellularDeathReason::engulfed ? "Your cell was engulfed" + : cause == network::CellularDeathReason::emerged ? "Your organism emerged" : "Your cell died"); ImGui::PopFont(); disabled_wrapped(cause == network::CellularDeathReason::starved ? "Its reserve could not pay upkeep. Its body became food." + : cause == network::CellularDeathReason::emerged + ? "It left the cellular region for the world, taking all its " + "matter with it. This cellular life is complete." : "Its body became food for another cell."); ImGui::TextWrapped("Your descendants live on as wildlife. You return as a new " "primitive cell."); @@ -1602,8 +1730,12 @@ void evolution_window(const PanelView& v, FormBuffers& form, PanelActions& a, bo ImGui::PushFont(nullptr, px(24)); ImGui::TextUnformatted("Shape this life"); ImGui::PopFont(); - disabled_wrapped("Your feeding earned one change. Each trades a capability against upkeep " - "and body mass. Buds inherit what you choose."); + const bool named = !offer->candidates.empty() && + named_mutation(diagnostics(v), offer->candidates.front()) != nullptr; + disabled_wrapped(named ? "Your play earned one change. Each has a benefit and a cost; what " + "you do makes some more likely to appear." + : "Your feeding earned one change. Each trades a capability against " + "upkeep and body mass. Buds inherit what you choose."); const auto count = static_cast(offer->candidates.size()); const int columns = compact ? 1 : std::max(1, count); if (ImGui::BeginTable("offers", columns, ImGuiTableFlags_SizingStretchSame)) { diff --git a/apps/evo-client/panels.hpp b/apps/evo-client/panels.hpp index b74deb2..3c2afbe 100644 --- a/apps/evo-client/panels.hpp +++ b/apps/evo-client/panels.hpp @@ -80,6 +80,7 @@ struct FormBuffers { bool engineering{}; bool evolution_open{}; // The mutation window (E or the callout opens it). bool notes_minimized{}, vitals_minimized{}, map_minimized{}; + bool bud_become{}; // Rules 13: the next bud is the player's cell. CellularControls cellular_controls; std::array endpoint{}, server_name{}, authority{}, grants{}; void load(const client::ConnectForm& form); @@ -126,6 +127,7 @@ struct PanelActions { std::optional> feed_patch; bool stop_feeding{}; std::optional cell_action; + bool cell_become{}; // With a bud: continue as it (v14). std::optional mutation; bool restart_life{}, keep_unknown{}; }; diff --git a/apps/evo-client/remote_session.hpp b/apps/evo-client/remote_session.hpp index 3b2ede9..2ab8f5e 100644 --- a/apps/evo-client/remote_session.hpp +++ b/apps/evo-client/remote_session.hpp @@ -262,13 +262,14 @@ class RemoteSession { [[nodiscard]] const CellularPlay& cellular_play() const noexcept { return cellular_play_; } - [[nodiscard]] bool request_cellular(CellAction kind, MutationChoice choice = {}) { + [[nodiscard]] bool request_cellular(CellAction kind, MutationChoice choice = {}, + bool become = false) { const auto lead = cellular_lead_.lead(); const auto tick = kind == CellAction::mutation ? server_tick_ : server_tick_ + lead + (sent_tick_ && *sent_tick_ == server_tick_ ? 1 : 0); - if (!cellular_trial_ || !cellular_play_.queue(kind, tick, choice)) + if (!cellular_trial_ || !cellular_play_.queue(kind, tick, choice, become)) return false; action_check_at_ = {}; if (kind != CellAction::mutation) @@ -501,8 +502,9 @@ class RemoteSession { return false; client::RegionSessionClientConfig config; if (cellular_trial_) - // Rules 12: v13 is v12 (deposits, light, producers) plus liquid motion and brake. - config.protocol_version = network::session_protocol_v13; + // Rules 13: v14 is v13 (deposits, light, producers, liquid motion and brake) plus the + // revamp: become, emerge, exclusions, catalog offers and the body block. + config.protocol_version = network::session_protocol_v14; const auto route = routes_.find(target_region_); config.transport = route != routes_.end() ? route->second : transport_; if (ticket_) { // A handoff: the ticket replaces a grant, once. @@ -634,7 +636,8 @@ class RemoteSession { const auto id = cellular_play_.allocate_id(); if (id == 0 || !client_->send_cellular_action( id, tick, steering.intention.move_x, steering.intention.move_y, - cellular_feed_target_, false, false, steering.intention.brake)) + cellular_feed_target_, false, false, steering.intention.brake, false, + false, cellular_controls_.exclude)) return; sent_tick_ = server_tick_; cellular_sent_tick_ = tick; @@ -652,12 +655,14 @@ class RemoteSession { bool sent = false; if (p.kind == CellAction::mutation) { sent = client_->send_cellular_mutation(p.id, p.tick, p.choice.life, p.choice.event, - p.choice.offer_tick, p.choice.operator_id); + p.choice.offer_tick, p.choice.operator_id, + p.choice.become); } else if (p.state == CellActionState::queued) { if (p.tick > server_tick_ + cellular_lead_.lead()) return; // Do not replace a movement/feeding intention already sent this tick. sent = client_->send_cellular_action( - p.id, p.tick, 0, 0, {}, p.kind == CellAction::engulf, p.kind == CellAction::bud); + p.id, p.tick, 0, 0, {}, p.kind == CellAction::engulf, p.kind == CellAction::bud, + false, p.become, p.kind == CellAction::emerge, cellular_controls_.exclude); if (sent) { sent_tick_ = server_tick_; // The discrete intention owns this tick's target. cellular_sent_tick_ = std::max(cellular_sent_tick_, p.tick); @@ -1010,7 +1015,7 @@ class RemoteSession { [[nodiscard]] const CellularPlay& cellular_play() const noexcept { return cellular_play_; } - [[nodiscard]] bool request_cellular(CellAction, MutationChoice = {}) { + [[nodiscard]] bool request_cellular(CellAction, MutationChoice = {}, bool = false) { return false; } [[nodiscard]] bool restart_cellular() { diff --git a/apps/evo-server/cellular_bridge.hpp b/apps/evo-server/cellular_bridge.hpp index f22590e..e86840b 100644 --- a/apps/evo-server/cellular_bridge.hpp +++ b/apps/evo-server/cellular_bridge.hpp @@ -110,9 +110,9 @@ class CellularBridge { config.select_cellular_mutation = [&host](const network::AccountId& account, std::uint64_t generation, const network::CellularMutationAction& m) { - const auto reply = - host.select_mutation(account.bytes, generation, m.action_id, - {m.life_identity, m.event_index, m.offer_tick, m.operator_id}); + const auto reply = host.select_mutation( + account.bytes, generation, m.action_id, + {m.life_identity, m.event_index, m.offer_tick, m.operator_id, m.become}); server::CellularMutationAnswer answer{ server::admit_status(reply.status), reply.tick, {}}; if (reply.outcome) @@ -284,6 +284,40 @@ class CellularBridge { c.min_speed_um_per_s, c.max_speed_um_per_s}; } + // Rules 13 (v14): the body block. Older sessions never see it. + diagnostics.members = life.revamp.members; + if (const auto genome = state.archive().find(life.identity.genome)) { + const auto& traits = genome->cellular_traits(); + const auto t = traits.value_or(biology::CellularTraits{}); + const std::array fields{ + t.density, t.upkeep_efficiency, t.growth_speed, t.collection[0], + t.collection[1], t.collection[2], t.collection[3], t.collection[4], + t.burn[0], t.burn[1], t.burn[2], t.burn[3], + t.engulf_capacity, t.kill_absorption, t.litter, t.recipe[0], + t.recipe[1], t.recipe[2], t.recipe[3], t.adhesion}; + if (traits) + diagnostics.traits = fields; + if (state.rules_version() >= server::cellular_lives_revamp_rules) { + const auto& rules = state.revamp_rules(); + diagnostics.emerge_members = static_cast( + std::min(rules.emerge_members, 0xFFFF)); + diagnostics.can_emerge = server::cellular_can_emerge(life, rules); + if (feedback != state.last_tick_feedback().end() && + feedback->life_id == life.identity.life && feedback->tick == tick) + diagnostics.exclude = feedback->exclude; + const auto burn = biology::cellular_burn( + rules.burn_pj_per_kfg, + traits ? t.burn : std::array{100, 100, 100, 100}, + diagnostics.exclude); + diagnostics.payable_energy_pj = + biology::cellular_payable_energy(life.reserve, burn, false); + } else { + diagnostics.payable_energy_pj = life.reserve.energy.value; + } + } + for (std::size_t c = 0; c < life.body.matter.size(); ++c) + diagnostics.total_mass_fg += + life.body.matter[c].value + life.reserve.matter[c].value; view.diagnostics = diagnostics; view.patches.reserve(perceived->size()); // ADR-0136 (rules 8): pools and bubbles go out as v11 deposits, the nearest 512 to @@ -462,6 +496,8 @@ class CellularBridge { ? network::CellularDeathReason::starved : corpse->cause == biology::CellularDeathCause::engulfed ? network::CellularDeathReason::engulfed + : corpse->cause == biology::CellularDeathCause::emerged + ? network::CellularDeathReason::emerged : network::CellularDeathReason::unrecorded; static_cast(sessions_->send_life_ended(network::AccountId{account}, {corpse->died_tick, life_id, cause})); @@ -510,17 +546,23 @@ class CellularBridge { std::uint64_t tick) { const network::AccountId account{life.account}; const auto session = sessions_->holder(account); - const auto& progress = life.mutation; + // Rules 13 offers are catalog offers (v14 only); earlier rules use the operator offer. + const bool named = state.rules_version() >= server::cellular_lives_revamp_rules; + const bool pending = named ? life.revamp.offer.count != 0 : life.mutation.offer.has_value(); const SentOffer current{life.account, session.value_or(0), life.identity.life, - progress.offer ? progress.event_index : 0, - progress.offer ? progress.offer_tick : 0}; + !pending ? 0 + : named ? life.revamp.offer.event_index + : life.mutation.event_index, + !pending ? 0 + : named ? life.revamp.offer.offer_tick + : life.mutation.offer_tick}; auto sent = std::ranges::find(offers_, life.account, &SentOffer::account); if (sent != offers_.end() && *sent == current) return; - if (!session || (!progress.offer && sent == offers_.end())) + if (!session || (!pending && sent == offers_.end())) return; // Nothing to show, or no one to show it to. - if (!sessions_->send_mutation_offer(account, server::offer_view(state, life, tick))) - return; // Not a v10 owner (or the stream refused): retried on a later tick. + if (!sessions_->send_mutation_offer(account, server::offer_view(state, life, tick), named)) + return; // Not a v10 (v14) owner (or the stream refused): retried on a later tick. if (sent != offers_.end()) *sent = current; else diff --git a/apps/evo-world-clone/main.cpp b/apps/evo-world-clone/main.cpp index dcfbae3..669d7a0 100644 --- a/apps/evo-world-clone/main.cpp +++ b/apps/evo-world-clone/main.cpp @@ -10,7 +10,7 @@ // evo-world-clone check-store --world W --region R --pg-* ... --objects DIR // [--reserve-mib N] // evo-world-clone provision --world W --region R --opening -// development-v1|primitive-v1|cellular-v1 to cellular-v9 +// development-v1|primitive-v1|cellular-v1 to cellular-v10 // --pg-* ... --objects DIR --build HEX [--commit HEX32] [--retain-build] // primitive-v1 also requires --frame N --source-id N, every --funding-*-* channel, // and one or more ordered --site X,Y values. @@ -28,7 +28,9 @@ // cellular-v8 (ADR-0176) also requires --light-pj N. cellular-v9 (rules 12, ADR-0177) // is cellular-v8 followed by the liquid upgrade: it also requires --tuning FILE (the Git // tuning file, whose region size must match --width-um/--height-um) and accepts -// --current-seed N (default: derived from the --commit bytes). +// --current-seed N (default: derived from the --commit bytes). cellular-v10 (rules 13, +// ADR-0179) is cellular-v9 followed by the revamp upgrade: it also requires +// --revamp-tuning FILE (the Git revamp tuning file). // primitive-v1 and cellular-v1/v2/v3 accept --life-allocator-start N // (ADR-0123): the world's life-identity allocator is created once at the operator-audited // start N; a later run leaves it untouched and refuses one that is below N. @@ -74,6 +76,7 @@ // Exit: 0 done, 2 usage, 3 source/history/database failure, 4 target/objects refused, // 5 target unknown, 6 compared histories differ. #include "evo/biology/cellular_habitat.hpp" +#include "evo/biology/cellular_revamp_tuning.hpp" #include "evo/persistence/checkpoint_store.hpp" #include "evo/persistence/region_clone.hpp" #include "evo/persistence/sha256.hpp" @@ -127,16 +130,22 @@ struct Options { std::optional light_pj; // cellular-v8/v9: pJ per square um per tick std::optional tuning_path; // cellular-v9: the Git tuning file std::optional current_seed; - std::optional tuning; // Parsed from tuning_path. + std::optional tuning; // Parsed from tuning_path. + std::optional revamp_tuning_path; // cellular-v10 + std::optional revamp_tuning; // Parsed from it. std::optional life_allocator_start; std::optional build; bool retain_build{}; bool crash{}; }; -// The openings that declare light: cellular-v8, and cellular-v9 which adds the liquid upgrade. +// The openings that declare light: cellular-v8, cellular-v9 which adds the liquid upgrade, and +// cellular-v10 which adds the revamp upgrade after it. bool lit_opening(std::string_view opening) { - return opening == "cellular-v8" || opening == "cellular-v9"; + return opening == "cellular-v8" || opening == "cellular-v9" || opening == "cellular-v10"; +} +bool liquid_opening(std::string_view opening) { + return opening == "cellular-v9" || opening == "cellular-v10"; } std::optional number(std::string_view text) { std::uint64_t value{}; @@ -349,8 +358,10 @@ std::optional parse(int argc, char** argv) { (value == "development-v1" || value == "primitive-v1" || value == "cellular-v1" || value == "cellular-v2" || value == "cellular-v3" || value == "cellular-v4" || value == "cellular-v5" || value == "cellular-v6" || value == "cellular-v7" || - value == "cellular-v8" || value == "cellular-v9")) + value == "cellular-v8" || value == "cellular-v9" || value == "cellular-v10")) o.opening = value; + else if (o.command == "provision" && flag == "--revamp-tuning" && !value.empty()) + o.revamp_tuning_path = std::string{value}; else if (o.command == "provision" && flag == "--light-pj" && n && *n > 0) o.light_pj = n; else if (o.command == "provision" && flag == "--tuning" && !value.empty()) @@ -442,11 +453,31 @@ std::optional parse(int argc, char** argv) { return std::nullopt; } else if (o.opening == "cellular-v7" || lit_opening(o.opening)) { // Pools and bubbles only: square patches belong to the earlier openings. Only - // cellular-v8 and v9 (ADR-0176) declare light; only v9 takes a tuning file. + // cellular-v8 to v10 (ADR-0176) declare light; v9 and v10 take a tuning file, and + // v10 the revamp tuning file. if (lit_opening(o.opening) != o.light_pj.has_value() || - (o.opening == "cellular-v9") != o.tuning_path.has_value() || - (o.current_seed && o.opening != "cellular-v9")) + liquid_opening(o.opening) != o.tuning_path.has_value() || + (o.opening == "cellular-v10") != o.revamp_tuning_path.has_value() || + (o.current_seed && !liquid_opening(o.opening))) return std::nullopt; + if (o.revamp_tuning_path) { + std::ifstream file(*o.revamp_tuning_path, std::ios::binary); + const std::string text{std::istreambuf_iterator(file), + std::istreambuf_iterator()}; + if (!file.good() && !file.eof()) { + std::printf("revamp tuning file unreadable: %s\n", + o.revamp_tuning_path->c_str()); + return std::nullopt; + } + auto parsed = biology::parse_cellular_revamp_tuning(text); + if (!parsed) { + std::printf("revamp tuning file refused at line %zu (%s): %s\n", + parsed.error().line, parsed.error().key.c_str(), + std::string{biology::describe(parsed.error().kind)}.c_str()); + return std::nullopt; + } + o.revamp_tuning = *parsed; + } if (o.tuning_path) { std::ifstream file(*o.tuning_path, std::ios::binary); const std::string text{std::istreambuf_iterator(file), @@ -593,7 +624,7 @@ std::vector probe_bytes() { // cellular-v9 (rules 12): the liquid rules from the tuning file, for the opening's area and // a current seed (given, or derived from the genesis commit's bytes 8-15). std::optional liquid_rules(const Options& o) { - if (o.opening != "cellular-v9" || !o.tuning || !o.cellular_width_um || !o.cellular_height_um) + if (!liquid_opening(o.opening) || !o.tuning || !o.cellular_width_um || !o.cellular_height_um) return std::nullopt; std::uint64_t seed = o.current_seed.value_or(0); if (!o.current_seed) { @@ -605,18 +636,27 @@ std::optional liquid_rules(const Options& o) { seed); } +// cellular-v10 (rules 13): the revamp rules from the revamp tuning file. +std::optional revamp_rules(const Options& o) { + if (o.opening != "cellular-v10" || !o.revamp_tuning) + return std::nullopt; + return server::cellular_revamp_rules(*o.revamp_tuning); +} + // ADR-0176 cellular-v8: a cellular-v7 genesis taken through one empty tick and the durable // bundle 9 -> 10 -> 11 -> 12 -> 13 upgrades, declaring the region's light. cellular-v9 adds the -// 13 -> 14 liquid upgrade. Resumable: it continues from whichever bundle the head has reached, -// and does nothing at its target bundle. +// 13 -> 14 liquid upgrade and cellular-v10 the 14 -> 15 revamp upgrade. Resumable: it continues +// from whichever bundle the head has reached, and does nothing at its target bundle. int finish_photosynthesis_opening(const Options& o, persistence::Postgres& db, const persistence::FilesystemObjectStore& store, std::uint64_t frame, const persistence::Sha256Digest& build, std::uint64_t light_pj, - const std::optional& liquid) { + const std::optional& liquid, + const std::optional& revamp) { const auto& key = o.source.key; - const auto target = - liquid ? persistence::cellular_v14_versions : persistence::cellular_v13_versions; + const auto target = revamp ? persistence::cellular_v15_versions + : liquid ? persistence::cellular_v14_versions + : persistence::cellular_v13_versions; // A finished opening needs no lease: a rerun (every Argo sync's provision hook) runs // while the region server holds it, and must report the region rather than fail. if (const auto current = persistence::load_region_checkpoint(db, key, timeout); current) { @@ -640,7 +680,7 @@ int finish_photosynthesis_opening(const Options& o, persistence::Postgres& db, auto head = persistence::load_region_checkpoint(db, key, timeout); if (!head) return finish(3); - for (unsigned step = 0; step < 7; ++step) { + for (unsigned step = 0; step < 8; ++step) { const auto manifest = persistence::decode_manifest(head->manifest); if (!manifest || manifest->profile != persistence::CheckpointProfile::cellular_lives_v1 || manifest->frame != frame) @@ -700,6 +740,9 @@ int finish_photosynthesis_opening(const Options& o, persistence::Postgres& db, else if (versions == persistence::cellular_v13_versions && liquid) upgraded = persistence::migrate_cellular_liquid_profile(db, store, *lease, *head, id, build, *liquid, timeout); + else if (versions == persistence::cellular_v14_versions && liquid && revamp) + upgraded = persistence::migrate_cellular_revamp_profile(db, store, *lease, *head, id, + build, *revamp, timeout); else return finish(4); if (!upgraded) { @@ -887,9 +930,9 @@ int provision(const Options& o) { "--commit to resolve genesis"); return 4; } - if (const auto finished = - finish_photosynthesis_opening(o, *db, *store, primitive_frame, build, - o.light_pj.value_or(0), liquid_rules(o)); + if (const auto finished = finish_photosynthesis_opening( + o, *db, *store, primitive_frame, build, o.light_pj.value_or(0), + liquid_rules(o), revamp_rules(o)); finished != 0) return finished; auto head = persistence::load_region_checkpoint(*db, o.source.key, timeout); @@ -942,9 +985,9 @@ int provision(const Options& o) { return 4; } if (lit_opening(o.opening)) { - if (const auto finished = - finish_photosynthesis_opening(o, *db, *store, primitive_frame, build, - o.light_pj.value_or(0), liquid_rules(o)); + if (const auto finished = finish_photosynthesis_opening( + o, *db, *store, primitive_frame, build, o.light_pj.value_or(0), liquid_rules(o), + revamp_rules(o)); finished != 0) return finished; auto head = persistence::load_region_checkpoint(*db, o.source.key, timeout); @@ -1091,6 +1134,15 @@ int summary(const Options& o) { static_cast(play->unrecorded), static_cast(play->owned_deaths), static_cast(play->wildlife_deaths)); + std::printf("revamp merged=%llu emerged=%llu organisms=%llu largest=%llu offers_pending=%llu " + "offers_earned=%llu spent_fg=%llu\n", + static_cast(play->merged), + static_cast(play->emerged), + static_cast(play->organisms), + static_cast(play->largest_organism), + static_cast(play->offers_pending), + static_cast(play->offers_earned), + static_cast(play->spent_matter_fg)); std::printf("lifespan_ticks min=%llu median=%llu max=%llu\n", static_cast(play->lifespan_min), static_cast(play->lifespan_median), diff --git a/deploy/kubernetes/region/dev-session-route/listener.yaml b/deploy/kubernetes/region/dev-session-route/listener.yaml index 36210d5..a59e986 100644 --- a/deploy/kubernetes/region/dev-session-route/listener.yaml +++ b/deploy/kubernetes/region/dev-session-route/listener.yaml @@ -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-20261023T104955-41ebed4e:1792766995"} + - {name: REGION_SESSION_WINDOW, value: "dev-20261026T112611-47258044:1793028371"} - {name: REGION_M10_MAX_GRANT_LIFETIME, value: "14400"} ports: # QUIC (ADR-0090): UDP only; nothing listens on TCP 7400. diff --git a/docs/adr/0179-cellular-gameplay-revamp.md b/docs/adr/0179-cellular-gameplay-revamp.md index 6bb7509..466be09 100644 --- a/docs/adr/0179-cellular-gameplay-revamp.md +++ b/docs/adr/0179-cellular-gameplay-revamp.md @@ -56,6 +56,20 @@ The project vision is the product authority. The maintainer settled both conflic player then starts a fresh life. This lets the full cellular loop be played several times before work on the 3D space. +## Durable form (2026-10-26) + +- **Bundle 15** `{13, 11, 2, 1, 1, 7, 6, 2, 1}`: rules 13 on owner format 11, development 7, + founder 6, raw trace 4. Schema 60 admits it raw-only, as bundle 14 is: the manifest, births + and profile-migration parsers normalize it to bundle 14; a bundle-15 trace selection's byte + 34 is its become flag; mutation results 0-6 (an organism's applied, life died, insufficient + funding, declined, split applied, split refused); the action input's become, emerge and + exclusion bits. +- **Opening `cellular-v10`.** `cellular-v9` followed by the durable 14 -> 15 revamp upgrade, + with `--revamp-tuning FILE` (the Git revamp tuning file); resumable and idempotent at bundle + 15. Recovery re-derives the target from the source and the rules it declares. +- **Session v14.** See + [schemas/network/session-v14-cellular-revamp.md](../../schemas/network/session-v14-cellular-revamp.md). + ## Alternatives - Keep the generic operator catalog and add weights (ADR-0135's rules-7 proposal): diff --git a/include/evo/biology/cellular_region_step.hpp b/include/evo/biology/cellular_region_step.hpp index a7fe6b1..92153cf 100644 --- a/include/evo/biology/cellular_region_step.hpp +++ b/include/evo/biology/cellular_region_step.hpp @@ -33,6 +33,15 @@ struct CellularRevampStepRules { std::uint32_t kill_bubble_per_thousand{500}; auto operator<=>(const CellularRevampStepRules&) const = default; }; +// Rules 13: engulf mass is the body plus the declared share of reserve matter. +[[nodiscard]] std::uint64_t cellular_engulf_mass(std::uint64_t body_mass, + const accounting::Inventory& reserve, + const CellularRevampStepRules& rules) noexcept; +// Rules 13: whether a hunter of this engulf mass and capacity may take prey of this engulf mass +// and membrane (nanometres), exactly as the region step decides. +[[nodiscard]] bool cellular_engulfable(std::uint64_t hunter_mass, std::uint16_t engulf_capacity, + std::uint64_t prey_mass, std::uint32_t prey_membrane_nm, + const CellularRevampStepRules& rules) noexcept; // Rules 13: one life's heritable feeding, energy and predation values, from its genome. struct CellularRevampLifeInput { CellularBurn burn{}; diff --git a/include/evo/client/region_session.hpp b/include/evo/client/region_session.hpp index 5dfe37f..8d1d6ab 100644 --- a/include/evo/client/region_session.hpp +++ b/include/evo/client/region_session.hpp @@ -59,20 +59,23 @@ class RegionSessionClient { // retries and reconnects). False unless established and sent. [[nodiscard]] bool send_action(std::uint64_t action_id, network::ActionKind kind, std::uint64_t tick); - // Protocol v7-v10. Reuse the exact same fields and action id after reconnect. `engulf` + // Protocol v7-v14. Reuse the exact same fields and action id after reconnect. `engulf` // and `bud` (ADR-0124/0125) are exclusive and need a v10 session and no intake target. + // `brake` needs v13 or v14; `become` (with `bud`), `emerge` (alone) and `exclude` (matter + // channels kept from burning) need v14. Older sessions never send them. [[nodiscard]] bool send_cellular_action(std::uint64_t action_id, std::uint64_t tick, std::int16_t move_x, std::int16_t move_y, std::optional> intake_target = {}, - bool engulf = false, bool bud = false, bool brake = false); + bool engulf = false, bool bud = false, bool brake = false, + bool become = false, bool emerge = false, std::uint8_t exclude = 0); // Protocol v10 (ADR-0121): choose one candidate of the life's outstanding offer. The // receipt names the tick it publishes with; the outcome follows that commit. `tick` is // the client's latest simulated tick (after the offer); the server schedules the next. [[nodiscard]] bool send_cellular_mutation(std::uint64_t action_id, std::uint64_t tick, std::uint64_t life_identity, std::uint64_t event_index, std::uint64_t offer_tick, - std::uint16_t operator_id); + std::uint16_t operator_id, bool become = false); [[nodiscard]] bool query_action(std::uint64_t action_id); // Primitive profile v5 only. The account and generation are always supplied by the // authenticated session; callers choose only a stable request id. diff --git a/include/evo/network/session_protocol.hpp b/include/evo/network/session_protocol.hpp index 2e2a44f..7b92fc4 100644 --- a/include/evo/network/session_protocol.hpp +++ b/include/evo/network/session_protocol.hpp @@ -45,19 +45,30 @@ inline constexpr std::uint16_t session_protocol_v12 = 12; // region's current configuration in its perception, each deposit's world velocity, and a brake // flag on cellular actions. inline constexpr std::uint16_t session_protocol_v13 = 13; -// v10 to v13 share every cellular message but the perception's contents and v13's brake. +// v14 (rules 13, ADR-0179) is v13 plus the cellular revamp: the body block in the perception, +// become, emerge and channel exclusions on actions, become on mutation choices, catalog offers +// and the emerged ending. +inline constexpr std::uint16_t session_protocol_v14 = 14; +// v10 to v14 share every cellular message but the perception's contents, v13's brake and v14's +// revamp fields. [[nodiscard]] constexpr bool cellular_v10_family(std::uint16_t version) noexcept { return version == session_protocol_v10 || version == session_protocol_v11 || - version == session_protocol_v12 || version == session_protocol_v13; + version == session_protocol_v12 || version == session_protocol_v13 || + version == session_protocol_v14; } // Versions whose perception lists pools and bubbles (ADR-0136) instead of square patches. [[nodiscard]] constexpr bool cellular_deposit_version(std::uint16_t version) noexcept { return version == session_protocol_v11 || version == session_protocol_v12 || - version == session_protocol_v13; + version == session_protocol_v13 || version == session_protocol_v14; } // Versions that carry captured light and producers (ADR-0176). [[nodiscard]] constexpr bool cellular_light_version(std::uint16_t version) noexcept { - return version == session_protocol_v12 || version == session_protocol_v13; + return version == session_protocol_v12 || version == session_protocol_v13 || + version == session_protocol_v14; +} +// Versions that carry liquid motion (rules 12). +[[nodiscard]] constexpr bool cellular_liquid_version(std::uint16_t version) noexcept { + return version == session_protocol_v13 || version == session_protocol_v14; } // The highest capability a version's mutation offers may name. [[nodiscard]] constexpr std::uint8_t @@ -208,6 +219,10 @@ struct CellularActionInput { bool engulf{}; bool bud{}; // Kind 3 (ADR-0125): fund one wildlife bud, zero coordinates, v10 only. bool brake{}; // Byte 13 bit 0 (schema 58, rules 12): oppose relative velocity. + // Schema 60 (rules 13): byte 13 bit 1 become the bud, bit 2 emerge; byte 14 the channels + // excluded from burning (bits 0-3: C, N, P, other). + bool become{}, emerge{}; + std::uint8_t exclude{}; friend bool operator==(const CellularActionInput&, const CellularActionInput&) = default; }; inline constexpr std::size_t cellular_action_input_bytes = 24; @@ -224,6 +239,10 @@ struct CellularAction { bool bud{}; // v13 (rules 12): brake against relative velocity instead of following the movement. bool brake{}; + // v14 (rules 13): with `bud`, continue as the bud; leave the region as an organism at the + // threshold (no target); matter channels excluded from burning (bits 0-3). + bool become{}, emerge{}; + std::uint8_t exclude{}; friend bool operator==(const CellularAction&, const CellularAction&) = default; }; // v10 reliable choice. The server binds these values to the authenticated account and @@ -232,12 +251,16 @@ struct CellularMutationAction { std::uint64_t session{}, epoch{}, action_id{}, tick{}; std::uint64_t life_identity{}, event_index{}, offer_tick{}; std::uint16_t operator_id{}; + bool become{}; // v14: continue as the offspring the choice splits off. friend bool operator==(const CellularMutationAction&, const CellularMutationAction&) = default; }; // v10 server-to-owner offer (ADR-0121, 11.4d): the life's outstanding earned offer, its // candidates in stable operator order (never ranked). Each candidate states the successor's // actual tradeoffs: its capability value and its maintenance and total mass. No candidates // (and zero event/offer) clears a consumed or absent offer. +// v14 (rules 13) keeps the layout for a named catalog mutation: `operator_id` is its catalog +// id, `parameter` its chance of appearing in parts per million, capability, effect, +// maintenance and mass zero, and the cost its tuned cost. The client names it from the catalog. struct CellularOfferedCandidate { std::uint16_t operator_id{}; std::uint8_t capability{}, effect{}; // biology::Capability, biology::MutationEffect. @@ -257,8 +280,9 @@ struct CellularMutationOffer { friend bool operator==(const CellularMutationOffer&, const CellularMutationOffer&) = default; }; // v10 (ADR-0129): the owner's life ended in `tick`. Cause 1 starved, 2 engulfed, 0 not -// recorded (rules below 3). Death is final; a new life is a new request. -enum class CellularDeathReason : std::uint8_t { unrecorded, starved, engulfed }; +// recorded (rules below 3); v14 adds 3, the organism emerged. Death is final; a new life is a +// new request. +enum class CellularDeathReason : std::uint8_t { unrecorded, starved, engulfed, emerged }; struct CellularLifeEnded { std::uint64_t tick{}, life_identity{}; CellularDeathReason cause{}; @@ -357,6 +381,14 @@ struct CellularLifeDiagnostics { // turn), the authoritative motion state the client predictor reconciles against. std::int32_t velocity_x_q10{}, velocity_y_q10{}; std::uint16_t heading{}; + // v14 only (rules 13): cells in the organism and the emergence threshold, the exclusions + // in effect, whether Emerge is open, what the reserve can pay as energy with matter standing + // in, total mass, and the heritable body traits (biology::CellularTraits field order). + std::uint16_t members{}, emerge_members{}; + std::uint8_t exclude{}; + bool can_emerge{}; + std::uint64_t payable_energy_pj{}, total_mass_fg{}; + std::array traits{}; friend bool operator==(const CellularLifeDiagnostics&, const CellularLifeDiagnostics&) = default; }; diff --git a/include/evo/persistence/checkpoint_store.hpp b/include/evo/persistence/checkpoint_store.hpp index 8c074ae..6b8880b 100644 --- a/include/evo/persistence/checkpoint_store.hpp +++ b/include/evo/persistence/checkpoint_store.hpp @@ -292,6 +292,12 @@ migrate_cellular_liquid_profile(Postgres&, const FilesystemObjectStore&, const L const CommittedCheckpoint&, Uuid commit, const Sha256Digest& build, const server::CellularLiquidRules& rules, std::chrono::milliseconds timeout, const PublishHooks& hooks = {}); +// Rules 13: explicit raw-only bundle 14 -> 15, declaring the region's revamp rules. +[[nodiscard]] std::expected +migrate_cellular_revamp_profile(Postgres&, const FilesystemObjectStore&, const LeaseGrant&, + const CommittedCheckpoint&, Uuid commit, const Sha256Digest& build, + const server::CellularRevampRules& rules, + std::chrono::milliseconds timeout, const PublishHooks& hooks = {}); // Verify the recorded no-tick operation under current authority, replaying its // entire source/target payload. Version upgrades and profile transitions retain // separate evidence; neither is inferred solely from the target tuple. diff --git a/include/evo/persistence/region_checkpoint.hpp b/include/evo/persistence/region_checkpoint.hpp index 45edb6d..4f97a94 100644 --- a/include/evo/persistence/region_checkpoint.hpp +++ b/include/evo/persistence/region_checkpoint.hpp @@ -89,9 +89,12 @@ inline constexpr CellularVersionBundle cellular_v12_versions{10, 8, 2, 1, 1, 4, inline constexpr CellularVersionBundle cellular_v13_versions{11, 9, 2, 1, 1, 5, 4, 2, 1}; // Rules 12 on owner format 10 (liquid region), development 6, founder 5 (ADR-0177). inline constexpr CellularVersionBundle cellular_v14_versions{12, 10, 2, 1, 1, 6, 5, 2, 1}; +// Rules 13 on owner format 11 (the cellular revamp), development 7, founder 6 (ADR-0179). +inline constexpr CellularVersionBundle cellular_v15_versions{13, 11, 2, 1, 1, 7, 6, 2, 1}; // Raw-only retained-plan bundles, which use trace 4 and their own SQL admission. [[nodiscard]] constexpr bool cellular_plan_bundle(const CellularVersionBundle& b) noexcept { - return b == cellular_v12_versions || b == cellular_v13_versions || b == cellular_v14_versions; + return b == cellular_v12_versions || b == cellular_v13_versions || b == cellular_v14_versions || + b == cellular_v15_versions; } // Zero means this bundle has no population representation. [[nodiscard]] constexpr std::uint32_t @@ -306,6 +309,17 @@ cellular_liquid_upgrade_manifest(const CheckpointManifest& predecessor, cellular_liquid_upgrade_payload(std::span payload, const CheckpointManifest& predecessor, const server::CellularLiquidRules& rules); +// Rules 13 (ADR-0179): explicit raw-only bundle 14 -> 15 upgrade declaring the revamp rules +// from the Git tuning file. The rules are the only input; recovery reads them from the target. +[[nodiscard]] std::expected +cellular_revamp_upgrade_manifest(const CheckpointManifest& predecessor, + const Sha256Digest& predecessor_digest, Uuid commit, + const LeaseGrant& lease, const Sha256Digest& build, + std::uint64_t payload_bytes, const Sha256Digest& payload_sha256); +[[nodiscard]] std::expected, CheckpointError> +cellular_revamp_upgrade_payload(std::span payload, + const CheckpointManifest& predecessor, + const server::CellularRevampRules& rules); // ADR-0174: explicit one-way, no-tick profile 5 -> 6 transition. The payload wraps the // identical population with its declared environment; bundle and policy are unchanged. [[nodiscard]] std::expected diff --git a/include/evo/server/lifecycle/cellular_batch.hpp b/include/evo/server/lifecycle/cellular_batch.hpp index 79ac20d..5a7ea72 100644 --- a/include/evo/server/lifecycle/cellular_batch.hpp +++ b/include/evo/server/lifecycle/cellular_batch.hpp @@ -61,6 +61,8 @@ struct CellularActionRecord { struct CellularMutationActionInput { std::uint64_t life_id{}, event_index{}, offer_tick{}; std::uint16_t operator_id{}; + // Rules 13: continue as the split's offspring. Stored as bit 15 of the operator (schema 60). + bool become{}; friend bool operator==(const CellularMutationActionInput&, const CellularMutationActionInput&) = default; }; diff --git a/include/evo/server/lifecycle/cellular_lives.hpp b/include/evo/server/lifecycle/cellular_lives.hpp index d089946..745a682 100644 --- a/include/evo/server/lifecycle/cellular_lives.hpp +++ b/include/evo/server/lifecycle/cellular_lives.hpp @@ -239,6 +239,7 @@ struct CellularLifeTickFeedback { CellularPresence presence{CellularPresence::active}; bool resume_blocked{}; accounting::Picojoules light{}; // Rules 11 (ADR-0175): light captured this tick. + std::uint8_t exclude{}; // Rules 13: the matter channels kept from burning this tick. auto operator<=>(const CellularLifeTickFeedback&) const = default; }; // Which owner version a new region starts on. Offers: format 2, rules 2 (the M11.3/11.4 @@ -280,6 +281,10 @@ enum class CellularLivesError : std::uint8_t { checksum, noncanonical }; +// Rules 13 (reproduction plan section 6): the genome an organism of `members` cells develops +// as (the target size times its members); the genome itself for a single cell. +[[nodiscard]] std::expected +cellular_organism_genome(const biology::Genome& genome, std::uint32_t members); // In-memory authoritative cellular owner. It consumes funded profile-3 opening // state but never mutates or reinterprets that checkpoint. Each tick is applied @@ -310,6 +315,8 @@ class CellularLives { [[nodiscard]] const biology::LineageArchive& archive() const noexcept; [[nodiscard]] accounting::Inventory nursery() const noexcept; [[nodiscard]] accounting::Inventory heat() const noexcept; + // Rules 13: burned matter and kill remainders waiting to drip back as bubbles. + [[nodiscard]] accounting::Inventory spent() const noexcept; [[nodiscard]] accounting::Inventory opening_total() const noexcept; [[nodiscard]] accounting::Inventory current_total() const noexcept; [[nodiscard]] const CellularBoundaryLedger& boundary_ledger() const noexcept; diff --git a/include/evo/server/lifecycle/cellular_play_summary.hpp b/include/evo/server/lifecycle/cellular_play_summary.hpp index 4840bcc..e6ed11e 100644 --- a/include/evo/server/lifecycle/cellular_play_summary.hpp +++ b/include/evo/server/lifecycle/cellular_play_summary.hpp @@ -22,6 +22,10 @@ struct CellularPlaySummary { std::uint64_t lifespan_min{}, lifespan_median{}, lifespan_max{}; // Reproduction and evolution: buds so far, mutations applied, living variety. std::uint64_t buds{}, mutations{}, living_genomes{}, deepest_lineage{}; + // Rules 13: living organisms and the largest one's cells; offers waiting for a choice and + // offers earned by the living; matter in the spent pool. + std::uint64_t organisms{}, largest_organism{}, offers_pending{}, offers_earned{}; + std::uint64_t spent_matter_fg{}; friend bool operator==(const CellularPlaySummary&, const CellularPlaySummary&) = default; }; diff --git a/include/evo/server/region_sessions.hpp b/include/evo/server/region_sessions.hpp index d0369c7..5e2c636 100644 --- a/include/evo/server/region_sessions.hpp +++ b/include/evo/server/region_sessions.hpp @@ -183,9 +183,12 @@ class RegionSessions { // A published v10 choice's outcome, to the account's current v10 session if any. [[nodiscard]] bool send_mutation_outcome(const network::AccountId& account, const network::ActionOutcome& outcome); - // The owner's outstanding offer (11.4d), to the account's current v10 session if any. + // The owner's outstanding offer (11.4d), to the account's current v10 session if any. A + // rules-13 catalog offer (`named`) goes only to a v14 session, an operator offer only to + // v10-v13. [[nodiscard]] bool send_mutation_offer(const network::AccountId& account, - const network::CellularMutationOffer& offer); + const network::CellularMutationOffer& offer, + bool named = false); // 11.8 (ADR-0129): the owner's life ended, with its cause, to its v10 session if any. [[nodiscard]] bool send_life_ended(const network::AccountId& account, const network::CellularLifeEnded& ended); diff --git a/migrations/0060_cellular_revamp_bundle.sql b/migrations/0060_cellular_revamp_bundle.sql new file mode 100644 index 0000000..32e3d4e --- /dev/null +++ b/migrations/0060_cellular_revamp_bundle.sql @@ -0,0 +1,323 @@ +-- Rules 13 (ADR-0179, Cellular_Revamp_Build_Plan.md): raw-only bundle 15 (rules 13 on owner +-- format 11: the cellular revamp) and exact bundle 14 -> 15 upgrades declaring the region's +-- revamp rules. Normalization is parser-local; stored evidence and retries retain real bytes. +-- Raw trace 4 is unchanged except that a bundle-15 mutation selection may set byte 34 (become). + +-- The canonical cellular action input: byte 13 bit 1 become (with a bud) and bit 2 emerge (no +-- target); byte 14 the matter channels excluded from burning. Widening cannot invalidate an +-- existing row; earlier inputs keep both zero. +CREATE OR REPLACE FUNCTION evolution.valid_cellular_action_input(p_input bytea, p_tick evolution.u64) +RETURNS boolean LANGUAGE plpgsql IMMUTABLE STRICT +SET search_path = pg_catalog, pg_temp AS $$ +BEGIN + IF octet_length(p_input) <> 24 THEN + RETURN false; + END IF; + IF evolution.manifest_uint(p_input, 0, 8) = 0 + OR evolution.manifest_uint(p_input, 0, 8) <> p_tick OR get_byte(p_input, 12) > 3 + OR get_byte(p_input, 13) > 7 OR get_byte(p_input, 14) > 15 OR get_byte(p_input, 15) <> 0 + OR (get_byte(p_input, 13) & 2 <> 0 AND get_byte(p_input, 12) <> 3) + OR (get_byte(p_input, 13) & 4 <> 0 AND get_byte(p_input, 12) <> 0) THEN + RETURN false; + END IF; + IF get_byte(p_input, 12) <> 1 AND substring(p_input FROM 17 FOR 8) <> '\x0000000000000000' THEN + RETURN false; + END IF; + RETURN true; +END $$; + +ALTER FUNCTION evolution.parse_checkpoint_manifest(bytea) RENAME TO parse_checkpoint_manifest_v59; +REVOKE ALL ON FUNCTION evolution.parse_checkpoint_manifest_v59(bytea) FROM PUBLIC, :"runtime_role"; +CREATE FUNCTION evolution.parse_checkpoint_manifest(m bytea) +RETURNS evolution.checkpoint_manifest LANGUAGE plpgsql IMMUTABLE +SET search_path=pg_catalog,pg_temp AS $$ +DECLARE c evolution.checkpoint_manifest; + b14 constant bytea := '\x0c0000000a00000002000000010000000100000006000000050000000200000001000000'; + b15 constant bytea := '\x0d0000000b00000002000000010000000100000007000000060000000200000001000000'; +BEGIN + IF m IS NOT NULL AND octet_length(m)=360 AND evolution.manifest_uint(m,12,4)=4 + AND substring(m FROM 161 FOR 36)=b15 THEN + c := evolution.parse_checkpoint_manifest_v59(overlay(m PLACING b14 FROM 161 FOR 36)); + c.versions := b15; + RETURN c; + END IF; + RETURN evolution.parse_checkpoint_manifest_v59(m); +END $$; +REVOKE ALL ON FUNCTION evolution.parse_checkpoint_manifest(bytea) FROM PUBLIC; + +ALTER FUNCTION evolution.cellular_births(bytea,bytea) RENAME TO cellular_births_v59; +REVOKE ALL ON FUNCTION evolution.cellular_births_v59(bytea,bytea) FROM PUBLIC, :"runtime_role"; +CREATE FUNCTION evolution.cellular_births(t bytea,m bytea) +RETURNS TABLE(account_id uuid,request_id evolution.u64,generation evolution.u64,identity evolution.u64,born evolution.u64) +LANGUAGE plpgsql IMMUTABLE SET search_path=pg_catalog,pg_temp AS $$ +DECLARE c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(m); +BEGIN + IF c.versions='\x0d0000000b00000002000000010000000100000007000000060000000200000001000000'::bytea THEN + m := overlay(m PLACING '\x0c0000000a00000002000000010000000100000006000000050000000200000001000000'::bytea FROM 161 FOR 36); + END IF; + RETURN QUERY SELECT * FROM evolution.cellular_births_v59(t,m); +END $$; +REVOKE ALL ON FUNCTION evolution.cellular_births(bytea,bytea) FROM PUBLIC; + +-- Results 5 split applied and 6 split refused (rules 13). +ALTER TABLE evolution.cellular_mutation_action_publications + DROP CONSTRAINT cellular_mutation_action_publications_result_check; +ALTER TABLE evolution.cellular_mutation_action_publications + ADD CONSTRAINT cellular_mutation_action_publications_result_check CHECK(result BETWEEN 0 AND 6); + +-- A bundle-15 selection's byte 34 is its become flag (0 or 1). The returned operator carries +-- it as bit 15, exactly as the reservation input stores it, so the block check compares them. +CREATE OR REPLACE FUNCTION evolution.cellular_mutation_selections(p_trace bytea, p_manifest bytea) +RETURNS TABLE(tick evolution.u64, life_id evolution.u64, event_index evolution.u64, + offer_tick evolution.u64, successor_identity evolution.u64, operator_id integer) +LANGUAGE plpgsql IMMUTABLE SECURITY INVOKER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE + c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(p_manifest); + revamp boolean := c.versions = + '\x0d0000000b00000002000000010000000100000007000000060000000200000001000000'::bytea; + ticks integer; + off integer := 112; + intent_count integer; + birth_count integer; + mutation_count integer; + previous_life numeric; + become integer; +BEGIN + PERFORM * FROM evolution.cellular_births(p_trace, p_manifest); -- Binding and structure. + IF evolution.manifest_uint(p_trace, 8, 4) NOT IN (3,4) THEN + RETURN; -- Format 2 carries no selections. + END IF; + ticks := (c.end_tick - c.begin_tick)::integer; + FOR tick_index IN 0 .. ticks - 1 LOOP + intent_count := evolution.manifest_uint(p_trace, off, 4)::integer; + birth_count := evolution.manifest_uint(p_trace, off + 4, 4)::integer; + mutation_count := evolution.manifest_uint(p_trace, off + 8, 4)::integer; + off := off + 16 + intent_count * 24 + birth_count * 40; + previous_life := 0; + FOR mutation_index IN 0 .. mutation_count - 1 LOOP + tick := c.begin_tick + tick_index + 1; + life_id := evolution.manifest_uint(p_trace, off, 8); + event_index := evolution.manifest_uint(p_trace, off + 8, 8); + offer_tick := evolution.manifest_uint(p_trace, off + 16, 8); + successor_identity := evolution.manifest_uint(p_trace, off + 24, 8); + operator_id := evolution.manifest_uint(p_trace, off + 32, 2)::integer; + become := get_byte(p_trace, off + 34); + IF life_id = 0 OR life_id <= previous_life OR event_index = 0 OR offer_tick = 0 + OR offer_tick >= tick OR successor_identity = 0 OR operator_id >= 32768 + OR become > (CASE WHEN revamp THEN 1 ELSE 0 END) OR (become = 1 AND operator_id = 0) + OR substring(p_trace FROM off + 36 FOR 5) <> '\x0000000000' THEN + RAISE EXCEPTION 'invalid cellular mutation selection' USING ERRCODE = '22023'; + END IF; + operator_id := operator_id + 32768 * become; + previous_life := life_id; + off := off + 40; + RETURN NEXT; + END LOOP; + END LOOP; +END $$; + +-- Schema 59's block check, with bundle 15's results: a decline is life died or declined; a +-- choice is applied (an organism), life died, insufficient funding, split applied or split +-- refused. Only bundle 15 stores become (operator bit 15), and only with a choice. +CREATE OR REPLACE FUNCTION evolution.check_cellular_mutation_block(p_manifest bytea, p_trace bytea, + p_mutations bytea, p_results bytea) +RETURNS integer LANGUAGE plpgsql STABLE SECURITY INVOKER +SET search_path = pg_catalog, pg_temp AS $$ +DECLARE + c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(p_manifest); + b15 constant bytea := '\x0d0000000b00000002000000010000000100000007000000060000000200000001000000'; + n integer; + account uuid; + account_bytes bytea; + action numeric; + tick numeric; + input bytea; + stored integer; + previous_tick numeric := -1; + previous_account bytea := ''::bytea; + previous_action numeric := -1; + applied numeric; + r evolution.cellular_mutation_reservations%ROWTYPE; +BEGIN + IF p_mutations IS NULL OR p_results IS NULL OR octet_length(p_mutations) = 0 + OR octet_length(p_mutations) % 64 <> 0 OR octet_length(p_mutations) / 64 > 1024 + OR octet_length(p_results) <> octet_length(p_mutations) / 64 THEN + RAISE EXCEPTION 'invalid cellular mutation block' USING ERRCODE = '22023'; + END IF; + n := octet_length(p_mutations) / 64; + IF (SELECT count(*) FROM evolution.cellular_mutation_selections(p_trace, p_manifest)) <> n THEN + RAISE EXCEPTION 'cellular mutation block does not cover the trace' USING ERRCODE = '22023'; + END IF; + FOR i IN 0 .. n - 1 LOOP + account_bytes := substring(p_mutations FROM 64 * i + 1 FOR 16); + account := encode(account_bytes, 'hex')::uuid; + action := evolution.manifest_uint(p_mutations, 64 * i + 16, 8); + input := substring(p_mutations FROM 64 * i + 25 FOR 34); + tick := evolution.manifest_uint(input, 0, 8); + stored := evolution.manifest_uint(input, 32, 2)::integer; + IF account = '00000000-0000-0000-0000-000000000000' OR action = 0 + OR NOT evolution.valid_cellular_mutation_input(input) + OR substring(p_mutations FROM 64 * i + 59 FOR 6) <> '\x000000000000' + OR (c.versions = b15 + AND ((stored % 32768 = 0 AND (stored >= 32768 OR get_byte(p_results,i) NOT IN (1,3))) + OR (stored % 32768 <> 0 AND get_byte(p_results,i) NOT IN (0,1,2,5,6)))) + OR (c.versions <> b15 AND stored >= 32768) + OR (c.versions IN ('\x0a0000000800000002000000010000000100000004000000030000000200000001000000'::bytea, + '\x0b0000000900000002000000010000000100000005000000040000000200000001000000'::bytea, + '\x0c0000000a00000002000000010000000100000006000000050000000200000001000000'::bytea) + AND (get_byte(p_results,i) NOT IN (1,3,4) + OR (stored=0 AND get_byte(p_results,i) NOT IN (1,3)) + OR (stored<>0 AND get_byte(p_results,i) NOT IN (1,4)))) + OR (c.versions NOT IN ('\x0a0000000800000002000000010000000100000004000000030000000200000001000000'::bytea, + '\x0b0000000900000002000000010000000100000005000000040000000200000001000000'::bytea, + '\x0c0000000a00000002000000010000000100000006000000050000000200000001000000'::bytea, + b15) + AND get_byte(p_results,i)>3) + OR tick <= c.begin_tick OR tick > c.end_tick + OR (tick, account_bytes, action) <= (previous_tick, previous_account, previous_action) THEN + RAISE EXCEPTION 'invalid cellular mutation record' USING ERRCODE = '22023'; + END IF; + previous_tick := tick; + previous_account := account_bytes; + previous_action := action; + SELECT * INTO r FROM evolution.cellular_mutation_reservations x + WHERE x.world_id = c.world_id AND x.account_id = account AND x.action_id = action; + -- The reservation's tick is the earliest the choice may apply at; the record carries + -- the tick it applied at, and the rest of the input must match exactly. + applied := tick; + IF NOT FOUND OR r.region_id <> c.region_id + OR substring(r.input_bytes FROM 9) <> substring(input FROM 9) + OR r.target_tick <> evolution.manifest_uint(r.input_bytes, 0, 8) + OR applied < r.target_tick THEN + RAISE EXCEPTION 'cellular mutation reservation conflicts' USING ERRCODE = 'EVL16'; + END IF; + IF NOT EXISTS (SELECT 1 FROM evolution.cellular_mutation_selections(p_trace, p_manifest) s + WHERE s.tick = applied AND s.successor_identity = r.successor_identity + AND s.life_id = evolution.manifest_uint(input, 8, 8) + AND s.event_index = evolution.manifest_uint(input, 16, 8) + AND s.offer_tick = evolution.manifest_uint(input, 24, 8) + AND s.operator_id = stored) THEN + RAISE EXCEPTION 'cellular mutation differs from its trace' USING ERRCODE = '22023'; + END IF; + END LOOP; + RETURN n; +END $$; + +ALTER FUNCTION evolution.publish_cellular_profile_migration(bytea) RENAME TO publish_cellular_profile_migration_v59; +REVOKE ALL ON FUNCTION evolution.publish_cellular_profile_migration_v59(bytea) FROM PUBLIC, :"runtime_role"; +CREATE OR REPLACE FUNCTION evolution.publish_cellular_profile_migration(p_manifest bytea) +RETURNS TABLE(region_frame evolution.u64, head_sequence evolution.u64, head_commit uuid, + head_digest text, head_tick evolution.u64) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE + c evolution.checkpoint_manifest := evolution.parse_checkpoint_manifest(p_manifest); + s evolution.checkpoint_manifest; + h evolution.region_heads%ROWTYPE; + p evolution.region_commits%ROWTYPE; + old evolution.region_commits%ROWTYPE; + frame evolution.u64; + d bytea := sha256(p_manifest); + source_bundle constant bytea := '\x0c0000000a00000002000000010000000100000006000000050000000200000001000000'; + target_bundle constant bytea := '\x0d0000000b00000002000000010000000100000007000000060000000200000001000000'; + zero32 constant bytea := decode(repeat('00', 32), 'hex'); +BEGIN + IF c.versions <> target_bundle THEN + RETURN QUERY SELECT * FROM evolution.publish_cellular_profile_migration_v59(p_manifest); + RETURN; + END IF; + IF c.profile <> 4 OR c.commit_sequence = 0 OR c.begin_tick <> c.end_tick + OR c.end_tick = 0 OR c.versions <> target_bundle + OR evolution.manifest_uint(p_manifest, 228, 4) <> 0 + OR evolution.manifest_uint(p_manifest, 232, 4) <> (CASE c.profile WHEN 4 THEN 4 ELSE 5 END) + OR evolution.manifest_uint(p_manifest, 236, 4) <> 1 + OR c.trace_bytes <> 0 OR c.trace_sha256 <> zero32 + OR c.decision_count <> 0 OR c.decisions_sha256 <> zero32 THEN + RAISE EXCEPTION 'invalid revamp profile migration' USING ERRCODE = '22023'; + END IF; + PERFORM evolution.check_region_lease(c.world_id, c.region_id, c.holder, c.epoch); + SELECT * INTO old FROM evolution.region_commits r WHERE r.commit_id = c.commit_id; + IF FOUND THEN + IF old.manifest <> p_manifest THEN + RAISE EXCEPTION 'cellular profile migration identity reused' USING ERRCODE = 'EVL07'; + END IF; + SELECT * INTO p FROM evolution.region_commits r + WHERE r.world_id = old.world_id AND r.region_id = old.region_id + AND r.commit_sequence = old.commit_sequence - 1; + IF NOT FOUND OR NOT EXISTS ( + SELECT 1 FROM evolution.cellular_profile_migrations m + WHERE m.target_commit = c.commit_id AND m.world_id = c.world_id + AND m.region_id = c.region_id AND m.source_sequence = p.commit_sequence + AND m.source_commit = p.commit_id AND m.source_manifest_sha256 = p.commit_digest + AND m.source_payload_sha256 = p.payload_sha256 AND m.source_versions = p.versions + AND m.target_sequence = old.commit_sequence AND m.target_manifest_sha256 = d + AND m.target_payload_sha256 = old.payload_sha256 AND m.target_versions = old.versions + AND m.source_commit = c.predecessor_commit + AND m.source_manifest_sha256 = c.predecessor_digest) THEN + RAISE EXCEPTION 'cellular profile migration identity reused' USING ERRCODE = 'EVL07'; + END IF; + SELECT l.frame_id INTO frame FROM evolution.region_leases l + WHERE l.world_id = c.world_id AND l.region_id = c.region_id; + RETURN QUERY SELECT frame, old.commit_sequence, old.commit_id, + encode(old.commit_digest, 'hex'), old.end_tick; + RETURN; + END IF; + IF EXISTS (SELECT 1 FROM evolution.population_interval_pending x + WHERE x.world_id = c.world_id AND x.region_id = c.region_id) THEN + RAISE EXCEPTION 'revamp upgrade waits for interval' USING ERRCODE = 'EVL18'; + END IF; + IF EXISTS (SELECT 1 FROM evolution.cellular_mutation_reservations x + WHERE x.world_id=c.world_id AND x.region_id=c.region_id AND NOT EXISTS + (SELECT 1 FROM evolution.cellular_mutation_action_publications a + WHERE a.world_id=x.world_id AND a.account_id=x.account_id AND a.action_id=x.action_id)) THEN + RAISE EXCEPTION 'revamp upgrade waits for mutation choice' USING ERRCODE='EVL18'; + END IF; + SELECT * INTO h FROM evolution.region_heads r + WHERE r.world_id = c.world_id AND r.region_id = c.region_id FOR UPDATE; + IF NOT FOUND OR h.commit_sequence = 18446744073709551615 + OR c.commit_sequence <> h.commit_sequence + 1 OR c.predecessor_commit <> h.commit_id + OR c.predecessor_digest <> h.digest OR c.begin_tick <> h.end_tick THEN + RAISE EXCEPTION 'region head moved' USING ERRCODE = 'EVL03'; + END IF; + SELECT * INTO p FROM evolution.region_commits r + WHERE r.world_id = c.world_id AND r.region_id = c.region_id + AND r.commit_sequence = h.commit_sequence; + IF NOT FOUND THEN + RAISE EXCEPTION 'missing migration predecessor' USING ERRCODE = 'XX000'; + END IF; + s := evolution.parse_checkpoint_manifest(p.manifest); + IF s.profile <> c.profile OR s.versions <> source_bundle OR p.versions <> source_bundle + OR c.frame_id <> s.frame_id OR c.tick_microseconds <> s.tick_microseconds + OR s.commit_id <> c.predecessor_commit OR s.end_tick <> c.end_tick + OR evolution.manifest_uint(p.manifest, 232, 4) <> (CASE c.profile WHEN 4 THEN 4 ELSE 5 END) + OR NOT EXISTS (SELECT 1 FROM evolution.retained_builds b + WHERE b.build_identity = c.build_identity) THEN + RAISE EXCEPTION 'unsupported revamp profile migration' USING ERRCODE = 'EVL06'; + END IF; + SELECT l.frame_id INTO frame FROM evolution.region_leases l + WHERE l.world_id = c.world_id AND l.region_id = c.region_id; + IF c.frame_id <> frame THEN + RAISE EXCEPTION 'foreign frame' USING ERRCODE = '22023'; + END IF; + INSERT INTO evolution.cellular_profile_migrations(target_commit, world_id, region_id, + source_sequence, source_commit, source_manifest_sha256, source_payload_sha256, + source_versions, target_sequence, target_manifest_sha256, target_payload_sha256, + target_versions) + VALUES (c.commit_id, c.world_id, c.region_id, p.commit_sequence, p.commit_id, + p.commit_digest, p.payload_sha256, p.versions, c.commit_sequence, d, + c.payload_sha256, c.versions); + INSERT INTO evolution.region_commits(world_id, region_id, commit_sequence, commit_id, + commit_digest, manifest, begin_tick, end_tick, published_epoch, tick_microseconds, + versions, build_identity, payload_bytes, payload_sha256) + VALUES (c.world_id, c.region_id, c.commit_sequence, c.commit_id, d, p_manifest, + c.begin_tick, c.end_tick, c.epoch, c.tick_microseconds, c.versions, + c.build_identity, c.payload_bytes, c.payload_sha256); + UPDATE evolution.region_heads r + SET commit_sequence = c.commit_sequence, commit_id = c.commit_id, digest = d, + end_tick = c.end_tick, published_epoch = c.epoch + WHERE r.world_id = c.world_id AND r.region_id = c.region_id; + RETURN QUERY SELECT frame, c.commit_sequence, c.commit_id, encode(d, 'hex'), c.end_tick; +END $$; +REVOKE ALL ON FUNCTION evolution.publish_cellular_profile_migration(bytea) FROM PUBLIC; +GRANT EXECUTE ON FUNCTION evolution.publish_cellular_profile_migration(bytea) TO :"runtime_role"; + +INSERT INTO evolution.schema_migrations(version,sha256) VALUES(60,:'migration_sha_60'); diff --git a/migrations/apply.sql b/migrations/apply.sql index 39bf1a9..de1c022 100644 --- a/migrations/apply.sql +++ b/migrations/apply.sql @@ -135,6 +135,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') SELECT :'history_v56' || ',57:' || :'migration_sha_57' AS history_v57 \gset SELECT :'history_v57' || ',58:' || :'migration_sha_58' AS history_v58 \gset SELECT :'history_v58' || ',59:' || :'migration_sha_59' AS history_v59 \gset + SELECT :'history_v59' || ',60:' || :'migration_sha_60' AS history_v60 \gset SELECT :'history' = :'history_v22' AS at_v22, :'history' = :'history_v23' AS at_v23, :'history' = :'history_v24' AS at_v24, @@ -172,8 +173,10 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') :'history' = :'history_v56' AS at_v56, :'history' = :'history_v57' AS at_v57, :'history' = :'history_v58' AS at_v58, - :'history' = :'history_v59' AS at_v59 \gset - \if :at_v59 + :'history' = :'history_v59' AS at_v59, + :'history' = :'history_v60' AS at_v60 \gset + \if :at_v60 + \elif :at_v59 \elif :at_v58 \elif :at_v57 \elif :at_v56 @@ -585,7 +588,8 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, coalesce(max(version), 0) = 56 AS at_v56, coalesce(max(version), 0) = 57 AS at_v57, coalesce(max(version), 0) = 58 AS at_v58, - coalesce(max(version), 0) = 59 AS at_v59 + coalesce(max(version), 0) = 59 AS at_v59, + coalesce(max(version), 0) = 60 AS at_v60 FROM evolution.schema_migrations \gset \if :at_v24 \ir 0025_cellular_v2_bundle.sql @@ -813,6 +817,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \elif :at_v57 \elif :at_v58 \elif :at_v59 +\elif :at_v60 \else \echo 'Unknown or changed migration history after v43' DO $$ BEGIN RAISE EXCEPTION 'unknown or changed migration history'; END $$; @@ -881,6 +886,10 @@ SELECT coalesce(max(version), 0) = 58 AS needs_v59 FROM evolution.schema_migrati \if :needs_v59 \ir 0059_durable_mutation_queue.sql \endif +SELECT coalesce(max(version), 0) = 59 AS needs_v60 FROM evolution.schema_migrations \gset +\if :needs_v60 + \ir 0060_cellular_revamp_bundle.sql +\endif -- Effective-privilege audit on every run, including no-ops (ADR-0060). Attributes -- alone are insufficient: predefined roles such as pg_write_all_data, PUBLIC -- grants or SET-able memberships would bypass the fenced functions. Checks the diff --git a/schemas/network/session-v14-cellular-revamp.md b/schemas/network/session-v14-cellular-revamp.md new file mode 100644 index 0000000..85fc30e --- /dev/null +++ b/schemas/network/session-v14-cellular-revamp.md @@ -0,0 +1,39 @@ +# Session v14: the cellular revamp + +Authority: [ADR-0179](../../docs/adr/0179-cellular-gameplay-revamp.md). v14 is +[v13](session-v13-cellular-liquid.md) with the rules-13 revamp; every other message and rule is +v13's. Older versions keep their exact layouts and never see a v14 field. + +**Perception.** The v13 prefix is followed by a 64-byte body block: + +| Bytes | Field | +|---:|---| +| 2 | Members: cells in the organism (1 for a single cell; at least 1 with a life) | +| 2 | Emergence threshold in members (0 below rules 13) | +| 1 | Matter channels kept from burning this tick (bits 0-3: C, N, P, other) | +| 1 | Flags: bit 0 Emerge is open; other bits zero | +| 2 | Reserved zero | +| 8 | Payable energy (pJ): the reserve's energy plus what its burnable matter stands in for | +| 8 | Total mass (fg): body and reserve matter | +| 2 each | The 20 heritable body traits in `biology::CellularTraits` order: density, upkeep efficiency, growth speed, collection (E, C, N, P, O), burn (C, N, P, O), engulf capacity, kill absorption, litter, recipe (C, N, P, O), adhesion | + +Without an owner life every field is zero. + +**Cellular action.** Byte 37 (the v13 flags) adds bit 1 become (only with a bud: the player +continues as the bud) and bit 2 emerge (only with no target). Byte 38 is the exclusion mask +(0-15). The canonical 24-byte action input stores them as byte 13 bits 1-2 and byte 14 +(schema 60). + +**Mutation choice.** Byte 58 is become (0 or 1): continue as the offspring the choice splits +off. A decline never becomes. The durable reservation input stores it as bit 15 of the +operator field (schema 60). + +**Mutation offer.** A rules-13 region offers named catalog mutations in the v10 candidate +layout: the operator field is the catalog id, the parameter its chance of appearing in parts +per million, capability, effect, maintenance and mass zero, and the cost its tuned cost. The +client names it, and shows its pro and con, from the shared catalog +(`biology::cellular_mutation`). Catalog offers go only to v14 sessions and operator offers only +to v10-v13 sessions. + +**Life ended.** Cause 3 is emerged: the organism left the region for the world, and this +cellular life is complete. Earlier versions read it as unrecorded. diff --git a/src/biology/cellular_region_step.cpp b/src/biology/cellular_region_step.cpp index 40c135d..5acaeef 100644 --- a/src/biology/cellular_region_step.cpp +++ b/src/biology/cellular_region_step.cpp @@ -101,16 +101,25 @@ std::optional revamp_limits(const CellularLifeStepInput& life, limits.shared = shared * static_cast(mult) / 1'000; return limits; } -// Rules 13: engulf mass is the body plus the declared share of reserve matter. std::uint64_t engulf_mass(const CellularLifeStepInput& life, const accounting::Inventory& reserve, const CellularRevampStepRules& rules) noexcept { - const auto carried = matter_of(reserve) / 100 * rules.engulf_reserve_percent + - matter_of(reserve) % 100 * rules.engulf_reserve_percent / 100; - const auto body = life.budget.phenotype.total_mass; - return carried > u64_max - body ? u64_max : body + carried; + return cellular_engulf_mass(life.budget.phenotype.total_mass, reserve, rules); } } // namespace +std::uint64_t cellular_engulf_mass(std::uint64_t body_mass, const accounting::Inventory& reserve, + const CellularRevampStepRules& rules) noexcept { + const auto carried = matter_of(reserve) / 100 * rules.engulf_reserve_percent + + matter_of(reserve) % 100 * rules.engulf_reserve_percent / 100; + return carried > u64_max - body_mass ? u64_max : body_mass + carried; +} +bool cellular_engulfable(std::uint64_t hunter_mass, std::uint16_t engulf_capacity, + std::uint64_t prey_mass, std::uint32_t prey_membrane_nm, + const CellularRevampStepRules& rules) noexcept { + return product_at_least(hunter_mass, std::uint64_t{engulf_capacity} * 10'000, prey_mass, + std::uint64_t{rules.engulf_ratio_milli} * prey_membrane_nm); +} + std::expected propose_cellular_region_step(std::uint64_t begin_tick, CellularArea area, std::span lives, diff --git a/src/client/session/region_session.cpp b/src/client/session/region_session.cpp index b0e2edc..5fae524 100644 --- a/src/client/session/region_session.cpp +++ b/src/client/session/region_session.cpp @@ -309,33 +309,39 @@ bool RegionSessionClient::send_action(std::uint64_t action_id, network::ActionKi bool RegionSessionClient::send_cellular_action( std::uint64_t action_id, std::uint64_t tick, std::int16_t move_x, std::int16_t move_y, std::optional> intake_target, bool engulf, bool bud, - bool brake) { + bool brake, bool become, bool emerge, std::uint8_t exclude) { auto& m = *impl_; + const bool revamp = m.protocol_version == network::session_protocol_v14; + network::CellularAction action{ + m.welcome ? m.welcome->session : 0, m.welcome ? m.welcome->epoch : 0, action_id, tick, + move_x, move_y, intake_target.has_value(), intake_target ? intake_target->first : 0, + intake_target ? intake_target->second : 0, engulf, bud, + // A brake needs v13 or v14; older sessions never send one. + brake && network::cellular_liquid_version(m.protocol_version)}; + action.become = revamp && become; + action.emerge = revamp && emerge; + action.exclude = revamp ? exclude : std::uint8_t{0}; return (m.protocol_version == network::session_protocol_v7 || m.protocol_version == network::session_protocol_v8 || m.protocol_version == network::session_protocol_v9 || network::cellular_v10_family(m.protocol_version)) && m.state == RegionSessionState::established && m.welcome && action_id != 0 && tick != 0 && - m.send(network::CellularAction{ - m.welcome->session, m.welcome->epoch, action_id, tick, move_x, move_y, - intake_target.has_value(), intake_target ? intake_target->first : 0, - intake_target ? intake_target->second : 0, engulf, bud, - // A brake needs v13; older sessions never send one. - brake && m.protocol_version == network::session_protocol_v13}); + m.send(action); } bool RegionSessionClient::send_cellular_mutation(std::uint64_t action_id, std::uint64_t tick, std::uint64_t life_identity, std::uint64_t event_index, std::uint64_t offer_tick, - std::uint16_t operator_id) { + std::uint16_t operator_id, bool become) { auto& m = *impl_; return network::cellular_v10_family(m.protocol_version) && m.state == RegionSessionState::established && m.welcome && action_id != 0 && offer_tick != 0 && tick > offer_tick && + (!become || m.protocol_version == network::session_protocol_v14) && m.send(network::CellularMutationAction{m.welcome->session, m.welcome->epoch, action_id, tick, life_identity, event_index, offer_tick, - operator_id}); + operator_id, become}); } bool RegionSessionClient::query_action(std::uint64_t action_id) { diff --git a/src/network/protocol/intent_admission.cpp b/src/network/protocol/intent_admission.cpp index ca438e9..b980ffb 100644 --- a/src/network/protocol/intent_admission.cpp +++ b/src/network/protocol/intent_admission.cpp @@ -238,9 +238,9 @@ ActionReceipt IntentAdmission::action(std::uint64_t session, const CellularActio const AdmissionFacts& facts) { const SessionAction base{m.session, m.epoch, m.action_id, static_cast(ActionKind::cellular), m.tick}; - const auto bytes = - encode_cellular_action_input({m.tick, m.move_x, m.move_y, m.has_intake_target, - m.intake_x_um, m.intake_y_um, m.engulf, m.bud, m.brake}); + const auto bytes = encode_cellular_action_input( + {m.tick, m.move_x, m.move_y, m.has_intake_target, m.intake_x_um, m.intake_y_um, m.engulf, + m.bud, m.brake, m.become, m.emerge, m.exclude}); auto* s = find(session); if (!s) return {m.action_id, AdmitStatus::unknown_session, facts.server_tick, m.tick}; @@ -280,9 +280,9 @@ std::optional IntentAdmission::admit(std::uint64_t session, const const AdmissionFacts& facts) { const SessionAction base{m.session, m.epoch, m.action_id, static_cast(ActionKind::cellular), m.tick}; - const auto bytes = - encode_cellular_action_input({m.tick, m.move_x, m.move_y, m.has_intake_target, - m.intake_x_um, m.intake_y_um, m.engulf, m.bud, m.brake}); + const auto bytes = encode_cellular_action_input( + {m.tick, m.move_x, m.move_y, m.has_intake_target, m.intake_x_um, m.intake_y_um, m.engulf, + m.bud, m.brake, m.become, m.emerge, m.exclude}); auto* s = find(session); if (!s) return ActionReceipt{m.action_id, AdmitStatus::unknown_session, facts.server_tick, m.tick}; diff --git a/src/network/protocol/session_protocol.cpp b/src/network/protocol/session_protocol.cpp index e329039..6638269 100644 --- a/src/network/protocol/session_protocol.cpp +++ b/src/network/protocol/session_protocol.cpp @@ -37,6 +37,12 @@ constexpr std::size_t cellular_perceived_producer_bytes = 8 + 2 + 6; constexpr std::size_t cellular_liquid_block_bytes = 4 + 4 + 2 + 1 + 1 + 8 + (9 * 4); constexpr std::size_t cellular_perception_v13_prefix_bytes = cellular_perception_v12_prefix_bytes + cellular_liquid_block_bytes; +// v14 (rules 13) appends the body block: members and threshold (2 x u16), exclusions, flags +// (bit 0 Emerge open), two reserved bytes, payable energy and total mass (2 x u64) and twenty +// u16 traits. +constexpr std::size_t cellular_revamp_block_bytes = 2 + 2 + 1 + 1 + 2 + 8 + 8 + (20 * 2); +constexpr std::size_t cellular_perception_v14_prefix_bytes = + cellular_perception_v13_prefix_bytes + cellular_revamp_block_bytes; constexpr std::size_t cellular_perceived_patch_bytes = 8 + 8 + (4 * 8); // v11: id, centre, radius, shape, drained flag and five 16-bit amount codes. constexpr std::size_t cellular_perceived_deposit_bytes = 4 + 4 + 4 + 2 + 1 + 1 + (5 * 2); @@ -70,8 +76,14 @@ bool valid_offer(const CellularMutationOffer& offer, std::uint16_t version) { return offer.event_index == 0 && offer.offer_tick == 0; std::uint16_t previous = 0; for (const auto& candidate : offer.candidates) { + // v14: catalog ids with a chance in parts per million and nothing operator-shaped. + const bool named = version == session_protocol_v14; if (candidate.operator_id <= previous || - candidate.capability > cellular_offer_capability_limit(version) || candidate.effect > 3) + (named ? candidate.capability != 0 || candidate.effect != 0 || + candidate.parameter > 1'000'000 || candidate.maintenance != 0 || + candidate.total_mass != 0 + : candidate.capability > cellular_offer_capability_limit(version) || + candidate.effect > 3)) return false; previous = candidate.operator_id; } @@ -214,7 +226,18 @@ std::vector encode_session(const SessionMessage& message, std::uin return {}; if (const auto* ended = std::get_if(&message); ended && (!cellular_v10_family(version) || ended->tick == 0 || ended->life_identity == 0 || - ended->cause > CellularDeathReason::engulfed)) + ended->cause > (version == session_protocol_v14 ? CellularDeathReason::emerged + : CellularDeathReason::engulfed))) + return {}; + if (const auto* choice = std::get_if(&message); + choice && choice->become && version != session_protocol_v14) + return {}; + // v14 alone carries become, emerge and exclusions; become needs a bud, emerge no target. + if (const auto* action = std::get_if(&message); + action && (action->become || action->emerge || action->exclude != 0) && + (version != session_protocol_v14 || action->exclude > 0x0F || + (action->become && !action->bud) || + (action->emerge && (action->bud || action->engulf || action->has_intake_target)))) return {}; // v9 has no room for engulf and bud effects or the bud cost; only v10 reports them // (ADR-0129). @@ -238,7 +261,15 @@ std::vector encode_session(const SessionMessage& message, std::uin // v12 and v13 carry captured light and producers (ADR-0176); v13 alone carries // liquid motion. const bool producers = cellular_light_version(version); - const bool liquid = version == session_protocol_v13; + const bool liquid = cellular_liquid_version(version); + const auto& body = perception->diagnostics; + if (version != session_protocol_v14 && body && + (body->members || body->emerge_members || body->exclude || body->can_emerge || + body->payable_energy_pj || body->total_mass_fg || + std::ranges::any_of(body->traits, [](std::uint16_t value) { return value != 0; }))) + return {}; + if (version == session_protocol_v14 && body && (body->members == 0 || body->exclude > 0x0F)) + return {}; if (!liquid && (perception->currents || (perception->diagnostics && (perception->diagnostics->velocity_x_q10 || perception->diagnostics->velocity_y_q10 || @@ -357,8 +388,11 @@ std::vector encode_session(const SessionMessage& message, std::uin put(out, static_cast(m.move_x), 2); put(out, static_cast(m.move_y), 2); out.push_back(m.has_intake_target ? 1 : m.engulf ? 2 : m.bud ? 3 : 0); // Target kind. - out.push_back(m.brake ? 1 : 0); // v13 flags: bit 0 brake. - put(out, 0, 2); + // v13 flags: bit 0 brake; v14 adds bit 1 become and bit 2 emerge. + out.push_back(static_cast((m.brake ? 1U : 0U) | (m.become ? 2U : 0U) | + (m.emerge ? 4U : 0U))); + out.push_back(m.exclude); // v14: channels excluded from burning. + out.push_back(0); put(out, m.intake_x_um, 4); put(out, m.intake_y_um, 4); return out; @@ -370,7 +404,8 @@ std::vector encode_session(const SessionMessage& message, std::uin m.event_index, m.offer_tick}) put(out, value, 8); put(out, m.operator_id, 2); - put(out, 0, 6); + out.push_back(m.become ? 1 : 0); // v14. + put(out, 0, 5); return out; } std::vector operator()(const CellularLifeEnded& m) const { @@ -407,13 +442,14 @@ std::vector encode_session(const SessionMessage& message, std::uin std::vector operator()(const CellularPerception& m) const { auto out = header(SessionMessageType::cellular_perception, - (version == session_protocol_v13 ? cellular_perception_v13_prefix_bytes + (version == session_protocol_v14 ? cellular_perception_v14_prefix_bytes + : version == session_protocol_v13 ? cellular_perception_v13_prefix_bytes : version == session_protocol_v12 ? cellular_perception_v12_prefix_bytes : cellular_v10_family(version) ? cellular_perception_v10_prefix_bytes : version == session_protocol_v9 ? cellular_perception_v9_prefix_bytes : cellular_perception_prefix_bytes) + m.patches.size() * cellular_perceived_patch_bytes + - m.deposits.size() * (version == session_protocol_v13 + m.deposits.size() * (cellular_liquid_version(version) ? cellular_perceived_liquid_deposit_bytes : cellular_perceived_deposit_bytes) + m.producers.size() * cellular_perceived_producer_bytes, @@ -446,7 +482,7 @@ std::vector encode_session(const SessionMessage& message, std::uin put(out, m.producers.size(), 2); put(out, 0, 6); } - if (version == session_protocol_v13) { + if (cellular_liquid_version(version)) { put(out, static_cast(d ? d->velocity_x_q10 : 0), 4); put(out, static_cast(d ? d->velocity_y_q10 : 0), 4); put(out, d ? d->heading : 0, 2); @@ -460,6 +496,18 @@ std::vector encode_session(const SessionMessage& message, std::uin c.max_speed_um_per_s}) put(out, value, 4); } + if (version == session_protocol_v14) { + const auto b = d.value_or(CellularLifeDiagnostics{}); + put(out, b.members, 2); + put(out, b.emerge_members, 2); + out.push_back(b.exclude); + out.push_back(b.can_emerge ? 1 : 0); + put(out, 0, 2); + put(out, b.payable_energy_pj, 8); + put(out, b.total_mass_fg, 8); + for (const auto value : b.traits) + put(out, value, 2); + } } else { put(out, 0, 5); } @@ -480,7 +528,7 @@ std::vector encode_session(const SessionMessage& message, std::uin out.push_back(deposit.drained ? 1 : 0); for (const auto code : deposit.amount_codes) put(out, code, 2); - if (version == session_protocol_v13) { + if (cellular_liquid_version(version)) { put(out, static_cast(deposit.velocity_x_um_s), 2); put(out, static_cast(deposit.velocity_y_um_s), 2); } @@ -721,14 +769,22 @@ std::expected decode_session(std::span(static_cast(get(payload, 32, 2))); m.move_y = static_cast(static_cast(get(payload, 34, 2))); // Target kind: 0 none, 1 patch intake, 2 engulf and 3 bud (v10 only, ADR-0124/0125). + const bool revamp = wire_version == session_protocol_v14; if (payload[36] > (cellular_v10_family(wire_version) ? 3 : 1) || - payload[37] > (wire_version == session_protocol_v13 ? 1 : 0) || payload[38] != 0 || - payload[39] != 0) + payload[37] > (revamp ? 7 + : wire_version == session_protocol_v13 ? 1 + : 0) || + payload[38] > (revamp ? 0x0F : 0) || payload[39] != 0) return std::unexpected(SessionCodecError::invalid_value); m.has_intake_target = payload[36] == 1; m.engulf = payload[36] == 2; m.bud = payload[36] == 3; - m.brake = payload[37] == 1; + m.brake = (payload[37] & 1U) != 0; + m.become = (payload[37] & 2U) != 0; + m.emerge = (payload[37] & 4U) != 0; + m.exclude = payload[38]; + if ((m.become && !m.bud) || (m.emerge && payload[36] != 0)) + return std::unexpected(SessionCodecError::invalid_value); m.intake_x_um = static_cast(get(payload, 40, 4)); m.intake_y_um = static_cast(get(payload, 44, 4)); if (!m.session || !m.epoch || !m.action_id || !m.tick || @@ -750,9 +806,11 @@ std::expected decode_session(std::span(get(payload, 56, 2)); + m.become = payload[58] == 1; if (!m.session || !m.epoch || !m.action_id || !m.tick || !m.life_identity || !m.event_index || !m.offer_tick || m.offer_tick >= m.tick || // operator 0 declines - std::ranges::any_of(payload.subspan(58, 6), + payload[58] > (wire_version == session_protocol_v14 ? 1 : 0) || + std::ranges::any_of(payload.subspan(59, 5), [](std::uint8_t value) { return value != 0; })) return std::unexpected(SessionCodecError::invalid_value); return m; @@ -766,7 +824,9 @@ std::expected decode_session(std::span static_cast(CellularDeathReason::engulfed) || + payload[16] > static_cast(wire_version == session_protocol_v14 + ? CellularDeathReason::emerged + : CellularDeathReason::engulfed) || std::ranges::any_of(payload.subspan(17, 7), [](std::uint8_t value) { return value != 0; })) return std::unexpected(SessionCodecError::invalid_value); @@ -823,9 +883,11 @@ std::expected decode_session(std::span decode_session(std::span(get(payload, at, 2)); + b.emerge_members = static_cast(get(payload, at + 2, 2)); + b.exclude = payload[at + 4]; + b.can_emerge = payload[at + 5] == 1; + b.payable_energy_pj = get(payload, at + 8, 8); + b.total_mass_fg = get(payload, at + 16, 8); + for (std::size_t i = 0; i < b.traits.size(); ++i) + b.traits.at(i) = static_cast(get(payload, at + 24 + i * 2, 2)); + const bool empty = b.members == 0 && b.emerge_members == 0 && b.exclude == 0 && + payload[at + 5] == 0 && b.payable_energy_pj == 0 && + b.total_mass_fg == 0 && + std::ranges::all_of(b.traits, [](auto v) { return v == 0; }); + if (b.exclude > 0x0F || payload[at + 5] > 1 || payload[at + 6] != 0 || + payload[at + 7] != 0 || (m.diagnostics ? b.members == 0 : !empty)) + return std::unexpected(SessionCodecError::invalid_value); + if (m.diagnostics) { + auto& d = *m.diagnostics; + d.members = b.members; + d.emerge_members = b.emerge_members; + d.exclude = b.exclude; + d.can_emerge = b.can_emerge; + d.payable_energy_pj = b.payable_energy_pj; + d.total_mass_fg = b.total_mass_fg; + d.traits = b.traits; + } + } std::size_t offset = prefix; if (deposits) { m.deposits.reserve(count); @@ -1167,8 +1258,11 @@ encode_cellular_action_input(const CellularActionInput& input) { : input.engulf ? 2 : input.bud ? 3 : 0); - bytes.push_back(input.brake ? 1 : 0); // Flags (schema 58): bit 0 brake. - put(bytes, 0, 2); + // Flags: bit 0 brake (schema 58), bit 1 become and bit 2 emerge (schema 60). + bytes.push_back(static_cast((input.brake ? 1U : 0U) | (input.become ? 2U : 0U) | + (input.emerge ? 4U : 0U))); + bytes.push_back(input.exclude); // Schema 60: channels excluded from burning. + bytes.push_back(0); put(bytes, input.intake_x_um, 4); put(bytes, input.intake_y_um, 4); std::array out{}; @@ -1180,7 +1274,7 @@ std::expected decode_cellular_action_input(std::span bytes) { if (bytes.size() != cellular_action_input_bytes) return std::unexpected(SessionCodecError::wrong_length); - if (bytes[12] > 3 || bytes[13] > 1 || bytes[14] != 0 || bytes[15] != 0) + if (bytes[12] > 3 || bytes[13] > 7 || bytes[14] > 0x0F || bytes[15] != 0) return std::unexpected(SessionCodecError::invalid_value); CellularActionInput input; input.tick = get(bytes, 0, 8); @@ -1189,11 +1283,15 @@ decode_cellular_action_input(std::span bytes) { input.has_intake_target = bytes[12] == 1; input.engulf = bytes[12] == 2; input.bud = bytes[12] == 3; - input.brake = bytes[13] == 1; + input.brake = (bytes[13] & 1U) != 0; + input.become = (bytes[13] & 2U) != 0; + input.emerge = (bytes[13] & 4U) != 0; + input.exclude = bytes[14]; input.intake_x_um = static_cast(get(bytes, 16, 4)); input.intake_y_um = static_cast(get(bytes, 20, 4)); if (input.tick == 0 || - (!input.has_intake_target && (input.intake_x_um != 0 || input.intake_y_um != 0))) + (!input.has_intake_target && (input.intake_x_um != 0 || input.intake_y_um != 0)) || + (input.become && !input.bud) || (input.emerge && bytes[12] != 0)) return std::unexpected(SessionCodecError::invalid_value); return input; } diff --git a/src/persistence/cellular_checkpoint_store.cpp b/src/persistence/cellular_checkpoint_store.cpp index e35325f..c46c8c6 100644 --- a/src/persistence/cellular_checkpoint_store.cpp +++ b/src/persistence/cellular_checkpoint_store.cpp @@ -93,7 +93,8 @@ std::optional applied_tick(const server::CellularBatch& trace, if (selection.life_id == action.input.life_id && selection.event_index == action.input.event_index && selection.offer_tick == action.input.offer_tick && - selection.operator_id == action.input.operator_id) { + selection.operator_id == action.input.operator_id && + selection.become == action.input.become) { if (found) return std::nullopt; found = trace.header.begin_tick + i + 1; @@ -120,7 +121,10 @@ bool prepared_mutations_are_canonical(const CellularPreparedCommit& prepared, prepared.mutations, manifest.begin_tick, manifest.end_tick); if (!decoded || decoded->size() != selections || prepared.results.size() != selections || std::ranges::any_of(prepared.results, [&](std::uint8_t result) { - return cellular_plan_bundle(manifest.cellular_versions) + // Rules 13 (bundle 15): applied (an organism), life died, insufficient funding, + // declined, split applied and split refused. + return manifest.cellular_versions == cellular_v15_versions ? result == 4 || result > 6 + : cellular_plan_bundle(manifest.cellular_versions) ? result != 1 && result != 3 && result != 4 : result > 3; })) @@ -396,6 +400,17 @@ std::expected migrate_cell }, cellular_liquid_upgrade_manifest); } +std::expected migrate_cellular_revamp_profile( + Postgres& db, const FilesystemObjectStore& objects, const LeaseGrant& lease, + const CommittedCheckpoint& predecessor, Uuid commit, const Sha256Digest& build, + const server::CellularRevampRules& rules, milliseconds timeout, const PublishHooks& hooks) { + return migrate_rules_profile( + db, objects, lease, predecessor, commit, build, timeout, hooks, + [rules](std::span payload, const CheckpointManifest& previous) { + return cellular_revamp_upgrade_payload(payload, previous, rules); + }, + cellular_revamp_upgrade_manifest); +} std::expected migrate_cellular_profile_to_v2(Postgres& db, const FilesystemObjectStore& objects, @@ -685,7 +700,9 @@ verify_cellular_no_tick_checkpoint(Postgres& db, const FilesystemObjectStore& ob const bool inheritance = m.cellular_versions == cellular_v12_versions; const bool photosynthesis = m.cellular_versions == cellular_v13_versions; const bool liquid = m.cellular_versions == cellular_v14_versions; - const auto derive = liquid ? cellular_liquid_upgrade_manifest + const bool revamp = m.cellular_versions == cellular_v15_versions; + const auto derive = revamp ? cellular_revamp_upgrade_manifest + : liquid ? cellular_liquid_upgrade_manifest : photosynthesis ? cellular_photosynthesis_upgrade_manifest : inheritance ? cellular_inheritance_upgrade_manifest : maturation ? cellular_maturation_upgrade_manifest @@ -698,7 +715,16 @@ verify_cellular_no_tick_checkpoint(Postgres& db, const FilesystemObjectStore& ob auto bytes = objects.get({source->payload_sha256, source->payload_bytes}); if (!bytes) return fail(RecoveryError::tail); - if (liquid) { + if (revamp) { + // The declared revamp rules are the upgrade's only input: read them from the target, + // then require the source to re-derive the exact target bytes with them. + auto target = restore_cellular_payload(payload, m); + if (!target) + return fail(RecoveryError::payload); + auto upgraded = cellular_revamp_upgrade_payload(*bytes, *source, (*target)->revamp_rules()); + if (!upgraded || !std::ranges::equal(*upgraded, payload)) + return fail(RecoveryError::history); + } else if (liquid) { // The declared liquid rules are the upgrade's only input: read them from the target, // then require the source to re-derive the exact target bytes with them. auto target = restore_cellular_payload(payload, m); diff --git a/src/persistence/population_checkpoint.cpp b/src/persistence/population_checkpoint.cpp index ace1175..e4dc6f7 100644 --- a/src/persistence/population_checkpoint.cpp +++ b/src/persistence/population_checkpoint.cpp @@ -251,4 +251,31 @@ cellular_liquid_upgrade_payload(std::span payload, return std::unexpected(CheckpointError::payload); return (*upgraded)->snapshot(); } +std::expected +cellular_revamp_upgrade_manifest(const CheckpointManifest& previous, + const Sha256Digest& previous_digest, Uuid commit, + const LeaseGrant& lease, const Sha256Digest& build, + std::uint64_t bytes, const Sha256Digest& digest) { + if (previous.profile != CheckpointProfile::cellular_lives_v1) + return std::unexpected(CheckpointError::unsupported); + return upgrade_manifest(previous, previous_digest, commit, lease, build, bytes, digest, + cellular_v14_versions, cellular_v15_versions); +} +std::expected, CheckpointError> +cellular_revamp_upgrade_payload(std::span payload, + const CheckpointManifest& previous, + const server::CellularRevampRules& rules) { + if (!supported(previous) || previous.profile != CheckpointProfile::cellular_lives_v1 || + previous.cellular_versions != cellular_v14_versions) + return std::unexpected(CheckpointError::unsupported); + if (!encode_manifest(previous) || previous.sequence == 0 || previous.end_tick == 0) + return std::unexpected(CheckpointError::chain); + auto state = restore_cellular_payload(payload, previous); + if (!state) + return std::unexpected(state.error()); + auto upgraded = (*state)->revamp_upgrade_candidate(rules); + if (!upgraded) + return std::unexpected(CheckpointError::payload); + return (*upgraded)->snapshot(); +} } // namespace evo::persistence diff --git a/src/persistence/region_lease_store.cpp b/src/persistence/region_lease_store.cpp index c914f51..bfea415 100644 --- a/src/persistence/region_lease_store.cpp +++ b/src/persistence/region_lease_store.cpp @@ -606,7 +606,7 @@ load_cellular_mutation_publications(Postgres& db, RegionKey key, const LeaseGran const auto action = parse_integer(row[1]); const auto input = unhex<34>(row[2].value_or(std::string{})); const auto result = parse_integer(row[3]); - if (!account || !action || *action == 0 || !input || !result || *result > 4) + if (!account || !action || *action == 0 || !input || !result || *result > 6) return std::unexpected{malformed(false)}; publications.push_back({*account, *action, *input, static_cast(*result)}); } diff --git a/src/server/cellular_region_host.cpp b/src/server/cellular_region_host.cpp index 1708064..300b25f 100644 --- a/src/server/cellular_region_host.cpp +++ b/src/server/cellular_region_host.cpp @@ -128,6 +128,28 @@ network::ActionOutcome action_outcome(const FinalCellularMutation& mutation) noe network::CellularMutationOffer offer_view(const CellularLives& state, const CellularOwnedLife& life, std::uint64_t tick) { network::CellularMutationOffer view{tick, life.identity.life, 0, 0, {}}; + if (state.rules_version() >= cellular_lives_revamp_rules) { + // Rules 13 (v14): catalog mutations with their chance and tuned cost; the client names + // them from the same catalog. + const auto& pending = life.revamp.offer; + if (pending.count == 0) + return view; + view.event_index = pending.event_index; + view.offer_tick = pending.offer_tick; + for (std::size_t k = 0; k < pending.count; ++k) { + const auto id = pending.ids.at(k); + if (id == 0 || id > biology::cellular_catalog_size) + continue; + const auto cost = cellular_mutation_cost(state.revamp_rules().mutations.at(id - 1u)); + network::CellularOfferedCandidate shown{ + id, 0, 0, pending.chances.at(k), 0, 0, cost.energy.value, {}}; + for (std::size_t channel = 0; channel < shown.cost_matter_fg.size(); ++channel) + shown.cost_matter_fg.at(channel) = cost.matter.at(channel).value; + view.candidates.push_back(shown); + } + std::ranges::sort(view.candidates, {}, &network::CellularOfferedCandidate::operator_id); + return view; + } const auto& offer = life.mutation.offer; if (!offer) return view; @@ -842,17 +864,29 @@ CellularRegionHost::select_mutation(const persistence::Uuid& account, std::uint6 // The choice must name this account's living cell and its exact outstanding offer. const auto life = std::ranges::find(state_->lives(), account, &CellularOwnedLife::account); if (life == state_->lives().end() || life->identity.life != input.life_id || - input.event_index == 0 || life->mutation.event_index != input.event_index || - life->mutation.offer_tick != input.offer_tick || input.offer_tick >= tick || + input.event_index == 0 || input.offer_tick >= tick || life->presence != CellularPresence::active) // ADR-0128: only an active life chooses. return {invalid, 0, {}}; - const auto& offer = life->mutation.offer; - // Operator 0 declines the exact offer (ADR-0120 amendment); otherwise it must be offered. - if (!offer || (input.operator_id != 0 && - !std::ranges::any_of(offer->candidates, [&](const auto& candidate) { - return candidate.operator_id == input.operator_id; - }))) - return {invalid, 0, {}}; + if (state_->rules_version() >= cellular_lives_revamp_rules) { + // Rules 13: the catalog offer; operator 0 declines, and become needs a choice. + const auto& offer = life->revamp.offer; + const auto end = offer.ids.begin() + offer.count; + if (offer.count == 0 || offer.event_index != input.event_index || + offer.offer_tick != input.offer_tick || (input.become && input.operator_id == 0) || + (input.operator_id != 0 && + std::ranges::find(offer.ids.begin(), end, input.operator_id) == end)) + return {invalid, 0, {}}; + } else { + const auto& offer = life->mutation.offer; + // Operator 0 declines the exact offer (ADR-0120 amendment); otherwise it must be offered. + if (input.become || life->mutation.event_index != input.event_index || + life->mutation.offer_tick != input.offer_tick || !offer || + (input.operator_id != 0 && + !std::ranges::any_of(offer->candidates, [&](const auto& candidate) { + return candidate.operator_id == input.operator_id; + }))) + return {invalid, 0, {}}; + } const auto grant = authority_.grant(); if (!grant) return {not_ready, 0, {}}; diff --git a/src/server/lifecycle/cellular_batch.cpp b/src/server/lifecycle/cellular_batch.cpp index 063a4f8..2dc4c4b 100644 --- a/src/server/lifecycle/cellular_batch.cpp +++ b/src/server/lifecycle/cellular_batch.cpp @@ -107,7 +107,9 @@ bool valid_action_input(const CellularActionRecord& action, std::uint64_t begin_ return !all_zero(action.account) && action.action_id != 0 && tick > begin_tick && tick <= end_tick && move_x >= -movement_limit && move_x <= movement_limit && move_y >= -movement_limit && move_y <= movement_limit && input[12] <= 3 && - input[13] <= 1 && all_zero(input.subspan(14, 2)) && + // Flags: brake, become (with a bud) and emerge (no target); then exclusions. + input[13] <= 7 && ((input[13] & 2U) == 0 || input[12] == 3) && + ((input[13] & 4U) == 0 || input[12] == 0) && input[14] <= 0x0F && input[15] == 0 && (input[12] == 1 || all_zero(input.subspan(16, 8))); } bool action_less(const CellularActionRecord& a, const CellularActionRecord& b) { @@ -400,7 +402,7 @@ encode_cellular_mutation_input(const CellularMutationActionRecord& action) { put(bytes, action.input.life_id, 8); put(bytes, action.input.event_index, 8); put(bytes, action.input.offer_tick, 8); - put(bytes, action.input.operator_id, 2); + put(bytes, action.input.operator_id | (action.input.become ? 0x8000U : 0U), 2); std::array out{}; std::ranges::copy(bytes, out.begin()); return out; @@ -418,10 +420,12 @@ decode_cellular_mutation_input(const std::array& account, std: action.input.life_id = get(input, 8, 8); action.input.event_index = get(input, 16, 8); action.input.offer_tick = get(input, 24, 8); - action.input.operator_id = static_cast(get(input, 32, 2)); + const auto stored = static_cast(get(input, 32, 2)); + action.input.operator_id = static_cast(stored & 0x7FFFU); + action.input.become = (stored & 0x8000U) != 0; if (action_id == 0 || action.tick == 0 || action.input.life_id == 0 || - action.input.event_index == 0 || action.input.offer_tick == 0 || - action.input.offer_tick >= action.tick) + (action.input.become && action.input.operator_id == 0) || action.input.event_index == 0 || + action.input.offer_tick == 0 || action.input.offer_tick >= action.tick) return std::nullopt; return action; } @@ -517,7 +521,8 @@ encode_cellular_mutation_action_block(std::span bytes, std:: action.input.life_id = get(record, 32, 8); action.input.event_index = get(record, 40, 8); action.input.offer_tick = get(record, 48, 8); - action.input.operator_id = static_cast(get(record, 56, 2)); - if (!all_zero(record.subspan(58, 6))) + const auto stored = static_cast(get(record, 56, 2)); + action.input.operator_id = static_cast(stored & 0x7FFFU); + action.input.become = (stored & 0x8000U) != 0; + if (!all_zero(record.subspan(58, 6)) || + (action.input.become && action.input.operator_id == 0)) return std::unexpected{CellularActionBlockError::format}; out.push_back(action); offset += cellular_mutation_action_record_bytes; @@ -587,7 +595,10 @@ match_cellular_actions_to_trace(const CellularLives& predecessor, const Cellular intent->intent.movement.y != std::bit_cast(static_cast(get(input, 10, 2))) || intent->intent.intake_target != target || intent->intent.engulf != (input[12] == 2) || - intent->intent.bud != (input[12] == 3) || intent->intent.brake != (input[13] == 1)) + intent->intent.bud != (input[12] == 3) || + intent->intent.brake != ((input[13] & 1U) != 0) || + intent->intent.become != ((input[13] & 2U) != 0) || + intent->intent.emerge != ((input[13] & 4U) != 0) || intent->intent.exclude != input[14]) return std::unexpected{CellularActionBlockError::mismatch}; } return {}; @@ -623,7 +634,8 @@ match_cellular_mutation_actions_to_trace(const CellularLives& predecessor, action.tick == tick && action.input.life_id == selection.life_id && action.input.event_index == selection.event_index && action.input.offer_tick == selection.offer_tick && - action.input.operator_id == selection.operator_id; + action.input.operator_id == selection.operator_id && + action.input.become == selection.become; }); if (matches != 1) return std::unexpected{CellularActionBlockError::mismatch}; @@ -645,7 +657,8 @@ match_cellular_mutation_actions_to_trace(const CellularLives& predecessor, if (departed == mutations.end() || departed->life_id != action.input.life_id || departed->event_index != action.input.event_index || departed->offer_tick != action.input.offer_tick || - departed->operator_id != action.input.operator_id) + departed->operator_id != action.input.operator_id || + departed->become != action.input.become) return std::unexpected{CellularActionBlockError::mismatch}; continue; } @@ -655,7 +668,24 @@ match_cellular_mutation_actions_to_trace(const CellularLives& predecessor, return std::unexpected{CellularActionBlockError::mismatch}; const auto selection = std::ranges::lower_bound(mutations, life->identity.life, {}, &CellularMutationSelection::life_id); - if (!life->mutation.offer) + if (predecessor.rules_version() >= cellular_lives_revamp_rules) { + // Rules 13: the catalog offer the life held; operator 0 declines it. + const auto& offer = life->revamp.offer; + const auto end = offer.ids.begin() + offer.count; + if (selection == mutations.end() || selection->life_id != life->identity.life || + selection->event_index != action.input.event_index || + selection->offer_tick != action.input.offer_tick || + selection->operator_id != action.input.operator_id || + selection->become != action.input.become || offer.count == 0 || + offer.event_index != action.input.event_index || + offer.offer_tick != action.input.offer_tick || + life->identity.life != action.input.life_id || + (action.input.operator_id != 0 && + std::ranges::find(offer.ids.begin(), end, action.input.operator_id) == end)) + return std::unexpected{CellularActionBlockError::mismatch}; + continue; + } + if (!life->mutation.offer || action.input.become) return std::unexpected{CellularActionBlockError::mismatch}; const auto offer = life->mutation.offer.value_or(biology::MutationOffer{}); if (selection == mutations.end() || selection->life_id != life->identity.life || diff --git a/src/server/lifecycle/cellular_lives.cpp b/src/server/lifecycle/cellular_lives.cpp index f8778f3..9982863 100644 --- a/src/server/lifecycle/cellular_lives.cpp +++ b/src/server/lifecycle/cellular_lives.cpp @@ -1023,6 +1023,11 @@ CellularLives::create(const PrimitiveLives& opening, return std::unique_ptr{new CellularLives{std::move(state)}}; } +std::expected +cellular_organism_genome(const biology::Genome& genome, std::uint32_t members) { + return organism_genome(genome, members); +} + bool cellular_can_emerge(const CellularOwnedLife& life, const CellularRevampRules& rules) noexcept { std::uint64_t mass{}; for (std::size_t c = 0; c < life.body.matter.size(); ++c) @@ -1084,6 +1089,9 @@ accounting::Inventory CellularLives::nursery() const noexcept { accounting::Inventory CellularLives::heat() const noexcept { return state_->heat; } +accounting::Inventory CellularLives::spent() const noexcept { + return state_->spent; +} accounting::Inventory CellularLives::opening_total() const noexcept { return state_->opening_total; } @@ -3555,6 +3563,7 @@ CellularLives::advance_tick_with_mutations(std::span i } if (input == ordered.end() || input->life_id != result.life_id) return std::unexpected{CellularLivesError::invalid_intents}; + feedback.back().exclude = input->intent.exclude; } // ADR-0128: each surviving life reports its presence after the tick; a suspended life, // which took no step, reports its unchanged reserve and any blocked resume. diff --git a/src/server/lifecycle/cellular_play_summary.cpp b/src/server/lifecycle/cellular_play_summary.cpp index e1f63ad..1d188da 100644 --- a/src/server/lifecycle/cellular_play_summary.cpp +++ b/src/server/lifecycle/cellular_play_summary.cpp @@ -15,7 +15,16 @@ summarize_cellular_play(const CellularLives& state) { summary.lingering += life.presence == CellularPresence::lingering ? 1 : 0; summary.suspended += life.presence == CellularPresence::suspended ? 1 : 0; genomes.push_back(life.identity.genome); + if (life.revamp.members > 1) { + ++summary.organisms; + summary.largest_organism = + std::max(summary.largest_organism, life.revamp.members); + } + summary.offers_pending += life.revamp.offer.count != 0 ? 1 : 0; + summary.offers_earned += life.revamp.events; } + for (const auto& channel : state.spent().matter) + summary.spent_matter_fg += channel.value; std::ranges::sort(genomes); const auto distinct = std::ranges::unique(genomes); genomes.erase(distinct.begin(), distinct.end()); diff --git a/src/server/lifecycle/wildlife_controller.cpp b/src/server/lifecycle/wildlife_controller.cpp index 0d9a4ae..2caad7a 100644 --- a/src/server/lifecycle/wildlife_controller.cpp +++ b/src/server/lifecycle/wildlife_controller.cpp @@ -1,6 +1,7 @@ #include "evo/server/lifecycle/wildlife_controller.hpp" #include "evo/biology/budding.hpp" +#include "evo/biology/cellular_burn.hpp" #include "evo/biology/cellular_motion.hpp" #include @@ -98,6 +99,22 @@ wildlife_intents(const CellularLives& state, std::uint64_t tick) { {0, -1'000}, {707, -707}}}; const auto temperature = state.ambient_temperature_millikelvin(); + // Rules 13 (ADR-0179): organisms develop as their scaled genome, engulf masses carry + // reserve matter, membranes are in nanometres, and reserve matter stands in for energy. + const bool revamp = state.rules_version() >= cellular_lives_revamp_rules; + const auto& revamp_rules = state.revamp_rules(); + const auto body_genome = + [&](const CellularOwnedLife& life) -> std::expected { + const auto genome = state.archive().find(life.identity.genome); + if (!genome) + return std::unexpected{CellularLivesError::archive}; + return revamp ? cellular_organism_genome(*genome, life.revamp.members) + : std::expected{*genome}; + }; + // A life from before the upgrade keeps its membrane in micrometres. + const auto membrane_nm = [](const biology::Genome& genome, std::uint32_t membrane) { + return genome.cellular_traits() ? membrane : membrane * 1'000; + }; std::vector intents; // Rules 7 prey facts for every cell in the world, derived once per tick: a per-hunter // derivation made the step quadratic in metabolic budgets. @@ -107,6 +124,7 @@ wildlife_intents(const CellularLives& state, std::uint64_t tick) { std::uint32_t extent{}, membrane{}; std::uint64_t mass{}; }; + std::vector engulf_masses; // Rules 13, beside prey_facts. std::vector prey_facts; const bool hunting = state.rules_version() >= cellular_lives_reproduction_rules && std::ranges::any_of(state.lives(), [](const CellularOwnedLife& life) { @@ -117,35 +135,56 @@ wildlife_intents(const CellularLives& state, std::uint64_t tick) { for (const auto& other : state.lives()) { if (other.presence == CellularPresence::suspended) continue; - const auto other_genome = state.archive().find(other.identity.genome); + const auto other_genome = body_genome(other); if (!other_genome) - return std::unexpected{CellularLivesError::archive}; + return std::unexpected{other_genome.error()}; const auto other_budget = biology::metabolic_budget( *other_genome, other.growth, {temperature, {}}, 1000, state.revamp_rules().body); const auto membrane = other_genome->parameter(biology::Capability::membrane); if (!other_budget || !membrane) return std::unexpected{CellularLivesError::biology}; prey_facts.push_back({other.identity.life, other.position, - other_budget->phenotype.extent, *membrane, + other_budget->phenotype.extent, + revamp ? membrane_nm(*other_genome, *membrane) : *membrane, other_budget->phenotype.total_mass}); + engulf_masses.push_back(biology::cellular_engulf_mass( + other_budget->phenotype.total_mass, other.reserve, revamp_rules.step)); } } for (const auto& life : state.lives()) { if (life.account != LifeAccount{}) continue; - const auto genome = state.archive().find(life.identity.genome); - if (!genome) + const auto expressed = state.archive().find(life.identity.genome); + const auto genome = body_genome(life); + if (!expressed || !genome) return std::unexpected{CellularLivesError::archive}; const auto budget = biology::metabolic_budget(*genome, life.growth, {temperature, {}}, 1000, state.revamp_rules().body); if (!budget) return std::unexpected{CellularLivesError::biology}; + const auto& traits = expressed->cellular_traits(); biology::CellularStepIntent intent{}; const auto offspring = state.archive().find(cellular_offspring_genome(life)); if (!offspring) return std::unexpected{CellularLivesError::archive}; - if ((tick + life.identity.life) % wildlife_bud_interval_ticks == 0 && - biology::fund_offspring(*genome, *offspring, life.growth, life.reserve, temperature)) { + // Rules 13: a single cell buds when it can pay the bud and its fee; an organism adds a + // member when it can, and stops one short of the emergence threshold (the owner refuses + // what it cannot fund). + const auto fee = + revamp + ? cellular_mutation_cost({.cost = revamp_rules.bud_fee, + .cost_scale_percent = revamp_rules.bud_fee_scale_percent}) + : accounting::Inventory{}; + bool fee_paid = life.reserve.energy.value >= fee.energy.value; + for (std::size_t c = 0; c < fee.matter.size(); ++c) + fee_paid = fee_paid && life.reserve.matter[c].value >= fee.matter[c].value; + const bool organism = revamp && life.revamp.members > 1; + const bool may_bud = + organism ? fee_paid && life.revamp.members + 1U < revamp_rules.emerge_members + : fee_paid && biology::fund_offspring(*expressed, *offspring, life.growth, + life.reserve, temperature) + .has_value(); + if ((tick + life.identity.life) % wildlife_bud_interval_ticks == 0 && may_bud) { intent.bud = true; intents.push_back({life.identity.life, intent}); continue; @@ -156,12 +195,18 @@ wildlife_intents(const CellularLives& state, std::uint64_t tick) { // players' cells included; otherwise feed. if (hunting) { bool prey = false; - for (const auto& other : prey_facts) { + const auto hunter_mass = biology::cellular_engulf_mass(budget->phenotype.total_mass, + life.reserve, revamp_rules.step); + const auto capacity = traits ? traits->engulf_capacity : std::uint16_t{100}; + for (std::size_t k = 0; k < prey_facts.size(); ++k) { + const auto& other = prey_facts[k]; if (other.life == life.identity.life || !biology::cellular_footprints_contact(life.position, extent, other.position, other.extent)) continue; - if (can_engulf(budget->phenotype.total_mass, other.mass, other.membrane)) { + if (revamp ? biology::cellular_engulfable(hunter_mass, capacity, engulf_masses[k], + other.membrane, revamp_rules.step) + : can_engulf(budget->phenotype.total_mass, other.mass, other.membrane)) { prey = true; break; } @@ -190,9 +235,21 @@ wildlife_intents(const CellularLives& state, std::uint64_t tick) { // Rules 11: a cell short of energy forages for energy (wildlife_food). const auto demand_period = budget->rate_microseconds / 50'000; const auto demand_per_tick = demand_period == 0 ? 0 : budget->demand.value / demand_period; - const bool hungry = - state.rules_version() >= cellular_lives_photosynthesis_rules && demand_per_tick != 0 && - life.reserve.energy.value / demand_per_tick < wildlife_energy_hunger_ticks; + // Rules 13: burnable reserve matter stands in for energy, so a cell rich in matter is + // not hungry. + const auto payable = + revamp + ? biology::cellular_payable_energy( + life.reserve, + biology::cellular_burn( + revamp_rules.burn_pj_per_kfg, + traits ? traits->burn : std::array{100, 100, 100, 100}, + 0), + false) + : life.reserve.energy.value; + const bool hungry = state.rules_version() >= cellular_lives_photosynthesis_rules && + demand_per_tick != 0 && + payable / demand_per_tick < wildlife_energy_hunger_ticks; const auto chosen = wildlife_food(*perceived, centre_x, centre_y, deposits, hungry); const auto nearest = chosen ? std::optional{chosen->address} : std::nullopt; if (nearest && deposits && chosen) { diff --git a/src/server/session/cellular_session_batch.cpp b/src/server/session/cellular_session_batch.cpp index 46c769f..8e8d42c 100644 --- a/src/server/session/cellular_session_batch.cpp +++ b/src/server/session/cellular_session_batch.cpp @@ -78,6 +78,10 @@ prepare_cellular_session_tick(const CellularLives& state, std::uint64_t tick, owned_intent->intent.bud = input->bud; // Rules 12: below them the owner refuses a brake, so only v13 sessions send one. owned_intent->intent.brake = input->brake; + // Rules 13 (v14): below them the owner refuses each of these. + owned_intent->intent.become = input->become; + owned_intent->intent.emerge = input->emerge; + owned_intent->intent.exclude = input->exclude; CellularActionRecord record; record.account = action.account.bytes; record.action_id = action.action_id; @@ -101,7 +105,10 @@ prepare_cellular_session_tick(const CellularLives& state, std::uint64_t tick, const auto life_id = little_endian(bytes, 8, 8); const auto event_index = little_endian(bytes, 16, 8); const auto offer_tick = little_endian(bytes, 24, 8); - const auto operator_id = static_cast(little_endian(bytes, 32, 2)); + const auto stored_operator = static_cast(little_endian(bytes, 32, 2)); + const auto operator_id = static_cast(stored_operator & 0x7FFFU); + const bool become = (stored_operator & 0x8000U) != 0; + const bool revamp = state.rules_version() >= cellular_lives_revamp_rules; // ADR-0121 amendment (schema 59): the reservation's tick is the earliest the choice // may bind at; the queue binds it at the first tick simulated after admission. if (reservation.account == persistence::Uuid{} || reservation.action_id == 0 || @@ -114,7 +121,17 @@ prepare_cellular_session_tick(const CellularLives& state, std::uint64_t tick, const auto life = std::ranges::find(state.lives(), life_id, [](const CellularOwnedLife& value) { return value.identity.life; }); - if (life != state.lives().end()) { + if ((become && (!revamp || operator_id == 0))) + return std::unexpected{CellularSessionBatchError::mutation}; + if (life != state.lives().end() && revamp) { + // Rules 13: the catalog offer the life holds; operator 0 declines it. + const auto& offer = life->revamp.offer; + const auto end = offer.ids.begin() + offer.count; + if (life->account != reservation.account || offer.count == 0 || + offer.event_index != event_index || offer.offer_tick != offer_tick || + (operator_id != 0 && std::ranges::find(offer.ids.begin(), end, operator_id) == end)) + return std::unexpected{CellularSessionBatchError::mutation}; + } else if (life != state.lives().end()) { if (life->account != reservation.account || life->mutation.event_index != event_index || life->mutation.offer_tick != offer_tick) return std::unexpected{CellularSessionBatchError::mutation}; @@ -136,12 +153,13 @@ prepare_cellular_session_tick(const CellularLives& state, std::uint64_t tick, previous.action_id == reservation.action_id; })) return std::unexpected{CellularSessionBatchError::duplicate_mutation}; - prepared.intents.mutations.push_back( - {life_id, event_index, offer_tick, reservation.successor_identity, operator_id}); - prepared.mutation_actions.push_back({reservation.account, - reservation.action_id, - tick, - {life_id, event_index, offer_tick, operator_id}}); + prepared.intents.mutations.push_back({life_id, event_index, offer_tick, + reservation.successor_identity, operator_id, become}); + prepared.mutation_actions.push_back( + {reservation.account, + reservation.action_id, + tick, + {life_id, event_index, offer_tick, operator_id, become}}); } std::ranges::sort(prepared.intents.mutations, {}, &CellularMutationSelection::life_id); std::ranges::sort(prepared.mutation_actions, [](const auto& left, const auto& right) { diff --git a/src/server/session/region_sessions.cpp b/src/server/session/region_sessions.cpp index 93079d0..e5a830f 100644 --- a/src/server/session/region_sessions.cpp +++ b/src/server/session/region_sessions.cpp @@ -152,12 +152,21 @@ struct RegionSessions::Impl { } // Reliable owner-only v10 messages, to the account's established v10 session. bool send_to_v10_owner(const network::AccountId& account, - const network::SessionMessage& message) { + const network::SessionMessage& message, bool named_offer = false) { for (const auto& c : connections) { if (c.state != State::established || !network::cellular_v10_family(c.protocol_version) || c.account_id != account) continue; + // Rules 13 offers name catalog mutations (v14); operator offers are v10-v13's. + if (std::holds_alternative(message) && + named_offer != (c.protocol_version == network::session_protocol_v14)) + return false; auto delivered = message; + // An emerged ending reads as unrecorded before v14. + if (auto* ended = std::get_if(&delivered); + ended && ended->cause == network::CellularDeathReason::emerged && + c.protocol_version != network::session_protocol_v14) + ended->cause = network::CellularDeathReason::unrecorded; // ADR-0176: before v12 an offer cannot name photosynthesis; its other choices // stay valid, so those candidates alone are withheld. if (auto* offer = std::get_if(&delivered)) @@ -628,7 +637,7 @@ struct RegionSessions::Impl { wire_version == network::session_protocol_v9 || network::cellular_v10_family(wire_version)) && !cellular_actions) || - wire_version > network::session_protocol_v13) + wire_version > network::session_protocol_v14) return close(c, SessionCloseReason::unsupported_version, now); } else if (wire_version != c.protocol_version) { return close(c, SessionCloseReason::unsupported_version, now); @@ -960,8 +969,17 @@ bool RegionSessions::send_cellular_perception(const network::AccountId& account, if (delivered.diagnostics) delivered.diagnostics->light_pj = 0; } - // Only v13 carries liquid motion (rules 12). - if (c.protocol_version != network::session_protocol_v13) { + // Only v14 carries the rules-13 body block. + if (c.protocol_version != network::session_protocol_v14 && delivered.diagnostics) { + auto& d = *delivered.diagnostics; + d.members = d.emerge_members = 0; + d.exclude = 0; + d.can_emerge = false; + d.payable_energy_pj = d.total_mass_fg = 0; + d.traits = {}; + } + // Only v13 and v14 carry liquid motion (rules 12). + if (!network::cellular_liquid_version(c.protocol_version)) { delivered.currents.reset(); if (delivered.diagnostics) { delivered.diagnostics->velocity_x_q10 = 0; @@ -995,8 +1013,8 @@ bool RegionSessions::send_life_ended(const network::AccountId& account, } bool RegionSessions::send_mutation_offer(const network::AccountId& account, - const network::CellularMutationOffer& offer) { - return impl_->send_to_v10_owner(account, offer); + const network::CellularMutationOffer& offer, bool named) { + return impl_->send_to_v10_owner(account, offer, named); } void RegionSessions::clear_cellular_perceptions(std::uint64_t tick) { diff --git a/tests/cellular_intent_protocol_tests.cpp b/tests/cellular_intent_protocol_tests.cpp index f688bd3..cede030 100644 --- a/tests/cellular_intent_protocol_tests.cpp +++ b/tests/cellular_intent_protocol_tests.cpp @@ -607,6 +607,117 @@ void v13_perception_carries_liquid_motion() { CHECK(!decode_session(old_brake)); } +// Rules 13: v14 is v13 plus the revamp: the body block in the view, become, emerge and +// exclusions on actions, become on choices, catalog offers and the emerged ending. Earlier +// versions refuse every revamp field. +void v14_carries_the_revamp() { + CellularLifeDiagnostics d; + d.reserve_energy_pj = 9; + d.members = 3; + d.emerge_members = 8; + d.exclude = 0b0101; + d.can_emerge = false; + d.payable_energy_pj = 12'000; + d.total_mass_fg = 24'000'000; + for (std::size_t i = 0; i < d.traits.size(); ++i) + d.traits.at(i) = static_cast(100 + i); + CellularPerception view{77, 7, {}, d}; + const auto bytes = encode_session(SessionMessage{view}, session_protocol_v14); + CHECK(bytes.size() == session_header_bytes + 18 + 64 + 40 + 16 + 56 + 64); + std::uint16_t version{}; + const auto decoded = decode_session(bytes, &version); + CHECK(decoded && version == session_protocol_v14 && + std::get(*decoded) == view); + CHECK(encode_session(SessionMessage{view}, session_protocol_v13).empty()); + // A life has at least one member; exclusions are four channels; the flag is 0 or 1. + auto none = view; + none.diagnostics->members = 0; + CHECK(encode_session(SessionMessage{none}, session_protocol_v14).empty()); + constexpr std::size_t block = session_header_bytes + 18 + 64 + 40 + 16 + 56; + auto bad = bytes; + bad[block + 4] = 0x10; + CHECK(!decode_session(bad)); + bad = bytes; + bad[block + 5] = 2; + CHECK(!decode_session(bad)); + bad = bytes; + bad[block + 6] = 1; + CHECK(!decode_session(bad)); + // A cleared view carries an empty block. + CellularPerception cleared{78, 0, {}, std::nullopt}; + const auto empty = encode_session(SessionMessage{cleared}, session_protocol_v14); + CHECK(std::get(*decode_session(empty)) == cleared); + auto stray = empty; + stray[block] = 1; + CHECK(!decode_session(stray)); + + // Actions: become with a bud, emerge without a target, exclusions; v14 only. + CellularAction become{1, 2, 3, 4, 0, 0, false, 0, 0}; + become.bud = true; + become.become = true; + become.exclude = 0x0F; + CHECK(std::get(*decode_session( + encode_session(SessionMessage{become}, session_protocol_v14))) == become); + CHECK(encode_session(SessionMessage{become}, session_protocol_v13).empty()); + auto lone = become; + lone.bud = false; + CHECK(encode_session(SessionMessage{lone}, session_protocol_v14).empty()); + CellularAction emerge{1, 2, 3, 4, 300, 0, false, 0, 0}; + emerge.emerge = true; + CHECK(std::get(*decode_session( + encode_session(SessionMessage{emerge}, session_protocol_v14))) == emerge); + auto feeding = emerge; + feeding.engulf = true; + CHECK(encode_session(SessionMessage{feeding}, session_protocol_v14).empty()); + auto wide = become; + wide.exclude = 0x10; + CHECK(encode_session(SessionMessage{wide}, session_protocol_v14).empty()); + auto forged = encode_session(SessionMessage{emerge}, session_protocol_v14); + forged[session_header_bytes + 36] = 3; // Emerge with a bud. + CHECK(!decode_session(forged)); + + // The canonical action input keeps them (schema 60). + CellularActionInput input{9, 0, 0, false, 0, 0, false, true, false, true, false, 0b0011}; + const auto stored = encode_cellular_action_input(input); + CHECK(stored[13] == 2 && stored[14] == 3 && decode_cellular_action_input(stored) == input); + auto loose = stored; + loose[12] = 0; // Become without the bud. + CHECK(!decode_cellular_action_input(loose)); + + // Choices: become travels only on v14. + CellularMutationAction choice{1, 2, 3, 40, 7, 1, 30, 12}; + choice.become = true; + CHECK(std::get(*decode_session( + encode_session(SessionMessage{choice}, session_protocol_v14))) == choice); + CHECK(encode_session(SessionMessage{choice}, session_protocol_v13).empty()); + + // Offers name catalog mutations with a chance and a cost, nothing operator-shaped. + CellularMutationOffer offer{40, 7, 1, 30, {}}; + CellularOfferedCandidate named{}; + named.operator_id = 12; + named.parameter = 700'000; + named.cost_energy_pj = 5; + named.cost_matter_fg = {1, 2, 3, 4}; + offer.candidates.push_back(named); + named.operator_id = 49; + named.parameter = 10; + offer.candidates.push_back(named); + CHECK(std::get(*decode_session( + encode_session(SessionMessage{offer}, session_protocol_v14))) == offer); + auto shaped = offer; + shaped.candidates[0].capability = 1; + CHECK(encode_session(SessionMessage{shaped}, session_protocol_v14).empty()); + auto certain = offer; + certain.candidates[0].parameter = 1'000'001; + CHECK(encode_session(SessionMessage{certain}, session_protocol_v14).empty()); + + // The emerged ending is v14's. + CellularLifeEnded emerged{50, 7, CellularDeathReason::emerged}; + CHECK(std::get(*decode_session( + encode_session(SessionMessage{emerged}, session_protocol_v14))) == emerged); + CHECK(encode_session(SessionMessage{emerged}, session_protocol_v13).empty()); +} + int main() { try { round_trip_and_version_gate(); @@ -622,6 +733,7 @@ int main() { v11_perception_carries_deposits(); v12_perception_carries_light_and_producers(); v13_perception_carries_liquid_motion(); + v14_carries_the_revamp(); std::puts( "PASS cellular protocol: v6 intention, v7 action, v8-v10 perception/action framing"); } catch (const std::exception& error) { diff --git a/tests/cellular_revamp_owner_tests.cpp b/tests/cellular_revamp_owner_tests.cpp index 8c3c123..68165ff 100644 --- a/tests/cellular_revamp_owner_tests.cpp +++ b/tests/cellular_revamp_owner_tests.cpp @@ -1,4 +1,5 @@ #include "evo/server/lifecycle/cellular_batch.hpp" +#include "evo/server/lifecycle/cellular_play_summary.hpp" #include "fixtures/cellular_ecology.hpp" #include @@ -348,6 +349,22 @@ void a_choice_splits_the_cell(bool become) { "a split below full growth was not refused with the offer kept"); closed(*state); } + // Rules 13 wildlife (the founder after become): its controller's intents are always + // admissible, with matter as energy, fee-aware buds and the revamp engulf test. + if (become) { + for (int tick = 0; tick < 300; ++tick) { + auto intents = checked(wildlife_intents(*state, state->tick() + 1), "wildlife intents"); + for (const auto& life : state->lives()) + if (life.account != LifeAccount{}) { + CellularLifeIntent owned{life.identity.life, {}}; + owned.intent.movement = {600, 300}; + intents.push_back(owned); + } + std::ranges::sort(intents, {}, &CellularLifeIntent::life_id); + checked(state->advance_tick(intents), "wildlife tick"); + } + closed(*state); + } const auto copy = restore(*state); require(copy->snapshot() == state->snapshot(), "a split region did not restore exactly"); } @@ -589,6 +606,10 @@ void an_organism_forms_grows_and_emerges() { closed(*state); require(cellular_can_emerge(life_of(*state, identity), state->revamp_rules()), "a three-member organism could not emerge"); + const auto summary = checked(summarize_cellular_play(*state), "play summary"); + require(summary.organisms == 1 && summary.largest_organism == 3 && summary.merged == 1 && + summary.offers_earned >= 1, + "the play summary missed the organism"); // Emerge: the whole organism leaves as an export and the life ends as emerged. const auto outgoing = state->boundary_ledger().outgoing; diff --git a/tests/cellular_session_batch_tests.cpp b/tests/cellular_session_batch_tests.cpp index f5e4bda..42fdcdf 100644 --- a/tests/cellular_session_batch_tests.cpp +++ b/tests/cellular_session_batch_tests.cpp @@ -323,6 +323,150 @@ void durable_mutation_reservations_bind_to_the_exact_offer() { (*departed_replay)->lives()[0].mutation.offer.has_value()); } +// Rules 13 (session v14): emerge, become and exclusions reach the owner's intents and the trace +// check, and a catalog choice with become binds to the revamp offer through its reservation. +std::unique_ptr revamp_owner() { + const auto endowment = biology::primitive_endowment(biology::primitive_founder_v3); + CHECK(endowment); + auto funding = endowment->body; + funding.energy.value = 2 * (endowment->reserve.energy.value + endowment->construction.value); + for (auto& channel : funding.matter) + channel.value *= 2; + auto primitive = + PrimitiveLives::create({94, 1, 1, 17, funding, {{1'000, 1'000}, {1'000, 4'000}}}); + CHECK(primitive); + biology::CellularHabitatConfig config{94, 1, 1, 48'000, 48'000, {}}; + config.format = biology::cellular_habitat_deposit_format; + auto habitat = biology::CellularHabitat::create(std::move(config)); + CHECK(habitat); + auto created = + CellularLives::create(**primitive, std::move(*habitat), {{48'000, 48'000}, 0, 293'150}, + CellularLivesProfile::foraging); + CHECK(created); + auto state = std::move(*created); + CHECK(state->advance_tick(std::span{})); + const auto step = [&](auto next) { + CHECK(next); + state = std::move(*next); + }; + step(state->migration_upgrade_candidate()); + step(state->maturation_upgrade_candidate()); + step(state->inheritance_upgrade_candidate()); + step(state->photosynthesis_upgrade_candidate({0, 1, {0}})); + step(state->liquid_upgrade_candidate( + {.currents = {5, 48'000, 48'000, 250, 2, 4, 3'000, 6'000, 60, 300}, + .founder = {.thrust_q10 = 20'480, + .reverse_thrust_q10 = 20'480, + .forward_drag_ppm = 95'163, + .lateral_drag_ppm = 95'163, + .turn = 3'276}, + .deposits = {.drift_radius_um = 200, + .max_drift_q10 = 100 * 1'024, + .drift_decay_ppm = 95'163, + .merged_cap = 8, + .bubble_radius_um = biology::cellular_mote_radius_um}})); + CellularRevampRules rules{.burn_pj_per_kfg = {2'000, 2'000, 2'000, 2'000}, + .step = {.membrane_collection_per_mille_per_point = 2, + .engulf_ratio_milli = 1'500, + .engulf_reserve_percent = 100, + .kill_bubble_per_thousand = 500}, + .drip_interval_ticks = 20, + .drip_bubble_pj = 20'000'000, + .drip_bubble_fg = 1'000'000, + .reserve_load_per_thousand = 1'000}; + rules.offer_interval_ticks = 40; + step(state->revamp_upgrade_candidate(rules)); + LifeRequest request{}; + request.account.back() = 2; + request.action = 1; + step(state->birth_candidate(request, {101, 101, 101, 101, {state->tick()}})); + return state; +} + +void rules_13_actions_and_choices_bind() { + auto state = revamp_owner(); + for (int tick = 0; tick < 40; ++tick) { + const std::array swim{CellularLifeIntent{101, {{1'000, 0}, {}}}}; + CHECK(state->advance_tick(swim)); + } + const auto& life = state->lives().front(); + CHECK(life.identity.life == 101 && life.revamp.offer.count == 3); + const auto tick = state->tick() + 1; + const std::array baseline{CellularLifeIntent{101, {}}}; + + // Emerge and exclusions travel in the canonical input and must match the trace. + const auto input = network::encode_cellular_action_input( + {tick, 300, 0, false, 0, 0, false, false, false, false, true, 0b0101}); + const std::array actions{network::CarriedAction{network::AccountId{life.account}, 90, tick, + network::ActionKind::cellular, input}}; + const auto prepared = prepare_cellular_session_tick(*state, tick, baseline, actions); + CHECK(prepared && prepared->intents.lives[0].intent.emerge && + prepared->intents.lives[0].intent.exclude == 0b0101); + CellularBatch batch; + batch.format_version = cellular_batch_inheritance_format; + batch.header = {state->world(), state->region(), state->frame(), {}, {}, state->tick(), tick}; + batch.header.predecessor.fill(1); + batch.header.predecessor_digest.fill(2); + batch.ticks.push_back(prepared->intents); + CHECK(match_cellular_actions_to_trace(*state, batch, prepared->actions)); + auto kept = batch; + kept.ticks[0].lives[0].intent.exclude = 0; + CHECK(!match_cellular_actions_to_trace(*state, kept, prepared->actions)); + + // A catalog choice with become (bit 15 of the stored operator). + persistence::CellularMutationReservation reservation; + reservation.account = life.account; + reservation.action_id = 43; + reservation.region = state->region(); + reservation.generation = 7; + reservation.target_tick = tick; + reservation.successor_identity = 9'500; + const auto put_field = [&](std::size_t offset, std::uint64_t value, std::size_t bytes) { + for (std::size_t i = 0; i < bytes; ++i) + reservation.input[offset + i] = static_cast(value >> (i * 8U)); + }; + const auto chosen = life.revamp.offer.ids.at(0); + put_field(0, tick, 8); + put_field(8, 101, 8); + put_field(16, life.revamp.offer.event_index, 8); + put_field(24, life.revamp.offer.offer_tick, 8); + put_field(32, chosen | 0x8000U, 2); + persistence::RegionHead head{}; + head.frame = state->frame(); + head.sequence = 3; + head.end_tick = state->tick(); + head.commit.fill(0x31); + head.digest.fill(0x41); + auto builder = CellularSessionBatchBuilder::create(*state, head); + CHECK(builder); + const std::array reservations{reservation}; + CHECK(builder->append(tick, baseline, {}, {}, reservations)); + const auto& selection = builder->batch().ticks.back().mutations.front(); + CHECK(selection.become && selection.operator_id == chosen && + builder->mutation_actions().front().input.become && + encode_cellular_mutation_input(builder->mutation_actions().front())[33] >= 0x80 && + match_cellular_mutation_actions_to_trace(*state, builder->batch(), + builder->mutation_actions())); + std::vector outcomes; + const auto replayed = replay_cellular_batch(*state, builder->batch(), outcomes); + CHECK(replayed && (*replayed)->snapshot() == builder->candidate().snapshot() && + outcomes.size() == 1 && outcomes.front().result == CellularMutationResult::split_applied); + // The player became the offspring. + const auto& lives = builder->candidate().lives(); + CHECK(std::ranges::find(lives, life.account, &CellularOwnedLife::account)->identity.life != + 101); + + // Become with a decline is refused. + auto declined = reservation; + declined.input[32] = 0; + declined.input[33] = 0x80; + auto refusing = CellularSessionBatchBuilder::create(*state, head); + CHECK(refusing); + const std::array declines{declined}; + CHECK(refusing->append(tick, baseline, {}, {}, declines).error() == + CellularSessionBatchError::mutation); +} + void builder_batches_reserved_birth_after_empty_tick() { auto primitive = PrimitiveLives::create({93, 1, 1, 17, founder_price(1), {{0, 0}}}); CHECK(primitive); @@ -414,6 +558,7 @@ void unavailable_birth_does_not_freeze_the_tick() { int main() try { actions_bind_to_owned_life_and_preserve_other_inputs(); durable_mutation_reservations_bind_to_the_exact_offer(); + rules_13_actions_and_choices_bind(); builder_batches_reserved_birth_after_empty_tick(); unavailable_birth_does_not_freeze_the_tick(); std::puts("cellular session batch: ok"); diff --git a/tests/client_remote_session.cpp b/tests/client_remote_session.cpp index ebbc045..a9f8424 100644 --- a/tests/client_remote_session.cpp +++ b/tests/client_remote_session.cpp @@ -594,12 +594,15 @@ void cellular_v10(const Files& files) { sent_view = r.tick; view_session = *session; sent_life = life; + // The trial client speaks v14: a single cell's view carries its body block, and a + // rules-13 region offers catalog mutations (here id 3 at a 50% chance). + CellularLifeDiagnostics body{}; + body.members = 1; CHECK(r.sessions->send_cellular_perception( - owner, - {r.tick, life, {}, life ? std::optional{CellularLifeDiagnostics{}} : std::nullopt})); + owner, {r.tick, life, {}, life ? std::optional{body} : std::nullopt})); if (offer && life != 0) - CHECK(r.sessions->send_mutation_offer(owner, - {r.tick, life, 1, 99, {{3, 2, 0, 50, 20, 30}}})); + CHECK(r.sessions->send_mutation_offer( + owner, {r.tick, life, 1, 99, {{3, 0, 0, 500'000, 0, 0}}}, true)); }; Client c; CHECK(c.host.connect( diff --git a/tests/client_ui_model.cpp b/tests/client_ui_model.cpp index 17ae09f..89217a6 100644 --- a/tests/client_ui_model.cpp +++ b/tests/client_ui_model.cpp @@ -496,6 +496,35 @@ void cellular_action_effects() { play.observe({204, 700, {}, effect}); CHECK(play.history().back().engulf == CellularEngulfResult::membrane_too_thick); } +// Rules 13 (v14): a bud may carry become, a choice its become, Emerge is a discrete action, +// and an emerged ending ends the life like any other. +void cellular_revamp_actions() { + using namespace evo::client_app; + using namespace evo::network; + CellularPlay play; + play.initialize(70); + play.connected(); + CellularLifeDiagnostics body; + body.members = 1; + play.observe({300, 800, {}, body}); + CHECK(play.queue(CellAction::bud, 301, {}, true) && required(play.pending()).become); + play.sent(); + play.outcome({required(play.pending()).id, ActionResult::committed, 301, 1}); + CHECK(play.history().back().become); + CHECK(play.queue(CellAction::engulf, 302, {}, true) && !required(play.pending()).become); + play.sent(); + play.outcome({required(play.pending()).id, ActionResult::committed, 302, 1}); + play.observe_offer(CellularMutationOffer{303, 800, 1, 300, {{12, 0, 0, 700'000, 0, 0}}}); + CHECK(play.queue(CellAction::mutation, 304, {800, 1, 300, 12, true}) && + required(play.pending()).choice.become); + play.sent(); + play.outcome({required(play.pending()).id, ActionResult::committed, 304, 1}); + CHECK(play.queue(CellAction::emerge, 305)); + play.sent(); + play.observe_end({305, 800, CellularDeathReason::emerged}); + CHECK(play.life() == 0 && play.ended() && play.ended()->cause == CellularDeathReason::emerged && + play.can_restart()); +} void cellular_energy_and_birth_wait() { using namespace evo::client_app; using namespace evo::network; @@ -576,6 +605,7 @@ int main() try { session_host(); cellular_play(); cellular_action_effects(); + cellular_revamp_actions(); cellular_energy_and_birth_wait(); cellular_assistance(); cell_headings(); diff --git a/tests/network_control.cpp b/tests/network_control.cpp index 8663d31..c9d1ea4 100644 --- a/tests/network_control.cpp +++ b/tests/network_control.cpp @@ -371,7 +371,7 @@ void session_codec() { mutated.at(0) ^= 1; CHECK(refused(decode_session(mutated), SessionCodecError::bad_magic)); mutated = bytes; - mutated.at(4) = 14; // A future version; protocol versions through 13 are supported. + mutated.at(4) = 15; // A future version; protocol versions through 14 are supported. CHECK(refused(decode_session(mutated), SessionCodecError::unsupported_version)); mutated = bytes; mutated.at(7) = 1; diff --git a/tests/region_migration_tests.cpp b/tests/region_migration_tests.cpp index d847d45..1a34dbb 100644 --- a/tests/region_migration_tests.cpp +++ b/tests/region_migration_tests.cpp @@ -225,6 +225,7 @@ void upgrade_across_migration_and_barrier() { " -v migration_sha_57=$(s 0057_photosynthesis_bundle.sql)" " -v migration_sha_58=$(s 0058_liquid_bundle.sql)" " -v migration_sha_59=$(s 0059_durable_mutation_queue.sql)" + " -v migration_sha_60=$(s 0060_cellular_revamp_bundle.sql)" " -v runtime_role=evo_runtime_test -f migrations/apply.sql" " > /dev/null 2>&1") != 0); CHECK(history(*owner_db) == "1,2,3,4,5,6,7"); @@ -242,7 +243,7 @@ void upgrade_across_migration_and_barrier() { "tools/migrate-postgres.sh\" > /dev/null") == 0); CHECK(history(*owner_db) == "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24," "25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46," - "47,48,49,50,51,52,53,54,55,56,57,58,59"); + "47,48,49,50,51,52,53,54,55,56,57,58,59,60"); CHECK(scalar(*owner_db, "SELECT (c.condeferrable AND c.condeferred AND " "c.confrelid = 'evolution.region_commits'::regclass)::text " "FROM pg_catalog.pg_constraint c WHERE c.conrelid = " diff --git a/tests/region_store_tests.cpp b/tests/region_store_tests.cpp index 774939e..3853338 100644 --- a/tests/region_store_tests.cpp +++ b/tests/region_store_tests.cpp @@ -810,6 +810,45 @@ void cellular_v9_provisioning_declares_liquid() { const auto manifest = decode_manifest(head->manifest); CHECK(manifest && manifest->cellular_versions == cellular_v14_versions && manifest->history_profile == cellular_revision_history_profile); + // Rules 13 (ADR-0179): cellular-v10 is cellular-v9 plus the durable bundle 14 -> 15 revamp + // upgrade declaring the Git revamp tuning file's rules; a rerun reports the region. + { + const ServerRegion v10{{9779, 1}, fresh("cellular-v10-provision-9779")}; + const std::string revamp = + env("EVO_SOURCE_ROOT") + "/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning"; + const std::string v10_commit = "c0c81e5c0f7e1d2ba1a0ce5c0f7e1d2f"; + provision_cellular(v10, "9779", "cellular-v10", build, v10_commit, motes, code, "--motes", + {"--light-pj", "40", "--tuning", tuning}); + CHECK(code != 0); // cellular-v10 requires --revamp-tuning. + const auto made = provision_cellular( + v10, "9779", "cellular-v10", build, v10_commit, motes, code, "--motes", + {"--light-pj", "40", "--tuning", tuning, "--revamp-tuning", revamp}); + CHECK(code == 0 && has(made, "provisioned world=9779 region=1 sequence=7 tick=1")); + const auto rerun = provision_cellular( + v10, "9779", "cellular-v10", build, v10_commit, motes, code, "--motes", + {"--light-pj", "40", "--tuning", tuning, "--revamp-tuning", revamp}); + CHECK(code == 0 && has(rerun, "already-provisioned world=9779 region=1 sequence=7 tick=1")); + const auto revamp_head = load_region_checkpoint(*db, v10.key, 5s); + CHECK(revamp_head); + const auto revamp_manifest = decode_manifest(revamp_head->manifest); + CHECK(revamp_manifest && revamp_manifest->cellular_versions == cellular_v15_versions && + revamp_manifest->history_profile == cellular_revision_history_profile); + // The upgrade's evidence recovers: the target re-derives from the source and its rules. + Sha256Digest retained{}; + retained.fill(0xEE); + auto store = + FilesystemObjectStore::open(v10.root, v10.key, evo::server::max_cellular_lives_bytes); + CHECK(store); + const auto lease = + acquire_region_lease(*db, v10.key, retained, std::chrono::seconds{30}, 5s); + CHECK(lease); + const std::array builds{retained}; + const auto recovered = + recover_cellular_checkpoint(*db, **store, v10.key, *lease, builds, 5s); + CHECK(recovered && + recovered->state->rules_version() == evo::server::cellular_lives_revamp_rules); + CHECK(release_region_lease(*db, v10.key, *lease, 5s)); + } #ifdef EVO_POSTGRES_M10 // A player is born on the liquid head and swims and brakes through the live server path: // host reservation, session batch builder, host publication with a braking trace. diff --git a/tools/ci/history-domain-check.sh b/tools/ci/history-domain-check.sh index a93b1f4..2ad77bd 100644 --- a/tools/ci/history-domain-check.sh +++ b/tools/ci/history-domain-check.sh @@ -58,7 +58,7 @@ for invalid in NULL "'00000000-0000-0000-0000-000000000000'"; do done # Reconstruct the exact pre-context metadata schema in this disposable database. # Restore the resulting real legacy backup through both supported workflows. -# Undo schema 59's queue publishers, schema 58's bundle-14 wrappers, schema 57's bundle-13 wrappers, schema 56's joint profile, schema 55's plan validators, schema 54's three +# Undo schema 60's bundle-15 wrappers, schema 59's queue publishers, schema 58's bundle-14 wrappers, schema 57's bundle-13 wrappers, schema 56's joint profile, schema 55's plan validators, schema 54's three # replacements and schema 53; the backup must contain the actual pre-context # function contracts and privileges. awk '/^CREATE FUNCTION evolution\.admit_population_interval\(/ {capture=1; sub(/^CREATE FUNCTION/,"CREATE OR REPLACE FUNCTION")} capture {print} capture && /^END \$\$;/ {capture=0}' \ @@ -76,6 +76,12 @@ awk '/^CREATE OR REPLACE FUNCTION evolution\.valid_cellular_action_input\(/ {cap "$root/migrations/0036_cellular_v5_budding_bundle.sql" | sql > /dev/null sql -v runtime_role="$EVO_PG_RUNTIME_ROLE" > /dev/null <<'SQL' DROP FUNCTION evolution.publish_cellular_profile_migration(bytea); +ALTER FUNCTION evolution.publish_cellular_profile_migration_v59(bytea) RENAME TO publish_cellular_profile_migration; +DROP FUNCTION evolution.cellular_births(bytea,bytea); +ALTER FUNCTION evolution.cellular_births_v59(bytea,bytea) RENAME TO cellular_births; +DROP FUNCTION evolution.parse_checkpoint_manifest(bytea); +ALTER FUNCTION evolution.parse_checkpoint_manifest_v59(bytea) RENAME TO parse_checkpoint_manifest; +DROP FUNCTION evolution.publish_cellular_profile_migration(bytea); ALTER FUNCTION evolution.publish_cellular_profile_migration_v57(bytea) RENAME TO publish_cellular_profile_migration; DROP FUNCTION evolution.cellular_births(bytea,bytea); ALTER FUNCTION evolution.cellular_births_v57(bytea,bytea) RENAME TO cellular_births; diff --git a/tools/ci/postgres-check.sh b/tools/ci/postgres-check.sh index 1d2cb83..6f50063 100644 --- a/tools/ci/postgres-check.sh +++ b/tools/ci/postgres-check.sh @@ -161,7 +161,7 @@ PGDATABASE=upgrade_path psql -X -v ON_ERROR_STOP=1 -1 -v "migration_sha=$v1_sha" -f "$root/migrations/0001_region_bootstrap.sql" > /dev/null test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',') FROM evolution.schema_migrations")" = 1 PGDATABASE=upgrade_path bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59 +test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60 # v2 heads have no payload binding: v2->v3 fails closed and leaves history at v2. v2_sha="$(sha256sum "$root/migrations/0002_region_fencing.sql")" v2_sha="${v2_sha%% *}" @@ -182,7 +182,7 @@ PGDATABASE=v3_commits psql -X -v ON_ERROR_STOP=1 \ -c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \ -c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '01000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32), 'hex'))" > /dev/null PGDATABASE=v3_commits bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 59:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59 +test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 60:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60 test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) FROM evolution.region_commits")" = 1 # Review P1: a v4 database holding a published (possibly terminal) checkpoint has # no durable decisions for it. The v5 upgrade must refuse before changing anything. @@ -236,7 +236,7 @@ PGDATABASE=v6_populated psql -X -v ON_ERROR_STOP=1 \ -c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \ -c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '02000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32) || repeat('00', 80), 'hex'))" > /dev/null PGDATABASE=v6_populated bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59 +test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60 test "$(PGDATABASE=v6_populated psql -XAtc "SELECT count(*) FROM evolution.region_commits c, LATERAL evolution.parse_checkpoint_manifest(c.manifest) m WHERE m.commit_sequence = 0 AND m.predecessor_commit IS NULL")" = 1 test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(conname, ',') FROM pg_constraint WHERE conrelid = 'evolution.region_heads'::regclass AND contype = 'c' AND pg_get_constraintdef(oid) LIKE '%end_tick%'")" = region_heads_published_tick phase permission-audit @@ -294,9 +294,9 @@ expect_audit_failure 'REVOKE EXECUTE ON FUNCTION evolution.load_world_cellular_m expect_audit_failure 'GRANT EXECUTE ON FUNCTION evolution.fork_restored_history_v1(uuid) TO evo_runtime_test' 'REVOKE EXECUTE ON FUNCTION evolution.fork_restored_history_v1(uuid) FROM evo_runtime_test' phase checksum-drift # Unknown future versions and checksum drift must not be repaired silently. -psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=60 WHERE version=59' +psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=61 WHERE version=60' if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi -psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=59 WHERE version=60" +psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=60 WHERE version=61" psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=14" if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=13" diff --git a/tools/migrate-postgres.sh b/tools/migrate-postgres.sh index 45d74e8..4ebd519 100644 --- a/tools/migrate-postgres.sh +++ b/tools/migrate-postgres.sh @@ -130,6 +130,8 @@ digest_58="$(sha256sum "$root/migrations/0058_liquid_bundle.sql")" digest_58="${digest_58%% *}" digest_59="$(sha256sum "$root/migrations/0059_durable_mutation_queue.sql")" digest_59="${digest_59%% *}" +digest_60="$(sha256sum "$root/migrations/0060_cellular_revamp_bundle.sql")" +digest_60="${digest_60%% *}" psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \ --set="migration_sha_2=$digest_2" --set="migration_sha_3=$digest_3" \ --set="migration_sha_4=$digest_4" --set="migration_sha_5=$digest_5" \ @@ -178,5 +180,6 @@ psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \ --set="migration_sha_53=$digest_53" --set="migration_sha_54=$digest_54" \ --set="migration_sha_55=$digest_55" --set="migration_sha_56=$digest_56" \ --set="migration_sha_57=$digest_57" --set="migration_sha_58=$digest_58" --set="migration_sha_59=$digest_59" \ + --set="migration_sha_60=$digest_60" \ --set="runtime_role=$runtime_role" \ --file="$root/migrations/apply.sql"