# Energy and matter accounting Locked: explicit biological costs and conservation. Ledger structure is recommended; coefficients/solvers are experiments, not claims of biochemical accuracy. M0 particles do not implement this model. | Quantity | Convention | |---|---| | Usable/source/work/heat energy | J inventories; W reported rates; explicit fixed-point quantum if adopted | | Material | kg or scaled mass; validated element composition | | Elements/nutrients | kg of specified element; mol requires explicit identity and conversion | | Temperature | K; intensive state, not conserved inventory | | Population | Nonnegative integer individuals or separately typed expected count | Material and its element composition are two views of the same matter, not additive inventories. Conserve an explicit 'other' component if the chemical basis is simplified. Reserve and structural chemical energy must not double count ingestible energy. Work may immediately become heat in a simplified model; it then cannot also remain available as mechanical energy. For each closed accounting interval: `E_end = E_start + external_input - exported_energy - unmodeled_heat_loss`. If heat is modeled, include its reservoir in E_end instead of that loss term. For every element k: `M_end[k] = M_start[k] + imported[k] - exported[k]`. Totals include environment, organisms, eggs/spores/cohorts, corpses, transfer escrow and suspended organisms. Death/reproduction/conversion are transfers. Atmospheric release is a transfer when atmosphere is modeled, otherwise an explicit boundary export. Light/geothermal flux is finite per area/interval; chemosynthesis consumes finite potential or recorded geological replenishment. `reserve_next = reserve + assimilation + capture - maintenance - locomotion - construction - reproduction - exported_reserve`. Every term has a counterpart. Unmet costs trigger the defined starvation policy, never a negative reserve or implicit loan. Overflow/excess follows named outputs. ```mermaid sequenceDiagram participant B as Biology participant L as Tick ledger participant R as Inventory owners B->>L: Propose(action ID, debits, credits, costs) L->>L: Validate dimensions, composition, bounds and phase L->>R: Reserve balances in stable order alt Sufficient resources L->>R: Commit balanced transfer exactly once L-->>B: Outcome and phenotype/lifecycle changes else Insufficient or stale L-->>B: Reject or explicitly quantified partial consumption end ``` The ledger is an in-process deterministic buffer, not a remote service or database write per transfer. Initial canonical entity/action allocation order introduces priority bias: measure against fair-share alternatives before tuning. Randomized fairness requires a purpose-specific recorded stream. Costs and outputs commit together; retries cannot double-spend. Partial ingestion is a declared quantity, not partially published offspring. Checked integer arithmetic carries division residuals. Floating-point solvers require finite checks, fixed reduction order and declared absolute/relative error budgets. Never conceal failed conservation by clamping balances. A density field is a view of owned finite inventory; consumers contend for that inventory. | Process | Debit → credit / limitation | |---|---| | Capture | finite flux + substrate → reserve/production + loss; area/efficiency bound | | Feeding | prey/resource matter + reserve → assimilation + waste + heat; ingestion bound | | Maintenance/movement | reserve → work/heat; phenotype demand and fixed interval | | Growth | material + reserve → structure + heat; developmental plan | | Reproduction | funded parent/environment inventory → offspring investment + heat | | Death | live compartments → corpse/detritus exactly once | | Decomposition | detritus + reactants → nutrients/chemical outputs/heat; rate/reactant bound | M2 uses explicitly synthetic founder fixtures, not unrelated wildlife in a persistent world. A simplified decomposition basis must balance completely; scalar biomass-to-nutrients is not full elemental chemistry. Expose source inputs, inventory/sink totals, unmet maintenance, failed transfers and per-element residuals. Distinguish cumulative quantities/rates; IDs are not metric labels. Tests: closed-box conservation, finite-source exhaustion, predation with waste, starvation nonnegativity, reproduction rollback, exactly-once death/decomposition, competing consumers, long-run rounding, overflow/NaN rejection, cross-tier escrow and independently recomputed seeded totals. Baseline metabolism, efficiencies, light attenuation, stoichiometry, heat fidelity and starvation rules remain open. Conservation alone does not guarantee a stable or enjoyable ecosystem. ## Implemented M2.1 boundary [ADR-0024](../adr/0024-conserved-inventory-ledger.md) scopes the initial `evo::accounting` library. Its ledger is independent of particle world state. Opening inventories are explicit; later operations only transfer quantities. Energy is in integer picojoules, disjoint C/N/P/other masses in femtograms. Other contains all unmodeled matter; this is not a complete biochemical basis. All quantities and global per-channel sums must fit u64. No float conversion, division or fractional-rate handling is exposed yet, so there is no rounding loss. ```cpp // include/evo/accounting/ledger.hpp (contract sketch) auto ledger = Ledger::create(opening_inventories); auto result = ledger->transfer(action_id, ordered_legs); ``` Each leg transfers the same bundle between distinct reservoir IDs. Atomic commit covers the entire ordered transaction and its monotonic action watermark. A rejected transaction consumes nothing, including its ID. A duplicate/older accepted ID is rejected. This is in-memory replay protection, not durable exactly-once delivery. The owner assigns deterministic order; competing consumers are first-funded, with no implicit fair-share or random priority rule. Reservoir meaning is caller-owned: source, reserve, substrate, structure, corpse, heat or escrow. The primitive does not enforce chemical reactions or prevent a caller from misclassifying heat as usable energy. M2.2 must provide restricted process operations and finite flux budgets. Never treat conservation as biological validity. There is no import/mint API, organism lifecycle, persisted ledger codec or cross-ledger transaction in M2.1. Persistent integration must checkpoint both inventories and action watermark atomically; M1 snapshots do not include them. ## Implemented M2.2 synthetic producer [ADR-0025](../adr/0025-finite-producer-process.md) defines the independent `evo::processes::ProducerProcess` fixture. It owns four reservoirs and exposes only read-only balances and exact-next-tick advancement. Source energy and C/N/P/other substrates are finite opening inventories. Capture divides actual source uptake between reserve and heat. Growth moves a configured whole recipe from substrates to structure and its energy cost from reserve to heat. The API cannot reuse heat. ```mermaid flowchart LR S[Finite source energy] -->|rate-limited capture| R[Producer reserve] S -->|conversion loss| H[Heat] N[Finite substrates] -->|funded recipe units| B[Producer structure] R -->|growth energy cost| H ``` Rates are rational inventories/recipe units per integer tick count. Independent carried remainders preserve capture, growth and efficiency fractions. Unfunded whole quotas expire; no starvation debt or future burst accumulates. Remainders and tick advance only after the ledger transaction succeeds. Arithmetic uses quotient/remainder decomposition, not overflow-prone numerator multiplication. This is a synthetic process, not a biological founder or organism. Its parameters do not select photosynthetic chemistry, area, metabolic efficiency, world time or the final units library. No producer state is attached to the particle world, serialized, connected to PostgreSQL or deployed. Later persistent integration must include config, reservoirs, tick and all three remainders in one checkpoint.