Files
aevolution/include/evo/network/session_protocol.hpp
T
dingoandClaude Opus 5.5 e2da92768c
Foundation / checks (client) (push) Successful in 5s
Foundation / checks (checks) (push) Successful in 5s
Foundation / checks (network) (push) Successful in 5s
Foundation / checks (ecs) (push) Successful in 5s
Foundation / checks (postgres) (push) Successful in 5s
Foundation / checks (tsan) (push) Successful in 5s
Foundation / checks (deploy) (push) Successful in 4m32s
Foundation / postgres-tools (push) Successful in 28s
Foundation / server-image (push) Successful in 4m21s
Foundation / image (push) Successful in 5m1s
feat(cellular): show growth and gate splits; DEV splits at half growth
Playtest: after one mutation every later choice came back "split refused"
because a split needs a grown cell, and the client gave no reason. The v14
body block now carries the body's growth per thousand (the reserved bytes)
and a split-ready flag; the client disables Stay / Become until the cell can
split ("Grow to split (now 62%)") and shows growth in the Body panel.
Adhesion and organism choices do not split and stay open.

The DEV revamp tuning splits once half grown (split_min_growth 500, was full
growth); it takes effect in the next region opened.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 08:28:57 -04:00

562 lines
28 KiB
C++

#pragma once
#include <array>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <optional>
#include <span>
#include <string>
#include <variant>
#include <vector>
// M10 session protocol v1 (ADR-0091 session, ADR-0092 intentions and actions;
// schemas/network/session-v1.md). Session, action and outcome messages travel on the QUIC
// reliable stream (one message per framed QUIC message); intentions, their receipts and the
// simulated watermark travel as QUIC DATAGRAMs.
// Each starts with an 8-byte header: magic "EVSN", version u16, type u8, flags u8 (0);
// every payload has a fixed size and explicit little-endian fields. Grants are opaque
// 160-byte credentials here. Later M10/M11 segments add message types under new versions.
namespace evo::network {
inline constexpr std::uint32_t session_magic = 0x4E535645; // Bytes "EVSN".
// v2 (M10.5, ADR-0093): v1 plus interest, snapshot chunks and snapshot acks.
// v3 (M10.6, ADR-0094): v2 plus probe marker records inside snapshot chunks.
// v4 (M10.8c, ADR-0096): v3 plus HandoffOffer and SessionRedirect (stream), close reasons
// handed_off and moved, and ghost marker records. v1-v3 were deployed to evolution-dev and
// are frozen; v4 remains the default. v5 adds reliable primitive-life operations.
inline constexpr std::uint16_t session_protocol_version = 4;
inline constexpr std::uint16_t session_protocol_v5 = 5;
inline constexpr std::uint16_t session_protocol_v6 = 6;
// v7 adds stable-id reliable cellular actions; v1-v6 wire layouts stay frozen.
inline constexpr std::uint16_t session_protocol_v7 = 7;
// v8 adds the authenticated owner's exact, bounded cellular perception view.
inline constexpr std::uint16_t session_protocol_v8 = 8;
// v9 adds owner-only current reserve and last committed tick effects to the v8 view.
inline constexpr std::uint16_t session_protocol_v9 = 9;
// v10 adds a reliable owner choice for a previously earned cellular mutation offer.
// Its durable effect is committed on the next cellular tick.
inline constexpr std::uint16_t session_protocol_v10 = 10;
// v11 (ADR-0136 step A) is v10 with the owner's view of pools and bubbles (deposits)
// instead of square patches; every other message is v10's.
inline constexpr std::uint16_t session_protocol_v11 = 11;
// v12 (ADR-0176) is v11 plus the owner's captured light and visible producers in its
// perception, and the photosynthesis capability (7) in mutation offers.
inline constexpr std::uint16_t session_protocol_v12 = 12;
// v13 (rules 12, ADR-0177) is v12 plus liquid motion: the owner's velocity and heading and the
// 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;
// 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_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_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 ||
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
cellular_offer_capability_limit(std::uint16_t version) noexcept {
return cellular_light_version(version) ? 7 : 6;
}
inline constexpr std::size_t max_cellular_perceived_patches = 256;
inline constexpr std::size_t max_cellular_perceived_deposits = 512;
inline constexpr std::size_t max_cellular_perceived_producers = 256;
inline constexpr std::size_t session_address_bytes = 64; // Endpoint or server name field.
inline constexpr std::size_t session_datagram_bytes = 1200; // Whole message, ADR-0089.
inline constexpr std::size_t session_header_bytes = 8;
inline constexpr std::size_t session_grant_wire_bytes = 160;
enum class SessionMessageType : std::uint8_t {
hello = 1, // Client -> server: grant.
welcome, // Server -> client.
refresh, // Client -> server: newer grant for the open session.
refresh_result, // Server -> client.
close, // Either way, then the sender closes the connection.
intention, // Client -> server, datagram: realtime movement intention.
intention_receipt, // Server -> client, datagram.
simulated_through, // Server -> client, datagram: cumulative simulated watermark.
action, // Client -> server, stream: discrete action with a stable id.
action_receipt, // Server -> client, stream.
action_outcome, // Server -> client, stream: final.
action_query, // Client -> server, stream: resolve an action by id.
interest, // Client -> server, stream: spatial focus (v2).
snapshot_chunk, // Server -> client, datagram: part of one snapshot (v2).
snapshot_ack, // Client -> server, datagram: newest complete snapshot (v2).
handoff_offer, // Server -> client, stream: continue at another region (v4).
redirect, // Server -> client, stream: the account's probe is elsewhere (v4).
primitive_life_request = 18,
primitive_life_receipt,
primitive_life_outcome,
primitive_life_query,
cellular_intention = 22,
cellular_action = 23,
cellular_perception = 24,
cellular_mutation_action = 25,
cellular_mutation_offer = 26, // Server -> owner, stream (v10).
cellular_life_ended = 27 // Server -> owner, stream (v10).
};
// Admission answers for intentions and actions (wire 0..10).
enum class AdmitStatus : std::uint8_t {
admitted = 0,
unknown_session, // Not this connection's session.
stale_epoch,
outside_window, // Tick not in server_tick + 1 ..= server_tick + window.
rate_limited, // Every attempt counts toward the window budget.
replayed, // Intention sequence not above the last admitted one.
invalid_vector,
too_many_unresolved,
invalid_action, // Unknown kind or zero action id.
duplicate, // Action id already known for this account: its state follows.
not_ready // The region has no current authority (starting, recovering, draining).
};
// Wire u16 (SessionAction::kind carries the raw value; admission validates it).
enum class ActionKind : std::uint8_t {
probe = 1, // No effect on biology: proves admission, scheduling and durability (M10.4).
cellular = 2 // v7 biological input, committed with profile-4 state (ADR-0111/0112).
};
enum class ActionResult : std::uint8_t {
committed_no_effect = 1, // Durable in commit `commit_sequence`; changed nothing.
not_committed, // Final: never part of a committed batch.
pending, // Query answer only: admitted, not yet final.
unknown, // Query answer only: no record of this action id.
committed // Cellular action committed; inspect the authoritative view (v7).
};
// Wire values 1..13. `connection_lost` is local only (the transport ended without a Close).
enum class SessionCloseReason : std::uint8_t {
client_closed = 1,
superseded, // A newer grant for the same account opened another session.
expired,
stale_epoch,
unauthenticated,
wrong_scope, // Environment, world or region.
stale_grant, // Replayed or older than a grant already presented.
rate_limited,
capacity,
protocol,
timeout, // No Hello before the deadline.
unsupported_version,
shutdown,
handed_off, // v4: the probe crossed to another region; a HandoffOffer preceded this.
moved, // v4: the account's probe is owned by another region (a Redirect may precede).
connection_lost = 255
};
enum class SessionCodecError : std::uint8_t {
truncated,
bad_magic,
unsupported_version,
unknown_type,
reserved_flags,
wrong_length,
invalid_value
};
using WireGrant = std::array<std::uint8_t, session_grant_wire_bytes>;
struct SessionHello {
std::uint32_t required_features{}; // Must be zero in v1.
WireGrant grant{};
};
struct SessionWelcome {
std::uint64_t session{}, epoch{}, world{}, frame{}, region{}, expires_at{};
std::uint64_t server_seconds{}; // Server wall clock at Welcome, for refresh timing.
std::uint64_t server_tick{}; // Simulated tick at Welcome, for scheduling.
friend bool operator==(const SessionWelcome&, const SessionWelcome&) = default;
};
struct SessionRefresh {
WireGrant grant{};
};
// accepted: 0 and the new expiry. Otherwise a refusal reason (stale_grant,
// unauthenticated, wrong_scope, expired, rate_limited); the session keeps its expiry.
struct SessionRefreshResult {
std::uint8_t status{};
std::uint64_t expires_at{};
friend bool operator==(const SessionRefreshResult&, const SessionRefreshResult&) = default;
};
struct SessionClose {
SessionCloseReason reason{};
};
// A movement intention carries only what the player wants: never position, energy or any
// other state claim. Vector components within the M9 bound (norm <= 1000).
struct SessionIntention {
std::uint64_t session{}, epoch{}, sequence{}, tick{};
std::int16_t move_x{}, move_y{};
friend bool operator==(const SessionIntention&, const SessionIntention&) = default;
};
// v6 biological input only: movement intent plus an optional address of a patch
// the client wants to feed from. The server checks range, contact and costs.
struct CellularIntention {
std::uint64_t session{}, epoch{}, sequence{}, tick{};
std::int16_t move_x{}, move_y{};
bool has_intake_target{};
std::uint32_t intake_x_um{}, intake_y_um{};
friend bool operator==(const CellularIntention&, const CellularIntention&) = default;
};
// Canonical biological input saved with a durable cellular action. Transport session,
// epoch and action id are deliberately absent so the same retry survives reconnects.
// Byte 12 is the target kind (ADR-0124): 0 none, 1 patch intake, 2 engulf with zero
// coordinates. Kind 2 is carried only by v10 sessions.
struct CellularActionInput {
std::uint64_t tick{};
std::int16_t move_x{}, move_y{};
bool has_intake_target{};
std::uint32_t intake_x_um{}, intake_y_um{};
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;
// v7 reliable input: stable account-scoped action id makes retries safe across reconnects.
// The server resolves the optional intake address and all biological effects.
struct CellularAction {
std::uint64_t session{}, epoch{}, action_id{}, tick{};
std::int16_t move_x{}, move_y{};
bool has_intake_target{};
std::uint32_t intake_x_um{}, intake_y_um{};
// v10 (ADR-0124): engulf a smaller contacted cell; exclusive with an intake target.
bool engulf{};
// v10 (ADR-0125): fund one wildlife bud; exclusive with intake and engulfment.
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
// action id, revalidates the exact outstanding offer, and reserves successor identity.
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.
std::uint32_t parameter{}; // The successor's value; zero when shed.
std::uint64_t maintenance{}, total_mass{};
// What choosing it costs this cell from its reserve (ADR-0129): construction energy and
// the matter each channel must add. Compare with the reserve in the diagnostics.
std::uint64_t cost_energy_pj{};
std::array<std::uint64_t, 4> cost_matter_fg{};
friend bool operator==(const CellularOfferedCandidate&,
const CellularOfferedCandidate&) = default;
};
inline constexpr std::size_t max_cellular_offered_candidates = 8;
struct CellularMutationOffer {
std::uint64_t tick{}, life_identity{}, event_index{}, offer_tick{};
std::vector<CellularOfferedCandidate> candidates;
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); 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{};
friend bool operator==(const CellularLifeEnded&, const CellularLifeEnded&) = default;
};
// v8 server-to-owner view. Addresses and current inventory are already filtered by
// authoritative cell position/range; provenance and account identity are omitted.
struct CellularPerceivedPatch {
std::uint32_t x_um{}, y_um{};
std::uint64_t energy_pj{};
std::array<std::uint64_t, 4> matter_fg{};
friend bool operator==(const CellularPerceivedPatch&, const CellularPerceivedPatch&) = default;
};
// v11 (ADR-0136): one pool or bubble in range. Amounts travel as 16-bit log codes (about
// 0.2 % precision: enough to size, colour and fade them); the HUD's exact numbers stay in
// the diagnostics. `drained` is set when some cell took from it on this tick.
enum class CellularDepositShape : std::uint8_t { pool = 1, bubble = 2 };
struct CellularPerceivedDeposit {
std::uint32_t id{}, x_um{}, y_um{}; // Centre.
std::uint16_t radius_um{};
CellularDepositShape shape{CellularDepositShape::bubble};
bool drained{};
std::array<std::uint16_t, 5> amount_codes{}; // Energy, then C, N, P, other.
// v13 only: world velocity in um/s (current plus induced drift); zero for pools.
std::int16_t velocity_x_um_s{}, velocity_y_um_s{};
friend bool operator==(const CellularPerceivedDeposit&,
const CellularPerceivedDeposit&) = default;
};
// 0 for 0; otherwise 1 + 512 * floor(log2 v) + the next 9 bits of v.
[[nodiscard]] constexpr std::uint16_t deposit_amount_code(std::uint64_t value) noexcept {
if (value == 0)
return 0;
unsigned bit = 63;
while ((value >> bit) == 0)
--bit;
const auto fraction = bit >= 9 ? (value >> (bit - 9)) & 511U : (value << (9 - bit)) & 511U;
return static_cast<std::uint16_t>(1 + 512 * bit + fraction);
}
// The smallest amount with that code.
[[nodiscard]] constexpr std::uint64_t deposit_amount_value(std::uint16_t code) noexcept {
if (code == 0)
return 0;
const unsigned bit = (code - 1U) / 512U;
const std::uint64_t mantissa = 512U + (code - 1U) % 512U;
return bit >= 9 ? mantissa << (bit - 9) : mantissa >> (9 - bit);
}
enum class CellularMovementResult : std::uint8_t {
not_reported,
no_movement,
moved,
blocked,
insufficient_energy
};
enum class CellularIntakeResult : std::uint8_t {
not_reported,
not_requested,
acquired,
missing_patch,
out_of_contact
};
// v10 tick effects (ADR-0129): what an engulf or bud intention did. v9 never reports them.
enum class CellularEngulfResult : std::uint8_t {
not_reported,
not_requested,
engulfed,
no_eligible_prey, // No longer sent: one of the three reasons below is.
unsupported,
no_contact, // No other cell touched it.
prey_too_large, // Touching cells were too large even with the thinnest membrane.
membrane_too_thick // A touching cell was small enough, but its membrane defended it.
};
enum class CellularBudOutcome : std::uint8_t {
not_reported,
not_requested,
budded,
not_able, // No reproduction capability, not fully grown, damaged, or suspended.
insufficient_funding,
no_placement
};
struct CellularLifeDiagnostics {
std::uint64_t reserve_energy_pj{};
std::array<std::uint64_t, 4> reserve_matter_fg{};
std::uint64_t maintenance_cost_pj{}, movement_cost_pj{};
CellularMovementResult movement{CellularMovementResult::not_reported};
CellularIntakeResult intake{CellularIntakeResult::not_reported};
bool has_tick_effects{};
CellularEngulfResult engulf{CellularEngulfResult::not_reported}; // v10 only.
CellularBudOutcome bud{CellularBudOutcome::not_reported}; // v10 only.
// v10 only (ADR-0129 amendment): what one bud takes from the reserve once the cell is
// fully grown: construction and provision energy plus matter per channel. All zero
// when this cell's genome cannot bud. Independent of tick effects.
std::uint64_t bud_cost_energy_pj{};
std::array<std::uint64_t, 4> bud_cost_matter_fg{};
std::uint64_t light_pj{}; // v12 only (ADR-0176): light this cell captured last tick.
// v13 only (rules 12): velocity relative to the liquid (Q10 um/s) and heading (65,536 per
// 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{};
// How grown the body is (per thousand), and whether a mutation choice can split it now.
std::uint16_t growth_per_thousand{};
bool split_ready{};
std::uint64_t payable_energy_pj{}, total_mass_fg{};
std::array<std::uint16_t, 20> traits{};
friend bool operator==(const CellularLifeDiagnostics&,
const CellularLifeDiagnostics&) = default;
};
// v12 (ADR-0176): a visible cell that carries photosynthesis, by organism, and its
// efficiency per thousand, so a client can draw its organelles.
struct CellularPerceivedProducer {
std::uint64_t organism{};
std::uint16_t photosynthesis_per_thousand{};
friend bool operator==(const CellularPerceivedProducer&,
const CellularPerceivedProducer&) = default;
};
// v13 (rules 12): the region's current configuration; the client regenerates the identical
// flow field from it (biology::CellularFlowField).
struct CellularCurrentsView {
std::uint64_t seed{};
std::uint32_t width_um{}, height_um{}, pitch_um{};
std::uint32_t min_count{}, max_count{};
std::uint32_t min_route_width_um{}, max_route_width_um{};
std::uint32_t min_speed_um_per_s{}, max_speed_um_per_s{};
friend bool operator==(const CellularCurrentsView&, const CellularCurrentsView&) = default;
};
struct CellularPerception {
std::uint64_t tick{}, life_identity{}; // zero life plus no patches clears the view.
std::vector<CellularPerceivedPatch> patches; // strictly ordered by (x_um, y_um).
// Present only on v9 for an active life. The values are authoritative observations,
// not client claims or additional simulation state.
std::optional<CellularLifeDiagnostics> diagnostics;
// v11 only (then `patches` is empty): pools and bubbles in range, by ascending id.
std::vector<CellularPerceivedDeposit> deposits{};
// v12 only: visible producers by ascending organism.
std::vector<CellularPerceivedProducer> producers{};
// v13 only, with an owner life in a liquid region.
std::optional<CellularCurrentsView> currents{};
friend bool operator==(const CellularPerception&, const CellularPerception&) = default;
};
struct IntentionReceipt {
std::uint64_t sequence{};
AdmitStatus status{};
std::uint64_t server_tick{};
friend bool operator==(const IntentionReceipt&, const IntentionReceipt&) = default;
};
// Every admitted intention up to `sequence` whose tick is <= `tick` has been simulated in
// `epoch` (cumulative, so a lost datagram is covered by the next).
struct SimulatedThrough {
std::uint64_t epoch{}, sequence{}, tick{};
friend bool operator==(const SimulatedThrough&, const SimulatedThrough&) = default;
};
struct SessionAction {
std::uint64_t session{}, epoch{}, action_id{};
std::uint16_t kind{}; // Raw wire value: an unknown kind is refused by admission.
std::uint64_t tick{};
friend bool operator==(const SessionAction&, const SessionAction&) = default;
};
// Receipt only: admitted means scheduled for `tick`, never simulated or durable.
struct ActionReceipt {
std::uint64_t action_id{};
AdmitStatus status{};
std::uint64_t server_tick{}, tick{};
friend bool operator==(const ActionReceipt&, const ActionReceipt&) = default;
};
struct ActionOutcome {
std::uint64_t action_id{};
ActionResult result{};
std::uint64_t tick{}, commit_sequence{}; // Zero unless a committed result is returned.
friend bool operator==(const ActionOutcome&, const ActionOutcome&) = default;
};
struct ActionQuery {
std::uint64_t action_id{};
friend bool operator==(const ActionQuery&, const ActionQuery&) = default;
};
enum class PrimitiveLifeResult : std::uint8_t {
born = 1,
insufficient_funding = 2,
no_placement = 3,
existing_life = 4,
cancelled = 5,
pending = 6,
unknown = 7
};
struct PrimitiveLifeRequest {
std::uint64_t session{}, epoch{}, request_id{};
friend bool operator==(const PrimitiveLifeRequest&, const PrimitiveLifeRequest&) = default;
};
struct PrimitiveLifeReceipt {
std::uint64_t request_id{};
AdmitStatus status{};
std::uint64_t server_tick{};
friend bool operator==(const PrimitiveLifeReceipt&, const PrimitiveLifeReceipt&) = default;
};
struct PrimitiveLifeOutcome {
std::uint64_t request_id{};
PrimitiveLifeResult result{};
std::uint64_t life_identity{}, commit_sequence{};
friend bool operator==(const PrimitiveLifeOutcome&, const PrimitiveLifeOutcome&) = default;
};
struct PrimitiveLifeQuery {
std::uint64_t request_id{};
friend bool operator==(const PrimitiveLifeQuery&, const PrimitiveLifeQuery&) = default;
};
// The client's spatial focus: one Z slice, a centre and a radius in cells. The server
// clamps the radius to its maximum and filters authoritatively (ADR-0093).
struct SessionInterest {
std::int64_t x{}, y{}, z{};
std::uint16_t radius{};
friend bool operator==(const SessionInterest&, const SessionInterest&) = default;
};
// One self-contained part of snapshot `tick`, a delta against snapshot `baseline` (0: a
// fresh baseline). `records` are whole entity records (replication.hpp); the snapshot is
// complete when all `count` chunks arrived.
struct SnapshotChunk {
std::uint64_t epoch{}, tick{}, baseline{}, field_revision{}, organism_revision{};
std::uint32_t mask{};
std::int64_t slice_z{};
std::uint8_t index{}, count{};
std::vector<std::uint8_t> records;
friend bool operator==(const SnapshotChunk&, const SnapshotChunk&) = default;
};
inline constexpr std::size_t snapshot_chunk_header_bytes = (5 * 8) + 4 + 8 + 2;
inline constexpr std::size_t max_snapshot_records_bytes =
session_datagram_bytes - session_header_bytes - snapshot_chunk_header_bytes;
// The newest snapshot the client assembled completely and applied.
struct SnapshotAck {
std::uint64_t epoch{}, tick{};
friend bool operator==(const SnapshotAck&, const SnapshotAck&) = default;
};
// A region's public address as a client dials it: "host:port" and the certificate name,
// printable ASCII (no spaces), 1-64 characters each.
struct RegionAddress {
std::uint64_t region{};
std::string endpoint, server_name;
friend bool operator==(const RegionAddress&, const RegionAddress&) = default;
};
// v4 (ADR-0096): the session's probe crossed into `destination`; log in there with `ticket`
// (a handoff ticket, used in Hello's grant slot). The source then closes with handed_off.
struct HandoffOffer {
std::array<std::uint8_t, 16> transfer{};
RegionAddress destination;
WireGrant ticket{};
friend bool operator==(const HandoffOffer&, const HandoffOffer&) = default;
};
// v4: at login, the account's probe is owned by `owner`; log in there with a grant for it.
struct SessionRedirect {
RegionAddress owner;
friend bool operator==(const SessionRedirect&, const SessionRedirect&) = default;
};
using SessionMessage =
std::variant<SessionHello, SessionWelcome, SessionRefresh, SessionRefreshResult, SessionClose,
SessionIntention, CellularIntention, CellularAction, IntentionReceipt,
SimulatedThrough, SessionAction, ActionReceipt, ActionOutcome, ActionQuery,
SessionInterest, SnapshotChunk, SnapshotAck, HandoffOffer, SessionRedirect,
PrimitiveLifeRequest, PrimitiveLifeReceipt, PrimitiveLifeOutcome,
PrimitiveLifeQuery, CellularPerception, CellularMutationAction,
CellularMutationOffer, CellularLifeEnded>;
[[nodiscard]] std::vector<std::uint8_t> encode_session(const SessionMessage& message);
[[nodiscard]] std::vector<std::uint8_t> encode_session(const SessionMessage& message,
std::uint16_t version);
// Exactly one message; any other length for its type rejects.
[[nodiscard]] std::expected<SessionMessage, SessionCodecError>
decode_session(std::span<const std::uint8_t> bytes);
[[nodiscard]] std::expected<SessionMessage, SessionCodecError>
decode_session(std::span<const std::uint8_t> bytes, std::uint16_t* version);
[[nodiscard]] std::array<std::uint8_t, cellular_action_input_bytes>
encode_cellular_action_input(const CellularActionInput& input);
[[nodiscard]] std::expected<CellularActionInput, SessionCodecError>
decode_cellular_action_input(std::span<const std::uint8_t> bytes);
} // namespace evo::network