From 21e3290528144b409c48c656bcccba739064e8ce Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 18:06:14 +0000 Subject: [PATCH 01/11] fix(predation): carcasses jaw-only, goldens and the stability floor that go with it (ADR 0026) PR #143 merged with the one-line carcass change from the Copilot bot but without the parts that make it pass: 4 predation goldens regenerated, the ecology-stability floor 15 to 8 (measured over 12 held-out seeds: means 37.7-77.2, minimum 10 on seed 6, maximum 118, none extinct), tests with negatives (only the jaw bites or sees carrion, a mandible does neither, the old table is still expressible) and the doc updates. Main's determinism shards 1 and 2 failed on both OSes at aed927b for exactly this reason (stale goldens; seed 6 under the floor). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Cn5qp4xBHxLnTrwReNXcf8 --- docs/decisions/0023-predation.md | 2 +- docs/decisions/0026-diets.md | 6 ++++-- docs/ecology/ecology.md | 2 +- docs/simulation/configuration.md | 2 +- packages/config/src/defaults.ts | 2 ++ packages/simulation/tests/golden/state-hashes.json | 8 ++++---- .../simulation/tests/predation/carnivore.test.ts | 10 +++++++++- .../tests/predation/death-and-carcass.test.ts | 13 ++++++++++--- .../simulation/tests/support/ecology-stability.ts | 7 ++++++- 9 files changed, 38 insertions(+), 14 deletions(-) diff --git a/docs/decisions/0023-predation.md b/docs/decisions/0023-predation.md index 6c6e945..51176b7 100644 --- a/docs/decisions/0023-predation.md +++ b/docs/decisions/0023-predation.md @@ -14,7 +14,7 @@ Owner decisions (2026-11-12): the first hunters are **emergent only** (no seeded 2. **What can be bitten.** A creature that is not itself, not a parent or child (kin are never prey; no species rule, because a species label drifts and would couple behaviour to a post hoc name), alive, no bigger than `maxPreyRatio` (1.5) times the biter's body radius (so the mouth's gape, bite size and size-for-size decide who eats whom), within the mouth's reach, inside the bite cone, and **not behind an obstacle that blocks movement** (the ADR 0022 field; reeds do not stop a bite). 3. **What a bite does.** The victim loses **energy**, at most what it has and what the biter's gut can hold: `min(energy, biteEnergy x gape factor)`. The biter's gut gains that times `trophicYield` (0.6) times the mouth's flesh yield, so **energy moves and is lost on the way, never created**: a drained or tiny victim is poor prey. The victim also takes **health damage** `biteDamage x gape factor x its own damageTaken`, so armor finally matters for something other than hazards. One bite a tick per mouth, the same cooldown and chewing slow-down as for food. An `organism-bitten` event carries both creatures, the damage, the energy taken and the intake. 4. **Death by predation.** `DeathCause` gains `'predation'`: a creature that was bitten within `attackWindow` (3 s) and then starved or was worn down is counted as killed by the bite, not by hunger or the weather (a victim drained to zero energy would otherwise be reported as starved). `organism-died` and the history record carry the killer. Old age stays old age. The bookkeeping (`lastBitten`) only labels deaths, never feeds back into the dynamics, and is **not hashed**. -5. **Carcasses.** With predation on, the world's configuration (`world/predationConfig.ts`, like the cluster scaling) appends a `carrion` food kind that never spawns by itself and gives every mouth form a carrion yield (jaw 1.2, mandible 0.8, radula 0.6, proboscis 0.2, sprout 0.1). Every death, from any cause, leaves one carcass where the creature died, worth `energyFraction` (0.6) of its energy and what was in its gut, if that is at least 5, while fewer than 40 are on the field; carcasses rot after 120 s. Ids come from the shared allocator in death order and nothing is drawn, so a run is the same however it is sliced. A carcass is an ordinary bitable food item, so scavengers need no new mechanism. With predation off, carcasses off or food kinds off, the very same configuration object is used, so those worlds are exactly what they were. +5. **Carcasses.** With predation on, the world's configuration (`world/predationConfig.ts`, like the cluster scaling) appends a `carrion` food kind that never spawns by itself and gives every mouth form a carrion yield (jaw 1.2, mandible 0.8, radula 0.6, proboscis 0.2, sprout 0.1; **since ADR 0026 the jaw's alone, every other form is 0**: jaws had got 5 percent of the carrion). Every death, from any cause, leaves one carcass where the creature died, worth `energyFraction` (0.6) of its energy and what was in its gut, if that is at least 5, while fewer than 40 are on the field; carcasses rot after 120 s. Ids come from the shared allocator in death order and nothing is drawn, so a run is the same however it is sliced. A carcass is an ordinary bitable food item, so scavengers need no new mechanism. With predation off, carcasses off or food kinds off, the very same configuration object is used, so those worlds are exactly what they were. 6. **Reward.** A predator's intake from a bite counts as a meal in its feeding reward; the prey already learn from `organism-damaged`. 7. **Drawn.** A ring effect where a bite lands, carrion as a dull red food dot, and a **Predation** row in the death-causes strip, shown only in a world where something has been killed by a bite. 8. **Constraints.** Predation needs `feeding.enabled` and `ecology.health.enabled` (validated: a bite is damage and eating is biting). It is **off by default** and pinned off for `classic` and `clusters`; the field layout is where it will be turned on. diff --git a/docs/decisions/0026-diets.md b/docs/decisions/0026-diets.md index 3f6ea7f..0a07630 100644 --- a/docs/decisions/0026-diets.md +++ b/docs/decisions/0026-diets.md @@ -1,6 +1,6 @@ # ADR 0026: Diets, what a mouth can eat, three fixes and what hard diets did -Status: accepted. Follows [ADR 0017](0017-feeding.md) (mouth forms and the yield matrix), [ADR 0023](0023-predation.md) (carcasses, the jaw) and [ADR 0025](0025-place-memory.md) (the third null result in a row). +Status: accepted. **Update, same day:** the owner decided carcasses are the jaw's alone (comment on PR #143), so that one change is shipped with its measured cost (below); hard plant diets are not. Follows [ADR 0017](0017-feeding.md) (mouth forms and the yield matrix), [ADR 0023](0023-predation.md) (carcasses, the jaw) and [ADR 0025](0025-place-memory.md) (the third null result in a row). ## The owner's observation @@ -52,7 +52,9 @@ The criteria stated before the runs (jaw alive in at least 4 of 8 at 100,000 tic ## Decision -Keep the three fixes. Do not change the diet table. Carcasses stay edible by every form with their present yields until the owner decides whether the realism of jaw-only carrion is worth a population about 11 percent lower and a predator boom in some worlds (a one-line config change: `predation.carcass.yields` to 0 for the four non-jaw forms, measured above). +Keep the three fixes. **Carcasses are the jaw's alone** (the owner's call, made after seeing the numbers above): `predation.carcass.yields` is 0 for sprout, proboscis, mandible and radula and 1.2 for the jaw, so only a jaw bites a carcass or sees one as food. It is exactly the "carrion for the jaw only" variant measured above, so those numbers are the shipped behaviour: population about 11 percent lower (56.8 to 50.3 over 16 seeds x 30,000 ticks), the carrion share of intake 5.3 to 0.7 percent (the carcasses mostly rot), and a predator boom in some worlds (one of eight at 100,000 ticks: 21 of 29 creatures jaws); a jaw alive at the end in 2 of 8 worlds rather than 1 of 8, which is inside the noise. No plant diet table is shipped: hard plant diets raised extinction in every variant tried and nothing helped the jaw. The owner's other point, that predators need a second food source, is the next project (eggs and nests). + +**Goldens:** 4 more entries move (the predation worlds `predation-ecology-12k`, `-reflex-8k`, `-evolving-bodies-6k`, `-lush-4k`), regenerated in the commit that causes it; the rest do not touch a carcass. ## Limits diff --git a/docs/ecology/ecology.md b/docs/ecology/ecology.md index a5f8c68..70bde99 100644 --- a/docs/ecology/ecology.md +++ b/docs/ecology/ecology.md @@ -106,4 +106,4 @@ Measured (default world, 16 seeds x 30,000 ticks, against the same worlds with o ## Predation (ADR 0023) -With `predation.enabled` a mouth that can bite creatures (only the jaw by default) takes the nearer of the best food and the best creature in its cone: a creature that is not kin, alive, no bigger than `maxPreyRatio` times the biter, within reach and not behind a solid obstacle. A bite moves energy from the victim to the biter's gut at a trophic loss (energy is never created), damages the victim (its armor reduces it) and is remembered for a few seconds so that a victim that then starves or is worn down is counted as **killed by predation**. Every death leaves a **carcass**, a carrion food item worth part of the dead creature's energy and gut that mandibles, radulas and jaws eat well and sprouts hardly at all, so there are scavengers without any new mechanism. On by default since step two, and pinned off for Classic, Clusters and Fixed bodies. A creature **sees** the nearest creature it could bite (prey) and the nearest that could bite it (a threat), through the same eyes and cover as any peer (brain inputs 40 to 47, zero without predation), and its innate prior hunts and flees on those (so does the reflex controller). Carnivory does not take hold from mutation alone, so a world also **starts with a small hunter group** (`anatomy.startingBody.groups`, 10 percent of the founders, a jaw on the grazer's body). **The jaw eats meat only** (step three): its yield on every plant is 0, so it neither bites nor sees plants and lives on creatures and carrion (a future egg food kind is one more yield). In step two it was as good as the mandible on plants; over 100,000 ticks that made jaws omnivores that took over a world (35 of 36 creatures, 82 percent of the energy still from plants) and ate each other. Strict carnivory is a hard niche here: a jaw lineage is alive at 100,000 ticks in about 1 of 8 worlds, because hunters reproduce at about replacement level and a lineage of two to four founders drifts out, whatever the meat yield, bite size, tails or group size tried (ADR 0023). A 20 percent group made 1 to 3 of 16 worlds go extinct, so the default is 10. +With `predation.enabled` a mouth that can bite creatures (only the jaw by default) takes the nearer of the best food and the best creature in its cone: a creature that is not kin, alive, no bigger than `maxPreyRatio` times the biter, within reach and not behind a solid obstacle. A bite moves energy from the victim to the biter's gut at a trophic loss (energy is never created), damages the victim (its armor reduces it) and is remembered for a few seconds so that a victim that then starves or is worn down is counted as **killed by predation**. Every death leaves a **carcass**, a carrion food item worth part of the dead creature's energy and gut that **only a jaw eats** (ADR 0026: every other mouth form yields exactly 0, so it neither bites a carcass nor sees one; carcasses used to be eaten by mandibles, radulas and sprouts too, and jaws got 5 percent of them). On by default since step two, and pinned off for Classic, Clusters and Fixed bodies. A creature **sees** the nearest creature it could bite (prey) and the nearest that could bite it (a threat), through the same eyes and cover as any peer (brain inputs 40 to 47, zero without predation), and its innate prior hunts and flees on those (so does the reflex controller). Carnivory does not take hold from mutation alone, so a world also **starts with a small hunter group** (`anatomy.startingBody.groups`, 10 percent of the founders, a jaw on the grazer's body). **The jaw eats meat only** (step three): its yield on every plant is 0, so it neither bites nor sees plants and lives on creatures and carrion (a future egg food kind is one more yield). In step two it was as good as the mandible on plants; over 100,000 ticks that made jaws omnivores that took over a world (35 of 36 creatures, 82 percent of the energy still from plants) and ate each other. Strict carnivory is a hard niche here: a jaw lineage is alive at 100,000 ticks in about 1 of 8 worlds, because hunters reproduce at about replacement level and a lineage of two to four founders drifts out, whatever the meat yield, bite size, tails or group size tried (ADR 0023). A 20 percent group made 1 to 3 of 16 worlds go extinct, so the default is 10. diff --git a/docs/simulation/configuration.md b/docs/simulation/configuration.md index 034ad69..03fa62b 100644 --- a/docs/simulation/configuration.md +++ b/docs/simulation/configuration.md @@ -104,7 +104,7 @@ Units: time is in **seconds** (one tick advances time by `timestep`), distance i | `predation.biteDamage`, `.biteEnergy`, `.trophicYield`, `.maxPreyRatio`, `.attackWindow` | >= 0; > 0; (0, 1]; > 0; > 0 (seconds) | Health damage of a bite and energy a bite takes from the victim (both at the founder's gape, damage reduced by the victim's armor); the share of the energy taken that reaches the biter's gut (the rest is lost); the biggest prey as a multiple of the biter's body radius; how long after a bite a death by starvation or damage counts as predation | | `predation.fleshYield.
` | >= 0 each | What each mouth form yields from a creature; zero means that form never bites creatures (only the jaw is above zero by default) | | `predation.carcass.enabled`, `.energyFraction`, `.minEnergy`, `.lifespan`, `.maxCount`, `.radius`, `.hardness` | boolean; (0, 1]; >= 0; >= 0 (seconds, 0 never rots); integer >= 0; > 0; > 0 | What a dead creature leaves where it died: a carrion food item worth this share of its energy and gut if at least `minEnergy`, up to `maxCount` on the field. With predation on, a `carrion` food kind is appended to the resource kinds (it never spawns by itself) | -| `predation.carcass.yields.` | >= 0 each | What each mouth form yields from a carcass, per unit bitten; 0 means the form neither bites nor sees carcasses (ADR 0026) | +| `predation.carcass.yields.` | >= 0 each | What each mouth form yields from a carcass, per unit bitten; 0 means the form neither bites nor sees carcasses. Default: **the jaw only (1.2)**, every other form 0 (ADR 0026); before that every form had a positive yield and jaws got 5 percent of the carrion | | `perception.organismsBlockSight`, `perception.maxSightChecks` | boolean; whole number >= 1 | `true` (default): another creature's body hides what is behind it from a viewer, for food and for other creatures; at most this many candidates are checked for something in the way (ADR 0019). `false` is the transparent world of Phase 3 (the Classic preset). | | `ecology.resourceKinds.kinds[].hardness` | > 0, default 1 | How many times harder than the baseline a kind is to bite: a bite takes `biteSize / hardness` | | `anatomy.founderOutline`, `anatomy.outlineDrag` | outline: count 5-16, 16 radii 0.35-1, 16 angles 0-1; >= 0 | The outline every founder starts with, and the extra movement cost per unit of outline roughness above the founder's (ADR 0013); size and drag factors are exactly 1 for the founder outline | diff --git a/packages/config/src/defaults.ts b/packages/config/src/defaults.ts index 9371b13..5f79dd4 100644 --- a/packages/config/src/defaults.ts +++ b/packages/config/src/defaults.ts @@ -420,6 +420,8 @@ export const DEFAULT_WORLD_CONFIG: Readonly = deepFreeze({ maxCount: 40, radius: 4, hardness: 1, + // Meat is the jaw's alone (ADR 0026, the owner's decision): every other mouth form yields exactly 0, so + // it neither bites a carcass nor sees one. It used to be eaten by everyone (jaws got 5 percent of it). yields: { sprout: 0, proboscis: 0, mandible: 0, radula: 0, jaw: 1.2 } } }, diff --git a/packages/simulation/tests/golden/state-hashes.json b/packages/simulation/tests/golden/state-hashes.json index fa8a175..d7cd63c 100644 --- a/packages/simulation/tests/golden/state-hashes.json +++ b/packages/simulation/tests/golden/state-hashes.json @@ -1347,14 +1347,14 @@ "seed": 7, "config": {}, "steps": 12000, - "expectedHash": "82a71ca77694b5cebe72b80fa1779218" + "expectedHash": "bb5365f32f6cf4ad304b19661013b54c" }, { "name": "predation-reflex-8k", "seed": 3, "config": { "learning": { "controller": "reflex" } }, "steps": 8000, - "expectedHash": "77f609256b658658dc66011fadae2aba" + "expectedHash": "ba847deb2c907ffb8c997675e16f2853" }, { "name": "predation-evolving-bodies-6k", @@ -1371,7 +1371,7 @@ "genetics": { "mutationRateScale": 3 } }, "steps": 6000, - "expectedHash": "24b72f1bbbc816e9aa563ecfcb0ee4ab" + "expectedHash": "ff6ecdeb75b3cb03edb09189d52a284d" }, { "name": "predation-lush-4k", @@ -1384,7 +1384,7 @@ } }, "steps": 4000, - "expectedHash": "551cf78d35dcb3cf05c3be08232ced5d" + "expectedHash": "7d816aed7cbf721448662cbb54803ec7" }, { "name": "predation-hunters-only-3k", diff --git a/packages/simulation/tests/predation/carnivore.test.ts b/packages/simulation/tests/predation/carnivore.test.ts index 9f70571..6d81e05 100644 --- a/packages/simulation/tests/predation/carnivore.test.ts +++ b/packages/simulation/tests/predation/carnivore.test.ts @@ -105,6 +105,14 @@ describe('what a mouth bites', () => { expect(events.eventsThisTick().some((e) => e.type === 'resource-bitten')).toBe(true) }) + it("a mandible does not bite carrion: a carcass is the jaw's alone (ADR 0026)", () => { + const cfg = config() + const { organism, food, events } = eat(false, carrionOf(cfg)) + expect(food.remaining).toBe(30) + expect(organism.gut).toBe(0) + expect(events.eventsThisTick().some((e) => e.type === 'resource-bitten')).toBe(false) + }) + it('a mandible still bites the same plant (negative: only the jaw changed)', () => { const { organism, food } = eat(false, GRASS) expect(food.remaining).toBeLessThan(30) @@ -138,7 +146,7 @@ describe('what a creature sees as food', () => { } it.each([false, true])( - 'a jaw sees carrion while a mandible sees plants but not carrion (occluding search: %s)', + 'a jaw sees carrion and not a plant; a mandible sees a plant and not carrion (occluding search: %s)', (occluding) => { const carrion = carrionOf(config()) expect(see(true, GRASS, occluding)).toBeNull() diff --git a/packages/simulation/tests/predation/death-and-carcass.test.ts b/packages/simulation/tests/predation/death-and-carcass.test.ts index 1bab726..f117451 100644 --- a/packages/simulation/tests/predation/death-and-carcass.test.ts +++ b/packages/simulation/tests/predation/death-and-carcass.test.ts @@ -224,12 +224,19 @@ describe('carcasses', () => { expect(withCarrion(noKinds)).toBe(noKinds) }) - it('makes a mandible get no carcass yield while jaws keep a positive yield', () => { + it("makes a carcass the jaw's alone: every other form yields exactly 0 (ADR 0026)", () => { const cfg = full() const kind = cfg.ecology.resourceKinds.kinds.length - 1 + for (const form of ['sprout', 'proboscis', 'mandible', 'radula'] as const) { + expect(cfg.anatomy.mouthForms[form][CARRION_KIND]).toBe(0) + } + expect(cfg.anatomy.mouthForms.jaw[CARRION_KIND]).toBeGreaterThan(0) + // the founder is a mandible: it digests nothing from a carcass const founder = organismFor(cfg, 1) - expect(factorsOf(founder.genome, cfg).dietEfficiency[kind]).toBeCloseTo(0, 9) - expect(cfg.predation.carcass.yields.jaw).toBeGreaterThan(0) + expect(factorsOf(founder.genome, cfg).dietEfficiency[kind]).toBe(0) + // negative: the old table (a mandible at 0.8) is still expressible and gives the old yield + const old = full({ predation: { carcass: { yields: { mandible: 0.8 } } } }) + expect(factorsOf(founder.genome, old).dietEfficiency[kind]).toBeCloseTo(0.8, 9) }) function carcasses(extra: WorldConfigOverrides = {}) { diff --git a/packages/simulation/tests/support/ecology-stability.ts b/packages/simulation/tests/support/ecology-stability.ts index 6a1e8f9..166e0e5 100644 --- a/packages/simulation/tests/support/ecology-stability.ts +++ b/packages/simulation/tests/support/ecology-stability.ts @@ -26,6 +26,11 @@ import { World } from '../../src/index' * means are 43.0-81.5, minimum 16, maximum 123, and no world went extinct. Only the ceiling * moved: 110 became 140 (it was 87 and 85 before bites and plants), still a seventh of * `maxPopulation`; means and the floor of 15 are as they were. + * + * Carcasses for the jaw alone (ADR 0026, the owner's decision) take the carrion energy away from the + * herbivores that were eating it (5 percent of all intake): over these 12 seeds (5-8 and 33-40, same + * sampling) means are 37.7-77.2, minimum 10 (seed 6; the next lowest is 17), maximum 118, and no world + * went extinct. The floor moved from 15 to 8; means and the ceiling hold. */ export function describeStability(seeds: readonly number[]): void { describe('the default ecology keeps held-out worlds alive', () => { @@ -42,7 +47,7 @@ export function describeStability(seeds: readonly number[]): void { expect(world.isExtinct).toBe(false) expect(mean).toBeGreaterThan(25) expect(mean).toBeLessThan(90) - expect(Math.min(...samples)).toBeGreaterThanOrEqual(15) + expect(Math.min(...samples)).toBeGreaterThanOrEqual(8) expect(Math.max(...samples)).toBeLessThanOrEqual(140) expect(world.validate()).toEqual({ ok: true, errors: [] }) // the ecology was actually in play From 6ec0574623dfa040a5da5731569e69160651d3b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 19:07:48 +0000 Subject: [PATCH 02/11] feat(life-cycle): sexes, carried clutches, eggs and hatching behind switches, hash schema 13 (ADR 0027) Two sexes (founders alternate, a newborn's sex is one reproduction draw), a female carries a conceived clutch for reproduction.eggs.incubation and pays carryCost, lays an egg, and the egg hatches after reproduction.eggs.hatch into a creature that keeps the stored genome, parents and the mother's species. Eggs and clutches count against maxPopulation; a carrying mother who dies loses the clutch (clutch-lost). Everything is off by default: sexes.enabled and eggs.enabled false take the old code path exactly. Hash schema 13 appends the egg counters, each creature's sex and carried clutch and the egg store after the version 12 tail. Switch-off proof: nine scenarios (field, instant eating, noise food, clusters, one cluster, lush, no predation, no ecology, reflex) with founder brains equal to the prior and mutation frozen give snapshots, events and records identical to the previous commit; the header and sample digests match the independent Python hasher. All 50 golden entries regenerated here only (the header carries the new version). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Cn5qp4xBHxLnTrwReNXcf8 --- docs/simulation/determinism.md | 10 +- packages/config/src/defaults.ts | 13 +- packages/config/src/validation.ts | 49 +++- packages/contracts/src/events.ts | 50 ++++ packages/contracts/src/index.ts | 9 + packages/contracts/src/snapshots.ts | 25 ++ packages/contracts/src/world.ts | 37 ++- packages/contracts/tests/contracts.test.ts | 11 +- .../tests/pick-colors-snapshot.test.ts | 30 +- packages/simulation/src/entities/EggStore.ts | 55 ++++ .../simulation/src/entities/OrganismStore.ts | 19 ++ .../src/metrics/MetricsCollector.ts | 25 +- .../src/organisms/reproductionReadiness.ts | 6 +- packages/simulation/src/serialization/hash.ts | 2 +- .../simulation/src/species/SpeciesRegistry.ts | 13 +- packages/simulation/src/systems/EggSystem.ts | 141 +++++++++ .../src/systems/MetabolismSystem.ts | 5 +- .../src/systems/ReproductionSystem.ts | 59 +++- packages/simulation/src/world/World.ts | 146 +++++++-- packages/simulation/src/world/invariants.ts | 51 ++++ .../simulation/tests/golden/state-hashes.json | 102 +++---- packages/simulation/tests/hash-clock.test.ts | 8 +- packages/simulation/tests/invariants.test.ts | 7 +- .../tests/lifecycle/lifecycle.test.ts | 277 ++++++++++++++++++ packages/simulation/tests/metrics.test.ts | 18 +- packages/simulation/tests/support/organism.ts | 2 + packages/ui/tests/support/fixtures.ts | 6 +- 27 files changed, 1065 insertions(+), 111 deletions(-) create mode 100644 packages/simulation/src/entities/EggStore.ts create mode 100644 packages/simulation/src/systems/EggSystem.ts create mode 100644 packages/simulation/tests/lifecycle/lifecycle.test.ts diff --git a/docs/simulation/determinism.md b/docs/simulation/determinism.md index 29eaf13..44d610b 100644 --- a/docs/simulation/determinism.md +++ b/docs/simulation/determinism.md @@ -207,6 +207,10 @@ Introduced with renewable plants (ADR 0021). Each resource's record gains four v Introduced with the prey and threat senses (ADR 0023, step two). The metrics section gains two counters, appended after the two remainders of section 12: `deathsByPredation` (u32) and `predationBites` (u32), both zero for ever without predation. The brain gets eight more inputs (`OBSERVATION_SIZE` 48) so every genome carries 514 weights instead of 450 (the hash covers weights as they are), and because founders draw one normal per weight from the `genetics` stream, **every founder's brain draws shift**: every golden entry regenerated (44 of 44 changed, in the commit that caused it). The header carries the new version. A byte-identical switch-off proof is therefore impossible (the brains differ); what was shown instead is that the new inputs are zero without predation, that the reflex controller is untouched (scenario A moved only through the mutation draws that follow the founders' extra ones, 29 / 47 / 18 to 28 / 46 / 18), and that the vectors below were recomputed with the independent Python hasher, which reproduced the version 11 values first. +#### Version 13 (current, the life cycle) + +Introduced with sexes, incubation and eggs (ADR 0027). Everything in version 12 is unchanged and a tail is appended after its predation counters: the four egg counters `eggsLaid`, `eggsHatched`, `eggsEaten`, `clutchesLost` (u32 each); then for every organism in ascending id order its `sex` (u8, `0` female, `1` male) and a boolean for a carried clutch followed, when carrying, by the clutch (the child's genome written exactly as an organism's is: ids, gene vector, brain, body genes; then the father's id u32, a boolean and u32 for the mother's species at conception, the egg's energy f64 and the lay tick f64); then the egg count (u32) and each egg in ascending id order (id u32, x f64, y f64, mother id u32, father id u32, species boolean and u32, energy f64, lay tick f64, hatch tick f64, then its genome). With sexes and eggs off the tail is four zero counters, a `0` and a `false` per organism and an egg count of zero, and the state before the tail is bit for bit the version 12 state. The header carries the new version, so every golden entry's hash moves (regenerated in the commit that caused it); the proof that nothing else moved is the equivalence harness: nine scenarios (field, instant eating, noise food, clusters, one cluster, lush, no predation, no ecology, the reflex controller) with founder brains equal to the prior and mutation frozen gave normalized snapshots, events and records **identical** to the previous commit through births and deaths with the life cycle off. The header and sample vectors below were recomputed with the independent Python hasher. + `WorldConfig` is **not** part of the hash; golden tests pin their config explicitly. Fields for later phases are appended as new sections or new fields with a version bump. ## 8. State identity versus the event log @@ -248,9 +252,9 @@ These are computed from the spec above with a reference script and must be repro | Input | `stateHash`-style output | | ---------------------------------------------------------------------------------- | ---------------------------------- | | no bytes | `027ae52ecfc796215593990d4b41437c` | -| header only: `"EVOH"`, `writeUint32(12)` | `d49b1e0b9a8a18f330c42958c075e1a5` | -| header, `writeUint32(7)`, `writeFloat64(-0)`, `writeFloat64(0.5)`, `writeUint8(1)` | `fa1c4aa87cacbdd6959a759e55fd84da` | -| same as above with `writeFloat64(+0)` instead of `-0` (proves canonicalization) | `fa1c4aa87cacbdd6959a759e55fd84da` | +| header only: `"EVOH"`, `writeUint32(13)` | `587210918be484b597a2acfc1f3e30d3` | +| header, `writeUint32(7)`, `writeFloat64(-0)`, `writeFloat64(0.5)`, `writeUint8(1)` | `a92127630cc9776a9793f49801069c1f` | +| same as above with `writeFloat64(+0)` instead of `-0` (proves canonicalization) | `a92127630cc9776a9793f49801069c1f` | **`normal()`** (depends on the engine's `ln`; values are exact binary64 results, shown in shortest round-trip form): diff --git a/packages/config/src/defaults.ts b/packages/config/src/defaults.ts index 5f79dd4..760a572 100644 --- a/packages/config/src/defaults.ts +++ b/packages/config/src/defaults.ts @@ -97,7 +97,18 @@ export const DEFAULT_WORLD_CONFIG: Readonly = deepFreeze({ overheadFraction: 0.6, cooldown: 45, searchRadius: 50, - mateSenseRadius: 250 + mateSenseRadius: 250, + // Off here; the life cycle (ADR 0027) is switched on in the measured commit. + sexes: { enabled: false }, + eggs: { + enabled: false, + incubation: 10, + hatch: 20, + carryCost: 0.1, + guardRadius: 20, + guardCost: 0.05, + guardDamage: 5 + } }, history: { maxEvents: 10_000, eventDetail: 'essential', maxHistoricalOrganisms: 10_000 }, // The evolution observatory (ADR 0024): derived indicators, sampled every 50 simulated seconds. diff --git a/packages/config/src/validation.ts b/packages/config/src/validation.ts index e4d3b21..b828299 100644 --- a/packages/config/src/validation.ts +++ b/packages/config/src/validation.ts @@ -85,13 +85,25 @@ const PLANT_KEYS = [ 'lifespan', 'maxPlants' ] +const SEXES_KEYS = ['enabled'] +const EGGS_KEYS = [ + 'enabled', + 'incubation', + 'hatch', + 'carryCost', + 'guardRadius', + 'guardCost', + 'guardDamage' +] const REPRODUCTION_KEYS = [ 'minEnergy', 'offspringInvestment', 'overheadFraction', 'cooldown', 'searchRadius', - 'mateSenseRadius' + 'mateSenseRadius', + 'sexes', + 'eggs' ] const HISTORY_KEYS = ['maxEvents', 'eventDetail', 'maxHistoricalOrganisms'] const OBSERVATORY_KEYS = ['enabled', 'sampleEvery', 'behaviourEvery', 'maxSamples'] @@ -356,6 +368,27 @@ export function validateWorldConfig(value: unknown): ValidationResult { { positive: true }, errors ) + const sexes = checkSection(reproduction, 'sexes', SEXES_KEYS, errors, 'reproduction.sexes') + if (sexes && typeof sexes['enabled'] !== 'boolean') { + errors.push('reproduction.sexes.enabled must be a boolean') + } + const eggs = checkSection(reproduction, 'eggs', EGGS_KEYS, errors, 'reproduction.eggs') + if (eggs) { + if (typeof eggs['enabled'] !== 'boolean') { + errors.push('reproduction.eggs.enabled must be a boolean') + } + for (const key of ['incubation', 'hatch', 'guardRadius'] as const) { + checkNumber(eggs, key, `reproduction.eggs.${key}`, { positive: true }, errors) + } + for (const key of ['carryCost', 'guardCost', 'guardDamage'] as const) { + checkNumber(eggs, key, `reproduction.eggs.${key}`, { nonnegative: true }, errors) + } + if (eggs['enabled'] === true && sexes && sexes['enabled'] !== true) { + errors.push( + 'reproduction.eggs.enabled requires reproduction.sexes.enabled (the female lays)' + ) + } + } if ( investment !== undefined && @@ -613,6 +646,18 @@ function mergeEnvironment(base: object, override: unknown): unknown { } } +/** Merges the reproduction section: `sexes` and `eggs` merge field by field. */ +function mergeReproduction(base: object, override: unknown): unknown { + if (override === undefined || !isObject(override)) return mergeSection(base, override) + const defaults = base as Record + return { + ...base, + ...override, + sexes: mergeSection(defaults['sexes'] as object, override['sexes']), + eggs: mergeSection(defaults['eggs'] as object, override['eggs']) + } +} + /** Merges a table of named sections, keeping unknown names so validation can report them. */ function mergeNamed(base: Record, override: Record): unknown { const result: Record = { ...base } @@ -645,7 +690,7 @@ export function resolveWorldConfig(overrides?: WorldConfigOverrides): WorldConfi environment: mergeEnvironment(base.environment, given['environment']), organisms: mergeSection(base.organisms, given['organisms']), resources: mergeResources(base.resources, given['resources']), - reproduction: mergeSection(base.reproduction, given['reproduction']), + reproduction: mergeReproduction(base.reproduction, given['reproduction']), history: mergeSection(base.history, given['history']), observatory: mergeSection(base.observatory, given['observatory']), genetics: mergeGenetics(base.genetics, given['genetics']), diff --git a/packages/contracts/src/events.ts b/packages/contracts/src/events.ts index 1cb6196..1c20ca3 100644 --- a/packages/contracts/src/events.ts +++ b/packages/contracts/src/events.ts @@ -21,6 +21,51 @@ export interface OrganismBornEvent extends BaseEvent { readonly position: Readonly } +/** A female laid an egg (ADR 0027). The clutch was conceived `incubation` seconds earlier. */ +export interface EggLaidEvent extends BaseEvent { + readonly type: 'egg-laid' + readonly eggId: EntityId + readonly motherId: EntityId + readonly fatherId: EntityId + readonly position: Readonly +} + +/** An egg hatched; the new creature also gets an `organism-born` event (ADR 0027). */ +export interface EggHatchedEvent extends BaseEvent { + readonly type: 'egg-hatched' + readonly eggId: EntityId + readonly organismId: EntityId + readonly motherId: EntityId + readonly fatherId: EntityId +} + +/** A carrying female died before she laid: the clutch and its energy are lost (ADR 0027). */ +export interface ClutchLostEvent extends BaseEvent { + readonly type: 'clutch-lost' + readonly motherId: EntityId + readonly fatherId: EntityId +} + +/** A mouth took an egg (ADR 0027): the egg is gone and its energy went to the biter's gut. */ +export interface EggEatenEvent extends BaseEvent { + readonly type: 'egg-eaten' + readonly eggId: EntityId + readonly predatorId: EntityId + /** The egg's stored energy. */ + readonly energyTaken: number + /** Energy that entered the gut. */ + readonly intake: number +} + +/** A parent defended its egg: the biter lost health and the egg was left alone (ADR 0027). */ +export interface EggGuardedEvent extends BaseEvent { + readonly type: 'egg-guarded' + readonly eggId: EntityId + readonly guardId: EntityId + readonly biterId: EntityId + readonly damage: number +} + export interface OrganismDiedEvent extends BaseEvent { readonly type: 'organism-died' readonly organismId: EntityId @@ -155,6 +200,11 @@ export interface HazardExpiredEvent extends BaseEvent { export type WorldEvent = | OrganismBornEvent | OrganismDiedEvent + | EggLaidEvent + | EggHatchedEvent + | ClutchLostEvent + | EggEatenEvent + | EggGuardedEvent | ResourceSpawnedEvent | ResourceBittenEvent | OrganismBittenEvent diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 7a28ffc..5ef188a 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -100,6 +100,9 @@ export type { PredationConfig, PerceptionConfig, ReproductionConfig, + ReproductionConfigOverrides, + SexesConfig, + EggsConfig, HistoryConfig, ObservatoryConfig, WorldConfig, @@ -109,6 +112,11 @@ export type { export type { OrganismBornEvent, OrganismDiedEvent, + EggLaidEvent, + EggHatchedEvent, + ClutchLostEvent, + EggEatenEvent, + EggGuardedEvent, ResourceSpawnedEvent, ResourceBittenEvent, OrganismBittenEvent, @@ -126,6 +134,7 @@ export type { WorldEventType } from './events' export type { + EggSnapshot, OrganismSnapshot, PartSnapshot, ResourceSnapshot, diff --git a/packages/contracts/src/snapshots.ts b/packages/contracts/src/snapshots.ts index e196231..d90480d 100644 --- a/packages/contracts/src/snapshots.ts +++ b/packages/contracts/src/snapshots.ts @@ -76,6 +76,24 @@ export interface OrganismSnapshot { readonly gut: number /** Gut capacity of this organism's body; zero when feeding is off. */ readonly gutCapacity: number + /** `0` female, `1` male; always `0` with `reproduction.sexes` off (ADR 0027). */ + readonly sex: 0 | 1 + /** Seconds until the carried clutch is laid, or `null` when not carrying (ADR 0027). */ + readonly carrying: number | null +} + +/** An egg in the world (ADR 0027). */ +export interface EggSnapshot { + readonly id: EntityId + readonly position: Readonly + readonly motherId: EntityId + readonly fatherId: EntityId + /** Energy stored in the egg. */ + readonly energy: number + /** Fraction of the way to hatching, in `[0, 1]`. */ + readonly progress: number + /** Whether a living parent is within `guardRadius` of it right now. */ + readonly guarded: boolean } /** A compact, retained record of an organism after it dies (docs/decisions/0005). */ @@ -137,6 +155,11 @@ export interface MetricsSnapshot { readonly energyWasted: number /** Total health lost to hazards and toxins. */ readonly damageTaken: number + /** Eggs laid, hatched, eaten, and clutches lost with a carrying mother (ADR 0027). */ + readonly eggsLaid: number + readonly eggsHatched: number + readonly eggsEaten: number + readonly clutchesLost: number } /** A read-only, deep-copied view of a world. Presentation layers consume this, never live state. */ @@ -151,5 +174,7 @@ export interface WorldSnapshot { readonly resources: readonly ResourceSnapshot[] /** Ascending id order. */ readonly hazards: readonly HazardSnapshot[] + /** Ascending id order; empty unless `reproduction.eggs` is on (ADR 0027). */ + readonly eggs: readonly EggSnapshot[] readonly metrics: MetricsSnapshot } diff --git a/packages/contracts/src/world.ts b/packages/contracts/src/world.ts index 43c77e8..01ab356 100644 --- a/packages/contracts/src/world.ts +++ b/packages/contracts/src/world.ts @@ -292,6 +292,41 @@ export interface ReproductionConfig { * mating signal, longer than the sensor radius; brain controller only, ADR 0010). */ mateSenseRadius: number + /** Two sexes: only a female and a male mate (ADR 0027). Off: any two ready creatures may. */ + sexes: SexesConfig + /** Incubation, eggs and guarding (ADR 0027). Off: a child is born at conception, as before. */ + eggs: EggsConfig +} + +/** Two sexes (ADR 0027). A newborn's sex is one draw from the `reproduction` stream; founders alternate. */ +export interface SexesConfig { + enabled: boolean +} + +/** + * A pregnancy and an egg instead of an instant birth (ADR 0027). Needs `sexes.enabled`: the female + * carries the clutch, lays an egg, and the egg hatches into a creature after `hatch`. + */ +export interface EggsConfig { + enabled: boolean + /** Seconds a female carries the clutch before laying. */ + incubation: number + /** Seconds an egg takes to hatch after it is laid. */ + hatch: number + /** Energy per second a carrying female pays on top of her metabolism. */ + carryCost: number + /** A living parent within this distance of its egg guards it (ADR 0027). */ + guardRadius: number + /** Energy per second a guarding parent pays, per guarded egg. */ + guardCost: number + /** Health a biter loses when a guarded egg is defended. */ + guardDamage: number +} + +/** A partial reproduction section merged onto the defaults. */ +export type ReproductionConfigOverrides = Partial> & { + sexes?: Partial + eggs?: Partial } export interface HistoryConfig { @@ -347,7 +382,7 @@ export interface WorldConfigOverrides { environment?: EnvironmentConfigOverrides organisms?: Partial resources?: ResourceConfigOverrides - reproduction?: Partial + reproduction?: ReproductionConfigOverrides history?: Partial observatory?: Partial genetics?: GeneticsConfigOverrides diff --git a/packages/contracts/tests/contracts.test.ts b/packages/contracts/tests/contracts.test.ts index 2f2f758..f59ddb9 100644 --- a/packages/contracts/tests/contracts.test.ts +++ b/packages/contracts/tests/contracts.test.ts @@ -39,6 +39,13 @@ function describeEvent(event: WorldEvent): string { return `hazard ${event.hazardId}` case 'hazard-expired': return `expired ${event.hazardId}` + case 'egg-laid': + case 'egg-hatched': + case 'egg-eaten': + case 'egg-guarded': + return `egg ${event.eggId}` + case 'clutch-lost': + return `clutch lost ${event.motherId}` default: { const unreachable: never = event return unreachable @@ -155,7 +162,9 @@ describe('contracts', () => { lifeStage: 'mature', reproductionCooldownRemaining: 0, gut: 0, - gutCapacity: 0 + gutCapacity: 0, + sex: 0, + carrying: null } const keys = Object.keys(snapshot) for (const forbidden of ['generation', 'genome', 'alive']) { diff --git a/packages/renderer/tests/pick-colors-snapshot.test.ts b/packages/renderer/tests/pick-colors-snapshot.test.ts index 8dbd3c3..45d02d0 100644 --- a/packages/renderer/tests/pick-colors-snapshot.test.ts +++ b/packages/renderer/tests/pick-colors-snapshot.test.ts @@ -145,7 +145,9 @@ describe('buildRenderSnapshot', () => { lifeStage: 'juvenile', reproductionCooldownRemaining: 0, gut: 0, - gutCapacity: 0 + gutCapacity: 0, + sex: 0, + carrying: null }, { id: 2, @@ -170,7 +172,9 @@ describe('buildRenderSnapshot', () => { lifeStage: 'mature', reproductionCooldownRemaining: 0, gut: 0, - gutCapacity: 0 + gutCapacity: 0, + sex: 0, + carrying: null } ], resources: [ @@ -193,6 +197,7 @@ describe('buildRenderSnapshot', () => { expiresAtTick: 100 } ], + eggs: [], metrics: { organismsBorn: 0, deathsByStarvation: 0, @@ -207,7 +212,11 @@ describe('buildRenderSnapshot', () => { reproductionFailures: 0, energyConsumed: 0, energyWasted: 0, - damageTaken: 0 + damageTaken: 0, + eggsLaid: 0, + eggsHatched: 0, + eggsEaten: 0, + clutchesLost: 0 } } @@ -346,11 +355,14 @@ describe('buildRenderSnapshot body data', () => { lifeStage: 'mature', reproductionCooldownRemaining: 0, gut: 0, - gutCapacity: 0 + gutCapacity: 0, + sex: 0, + carrying: null } ], resources: [], hazards: [], + eggs: [], metrics: {} as never }, { worldWidth: 500, worldHeight: 500, season: null, selectedId: null } @@ -394,11 +406,14 @@ describe('speedRatio', () => { lifeStage: 'mature', reproductionCooldownRemaining: 0, gut: 0, - gutCapacity: 0 + gutCapacity: 0, + sex: 0, + carrying: null } ], resources: [], hazards: [], + eggs: [], metrics: {} as never }, { @@ -456,11 +471,14 @@ describe('colorByHue', () => { lifeStage: 'mature' as const, reproductionCooldownRemaining: 0, gut: 0, - gutCapacity: 0 + gutCapacity: 0, + sex: 0 as const, + carrying: null } ], resources: [], hazards: [], + eggs: [], metrics: {} as never } const context = { worldWidth: 1, worldHeight: 1, season: null, selectedId: null } diff --git a/packages/simulation/src/entities/EggStore.ts b/packages/simulation/src/entities/EggStore.ts new file mode 100644 index 0000000..374c9db --- /dev/null +++ b/packages/simulation/src/entities/EggStore.ts @@ -0,0 +1,55 @@ +import type { EntityId, Genome } from '@evo/contracts' + +/** An egg lying in the world (ADR 0027): a child that has not hatched yet. */ +export interface EggState { + readonly id: EntityId + readonly x: number + readonly y: number + /** The child's genome, recombined at conception. */ + readonly genome: Genome + readonly motherId: EntityId + readonly fatherId: EntityId + /** The mother's species at conception (she may be dead when it hatches). */ + readonly speciesId: number | null + /** Energy stored in the egg; the newborn starts with it. */ + readonly energy: number + readonly layTick: number + readonly hatchTick: number +} + +/** + * Holds the eggs. Same ascending-id-order contract as `OrganismStore`: ids come from the shared + * `IdGenerator` in laying order, so a `Map`'s insertion order is ascending id order. + */ +export class EggStore { + private readonly byId = new Map() + private maxId: EntityId | null = null + + add(egg: EggState): void { + if (this.byId.has(egg.id)) throw new RangeError(`egg id ${egg.id} already exists`) + if (this.maxId !== null && egg.id <= this.maxId) { + throw new RangeError( + `egg id ${egg.id} is not greater than the highest id added so far (${this.maxId})` + ) + } + this.maxId = egg.id + this.byId.set(egg.id, egg) + } + + get(id: EntityId): EggState | undefined { + return this.byId.get(id) + } + + remove(id: EntityId): boolean { + return this.byId.delete(id) + } + + get size(): number { + return this.byId.size + } + + /** A fresh array of the eggs in ascending id order. */ + values(): EggState[] { + return Array.from(this.byId.values()) + } +} diff --git a/packages/simulation/src/entities/OrganismStore.ts b/packages/simulation/src/entities/OrganismStore.ts index a49443c..5cf73c0 100644 --- a/packages/simulation/src/entities/OrganismStore.ts +++ b/packages/simulation/src/entities/OrganismStore.ts @@ -1,6 +1,21 @@ import type { EntityId, Genome } from '@evo/contracts' import type { BrainState } from '../learning/BrainState' +/** + * A clutch a female is carrying (ADR 0027): the child's genome was recombined at conception, so + * what hatches is fixed from the moment the pair mated. Lost with the mother if she dies first. + */ +export interface PregnancyState { + readonly genome: Genome + readonly fatherId: EntityId + /** The mother's species at conception, kept for the child because she may be dead by then. */ + readonly speciesId: number | null + /** Energy the egg will hold: what the parents invested, capped by the child's capacity. */ + readonly energy: number + /** The tick the egg is laid. */ + readonly layTick: number +} + /** Live, mutable organism state. Systems mutate these fields directly through `values()`. */ export interface OrganismState { readonly id: EntityId @@ -28,6 +43,10 @@ export interface OrganismState { * under `'reflex'`. The genome stays immutable; learning moves the overlay in here. */ brain: BrainState | null + /** `0` female, `1` male (ADR 0027); always `0` with `reproduction.sexes` off. */ + readonly sex: 0 | 1 + /** The clutch being carried; `null` for males, and for a female who is not pregnant. */ + pregnancy: PregnancyState | null } /** diff --git a/packages/simulation/src/metrics/MetricsCollector.ts b/packages/simulation/src/metrics/MetricsCollector.ts index 8b00031..86e16c1 100644 --- a/packages/simulation/src/metrics/MetricsCollector.ts +++ b/packages/simulation/src/metrics/MetricsCollector.ts @@ -20,6 +20,10 @@ export class MetricsCollector { private energyConsumed = 0 private energyWasted = 0 private damageTaken = 0 + private eggsLaid = 0 + private eggsHatched = 0 + private eggsEaten = 0 + private clutchesLost = 0 private extinctTick: number | null = null /** Folds one tick's events into the running counters. */ @@ -75,6 +79,21 @@ export class MetricsCollector { case 'organism-damaged': this.damageTaken += event.amount break + case 'egg-laid': + this.eggsLaid += 1 + break + case 'egg-hatched': + this.eggsHatched += 1 + break + case 'egg-eaten': + this.eggsEaten += 1 + this.energyConsumed += event.intake + this.energyWasted += Math.max(0, event.energyTaken - event.intake) + break + case 'clutch-lost': + this.clutchesLost += 1 + break + case 'egg-guarded': case 'organism-moved': case 'energy-changed': case 'season-changed': @@ -116,7 +135,11 @@ export class MetricsCollector { reproductionFailures: this.reproductionFailures, energyConsumed: this.energyConsumed, energyWasted: this.energyWasted, - damageTaken: this.damageTaken + damageTaken: this.damageTaken, + eggsLaid: this.eggsLaid, + eggsHatched: this.eggsHatched, + eggsEaten: this.eggsEaten, + clutchesLost: this.clutchesLost } } } diff --git a/packages/simulation/src/organisms/reproductionReadiness.ts b/packages/simulation/src/organisms/reproductionReadiness.ts index 266535c..8bc1561 100644 --- a/packages/simulation/src/organisms/reproductionReadiness.ts +++ b/packages/simulation/src/organisms/reproductionReadiness.ts @@ -40,9 +40,13 @@ export class ReproductionReadiness { return Math.max(organism.genome.reproduction.minEnergy, this.costFor(organism, tick)) } - /** Mature, off cooldown and holding at least the threshold: able to attempt (or to be a partner). */ + /** + * Mature, off cooldown and holding at least the threshold: able to attempt (or to be a partner). + * A female carrying a clutch is not (ADR 0027). + */ isReady(organism: OrganismState, tick: number): boolean { return ( + organism.pregnancy === null && lifeStageFor(organism.age, organism.genome.physical) !== 'juvenile' && organism.reproductionCooldownRemaining <= 0 && organism.energy >= this.thresholdFor(organism, tick) diff --git a/packages/simulation/src/serialization/hash.ts b/packages/simulation/src/serialization/hash.ts index e05fbd9..ba3f64f 100644 --- a/packages/simulation/src/serialization/hash.ts +++ b/packages/simulation/src/serialization/hash.ts @@ -4,7 +4,7 @@ import { utf8Encode } from './utf8' * Version of the canonical state-hash layout (determinism.md, section 7.3). Any change to the * field list, order, or encoding requires bumping this and regenerating the golden hashes. */ -export const HASH_SCHEMA_VERSION = 12 +export const HASH_SCHEMA_VERSION = 13 const HEADER_MAGIC = 'EVOH' diff --git a/packages/simulation/src/species/SpeciesRegistry.ts b/packages/simulation/src/species/SpeciesRegistry.ts index add1721..691f9b3 100644 --- a/packages/simulation/src/species/SpeciesRegistry.ts +++ b/packages/simulation/src/species/SpeciesRegistry.ts @@ -45,6 +45,11 @@ export interface SpeciesAssignment { genome: Genome /** The organism whose species the new species descends from if one is founded (the mother). */ parentOrganismId: EntityId | null + /** + * The species the mother belonged to when the child was conceived (ADR 0027): an egg may hatch + * after she has died, so her species is carried here instead of looked up. Absent: looked up. + */ + parentSpeciesId?: SpeciesId | null tick: number /** * Founders of the cluster layout name the species they belong to (docs/decisions/0014): the @@ -153,9 +158,11 @@ export class SpeciesRegistry implements SpeciesQueries, SpeciesTracker { species = nearest } else { const parentSpecies = - request.parentOrganismId === null - ? undefined - : this.speciesByOrganism.get(request.parentOrganismId) + request.parentSpeciesId !== undefined + ? (request.parentSpeciesId ?? undefined) + : request.parentOrganismId === null + ? undefined + : this.speciesByOrganism.get(request.parentOrganismId) species = { id: this.entries.length, representative: request.genome, diff --git a/packages/simulation/src/systems/EggSystem.ts b/packages/simulation/src/systems/EggSystem.ts new file mode 100644 index 0000000..30cb589 --- /dev/null +++ b/packages/simulation/src/systems/EggSystem.ts @@ -0,0 +1,141 @@ +import type { WorldConfig } from '@evo/contracts' +import type { EggStore } from '../entities/EggStore' +import type { IdGenerator } from '../entities/IdGenerator' +import type { OrganismState, OrganismStore } from '../entities/OrganismStore' +import type { EventLog } from '../events/EventLog' +import { architectureOf } from '../genetics/GenomeFactory' +import { brainLayoutOf } from '../learning/BrainLayout' +import type { BrainLayout } from '../learning/BrainLayout' +import { createBrainState } from '../learning/BrainState' +import type { LineageStore } from '../lineage/LineageStore' +import { TWO_PI, wrapAngle } from '../math/scalar' +import { maxHealthOf } from '../organisms/traits' +import type { SeededRandom } from '../random/SeededRandom' +import type { SpeciesTracker } from '../species/SpeciesRegistry' + +/** + * The life cycle between conception and a living creature (ADR 0027): a carrying female lays her + * egg when the clutch is due, and an egg hatches into a creature `hatch` seconds after it was laid. + * Runs right after `ReproductionSystem` (which conceives) in the reproduction stage, only with + * `reproduction.eggs.enabled`. + * + * Laying goes in ascending mother id and hatching in ascending egg id, so the shared id counter + * stays in creation order. Nothing here draws a random number except the newborn's heading and + * sex (the same two draws an instant birth makes after its position jitter). + */ +export class EggSystem { + private readonly layout: BrainLayout + + constructor( + private readonly config: WorldConfig, + private readonly organisms: OrganismStore, + private readonly eggs: EggStore, + private readonly ids: IdGenerator, + private readonly lineage: LineageStore, + private readonly random: SeededRandom, + private readonly events: EventLog, + private readonly species: SpeciesTracker + ) { + this.layout = brainLayoutOf(architectureOf(config.genetics.brain)) + } + + update(tick: number): void { + const hatchTicks = Math.max( + 1, + Math.ceil(this.config.reproduction.eggs.hatch / this.config.timestep) + ) + + // Lay every clutch that is due, in ascending mother id. + for (const mother of this.organisms.values()) { + const pregnancy = mother.pregnancy + if (pregnancy === null || pregnancy.layTick > tick) continue + const eggId = this.ids.allocate() + this.eggs.add({ + id: eggId, + x: mother.x, + y: mother.y, + genome: pregnancy.genome, + motherId: mother.id, + fatherId: pregnancy.fatherId, + speciesId: pregnancy.speciesId, + energy: pregnancy.energy, + layTick: tick, + hatchTick: tick + hatchTicks + }) + mother.pregnancy = null + this.events.record({ + type: 'egg-laid', + tick, + eggId, + motherId: mother.id, + fatherId: pregnancy.fatherId, + position: { x: mother.x, y: mother.y } + }) + } + + // Hatch every egg that is ready, in ascending egg id. + for (const egg of this.eggs.values()) { + if (egg.hatchTick > tick) continue + this.eggs.remove(egg.id) + const organismId = this.ids.allocate() + const genome = egg.genome + const heading = wrapAngle(this.random.float() * TWO_PI) + const sex: 0 | 1 = this.random.float() < 0.5 ? 0 : 1 + const child: OrganismState = { + id: organismId, + parentIds: [egg.motherId, egg.fatherId], + genome, + x: egg.x, + y: egg.y, + vx: 0, + vy: 0, + heading, + age: 0, + energy: egg.energy, + health: maxHealthOf(genome, this.config), + birthTick: tick, + reproductionCooldownRemaining: 0, + lastTurnMagnitude: 0, + gut: 0, + biteCooldown: 0, + brain: + this.config.learning.controller === 'brain' + ? createBrainState(genome, this.layout, egg.energy) + : null, + sex, + pregnancy: null + } + this.organisms.add(child) + this.lineage.register({ + genomeId: genome.id, + parentGenomeIds: genome.parentIds, + organismId, + tick + }) + const speciesId = this.species.assign({ + organismId, + genome, + parentOrganismId: egg.motherId, + parentSpeciesId: egg.speciesId, + tick + }) + this.events.record({ + type: 'egg-hatched', + tick, + eggId: egg.id, + organismId, + motherId: egg.motherId, + fatherId: egg.fatherId + }) + this.events.record({ + type: 'organism-born', + tick, + organismId, + genomeId: genome.id, + parentIds: [egg.motherId, egg.fatherId], + speciesId, + position: { x: egg.x, y: egg.y } + }) + } + } +} diff --git a/packages/simulation/src/systems/MetabolismSystem.ts b/packages/simulation/src/systems/MetabolismSystem.ts index d4786aa..78d7de7 100644 --- a/packages/simulation/src/systems/MetabolismSystem.ts +++ b/packages/simulation/src/systems/MetabolismSystem.ts @@ -58,7 +58,10 @@ export class MetabolismSystem { dt const previous = organism.energy const healing = this.regen?.get(organism.id) ?? 0 - organism.energy = healing > 0 ? previous - cost - healing : previous - cost + // A female carrying a clutch pays to carry it (ADR 0027); never, with eggs off. + const total = + organism.pregnancy === null ? cost : cost + this.config.reproduction.eggs.carryCost * dt + organism.energy = healing > 0 ? previous - total - healing : previous - total organism.age = organism.age + dt if (this.emitVerbose) { diff --git a/packages/simulation/src/systems/ReproductionSystem.ts b/packages/simulation/src/systems/ReproductionSystem.ts index d14a554..cd17f43 100644 --- a/packages/simulation/src/systems/ReproductionSystem.ts +++ b/packages/simulation/src/systems/ReproductionSystem.ts @@ -1,4 +1,5 @@ import type { EntityId, Genome, WorldConfig } from '@evo/contracts' +import { EggStore } from '../entities/EggStore' import type { IdGenerator } from '../entities/IdGenerator' import type { OrganismState, OrganismStore } from '../entities/OrganismStore' import type { EventLog } from '../events/EventLog' @@ -54,7 +55,9 @@ export class ReproductionSystem { private readonly random: SeededRandom, private readonly events: EventLog, private readonly species: SpeciesTracker = NO_SPECIES, - ecology: EcologyModel | null = null + ecology: EcologyModel | null = null, + /** The eggs in the world; they count against `maxPopulation` with the clutches being carried (ADR 0027). */ + private readonly eggs: EggStore = new EggStore() ) { this.unbounded = ecology !== null && ecology.clusters !== null this.readiness = new ReproductionReadiness(config, ecology) @@ -97,12 +100,20 @@ export class ReproductionSystem { const { width, height } = this.config.environment const unbounded = this.unbounded + const { sexes, eggs: eggConfig } = this.config.reproduction + const sexed = sexes.enabled + const eggsOn = eggConfig.enabled + const initiators = this.organisms.values() + // Eggs and carried clutches are creatures-to-be and count against the population cap (ADR 0027); + // with eggs off both are zero and the cap is exactly the old one. + let committed = eggsOn ? this.eggs.size : 0 for (const organism of initiators) { organism.reproductionCooldownRemaining = Math.max( 0, organism.reproductionCooldownRemaining - dt ) + if (organism.pregnancy !== null) committed += 1 } const pairedIds = new Set() @@ -111,7 +122,7 @@ export class ReproductionSystem { if (!this.readiness.isReady(organism, tick)) continue if (pairedIds.has(organism.id)) continue - if (this.organisms.size >= this.config.maxPopulation) { + if (this.organisms.size + committed >= this.config.maxPopulation) { this.events.record({ type: 'reproduction-attempted', tick, @@ -129,6 +140,7 @@ export class ReproductionSystem { genome.reproduction.searchRadius, (item) => item.id !== organism.id && + (!sexed || item.sex !== organism.sex) && this.sameSpecies(organism, item) && !pairedIds.has(item.id) && this.readiness.isReady(item, tick) @@ -154,8 +166,14 @@ export class ReproductionSystem { organism.reproductionCooldownRemaining = genome.reproduction.cooldown partner.reproductionCooldownRemaining = partner.genome.reproduction.cooldown - const childId = this.ids.allocate() - const [mother, father] = organism.id < partner.id ? [organism, partner] : [partner, organism] + // With two sexes the female is the mother; otherwise the lower id is (as ever). + const [mother, father] = sexed + ? organism.sex === 0 + ? [organism, partner] + : [partner, organism] + : organism.id < partner.id + ? [organism, partner] + : [partner, organism] const parentIds: EntityId[] = [mother.id, father.id] const childGenome = this.recombiner.combine( this.effectiveGenome(mother.genome, mother.brain), @@ -163,6 +181,33 @@ export class ReproductionSystem { this.geneticsRandom ) + if (eggsOn) { + // The child is conceived now (its genome is fixed) and carried until it is laid (ADR 0027). + const energy = Math.min( + genome.reproduction.offspringInvestment + partner.genome.reproduction.offspringInvestment, + maxEnergyOf(childGenome, this.config) + ) + mother.pregnancy = { + genome: childGenome, + fatherId: father.id, + speciesId: this.species.speciesOf(mother.id) ?? null, + energy, + layTick: tick + Math.max(1, Math.ceil(eggConfig.incubation / dt)) + } + committed += 1 + this.events.record({ + type: 'reproduction-attempted', + tick, + organismId: organism.id, + partnerId: partner.id, + childId: null, + succeeded: true, + failureReason: null + }) + continue + } + const childId = this.ids.allocate() + const midX = (organism.x + partner.x) / 2 const midY = (organism.y + partner.y) / 2 const radius = bodyRadiusOf(genome, this.config) @@ -172,6 +217,8 @@ export class ReproductionSystem { const x = unbounded ? offsetX : clamp(offsetX, 0, width) const y = unbounded ? offsetY : clamp(offsetY, 0, height) const heading = wrapAngle(this.random.float() * TWO_PI) + // One draw decides the child's sex (ADR 0027); none with a single sex, so the stream is as before. + const sex: 0 | 1 = sexed ? (this.random.float() < 0.5 ? 0 : 1) : 0 const childEnergy = Math.min( genome.reproduction.offspringInvestment + partner.genome.reproduction.offspringInvestment, @@ -197,7 +244,9 @@ export class ReproductionSystem { brain: this.config.learning.controller === 'brain' ? createBrainState(childGenome, this.layout, childEnergy) - : null + : null, + sex, + pregnancy: null } this.organisms.add(child) this.lineage.register({ diff --git a/packages/simulation/src/world/World.ts b/packages/simulation/src/world/World.ts index 1b8ad13..1358179 100644 --- a/packages/simulation/src/world/World.ts +++ b/packages/simulation/src/world/World.ts @@ -6,6 +6,7 @@ import type { Capabilities, ClusterLayoutSnapshot, ClusterReport, + EggSnapshot, EntityId, EvolutionSeries, Genome, @@ -45,6 +46,7 @@ import { Carcasses } from '../ecology/Carcasses' import { ObstacleField } from '../ecology/ObstacleField' import { ClusterTerrain } from '../ecology/ClusterTerrain' import { RegionMap } from '../ecology/RegionMap' +import { EggStore } from '../entities/EggStore' import { IdGenerator } from '../entities/IdGenerator' import type { OrganismState } from '../entities/OrganismStore' import { OrganismStore } from '../entities/OrganismStore' @@ -96,6 +98,7 @@ import { StateHasher } from '../serialization/hash' import { SpatialHash } from '../spatial/SpatialHash' import { BrainSystem } from '../systems/BrainSystem' import { DeathSystem } from '../systems/DeathSystem' +import { EggSystem } from '../systems/EggSystem' import { DecisionSystem } from '../systems/DecisionSystem' import { EnvironmentSystem } from '../systems/EnvironmentSystem' import { HealthSystem } from '../systems/HealthSystem' @@ -142,6 +145,8 @@ export class World { private readonly ids: IdGenerator private readonly randomStreams: RandomStreams private readonly organisms: OrganismStore + /** The eggs in the world (ADR 0027); always empty with `reproduction.eggs` off. */ + private readonly eggStore: EggStore = new EggStore() private readonly resources: ResourceStore private readonly metricsCollector: MetricsCollector /** The evolution observatory (ADR 0024): read-only, unhashed, `null` when switched off. */ @@ -196,6 +201,8 @@ export class World { private readonly healthSystem: HealthSystem private readonly migrationSystem: MigrationSystem private readonly reproductionSystem: ReproductionSystem + /** Lays and hatches eggs (ADR 0027); `null` with eggs off. */ + private readonly eggSystem: EggSystem | null private readonly deathSystem: DeathSystem private readonly validateEveryTicks: number | undefined @@ -326,9 +333,10 @@ export class World { radius: this.config.reproduction.mateSenseRadius, readiness: new ReproductionReadiness(this.config, this.ecology), compatible: (a, b) => - !this.config.species.enabled || - !this.config.species.reproductiveIsolation || - this.speciesRegistry.speciesOf(a.id) === this.speciesRegistry.speciesOf(b.id) + (!this.config.reproduction.sexes.enabled || a.sex !== b.sex) && + (!this.config.species.enabled || + !this.config.species.reproductiveIsolation || + this.speciesRegistry.speciesOf(a.id) === this.speciesRegistry.speciesOf(b.id)) } : undefined, // Creatures' bodies (ADR 0016 "Line of sight") and obstacles that block sight (ADR 0022) hide @@ -427,8 +435,21 @@ export class World { this.randomStreams.get('reproduction'), this.events, this.speciesRegistry, - this.ecology + this.ecology, + this.eggStore ) + this.eggSystem = this.config.reproduction.eggs.enabled + ? new EggSystem( + this.config, + this.organisms, + this.eggStore, + this.ids, + this.lineageStore, + this.randomStreams.get('reproduction'), + this.events, + this.speciesRegistry + ) + : null const carrionKind = kindNamesOf(this.config).indexOf(CARRION_KIND) this.carcasses = carrionKind >= 0 @@ -447,9 +468,18 @@ export class World { windowTicks: Math.ceil(this.config.predation.attackWindow / this.config.timestep) } : undefined, - this.carcasses === null - ? undefined - : (organism, _cause, tick) => (this.carcasses as Carcasses).drop(organism, tick) + (organism, _cause, tick) => { + this.carcasses?.drop(organism, tick) + // A carrying mother who dies loses the clutch and its energy (ADR 0027). + if (organism.pregnancy !== null) { + this.events.record({ + type: 'clutch-lost', + tick, + motherId: organism.id, + fatherId: organism.pregnancy.fatherId + }) + } + } ) this.events.beginTick() @@ -566,7 +596,10 @@ export class World { brain: this.config.learning.controller === 'brain' ? createBrainState(genome, this.brainLayout, this.config.organisms.initialEnergy) - : null + : null, + // Founders alternate sex, draw-free (ADR 0027); all the same sex with one sex. + sex: this.config.reproduction.sexes.enabled ? ((i % 2) as 0 | 1) : 0, + pregnancy: null } this.organisms.add(organism) this.lineageStore.register({ @@ -931,6 +964,7 @@ export class World { this.healthSystem.update(tick) this.metabolismSystem.update(tick) this.reproductionSystem.update(tick) + this.eggSystem?.update(tick) this.deathSystem.update(tick) this.carcasses?.update(tick) if (this.config.learning.controller === 'brain') this.brainSystem.settle(tick) @@ -960,6 +994,7 @@ export class World { validate(): ValidationResult { return checkInvariants({ organisms: this.organisms.values(), + eggs: this.eggStore.values(), resources: this.resources.values(), config: this.config, tick: this.clockImpl.tick, @@ -975,6 +1010,20 @@ export class World { }) } + /** The eggs, ascending id (ADR 0027). Deep-copied. */ + private eggSnapshots(): EggSnapshot[] { + const tick = this.clockImpl.tick + return this.eggStore.values().map((egg) => ({ + id: egg.id, + position: { x: egg.x, y: egg.y }, + motherId: egg.motherId, + fatherId: egg.fatherId, + energy: egg.energy, + progress: Math.min(1, Math.max(0, (tick - egg.layTick) / (egg.hatchTick - egg.layTick))), + guarded: false + })) + } + /** A read-only, deep-copied view of the world, safe to hand to a renderer or UI. */ snapshot(): WorldSnapshot { const clockState = this.clockImpl.state() @@ -1009,10 +1058,16 @@ export class World { lifeStage: lifeStageFor(organism.age, this.config.organisms), reproductionCooldownRemaining: organism.reproductionCooldownRemaining, gut: organism.gut, - gutCapacity: this.config.feeding.enabled ? gutCapacityOf(organism.genome, this.config) : 0 + gutCapacity: this.config.feeding.enabled ? gutCapacityOf(organism.genome, this.config) : 0, + sex: organism.sex, + carrying: + organism.pregnancy === null + ? null + : Math.max(0, organism.pregnancy.layTick - clockState.tick) * this.config.timestep })), resources: this.resourceSnapshots(), hazards: this.hazardSnapshots(), + eggs: this.eggSnapshots(), metrics: this.metricsCollector.snapshot() } } @@ -1071,22 +1126,7 @@ export class World { hasher.writeUint32(organism.parentIds.length) for (const parentId of organism.parentIds) hasher.writeUint32(parentId) - const genome = organism.genome - hasher.writeUint32(genome.id) - hasher.writeUint32(genome.parentIds.length) - for (const parentId of genome.parentIds) hasher.writeUint32(parentId) - for (const value of genomeToVector(genome)) hasher.writeFloat64(value) - const { architecture, weights } = genome.brain - hasher - .writeUint32(architecture.inputSize) - .writeUint32(architecture.hiddenSize) - .writeUint32(architecture.memorySize) - .writeUint32(architecture.outputSize) - .writeUint32(weights.length) - for (const weight of weights) hasher.writeFloat64(weight) - // Schema v6: the body genes follow the brain weights (docs/decisions/0012). - hasher.writeUint32(genome.body.genes.length) - for (const gene of genome.body.genes) hasher.writeFloat64(gene) + writeGenome(hasher, organism.genome) writeBrainState(hasher, organism.brain) hasher.writeFloat64(organism.health) // Schema v10: the feeding state follows health (docs/decisions/0017). @@ -1147,11 +1187,67 @@ export class World { .writeFloat64(this.environmentSystem.stormRemainder) // Schema v12 tail: the predation counters (docs/decisions/0023). hasher.writeUint32(metrics.deathsByPredation).writeUint32(metrics.predationBites) + // Schema v13 tail: the life cycle (docs/decisions/0027): the egg counters, each creature's sex + // and carried clutch, and the eggs. All zero or empty with sexes and eggs off. + hasher + .writeUint32(metrics.eggsLaid) + .writeUint32(metrics.eggsHatched) + .writeUint32(metrics.eggsEaten) + .writeUint32(metrics.clutchesLost) + for (const organism of organisms) { + hasher.writeUint8(organism.sex) + const pregnancy = organism.pregnancy + hasher.writeBoolean(pregnancy !== null) + if (pregnancy !== null) { + writeGenome(hasher, pregnancy.genome) + hasher + .writeUint32(pregnancy.fatherId) + .writeBoolean(pregnancy.speciesId !== null) + .writeUint32(pregnancy.speciesId ?? 0) + .writeFloat64(pregnancy.energy) + .writeFloat64(pregnancy.layTick) + } + } + const eggs = this.eggStore.values() + hasher.writeUint32(eggs.length) + for (const egg of eggs) { + hasher + .writeUint32(egg.id) + .writeFloat64(egg.x) + .writeFloat64(egg.y) + .writeUint32(egg.motherId) + .writeUint32(egg.fatherId) + .writeBoolean(egg.speciesId !== null) + .writeUint32(egg.speciesId ?? 0) + .writeFloat64(egg.energy) + .writeFloat64(egg.layTick) + .writeFloat64(egg.hatchTick) + writeGenome(hasher, egg.genome) + } return hasher.digest() } } +/** Writes a genome: its ids, gene vector, brain and body (the order the hash has always used). */ +function writeGenome(hasher: StateHasher, genome: Genome): void { + hasher.writeUint32(genome.id) + hasher.writeUint32(genome.parentIds.length) + for (const parentId of genome.parentIds) hasher.writeUint32(parentId) + for (const value of genomeToVector(genome)) hasher.writeFloat64(value) + const { architecture, weights } = genome.brain + hasher + .writeUint32(architecture.inputSize) + .writeUint32(architecture.hiddenSize) + .writeUint32(architecture.memorySize) + .writeUint32(architecture.outputSize) + .writeUint32(weights.length) + for (const weight of weights) hasher.writeFloat64(weight) + // Schema v6: the body genes follow the brain weights (docs/decisions/0012). + hasher.writeUint32(genome.body.genes.length) + for (const gene of genome.body.genes) hasher.writeFloat64(gene) +} + /** The upper bound of a gene's range, used to size spatial grids. */ function geneRangeMax(specs: readonly GeneSpec[], path: string): number { const spec = specs.find((candidate) => candidate.path === path) diff --git a/packages/simulation/src/world/invariants.ts b/packages/simulation/src/world/invariants.ts index 31b45d5..22c9dc1 100644 --- a/packages/simulation/src/world/invariants.ts +++ b/packages/simulation/src/world/invariants.ts @@ -1,5 +1,6 @@ import type { MetricsSnapshot, ValidationResult, WorldConfig } from '@evo/contracts' import type { HazardState } from '../ecology/HazardStore' +import type { EggState } from '../entities/EggStore' import type { OrganismState } from '../entities/OrganismStore' import { FREE_SLOT, HUB_SLOT } from '../entities/ResourceStore' import type { ResourceState } from '../entities/ResourceStore' @@ -14,6 +15,8 @@ import type { LineageQueries } from '../lineage/LineageStore' export interface InvariantContext { readonly organisms: readonly OrganismState[] readonly resources: readonly ResourceState[] + /** The eggs (ADR 0027), ascending id; empty with eggs off. */ + readonly eggs: readonly EggState[] readonly config: WorldConfig readonly tick: number readonly extinctionTick: number | null @@ -164,6 +167,7 @@ export function checkInvariants(context: InvariantContext): ValidationResult { const { organisms, resources, + eggs, config, tick, extinctionTick, @@ -186,6 +190,53 @@ export function checkInvariants(context: InvariantContext): ValidationResult { errors.push(`population (${organisms.length}) exceeds maxPopulation (${config.maxPopulation})`) } + // The life cycle (ADR 0027): eggs and carried clutches are creatures-to-be and count against the cap. + const carrying = organisms.filter((organism) => organism.pregnancy !== null).length + if (organisms.length + eggs.length + carrying > config.maxPopulation) { + errors.push( + `population (${organisms.length}) with ${eggs.length} eggs and ${carrying} clutches exceeds maxPopulation (${config.maxPopulation})` + ) + } + if (!config.reproduction.eggs.enabled && (eggs.length > 0 || carrying > 0)) { + errors.push('eggs or clutches exist with reproduction.eggs switched off') + } + let previousEggId = -1 + for (const egg of eggs) { + if (egg.id <= previousEggId) + errors.push(`eggs are not in strictly ascending id order at egg ${egg.id}`) + previousEggId = egg.id + if (egg.id >= nextEntityId) errors.push(`egg ${egg.id} has an id beyond nextEntityId`) + for (const [field, value] of [ + ['x', egg.x], + ['y', egg.y], + ['energy', egg.energy] + ] as const) { + if (!Number.isFinite(value)) errors.push(`egg ${egg.id}: ${field} is not finite (${value})`) + } + if (egg.energy < 0) errors.push(`egg ${egg.id}: energy is negative (${egg.energy})`) + if (egg.hatchTick <= egg.layTick || egg.layTick > tick) { + errors.push( + `egg ${egg.id}: lay tick ${egg.layTick} and hatch tick ${egg.hatchTick} are inconsistent at tick ${tick}` + ) + } + if (egg.motherId >= nextEntityId || egg.fatherId >= nextEntityId) { + errors.push(`egg ${egg.id} names a parent beyond nextEntityId`) + } + } + for (const organism of organisms) { + if (organism.sex !== 0 && organism.sex !== 1) { + errors.push(`organism ${organism.id}: sex is ${organism.sex}`) + } + if (organism.pregnancy !== null) { + if (organism.sex !== 0) errors.push(`organism ${organism.id}: a male is carrying a clutch`) + if (organism.pregnancy.layTick <= tick - 1 && organism.pregnancy.layTick < tick) { + errors.push( + `organism ${organism.id}: clutch was due at ${organism.pregnancy.layTick} and is still carried at ${tick}` + ) + } + } + } + let previousOrganismId = -1 for (const organism of organisms) { if (organism.id <= previousOrganismId) { diff --git a/packages/simulation/tests/golden/state-hashes.json b/packages/simulation/tests/golden/state-hashes.json index d7cd63c..716f008 100644 --- a/packages/simulation/tests/golden/state-hashes.json +++ b/packages/simulation/tests/golden/state-hashes.json @@ -1,5 +1,5 @@ { - "hashSchemaVersion": 12, + "hashSchemaVersion": 13, "engineVersion": "0.12.0", "entries": [ { @@ -30,7 +30,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 1000, - "expectedHash": "eadf6305a347265e8aa7f4afb083f3ce" + "expectedHash": "8f71809ee45b7b9dfcc83291648895e7" }, { "name": "default-instant-eating-3k", @@ -61,7 +61,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 3000, - "expectedHash": "8e3107ac3b5acf13046d9d9fd19d7856" + "expectedHash": "205f4d364e31c034964266634f1c7218" }, { "name": "scenario-a-instant-eating-5k", @@ -102,7 +102,7 @@ } }, "steps": 5000, - "expectedHash": "acf58fc9d29150507753e86d54580b2b" + "expectedHash": "fac0167fd79b9527c9752d6659f1c6e6" }, { "name": "scenario-a-foraging-5k", @@ -142,7 +142,7 @@ } }, "steps": 5000, - "expectedHash": "f2305c80747aaedfabfef60420fe3da3" + "expectedHash": "ce2828cb4db3716818d7c71d3c7478ba" }, { "name": "scenario-b-extinction-20k", @@ -182,7 +182,7 @@ "environment": { "width": 500, "height": 500 } }, "steps": 20000, - "expectedHash": "4cde95edadc2f3d5663db05dd8c87ddd" + "expectedHash": "83ed1cf8c434965662b06c49c919a510" }, { "name": "verbose-events-200", @@ -222,7 +222,7 @@ } }, "steps": 200, - "expectedHash": "46ecf033718e3e123918325a95aa1a15" + "expectedHash": "29935eccf7614daf4a592ef466a751d4" }, { "name": "zero-population-100", @@ -262,7 +262,7 @@ "environment": { "width": 500, "height": 500 } }, "steps": 100, - "expectedHash": "3af7b11317af28e131a25b599ae71c7e" + "expectedHash": "6afbda6341858bf801fbcc52f2f5044a" }, { "name": "long-run-100k", @@ -292,7 +292,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 100000, - "expectedHash": "43f483885de7b8f74ce88bde897ba99f" + "expectedHash": "b670887850be03e611c27ecd2a8bbbaf" }, { "name": "reflex-default-1k", @@ -331,7 +331,7 @@ } }, "steps": 1000, - "expectedHash": "22c783ada5c90252b42556e3cbdb40b0" + "expectedHash": "f258aa73d70b4640fc7bdb606e70393b" }, { "name": "reflex-scenario-a-5k", @@ -371,7 +371,7 @@ } }, "steps": 5000, - "expectedHash": "dfafc319bb74ad50f439516f528b2352" + "expectedHash": "c809906d101da606e2411f05b68e71cc" }, { "name": "reflex-scenario-b-20k", @@ -411,7 +411,7 @@ "environment": { "width": 500, "height": 500 } }, "steps": 20000, - "expectedHash": "eb4324f31f24da2362602b24470913b3" + "expectedHash": "08e9480136f7fbec4610657d72df4b3b" }, { "name": "reflex-long-run-100k", @@ -450,7 +450,7 @@ } }, "steps": 100000, - "expectedHash": "da32da64f72ecac691d229b9b6c8b7c8" + "expectedHash": "ab4272d259b1016e699a296e55a1ba3c" }, { "name": "brain-hebbian-5k", @@ -490,7 +490,7 @@ } }, "steps": 5000, - "expectedHash": "a9e5cf88eb8fbcc621740cb3b1add282" + "expectedHash": "3ce3a79e73fb8b4326b9ff968a54822b" }, { "name": "brain-learning-off-5k", @@ -530,7 +530,7 @@ } }, "steps": 5000, - "expectedHash": "2d320cf6565e20b3eb48765efc01bc3f" + "expectedHash": "5ff17b38b076f11521fc574aab2f607a" }, { "name": "brain-random-prior-off-5k", @@ -571,7 +571,7 @@ } }, "steps": 5000, - "expectedHash": "b02651d87b5bea6e75f6ccb0e98ed29e" + "expectedHash": "07b7443249d4aafc6bc804c431e1d366" }, { "name": "ecology-default-12k", @@ -601,7 +601,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 12000, - "expectedHash": "0bffe13a256db88e31eb5bd7a3517446" + "expectedHash": "34e6421db6ba22622877967c590b5a7e" }, { "name": "ecology-reflex-8k", @@ -632,7 +632,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 8000, - "expectedHash": "f20979342112231e6fd7428fbb879c24" + "expectedHash": "c1565c19600cda506d694a827cd2c43d" }, { "name": "ecology-lethal-hazards-3k", @@ -667,7 +667,7 @@ } }, "steps": 3000, - "expectedHash": "b138384267dc7b2694661738dc34ea30" + "expectedHash": "a67879bd25d324791b5713419f7ee361" }, { "name": "anatomy-on-evolving-6k", @@ -707,7 +707,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 6000, - "expectedHash": "2c06cf6f0fec093bd63e2f53614cc8f6" + "expectedHash": "f9bf7561dcf7025914e4d6920092463a" }, { "name": "anatomy-on-reflex-4k", @@ -748,7 +748,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 4000, - "expectedHash": "b2a40f52021592c05214ee92dc2d7c43" + "expectedHash": "3f7b824e58437e6cded90713448136d9" }, { "name": "clusters-small-6k", @@ -783,7 +783,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 6000, - "expectedHash": "00f628899220817a0726ed3e54b9554e" + "expectedHash": "dce98f47abb2dad02670fbee8c33bfd6" }, { "name": "clusters-small-reflex-4k", @@ -819,7 +819,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 4000, - "expectedHash": "1f248f7fda10ae103e2724021a947397" + "expectedHash": "fca48beeb235e035755e49a374f48e5a" }, { "name": "archetypes-default-1k", @@ -849,7 +849,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 1000, - "expectedHash": "689478ff39ae8d3bf1282d88af5c2dca" + "expectedHash": "1a6154bcc6980f3385427f807de1c093" }, { "name": "archetypes-ecology-12k", @@ -879,7 +879,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 12000, - "expectedHash": "d2b9cd57ea4c081d5e2b2ded495618b5" + "expectedHash": "1e5e7ffe9384bf2e61e2c9240f828208" }, { "name": "archetypes-reflex-8k", @@ -910,7 +910,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 8000, - "expectedHash": "c0542a948d9d04f6dd29bfb3a610feb8" + "expectedHash": "abc12eaecff3c5de5cd2511b87e90d53" }, { "name": "archetypes-evolving-bodies-6k", @@ -949,7 +949,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 6000, - "expectedHash": "56597d64fe363d7f45b9a60d53eefde1" + "expectedHash": "4794af4317c6cdd171bf7939d999c21d" }, { "name": "archetype-forced-grazer-3k", @@ -981,7 +981,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 3000, - "expectedHash": "00ae0279a4869f17e1f3197687e03a0e" + "expectedHash": "721b47c6c843ec9b99f2b8aaf7b9cbe4" }, { "name": "archetype-forced-fungus-scraper-3k", @@ -1013,7 +1013,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 3000, - "expectedHash": "d1dc0ba286227c9a77ebaa546118d87c" + "expectedHash": "471bd9bf3b446342aa6b07be1bde9fb7" }, { "name": "archetype-forced-tank-3k", @@ -1043,7 +1043,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 3000, - "expectedHash": "320cdf7945c99f4e7a292305e01288b0" + "expectedHash": "a247ee5dafffbe33b5177f48e810ae9f" }, { "name": "noise-food-4k", @@ -1073,7 +1073,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 4000, - "expectedHash": "36b550127d7f1be84248ea73fe810bc0" + "expectedHash": "4ba0f0fa9cfb9ced70954216c1ba423c" }, { "name": "noise-reflex-3k", @@ -1104,7 +1104,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 3000, - "expectedHash": "14ab13b351238507fed18b1e58fbee54" + "expectedHash": "49a124d2eea35f66a665953a81350af9" }, { "name": "plants-6k", @@ -1134,7 +1134,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 6000, - "expectedHash": "93d65e057d0e0fbf4e2fab8e76ae652e" + "expectedHash": "633274a7923a3ef1ba0d4efcc2b0b04f" }, { "name": "plants-noise-reflex-5k", @@ -1165,7 +1165,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 5000, - "expectedHash": "6bb542d77a8174ce71d3377a3dad40cf" + "expectedHash": "8c5aa335f11224a3006910dacbbc29ed" }, { "name": "plants-brain-evolving-8k", @@ -1198,7 +1198,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 8000, - "expectedHash": "68a92946ed3370eb549f0a458541a96a" + "expectedHash": "3141079a4f55c7569ee981a4f6c44541" }, { "name": "food-default-1k", @@ -1209,7 +1209,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 1000, - "expectedHash": "31b76e0bfbf24213d61276d8cba0c26c" + "expectedHash": "668cd3e890fd9210fff83b877d3809f1" }, { "name": "food-default-ecology-12k", @@ -1220,7 +1220,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 12000, - "expectedHash": "00cfbbfd4828b0d76d58b1415a608729" + "expectedHash": "421caebbbca6354f8c7877aa12b3559a" }, { "name": "food-default-reflex-8k", @@ -1232,7 +1232,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 8000, - "expectedHash": "adcb66c66808ebeb11cac55fc81f3155" + "expectedHash": "21a234445828a0656a8402b1c8ee6e91" }, { "name": "food-default-evolving-bodies-6k", @@ -1252,7 +1252,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 6000, - "expectedHash": "fe69449e6c2892c9529a857b2b8e0243" + "expectedHash": "2f89d6efcf9200911c5d99ae0f93a3a7" }, { "name": "food-lush-4k", @@ -1268,7 +1268,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 4000, - "expectedHash": "1c08f874f067af38dfb56f0b75d97124" + "expectedHash": "5b184f4bcdc372fe2bc4b540a374479d" }, { "name": "obstacles-default-1k", @@ -1278,7 +1278,7 @@ "anatomy": { "startingBody": { "groups": [] } } }, "steps": 1000, - "expectedHash": "81738362d81609084a5376e18ea20c52" + "expectedHash": "54c302d9bafa86ef378e2ac9f230cce4" }, { "name": "obstacles-ecology-12k", @@ -1288,7 +1288,7 @@ "anatomy": { "startingBody": { "groups": [] } } }, "steps": 12000, - "expectedHash": "84950d17f6782508faadf4f4a40597ae" + "expectedHash": "87ffc09317dae86c556a2663151e3f5e" }, { "name": "obstacles-reflex-8k", @@ -1299,7 +1299,7 @@ "learning": { "controller": "reflex" } }, "steps": 8000, - "expectedHash": "cb2b8dbe71778f9dd75314861ea9b641" + "expectedHash": "e54088160f14df93fa3ede87383be314" }, { "name": "obstacles-evolving-bodies-6k", @@ -1318,7 +1318,7 @@ "genetics": { "mutationRateScale": 3 } }, "steps": 6000, - "expectedHash": "ad858c84fc69bf2362341ca55a5ab5ca" + "expectedHash": "367a0055c7669406c1fb5ad515f8051f" }, { "name": "obstacles-lush-4k", @@ -1333,28 +1333,28 @@ } }, "steps": 4000, - "expectedHash": "cd86aa4f8fa2dec7540afac4414bf30c" + "expectedHash": "1cc62d2e15be89f8b1115afc1a6786f2" }, { "name": "predation-default-1k", "seed": 12345, "config": {}, "steps": 1000, - "expectedHash": "90d27853de3997d3a6dfca57f2552a2a" + "expectedHash": "e8e0eb06f270958a6cb383f4d617af67" }, { "name": "predation-ecology-12k", "seed": 7, "config": {}, "steps": 12000, - "expectedHash": "bb5365f32f6cf4ad304b19661013b54c" + "expectedHash": "7ed8b2be4de980be9fe9350485ff0cb5" }, { "name": "predation-reflex-8k", "seed": 3, "config": { "learning": { "controller": "reflex" } }, "steps": 8000, - "expectedHash": "ba847deb2c907ffb8c997675e16f2853" + "expectedHash": "1be318afaf35b3335173cd19e173ef82" }, { "name": "predation-evolving-bodies-6k", @@ -1371,7 +1371,7 @@ "genetics": { "mutationRateScale": 3 } }, "steps": 6000, - "expectedHash": "ff6ecdeb75b3cb03edb09189d52a284d" + "expectedHash": "0be79e3f67ec55bd9a9341b000b086ae" }, { "name": "predation-lush-4k", @@ -1384,7 +1384,7 @@ } }, "steps": 4000, - "expectedHash": "7d816aed7cbf721448662cbb54803ec7" + "expectedHash": "f7ea0143bb41ffaaa1ec8fade4f41478" }, { "name": "predation-hunters-only-3k", @@ -1393,7 +1393,7 @@ "anatomy": { "startingBody": { "mode": "archetypes", "archetype": "hunter", "groups": [] } } }, "steps": 3000, - "expectedHash": "3c461f1ac3cd4bff8f63f0c36d06d467" + "expectedHash": "0d630b3c54e43bd9dd34dc2d8c4e66b6" } ] } diff --git a/packages/simulation/tests/hash-clock.test.ts b/packages/simulation/tests/hash-clock.test.ts index f266170..73a1a79 100644 --- a/packages/simulation/tests/hash-clock.test.ts +++ b/packages/simulation/tests/hash-clock.test.ts @@ -2,20 +2,20 @@ import { describe, expect, it } from 'vitest' import { HASH_SCHEMA_VERSION, SimulationClock, StateHasher, utf8Encode } from '../src/index' /** - * Test vectors from docs/simulation/determinism.md, section 10. The version 12 values (the header and + * Test vectors from docs/simulation/determinism.md, section 10. The version 13 values (the header and * the sample) were computed with an independent Python implementation of the hasher, which also * reproduces the version 5 values exactly. */ describe('StateHasher', () => { it('matches the published vectors', () => { expect(new StateHasher().digest()).toBe('027ae52ecfc796215593990d4b41437c') - expect(StateHasher.withHeader().digest()).toBe('d49b1e0b9a8a18f330c42958c075e1a5') + expect(StateHasher.withHeader().digest()).toBe('587210918be484b597a2acfc1f3e30d3') const sample = StateHasher.withHeader() .writeUint32(7) .writeFloat64(-0) .writeFloat64(0.5) .writeUint8(1) - expect(sample.digest()).toBe('fa1c4aa87cacbdd6959a759e55fd84da') + expect(sample.digest()).toBe('a92127630cc9776a9793f49801069c1f') }) it('canonicalizes -0 to +0', () => { @@ -89,7 +89,7 @@ describe('StateHasher', () => { }) it('exposes the schema version written into the header', () => { - expect(HASH_SCHEMA_VERSION).toBe(12) + expect(HASH_SCHEMA_VERSION).toBe(13) }) it('writes booleans as one byte', () => { diff --git a/packages/simulation/tests/invariants.test.ts b/packages/simulation/tests/invariants.test.ts index b165221..350da98 100644 --- a/packages/simulation/tests/invariants.test.ts +++ b/packages/simulation/tests/invariants.test.ts @@ -30,7 +30,11 @@ const zeroMetrics: MetricsSnapshot = { reproductionFailures: 0, energyConsumed: 0, energyWasted: 0, - damageTaken: 0 + damageTaken: 0, + eggsLaid: 0, + eggsHatched: 0, + eggsEaten: 0, + clutchesLost: 0 } const organism = (id: number, overrides: Partial = {}): OrganismState => @@ -64,6 +68,7 @@ const lineageFor = (organisms: readonly OrganismState[]): LineageStore => { const baseContext = (overrides: Partial = {}): InvariantContext => ({ organisms: [], resources: [], + eggs: [], config: DEFAULT_WORLD_CONFIG, tick: 100, extinctionTick: null, diff --git a/packages/simulation/tests/lifecycle/lifecycle.test.ts b/packages/simulation/tests/lifecycle/lifecycle.test.ts new file mode 100644 index 0000000..da55ab1 --- /dev/null +++ b/packages/simulation/tests/lifecycle/lifecycle.test.ts @@ -0,0 +1,277 @@ +import { describe, expect, it } from 'vitest' +import { resolveWorldConfig } from '@evo/config' +import type { WorldConfigOverrides, WorldEvent } from '@evo/contracts' +import { EventLog } from '../../src/events/EventLog' +import { OrganismStore } from '../../src/entities/OrganismStore' +import { MetabolismSystem } from '../../src/systems/MetabolismSystem' +import { World } from '../../src/index' +import { organismFor } from '../support/organism' + +/** The life cycle (ADR 0027): two sexes, a carried clutch, an egg, a hatchling. */ +const LIFE: WorldConfigOverrides = { + reproduction: { sexes: { enabled: true }, eggs: { enabled: true } } +} +const DT = 0.1 + +interface Run { + world: World + events: WorldEvent[] + /** The sex of every creature seen, by id. */ + sexes: Map +} + +/** Runs a world and collects every event and every creature's sex, tick by tick. */ +function run(config: WorldConfigOverrides, seed: number, ticks: number): Run { + const world = World.create({ seed, config, validateEveryTicks: 50 }) + const events: WorldEvent[] = [] + const sexes = new Map() + const note = (): void => { + for (const organism of world.snapshot().organisms) sexes.set(organism.id, organism.sex) + } + note() + for (let t = 0; t < ticks; t++) { + world.step() + events.push(...world.events.eventsThisTick()) + note() + } + return { world, events, sexes } +} + +const ofType = ( + events: readonly WorldEvent[], + type: T +): Extract[] => + events.filter((event): event is Extract => event.type === type) + +describe('configuration', () => { + it('eggs need two sexes (the female lays)', () => { + expect(() => resolveWorldConfig({ reproduction: { eggs: { enabled: true } } })).toThrow( + /requires reproduction.sexes.enabled/ + ) + expect(() => resolveWorldConfig(LIFE)).not.toThrow() + }) + + it('rejects bad times, radii and costs, and unknown keys', () => { + for (const eggs of [ + { incubation: 0 }, + { hatch: -1 }, + { guardRadius: 0 }, + { carryCost: -0.1 }, + { guardCost: -1 }, + { guardDamage: -1 }, + { enabled: 'yes' } + ]) { + expect(() => resolveWorldConfig({ reproduction: { eggs } as never })).toThrow() + } + expect(() => resolveWorldConfig({ reproduction: { sexes: { enabled: 1 } } as never })).toThrow() + expect(() => resolveWorldConfig({ reproduction: { eggs: { nest: true } } as never })).toThrow() + }) + + it('is off by default: the default world has one sex and no eggs', () => { + const config = resolveWorldConfig() + // The measured defaults are switched on in the last commit of the life-cycle work; until then off. + expect(config.reproduction.sexes.enabled).toBe(false) + expect(config.reproduction.eggs.enabled).toBe(false) + }) +}) + +describe('switched off', () => { + it('has no eggs, no clutches and every creature is sex 0', () => { + const { world, events } = run({}, 3, 1500) + expect(ofType(events, 'egg-laid')).toHaveLength(0) + expect(ofType(events, 'clutch-lost')).toHaveLength(0) + const snapshot = world.snapshot() + expect(snapshot.eggs).toEqual([]) + expect(snapshot.organisms.every((o) => o.sex === 0 && o.carrying === null)).toBe(true) + expect(snapshot.metrics.eggsLaid).toBe(0) + }) +}) + +describe('two sexes', () => { + it('founders alternate sex, draw-free', () => { + const world = World.create({ seed: 5, config: LIFE }) + const sexes = world.snapshot().organisms.map((o) => o.sex) + expect(sexes.slice(0, 6)).toEqual([0, 1, 0, 1, 0, 1]) + expect(sexes.filter((s) => s === 0).length).toBe(Math.ceil(sexes.length / 2)) + }) + + it('only a female and a male conceive; the female is the mother', () => { + const { events, sexes } = run(LIFE, 1, 4000) + const conceptions = ofType(events, 'reproduction-attempted').filter((e) => e.succeeded) + expect(conceptions.length).toBeGreaterThan(3) + for (const attempt of conceptions) { + const pair = [attempt.organismId, attempt.partnerId as number].map((id) => sexes.get(id)) + expect([...pair].sort()).toEqual([0, 1]) + } + for (const laid of ofType(events, 'egg-laid')) { + expect(sexes.get(laid.motherId)).toBe(0) + expect(sexes.get(laid.fatherId)).toBe(1) + } + }) + + it('negative: with one sex, same-sex pairs do occur (every creature is sex 0)', () => { + const { events, sexes } = run({}, 1, 3000) + const births = ofType(events, 'organism-born').filter((e) => e.parentIds.length === 2) + expect(births.length).toBeGreaterThan(3) + expect([...sexes.values()].every((s) => s === 0)).toBe(true) + }) + + it('an instant birth with two sexes draws the newborn sex about evenly', () => { + const { events, sexes } = run({ reproduction: { sexes: { enabled: true } } }, 2, 6000) + const born = ofType(events, 'organism-born').filter((e) => e.parentIds.length === 2) + expect(born.length).toBeGreaterThan(25) + const females = born.filter((e) => sexes.get(e.organismId) === 0).length + expect(females / born.length).toBeGreaterThan(0.25) + expect(females / born.length).toBeLessThan(0.75) + }) +}) + +describe('incubation, laying and hatching', () => { + const lifeRun = run(LIFE, 1, 4500) + + it('lays exactly one egg per conception after exactly `incubation`, at the mother', () => { + const { events } = lifeRun + const laid = ofType(events, 'egg-laid') + expect(laid.length).toBeGreaterThan(3) + const incubation = Math.ceil(resolveWorldConfig(LIFE).reproduction.eggs.incubation / DT) + for (const egg of laid) { + const conception = ofType(events, 'reproduction-attempted').find( + (e) => + e.succeeded && + [e.organismId, e.partnerId].includes(egg.motherId) && + [e.organismId, e.partnerId].includes(egg.fatherId) && + e.tick === egg.tick - incubation + ) + expect(conception).toBeDefined() + expect(conception?.childId).toBeNull() + } + }) + + it('hatches exactly `hatch` after it was laid, not one tick earlier', () => { + const { events, world } = lifeRun + const hatch = Math.ceil(resolveWorldConfig(LIFE).reproduction.eggs.hatch / DT) + const hatched = ofType(events, 'egg-hatched') + expect(hatched.length).toBeGreaterThan(2) + for (const h of hatched) { + const laid = ofType(events, 'egg-laid').find((e) => e.eggId === h.eggId) + expect(laid).toBeDefined() + expect((laid?.tick ?? 0) + hatch).toBe(h.tick) + } + expect(world.snapshot().metrics.eggsHatched).toBe(hatched.length) + }) + + it('a hatchling is born with its parents, and the birth event comes with the hatch', () => { + const { events } = lifeRun + for (const h of ofType(events, 'egg-hatched')) { + const born = ofType(events, 'organism-born').find((e) => e.organismId === h.organismId) + expect(born?.tick).toBe(h.tick) + expect(born?.parentIds).toEqual([h.motherId, h.fatherId]) + } + }) + + it('shows the clutch while carried and the egg while it lies; males never carry', () => { + const world = World.create({ seed: 1, config: LIFE }) + let sawCarrying = false + let sawEgg = false + for (let t = 0; t < 4000; t++) { + world.step() + const snapshot = world.snapshot() + for (const o of snapshot.organisms) { + if (o.carrying !== null) { + sawCarrying = true + expect(o.sex).toBe(0) + } + } + for (const egg of snapshot.eggs) { + sawEgg = true + expect(egg.progress).toBeGreaterThanOrEqual(0) + expect(egg.progress).toBeLessThan(1) + } + } + expect(sawCarrying).toBe(true) + expect(sawEgg).toBe(true) + }) + + it('counts every egg against the population cap', () => { + const world = World.create({ + seed: 2, + config: { ...LIFE, maxPopulation: 26 }, + validateEveryTicks: 1 + }) + let peak = 0 + for (let t = 0; t < 3500; t++) { + world.step() + const snapshot = world.snapshot() + const carrying = snapshot.organisms.filter((o) => o.carrying !== null).length + peak = Math.max(peak, snapshot.organisms.length + snapshot.eggs.length + carrying) + expect(snapshot.organisms.length + snapshot.eggs.length + carrying).toBeLessThanOrEqual(26) + } + expect(peak).toBeGreaterThan(21) + }) + + it('a clutch is lost with its mother, and the loss is counted', () => { + // Carrying is made ruinous so that carriers die before they lay. + const ruinous = run( + { reproduction: { sexes: { enabled: true }, eggs: { enabled: true, carryCost: 40 } } }, + 1, + 4000 + ) + const lost = ofType(ruinous.events, 'clutch-lost') + expect(lost.length).toBeGreaterThan(0) + expect(ruinous.world.snapshot().metrics.clutchesLost).toBe(lost.length) + // Negative: the normal cost loses few or none. + const normal = ofType(lifeRun.events, 'clutch-lost').length + expect(normal).toBeLessThan(lost.length) + }) + + it('is deterministic and the same stepped, chunked or run at once, across hatches', () => { + const a = World.create({ seed: 4, config: LIFE }) + a.run(3000) + const b = World.create({ seed: 4, config: LIFE }) + for (let t = 0; t < 3000; t++) b.step() + const c = World.create({ seed: 4, config: LIFE }) + c.run(1234) + c.run(1766) + expect(a.snapshot().metrics.eggsHatched).toBeGreaterThan(0) + expect(b.stateHash()).toBe(a.stateHash()) + expect(c.stateHash()).toBe(a.stateHash()) + }) +}) + +describe('the hash covers the life cycle', () => { + it('differs with sexes on and off, and with eggs on and off', () => { + const hash = (config: WorldConfigOverrides): string => { + const world = World.create({ seed: 6, config }) + world.run(1500) + return world.stateHash() + } + const off = hash({}) + const sexes = hash({ reproduction: { sexes: { enabled: true } } }) + const eggs = hash(LIFE) + expect(new Set([off, sexes, eggs]).size).toBe(3) + }) +}) + +describe('carrying costs energy', () => { + it('a pregnant female pays `carryCost` per second on top; a male and an empty female pay none', () => { + const config = resolveWorldConfig({ + ...LIFE, + reproduction: { sexes: { enabled: true }, eggs: { enabled: true, carryCost: 2 } }, + learning: { controller: 'reflex' } + }) + const pregnancy = organismFor(config, 9).genome + const energyAfter = (overrides: Parameters[2]): number => { + const organisms = new OrganismStore() + organisms.add(organismFor(config, 1, { energy: 50, ...overrides })) + new MetabolismSystem(config, organisms, new EventLog(10), null).update(1) + return (organisms.get(1) as { energy: number }).energy + } + const empty = energyAfter({ sex: 0 }) + const carrying = energyAfter({ + sex: 0, + pregnancy: { genome: pregnancy, fatherId: 2, speciesId: null, energy: 20, layTick: 50 } + }) + expect(empty - carrying).toBeCloseTo(2 * DT, 10) + expect(energyAfter({ sex: 1 })).toBe(empty) + }) +}) diff --git a/packages/simulation/tests/metrics.test.ts b/packages/simulation/tests/metrics.test.ts index 455aa6a..c2d2c3c 100644 --- a/packages/simulation/tests/metrics.test.ts +++ b/packages/simulation/tests/metrics.test.ts @@ -22,7 +22,11 @@ describe('MetricsCollector', () => { reproductionFailures: 0, energyConsumed: 0, energyWasted: 0, - damageTaken: 0 + damageTaken: 0, + eggsLaid: 0, + eggsHatched: 0, + eggsEaten: 0, + clutchesLost: 0 }) }) @@ -95,7 +99,11 @@ describe('MetricsCollector', () => { reproductionFailures: 1, energyConsumed: 20, energyWasted: 10, - damageTaken: 0 + damageTaken: 0, + eggsLaid: 0, + eggsHatched: 0, + eggsEaten: 0, + clutchesLost: 0 }) }) @@ -197,7 +205,11 @@ describe('MetricsCollector', () => { reproductionFailures: 0, energyConsumed: 0, energyWasted: 0, - damageTaken: 0 + damageTaken: 0, + eggsLaid: 0, + eggsHatched: 0, + eggsEaten: 0, + clutchesLost: 0 }) }) diff --git a/packages/simulation/tests/support/organism.ts b/packages/simulation/tests/support/organism.ts index ffc2f7a..dfd7fc0 100644 --- a/packages/simulation/tests/support/organism.ts +++ b/packages/simulation/tests/support/organism.ts @@ -56,6 +56,8 @@ export function organismFor( gut: 0, biteCooldown: 0, brain: null, + sex: 0, + pregnancy: null, ...overrides } } diff --git a/packages/ui/tests/support/fixtures.ts b/packages/ui/tests/support/fixtures.ts index 07cc3c9..7b9c445 100644 --- a/packages/ui/tests/support/fixtures.ts +++ b/packages/ui/tests/support/fixtures.ts @@ -35,7 +35,11 @@ export function view(overrides: Partial = {}): ViewState { reproductionFailures: 750, energyConsumed: 0, energyWasted: 0, - damageTaken: 0 + damageTaken: 0, + eggsLaid: 0, + eggsHatched: 0, + eggsEaten: 0, + clutchesLost: 0 }, history: [ { From aa18f9f6bccb0da17b641fc7ecf952f8d8196306 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 19:11:14 +0000 Subject: [PATCH 03/11] feat(life-cycle): guarding and egg predation (ADR 0027) A parent within reproduction.eggs.guardRadius of its egg guards it and pays guardCost a second per egg. A bite at a guarded egg is stopped: the egg stays and the biter takes guardDamage, counted as the guard's bite for the death label. An unguarded egg is eaten whole by any mouth with a flesh yield (the gut takes what it can, at the trophic yield; a full gut refuses it), never by a mandible or a parent. Eggs are prey in the senses of a body that bites creatures, and a parent senses the way back to its own egg through the existing home inputs (present beyond the guard radius, full at three times it), so no observation or weight changes. Switches are still off. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Cn5qp4xBHxLnTrwReNXcf8 --- packages/simulation/src/organisms/eggs.ts | 29 ++ .../simulation/src/systems/BrainSystem.ts | 54 +++- packages/simulation/src/systems/EggSystem.ts | 10 + .../src/systems/InteractionSystem.ts | 156 +++++++++- .../src/systems/PerceptionSystem.ts | 28 +- packages/simulation/src/world/World.ts | 16 +- .../tests/lifecycle/egg-predation.test.ts | 289 ++++++++++++++++++ 7 files changed, 573 insertions(+), 9 deletions(-) create mode 100644 packages/simulation/src/organisms/eggs.ts create mode 100644 packages/simulation/tests/lifecycle/egg-predation.test.ts diff --git a/packages/simulation/src/organisms/eggs.ts b/packages/simulation/src/organisms/eggs.ts new file mode 100644 index 0000000..a747935 --- /dev/null +++ b/packages/simulation/src/organisms/eggs.ts @@ -0,0 +1,29 @@ +import type { EntityId, WorldConfig } from '@evo/contracts' +import type { EggState } from '../entities/EggStore' +import type { OrganismState, OrganismStore } from '../entities/OrganismStore' + +/** The size of an egg as a bite target: as big as a piece of food. */ +export function eggRadiusOf(config: WorldConfig): number { + return config.resources.radius +} + +/** + * The living parents of `egg` that are guarding it (ADR 0027): within `guardRadius` of it right now, + * mother first. A dead or distant parent guards nothing. + */ +export function guardsOf( + egg: EggState, + organisms: OrganismStore, + guardRadius: number +): OrganismState[] { + const guards: OrganismState[] = [] + const limit = guardRadius * guardRadius + for (const id of [egg.motherId, egg.fatherId] as readonly EntityId[]) { + const parent = organisms.get(id) + if (parent === undefined || parent.health <= 0) continue + const dx = parent.x - egg.x + const dy = parent.y - egg.y + if (dx * dx + dy * dy <= limit) guards.push(parent) + } + return guards +} diff --git a/packages/simulation/src/systems/BrainSystem.ts b/packages/simulation/src/systems/BrainSystem.ts index ad13c2a..d991345 100644 --- a/packages/simulation/src/systems/BrainSystem.ts +++ b/packages/simulation/src/systems/BrainSystem.ts @@ -10,6 +10,7 @@ import type { ThreatBuffer } from '../buffers/types' import type { EcologyModel } from '../ecology/EcologyModel' +import type { EggState, EggStore } from '../entities/EggStore' import type { OrganismState, OrganismStore } from '../entities/OrganismStore' import type { EventLog } from '../events/EventLog' import { architectureOf } from '../genetics/GenomeFactory' @@ -53,6 +54,8 @@ const HOME_OUTER = 1.1 */ export class BrainSystem { private readonly layout: BrainLayout + /** Each parent's eggs this tick, by parent id (ADR 0027); empty without eggs. */ + private parentEggs = new Map() private readonly learner: LearningAlgorithm private readonly params: LearningParams @@ -69,7 +72,9 @@ export class BrainSystem { private readonly mateBuffer?: MateBuffer, /** Prey and threat sightings (ADR 0023): empty or absent with predation off. */ private readonly preyBuffer?: PreyBuffer, - private readonly threatBuffer?: ThreatBuffer + private readonly threatBuffer?: ThreatBuffer, + /** The eggs, with `reproduction.eggs` on: a parent senses the way back to its own egg (ADR 0027). */ + private readonly eggs?: EggStore ) { this.layout = brainLayoutOf(architectureOf(config.genetics.brain)) this.learner = createLearner(config.learning.algorithm) @@ -125,8 +130,12 @@ export class BrainSystem { private homeOf( organism: OrganismState ): { present: number; bearingCos: number; bearingSin: number } | null { + // A parent with an egg lying about senses the way back to it instead (ADR 0027), once it has + // strayed beyond the guard radius; the same three inputs, so the brain needs no new weights. + const nest = this.nestOf(organism) + if (nest !== null && nest.present > 0) return nest const layout = this.ecology === null ? null : this.ecology.clusters - if (layout === null) return null + if (layout === null) return nest const centre = layout.centres[layout.nearestCluster(organism.x, organism.y)] as { x: number y: number @@ -146,6 +155,36 @@ export class BrainSystem { return { present, bearingCos: cos(bearing), bearingSin: sin(bearing) } } + /** + * The way back to the nearest egg this organism laid or fathered (ADR 0027): `present` grows from 0 + * at the guard radius to 1 at three times it, and the bearing is in the body frame. `null` without + * an egg of its own, and `present` 0 while it is within the guard radius (it is already there). + */ + private nestOf( + organism: OrganismState + ): { present: number; bearingCos: number; bearingSin: number } | null { + const mine = this.parentEggs.get(organism.id) + if (mine === undefined) return null + let best: EggState | null = null + let bestDistance = Infinity + for (const egg of mine) { + const dx = egg.x - organism.x + const dy = egg.y - organism.y + const d = dx * dx + dy * dy + if (d < bestDistance) { + best = egg + bestDistance = d + } + } + if (best === null) return null + const radius = this.config.reproduction.eggs.guardRadius + const distance = Math.sqrt(bestDistance) + const present = Math.min(1, Math.max(0, (distance - radius) / (2 * radius))) + if (present === 0) return { present: 0, bearingCos: 0, bearingSin: 0 } + const bearing = atan2(best.y - organism.y, best.x - organism.x) - organism.heading + return { present, bearingCos: cos(bearing), bearingSin: sin(bearing) } + } + /** The coarse novelty-grid cell an organism stands in. */ private cellOf(organism: OrganismState): number { const place = this.local(organism) @@ -162,6 +201,17 @@ export class BrainSystem { decide(tick = 0): void { this.intentBuffer.clear() + // Who has an egg lying about, and where (ADR 0027); the sense is only worked out for them. + this.parentEggs.clear() + if (this.eggs !== undefined) { + for (const egg of this.eggs.values()) { + for (const parentId of [egg.motherId, egg.fatherId]) { + const list = this.parentEggs.get(parentId) + if (list === undefined) this.parentEggs.set(parentId, [egg]) + else list.push(egg) + } + } + } const dt = this.config.timestep const { foodHorizon, enabled } = this.config.learning diff --git a/packages/simulation/src/systems/EggSystem.ts b/packages/simulation/src/systems/EggSystem.ts index 30cb589..14e1f46 100644 --- a/packages/simulation/src/systems/EggSystem.ts +++ b/packages/simulation/src/systems/EggSystem.ts @@ -9,6 +9,7 @@ import type { BrainLayout } from '../learning/BrainLayout' import { createBrainState } from '../learning/BrainState' import type { LineageStore } from '../lineage/LineageStore' import { TWO_PI, wrapAngle } from '../math/scalar' +import { guardsOf } from '../organisms/eggs' import { maxHealthOf } from '../organisms/traits' import type { SeededRandom } from '../random/SeededRandom' import type { SpeciesTracker } from '../species/SpeciesRegistry' @@ -73,6 +74,15 @@ export class EggSystem { }) } + // Guarding costs energy: every parent beside an egg pays `guardCost` a second for it (ADR 0027). + const { guardRadius, guardCost } = this.config.reproduction.eggs + if (guardCost > 0) { + const toll = guardCost * this.config.timestep + for (const egg of this.eggs.values()) { + for (const guard of guardsOf(egg, this.organisms, guardRadius)) guard.energy -= toll + } + } + // Hatch every egg that is ready, in ascending egg id. for (const egg of this.eggs.values()) { if (egg.hatchTick > tick) continue diff --git a/packages/simulation/src/systems/InteractionSystem.ts b/packages/simulation/src/systems/InteractionSystem.ts index 35abc38..27e1859 100644 --- a/packages/simulation/src/systems/InteractionSystem.ts +++ b/packages/simulation/src/systems/InteractionSystem.ts @@ -12,7 +12,9 @@ import { factorsOf, kindNamesOf } from '../organisms/bodyFactors' import { cos, sin } from '../math/trig' import { mouthsOf } from '../organisms/mouths' import { bodyRadiusOf, gutCapacityOf, maxEnergyOf } from '../organisms/traits' +import { eggRadiusOf, guardsOf } from '../organisms/eggs' import { canBite, currentRadiusOf } from '../organisms/predation' +import type { EggState, EggStore } from '../entities/EggStore' import { SIGHT_BLOCKER_MARGIN, segmentHitsCircle } from '../spatial/sight' import type { SpatialHash, SpatialHit } from '../spatial/SpatialHash' @@ -31,6 +33,8 @@ export interface PredationSensing { readonly lastBitten: LastBitten /** Obstacles that block movement also stop a bite. */ readonly obstacles: ObstacleField + /** The eggs a flesh-eating mouth may take, with `reproduction.eggs` on (ADR 0027). */ + readonly eggs?: EggStore } /** @@ -48,6 +52,7 @@ export interface PredationSensing { * dropped. */ export class InteractionSystem { + private eggList: EggState[] = [] private readonly emitVerbose: boolean private readonly kindsOn: boolean /** Query reach: the largest resource radius of any kind. */ @@ -98,6 +103,8 @@ export class InteractionSystem { const cosCone = cos(this.config.feeding.biteCone) this.damage?.clear() this.predation?.buffer.clear() + // The eggs lying about this tick (ADR 0027); one list for every biter, empty without eggs. + this.eggList = this.predation?.eggs === undefined ? [] : this.predation.eggs.values() for (const organism of this.organisms.values()) { organism.biteCooldown = Math.max(0, organism.biteCooldown - dt) @@ -152,8 +159,38 @@ export class InteractionSystem { bodyRadius, cosCone }) - if (prey !== null && (!hit || prey.distanceSquared < hit.distanceSquared)) { - this.bitePrey(organism, body.biteSize, body.biteRate, prey.item, flesh, room, tick) + // An egg lying in reach is a meal too, and is guarded by a parent beside it (ADR 0027). + const egg = this.eggFor(organism, organism.x + mx, organism.y + my, { + mx, + my, + reach, + bodyRadius, + cosCone + }) + const eggNearer = + egg !== null && (prey === null || egg.distanceSquared < prey.distanceSquared) + const nearest = eggNearer ? (egg as { distanceSquared: number }) : prey + if (nearest !== null && (!hit || nearest.distanceSquared < hit.distanceSquared)) { + if (eggNearer) { + this.biteEgg( + organism, + body.biteRate, + (egg as { item: EggState }).item, + flesh, + room, + tick + ) + } else { + this.bitePrey( + organism, + body.biteSize, + body.biteRate, + (prey as SpatialHit).item, + flesh, + room, + tick + ) + } break } } @@ -278,6 +315,121 @@ export class InteractionSystem { ) } + /** The nearest egg this mouth could take: in reach and in the cone, not a parent's own, nothing solid between. */ + private eggFor( + predator: OrganismState, + mouthX: number, + mouthY: number, + geometry: { + readonly mx: number + readonly my: number + readonly reach: number + readonly bodyRadius: number + readonly cosCone: number + } + ): { item: EggState; distanceSquared: number } | null { + if (this.eggList.length === 0) return null + const { obstacles, eggs } = this.predation as PredationSensing + const radius = eggRadiusOf(this.config) + const limit = geometry.reach + radius + let best: { item: EggState; distanceSquared: number } | null = null + for (const egg of this.eggList) { + if (egg.motherId === predator.id || egg.fatherId === predator.id) continue + if ((eggs as EggStore).get(egg.id) === undefined) continue + const dx = egg.x - mouthX + const dy = egg.y - mouthY + const distanceSquared = dx * dx + dy * dy + if (distanceSquared > limit * limit) continue + if (best !== null && distanceSquared >= best.distanceSquared) continue + const fx = egg.x - predator.x + const fy = egg.y - predator.y + const target = fx * fx + fy * fy + const mouthLength = geometry.mx * geometry.mx + geometry.my * geometry.my + if (target > 0 && mouthLength > 0) { + if ( + fx * geometry.mx + fy * geometry.my < + geometry.cosCone * Math.sqrt(target * mouthLength) + ) { + continue + } + } + if (obstacles.maxMovementRadius > 0) { + const half = Math.sqrt(distanceSquared) / 2 + const blocked = obstacles.some( + (mouthX + egg.x) / 2, + (mouthY + egg.y) / 2, + half + obstacles.maxMovementRadius, + (o) => + o.blocksMovement && segmentHitsCircle(mouthX, mouthY, egg.x, egg.y, o.x, o.y, o.radius) + ) + if (blocked) continue + } + best = { item: egg, distanceSquared } + } + return best + } + + /** + * One bite at an egg (ADR 0027). With a parent beside it the bite is stopped: the egg is left + * alone and the biter takes `guardDamage`, counted as a bite by the guard. Otherwise the egg is + * eaten whole: it is gone and what the gut can hold of its energy, at the trophic yield and the + * mouth's flesh yield, goes in; the rest is lost. + */ + private biteEgg( + predator: OrganismState, + biteRate: number, + egg: EggState, + flesh: number, + room: number, + tick: number + ): void { + const { eggs: eggConfig } = this.config.reproduction + const { predation, feeding } = this.config + const { buffer, lastBitten, eggs } = this.predation as PredationSensing + const guards = guardsOf(egg, this.organisms, eggConfig.guardRadius) + if (guards.length > 0) { + const guard = guards[0] as OrganismState + const damage = eggConfig.guardDamage * factorsOf(predator.genome, this.config).damageTaken + const entry = buffer.get(predator.id) + if (entry === undefined) { + buffer.set(predator.id, { damage, attackerId: guard.id, hardest: damage }) + } else { + entry.damage += damage + if (damage > entry.hardest) { + entry.hardest = damage + entry.attackerId = guard.id + } + } + lastBitten.set(predator.id, { attackerId: guard.id, tick }) + predator.biteCooldown = feeding.biteInterval / biteRate + this.events.record({ + type: 'egg-guarded', + tick, + eggId: egg.id, + guardId: guard.id, + biterId: predator.id, + damage + }) + return + } + const perEnergy = predation.trophicYield * flesh + const whole = egg.energy * perEnergy + // A gut with no real room for the meal is full, as for food. + if (room < MIN_BITE_FRACTION * whole) return + const intake = Math.min(whole, room) + predator.gut = Math.min(predator.gut + intake, room + predator.gut) + predator.biteCooldown = feeding.biteInterval / biteRate + ;(eggs as EggStore).remove(egg.id) + this.events.record({ + type: 'egg-eaten', + tick, + eggId: egg.id, + predatorId: predator.id, + energyTaken: egg.energy, + intake + }) + } + /** * One bite of a creature (ADR 0023): the victim loses energy (at most what it has, and what the * bitter's gut can take) and health (armor applies); the bitter's gut gains the energy taken times diff --git a/packages/simulation/src/systems/PerceptionSystem.ts b/packages/simulation/src/systems/PerceptionSystem.ts index 95cabba..c103722 100644 --- a/packages/simulation/src/systems/PerceptionSystem.ts +++ b/packages/simulation/src/systems/PerceptionSystem.ts @@ -12,6 +12,7 @@ import type { import type { EcologyModel } from '../ecology/EcologyModel' import type { HazardStore } from '../ecology/HazardStore' import type { ObstacleField } from '../ecology/ObstacleField' +import type { EggState, EggStore } from '../entities/EggStore' import type { OrganismState, OrganismStore } from '../entities/OrganismStore' import type { ResourceState } from '../entities/ResourceStore' import { cos, sin } from '../math/trig' @@ -20,7 +21,7 @@ import { bodyRadiusOf } from '../organisms/traits' import type { ReproductionReadiness } from '../organisms/reproductionReadiness' import { SIGHT_BLOCKER_MARGIN, segmentHitsCircle } from '../spatial/sight' import type { SpatialHash, SpatialHit } from '../spatial/SpatialHash' -import { peerRole } from '../organisms/predation' +import { bitesCreatures, peerRole } from '../organisms/predation' /** What `PerceptionSystem` needs to also find the nearest other organism (brain controller only). */ export interface PeerSensing { @@ -50,6 +51,8 @@ export interface PredationSensing { readonly organismIndex: SpatialHash readonly prey: PreyBuffer readonly threat: ThreatBuffer + /** With `reproduction.eggs` on, an egg lying in sight is prey for a body that bites creatures (ADR 0027). */ + readonly eggs?: EggStore } /** @@ -174,6 +177,9 @@ export class PerceptionSystem { if (distanceSquared <= reach * reach) this.foodScratch.push({ item, distanceSquared }) } + /** The eggs lying about this tick, for the prey search (ADR 0027). */ + private eggList: EggState[] = [] + private readonly collectPeer = (item: OrganismState, distanceSquared: number): void => { if (item.id === this.cSelf) return const reach = this.reachFor(item.x - this.cX, item.y - this.cY, distanceSquared) @@ -257,11 +263,31 @@ export class PerceptionSystem { if (role === 'prey') prey = seen else threat = seen } + // An egg is prey too, whatever is nearer (ADR 0027): a hunter sees the nearest meal it could take. + if (this.eggList.length > 0 && bitesCreatures(organism.genome, this.config)) { + for (const egg of this.eggList) { + if (egg.motherId === organism.id || egg.fatherId === organism.id) continue + const dx = egg.x - this.cX + const dy = egg.y - this.cY + const distanceSquared = dx * dx + dy * dy + if (prey !== null && distanceSquared >= prey.distanceSquared) continue + const reach = this.reachFor(dx, dy, distanceSquared) + if (distanceSquared > reach * reach) continue + if (this.blockers !== undefined && this.blocked(organism, egg.x, egg.y, null)) continue + prey = { + organismId: egg.id, + position: { x: egg.x, y: egg.y }, + distanceSquared + } + } + } sensing.prey.set(organism.id, prey) sensing.threat.set(organism.id, threat) } update(tick = 0): void { + this.eggList = + this.predationSensing?.eggs === undefined ? [] : this.predationSensing.eggs.values() this.perceptionBuffer.clear() this.peers?.buffer.clear() this.hazardSensing?.buffer.clear() diff --git a/packages/simulation/src/world/World.ts b/packages/simulation/src/world/World.ts index 1358179..3fb8d4d 100644 --- a/packages/simulation/src/world/World.ts +++ b/packages/simulation/src/world/World.ts @@ -50,6 +50,7 @@ import { EggStore } from '../entities/EggStore' import { IdGenerator } from '../entities/IdGenerator' import type { OrganismState } from '../entities/OrganismStore' import { OrganismStore } from '../entities/OrganismStore' +import { guardsOf } from '../organisms/eggs' import { lifeStageFor } from '../organisms/lifeStage' import { ReproductionReadiness } from '../organisms/reproductionReadiness' import { @@ -344,7 +345,12 @@ export class World { this.sightBlockers(), // Prey and threats (ADR 0023): only with predation on; the buffers stay empty otherwise. this.config.predation.enabled - ? { organismIndex: this.organismIndex, prey: this.preyBuffer, threat: this.threatBuffer } + ? { + organismIndex: this.organismIndex, + prey: this.preyBuffer, + threat: this.threatBuffer, + ...(this.config.reproduction.eggs.enabled ? { eggs: this.eggStore } : {}) + } : undefined ) this.decisionSystem = new DecisionSystem( @@ -368,7 +374,8 @@ export class World { this.hazardBuffer, this.mateBuffer, this.preyBuffer, - this.threatBuffer + this.threatBuffer, + this.config.reproduction.eggs.enabled ? this.eggStore : undefined ) this.movementSystem = new MovementSystem( this.config, @@ -398,7 +405,8 @@ export class World { organismIndex: this.organismIndex, buffer: this.predationBuffer, lastBitten: this.lastBitten, - obstacles: this.obstacleField + obstacles: this.obstacleField, + ...(this.config.reproduction.eggs.enabled ? { eggs: this.eggStore } : {}) } : undefined ) @@ -1020,7 +1028,7 @@ export class World { fatherId: egg.fatherId, energy: egg.energy, progress: Math.min(1, Math.max(0, (tick - egg.layTick) / (egg.hatchTick - egg.layTick))), - guarded: false + guarded: guardsOf(egg, this.organisms, this.config.reproduction.eggs.guardRadius).length > 0 })) } diff --git a/packages/simulation/tests/lifecycle/egg-predation.test.ts b/packages/simulation/tests/lifecycle/egg-predation.test.ts new file mode 100644 index 0000000..a6333da --- /dev/null +++ b/packages/simulation/tests/lifecycle/egg-predation.test.ts @@ -0,0 +1,289 @@ +import { describe, expect, it } from 'vitest' +import { resolveWorldConfig } from '@evo/config' +import type { FounderPart, WorldConfig, WorldConfigOverrides } from '@evo/contracts' +import type { LastBitten, PredationBuffer } from '../../src/buffers/types' +import { ObstacleField } from '../../src/ecology/ObstacleField' +import { EggStore } from '../../src/entities/EggStore' +import type { EggState } from '../../src/entities/EggStore' +import { OrganismStore } from '../../src/entities/OrganismStore' +import type { OrganismState } from '../../src/entities/OrganismStore' +import { ResourceStore } from '../../src/entities/ResourceStore' +import type { ResourceState } from '../../src/entities/ResourceStore' +import { EventLog } from '../../src/events/EventLog' +import { founderBodyVector } from '../../src/genetics/BodyGenes' +import { genomeFromParts, genomeToVector } from '../../src/genetics/GenomeFactory' +import { mouthsOf } from '../../src/organisms/mouths' +import { guardsOf } from '../../src/organisms/eggs' +import { bodyRadiusOf } from '../../src/organisms/traits' +import { SpatialHash } from '../../src/spatial/SpatialHash' +import { EggSystem } from '../../src/systems/EggSystem' +import { InteractionSystem } from '../../src/systems/InteractionSystem' +import { LineageStore } from '../../src/lineage/LineageStore' +import { IdGenerator } from '../../src/entities/IdGenerator' +import { SeededRandom } from '../../src/random/SeededRandom' +import { deriveStreamWords } from '../../src/random/streams' +import { organismFor } from '../support/organism' +import { withoutEcology } from '../support/ecology' + +// Eggs are food for flesh-eating mouths and are defended by a parent beside them (ADR 0027). + +const config = (extra: WorldConfigOverrides = {}): WorldConfig => + resolveWorldConfig( + withoutEcology({ + ...extra, + learning: { controller: 'reflex' }, + ecology: { health: { enabled: true } }, + predation: { enabled: true }, + reproduction: { + sexes: { enabled: true }, + eggs: { enabled: true }, + ...extra.reproduction + } as never + }) + ) + +const founderOf = (cfg: WorldConfig): FounderPart[] => cfg.anatomy.founder.map((p) => ({ ...p })) + +function withMouth(o: OrganismState, cfg: WorldConfig, jaw: boolean): OrganismState { + const parts = founderOf(cfg).map((p) => + p.type === 'mouth' && jaw + ? { ...p, stats: [p.stats[0] ?? 0.5, p.stats[1] ?? 0.5, 0.9, 0.5, 0.5, 0.5] } + : p + ) + const genome = genomeFromParts({ + id: o.genome.id, + parentIds: o.genome.parentIds, + vector: genomeToVector(o.genome), + architecture: o.genome.brain.architecture, + weights: o.genome.brain.weights, + body: founderBodyVector({ ...cfg.anatomy, founder: parts }) + }) + return { ...o, genome } +} + +interface Scene { + readonly biter: OrganismState + readonly parent: OrganismState + readonly eggs: EggStore + readonly events: EventLog + readonly buffer: PredationBuffer + readonly lastBitten: LastBitten + tick(t?: number): void +} + +interface Options { + readonly jaw?: boolean + /** Whether the egg's mother (id 2) stands beside it. */ + readonly parentAt?: 'beside' | 'far' | 'dead' + readonly biterIsParent?: boolean +} + +/** A biter (id 1) with its mouth 3 units from an egg (id 3) of mother 2 and father 4. */ +function scene(cfg: WorldConfig, options: Options = {}): Scene { + const biter = withMouth( + organismFor(cfg, 1, { x: 100, y: 100, age: 200, energy: 50, sex: 1 }), + cfg, + options.jaw !== false + ) + const [mouthPoint] = mouthsOf(biter.genome, cfg) + const radius = bodyRadiusOf(biter.genome, cfg) + const mouth = { + x: biter.x + (mouthPoint?.x ?? 0) * radius, + y: biter.y + (mouthPoint?.y ?? 0) * radius + } + const egg: EggState = { + id: 3, + x: mouth.x + 3, + y: mouth.y, + genome: organismFor(cfg, 9).genome, + motherId: options.biterIsParent === true ? 1 : 2, + fatherId: 4, + speciesId: null, + energy: 20, + layTick: 0, + hatchTick: 200 + } + const parentX = options.parentAt === 'far' ? egg.x + 200 : egg.x + 2 + const parent = organismFor(cfg, 2, { x: parentX, y: egg.y, age: 200, energy: 50 }) + const organisms = new OrganismStore() + organisms.add(biter) + if (options.parentAt !== 'dead') organisms.add(parent) + const eggs = new EggStore() + eggs.add(egg) + const resources = new ResourceStore() + const resourceIndex = new SpatialHash(60, (r) => r) + resourceIndex.rebuild([]) + const organismIndex = new SpatialHash(60, (o) => o) + organismIndex.rebuild(organisms.values()) + const events = new EventLog(1000) + const buffer: PredationBuffer = new Map() + const lastBitten: LastBitten = new Map() + const system = new InteractionSystem( + cfg, + organisms, + resources, + resourceIndex, + events, + undefined, + null, + new Map(), + { organismIndex, buffer, lastBitten, obstacles: ObstacleField.empty(), eggs } + ) + return { + biter, + parent, + eggs, + events, + buffer, + lastBitten, + tick(t = 1) { + events.beginTick() + system.update(t) + } + } +} + +const ofType = (s: Scene, type: string) => s.events.eventsThisTick().filter((e) => e.type === type) + +describe('an unguarded egg is a meal for a jaw', () => { + it('is eaten whole: gone, its energy in the gut at the trophic loss and the flesh yield', () => { + const cfg = config() + const s = scene(cfg, { parentAt: 'far' }) + s.tick() + expect(s.eggs.size).toBe(0) + const [event] = ofType(s, 'egg-eaten') + expect(event).toMatchObject({ type: 'egg-eaten', eggId: 3, predatorId: 1, energyTaken: 20 }) + const expected = 20 * cfg.predation.trophicYield * cfg.predation.fleshYield.jaw + expect(s.biter.gut).toBeCloseTo(expected, 9) + expect(ofType(s, 'egg-guarded')).toEqual([]) + }) + + it('a dead parent guards nothing: the egg is eaten', () => { + const s = scene(config(), { parentAt: 'dead' }) + s.tick() + expect(s.eggs.size).toBe(0) + }) + + it('a mouth with no flesh yield never takes an egg: the founder, a mandible (negative)', () => { + const s = scene(config(), { jaw: false, parentAt: 'far' }) + s.tick() + expect(s.eggs.size).toBe(1) + expect(ofType(s, 'egg-eaten')).toEqual([]) + expect(s.biter.gut).toBe(0) + }) + + it("a creature never eats its own egg (negative: someone else's is eaten)", () => { + const own = scene(config(), { parentAt: 'far', biterIsParent: true }) + own.tick() + expect(own.eggs.size).toBe(1) + const other = scene(config(), { parentAt: 'far' }) + other.tick() + expect(other.eggs.size).toBe(0) + }) + + it('a full gut refuses the egg and it stays', () => { + const cfg = config() + const s = scene(cfg, { parentAt: 'far' }) + s.biter.gut = 1e9 + s.tick() + expect(s.eggs.size).toBe(1) + }) + + it('eggs are not eaten when the world has no eggs switched on for the system (negative)', () => { + const cfg = config() + const s = scene(cfg, { parentAt: 'far' }) + // A system built without the egg store knows of no eggs. + const organisms = new OrganismStore() + organisms.add(s.biter) + const index = new SpatialHash(60, (o) => o) + index.rebuild(organisms.values()) + const resourceIndex = new SpatialHash(60, (r) => r) + resourceIndex.rebuild([]) + const events = new EventLog(10) + const system = new InteractionSystem( + cfg, + organisms, + new ResourceStore(), + resourceIndex, + events, + undefined, + null, + new Map(), + { + organismIndex: index, + buffer: new Map(), + lastBitten: new Map(), + obstacles: ObstacleField.empty() + } + ) + events.beginTick() + system.update(1) + expect(s.eggs.size).toBe(1) + }) +}) + +describe('a parent beside its egg guards it', () => { + it('stops the bite, leaves the egg, hurts the biter and counts it as the guard’s bite', () => { + const cfg = config() + const s = scene(cfg, { parentAt: 'beside' }) + s.tick() + expect(s.eggs.size).toBe(1) + const [event] = ofType(s, 'egg-guarded') + expect(event).toMatchObject({ eggId: 3, guardId: 2, biterId: 1 }) + expect(s.biter.gut).toBe(0) + expect(s.buffer.get(1)?.attackerId).toBe(2) + expect(s.buffer.get(1)?.damage).toBeGreaterThan(0) + expect(s.lastBitten.get(1)).toEqual({ attackerId: 2, tick: 1 }) + expect(ofType(s, 'egg-eaten')).toEqual([]) + }) + + it('a parent farther than the guard radius does not guard (negative)', () => { + const cfg = config() + const s = scene(cfg, { parentAt: 'far' }) + const egg = s.eggs.get(3) as EggState + const organisms = new OrganismStore() + organisms.add(s.parent) + expect(guardsOf(egg, organisms, cfg.reproduction.eggs.guardRadius)).toEqual([]) + const near = organismFor(cfg, 2, { x: egg.x + 5, y: egg.y }) + const nearStore = new OrganismStore() + nearStore.add(near) + expect(guardsOf(egg, nearStore, cfg.reproduction.eggs.guardRadius)).toHaveLength(1) + }) + + it('guarding costs the parent guardCost a second, and nothing without an egg beside it', () => { + const cfg = config({ + reproduction: { eggs: { enabled: true, guardCost: 3 } } as never + }) + const organisms = new OrganismStore() + const parent = organismFor(cfg, 2, { x: 10, y: 10, energy: 50 }) + const stranger = organismFor(cfg, 5, { x: 10, y: 10, energy: 50 }) + organisms.add(parent) + organisms.add(stranger) + const eggs = new EggStore() + eggs.add({ + id: 6, + x: 12, + y: 10, + genome: organismFor(cfg, 9).genome, + motherId: 2, + fatherId: 4, + speciesId: null, + energy: 20, + layTick: 0, + hatchTick: 500 + }) + const system = new EggSystem( + cfg, + organisms, + eggs, + new IdGenerator(), + new LineageStore(), + new SeededRandom(deriveStreamWords(1, 'reproduction')), + new EventLog(10), + { assign: () => null, release: () => undefined, speciesOf: () => undefined } + ) + system.update(1) + expect(parent.energy).toBeCloseTo(50 - 3 * cfg.timestep, 9) + expect(stranger.energy).toBe(50) + }) +}) From ab5c9a9ad5c8dc263d469b46f775d0ccbe6854a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 19:31:52 +0000 Subject: [PATCH 04/11] feat(life-cycle): ageing (decline and a rising chance of dying), eggs drawn, life probe (ADR 0027) Ageing, off by default (ageing.enabled): past its own senescenceAge a creature burns more (metabolismRise), is slower (speedLoss) and needs more energy to breed (fertilityLoss), and instead of the hard cutoff at maxAge it faces a chance of dying per second that rises with how far past senescenceAge it is (hazard x s), with certain death at ceiling x maxAge. One draw per old creature per tick from the world stream, none in prime or with ageing off. The snapshot's lifeStage now uses the creature's own senescence genes instead of the world's baseline. Eggs are drawn as flat pale discs that fill as they near hatching, with a ring when a parent guards them, on an Eggs layer (default on); tests/probe/life.probe.ts measures the life cycle. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Cn5qp4xBHxLnTrwReNXcf8 --- packages/config/src/ageing.ts | 20 ++ packages/config/src/defaults.ts | 9 + packages/config/src/validation.ts | 6 +- packages/contracts/src/index.ts | 2 + packages/contracts/src/render.ts | 15 ++ packages/contracts/src/world.ts | 21 ++ packages/renderer/src/pixi/PixiRenderer.ts | 36 +++ packages/renderer/src/snapshot.ts | 12 + packages/simulation/src/organisms/ageing.ts | 37 +++ .../src/organisms/reproductionReadiness.ts | 8 +- .../simulation/src/systems/BrainSystem.ts | 4 +- .../simulation/src/systems/DeathSystem.ts | 27 ++- .../src/systems/MetabolismSystem.ts | 3 + .../simulation/src/systems/MovementSystem.ts | 7 +- packages/simulation/src/world/World.ts | 11 +- .../simulation/tests/lifecycle/ageing.test.ts | 227 ++++++++++++++++++ packages/simulation/tests/probe/life.probe.ts | 127 ++++++++++ packages/ui/src/Controls.tsx | 1 + 18 files changed, 562 insertions(+), 11 deletions(-) create mode 100644 packages/config/src/ageing.ts create mode 100644 packages/simulation/src/organisms/ageing.ts create mode 100644 packages/simulation/tests/lifecycle/ageing.test.ts create mode 100644 packages/simulation/tests/probe/life.probe.ts diff --git a/packages/config/src/ageing.ts b/packages/config/src/ageing.ts new file mode 100644 index 0000000..e267364 --- /dev/null +++ b/packages/config/src/ageing.ts @@ -0,0 +1,20 @@ +import { checkNumber, checkSection } from './checks' +import type { PlainObject } from './checks' + +const AGEING_KEYS = ['enabled', 'metabolismRise', 'speedLoss', 'fertilityLoss', 'hazard', 'ceiling'] + +/** Validates the top-level `ageing` section of a complete configuration (ADR 0027). */ +export function checkAgeing(root: PlainObject, errors: string[]): void { + const ageing = checkSection(root, 'ageing', AGEING_KEYS, errors) + if (!ageing) return + if (typeof ageing['enabled'] !== 'boolean') errors.push('ageing.enabled must be a boolean') + for (const key of ['metabolismRise', 'fertilityLoss', 'hazard'] as const) { + checkNumber(ageing, key, `ageing.${key}`, { nonnegative: true }, errors) + } + const loss = checkNumber(ageing, 'speedLoss', 'ageing.speedLoss', { nonnegative: true }, errors) + if (loss !== undefined && loss >= 1) errors.push('ageing.speedLoss must be less than 1') + const ceiling = checkNumber(ageing, 'ceiling', 'ageing.ceiling', {}, errors) + if (ceiling !== undefined && ceiling <= 1) { + errors.push('ageing.ceiling must be greater than 1 (a multiple of maxAge)') + } +} diff --git a/packages/config/src/defaults.ts b/packages/config/src/defaults.ts index 760a572..05f2afa 100644 --- a/packages/config/src/defaults.ts +++ b/packages/config/src/defaults.ts @@ -441,6 +441,15 @@ export const DEFAULT_WORLD_CONFIG: Readonly = deepFreeze({ perception: { organismsBlockSight: true, maxSightChecks: 6 + }, + // Ageing (ADR 0027): off here; switched on in the measured commit. + ageing: { + enabled: false, + metabolismRise: 0.5, + speedLoss: 0.3, + fertilityLoss: 0.5, + hazard: 0.04, + ceiling: 2 } } satisfies WorldConfig) diff --git a/packages/config/src/validation.ts b/packages/config/src/validation.ts index b828299..0b434d4 100644 --- a/packages/config/src/validation.ts +++ b/packages/config/src/validation.ts @@ -16,6 +16,7 @@ import { checkEcology } from './ecology' import { checkSpecies } from './species' import { checkAnatomy } from './anatomy' import { checkFeeding } from './feeding' +import { checkAgeing } from './ageing' import { checkPerception } from './perception' import { checkPredation } from './predation' import { checkClusters } from './clusters' @@ -37,6 +38,7 @@ const ROOT_KEYS = [ 'feeding', 'predation', 'perception', + 'ageing', 'observatory' ] const ENVIRONMENT_KEYS = ['width', 'height', 'layout', 'clusters'] @@ -446,6 +448,7 @@ export function validateWorldConfig(value: unknown): ValidationResult { checkFeeding(value, errors) checkPredation(value, errors) checkPerception(value, errors) + checkAgeing(value, errors) return { ok: errors.length === 0, errors } } @@ -700,7 +703,8 @@ export function resolveWorldConfig(overrides?: WorldConfigOverrides): WorldConfi anatomy: mergeAnatomy(base.anatomy, given['anatomy']), feeding: mergeSection(base.feeding, given['feeding']), predation: mergePredation(base.predation, given['predation']), - perception: mergeSection(base.perception, given['perception']) + perception: mergeSection(base.perception, given['perception']), + ageing: mergeSection(base.ageing, given['ageing']) } const result = validateWorldConfig(merged) if (!result.ok) throw new ConfigValidationError(result.errors) diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 5ef188a..ae02992 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -100,6 +100,7 @@ export type { PredationConfig, PerceptionConfig, ReproductionConfig, + AgeingConfig, ReproductionConfigOverrides, SexesConfig, EggsConfig, @@ -147,6 +148,7 @@ export { RENDER_LAYERS, DEFAULT_RENDER_LAYERS } from './render' export type { RenderOrganism, RenderResource, + RenderEgg, RenderHazard, RenderEffect, RenderSnapshot, diff --git a/packages/contracts/src/render.ts b/packages/contracts/src/render.ts index 664db52..a0e3185 100644 --- a/packages/contracts/src/render.ts +++ b/packages/contracts/src/render.ts @@ -57,6 +57,18 @@ export interface RenderResource { readonly bud?: { readonly x: number; readonly y: number; readonly progress: number } | null } +/** An egg lying in the world (ADR 0027): a small flat shape that fills as it nears hatching. */ +export interface RenderEgg { + readonly id: EntityId + readonly x: number + readonly y: number + readonly radius: number + /** Fraction of the way to hatching, in `[0, 1]`. */ + readonly progress: number + /** Whether a living parent is beside it. */ + readonly guarded: boolean +} + export interface RenderHazard { readonly id: number readonly kind: HazardKind @@ -82,6 +94,7 @@ export interface RenderSnapshot { readonly season: Season | null readonly organisms: readonly RenderOrganism[] readonly resources: readonly RenderResource[] + readonly eggs: readonly RenderEgg[] readonly hazards: readonly RenderHazard[] readonly effects: readonly RenderEffect[] readonly selectedEntityId: EntityId | null @@ -94,6 +107,7 @@ export const RENDER_LAYERS = [ 'hazards', 'obstacles', 'resources', + 'eggs', 'organisms', 'trails', 'selection', @@ -109,6 +123,7 @@ export const DEFAULT_RENDER_LAYERS: RenderLayers = { hazards: true, obstacles: true, resources: true, + eggs: true, organisms: true, trails: false, selection: true, diff --git a/packages/contracts/src/world.ts b/packages/contracts/src/world.ts index 01ab356..a577f56 100644 --- a/packages/contracts/src/world.ts +++ b/packages/contracts/src/world.ts @@ -329,6 +329,25 @@ export type ReproductionConfigOverrides = Partial } +/** + * Ageing (ADR 0027): once a creature is past its own `senescenceAge` it declines, and instead of a + * hard cutoff at `maxAge` it faces a chance of dying that rises with age. With `s` the share of the + * way from `senescenceAge` to `maxAge` (above 1 past `maxAge`), off means the old behaviour exactly. + */ +export interface AgeingConfig { + enabled: boolean + /** Metabolism rises by this much at `s = 1` (and is capped at `s = 2`): cost times `1 + metabolismRise * s`. */ + metabolismRise: number + /** Share of top speed lost at `s = 1`, in `[0, 1)`. */ + speedLoss: number + /** The energy needed to reproduce rises by this share at `s = 1`: an old creature breeds less. */ + fertilityLoss: number + /** Chance per second of dying at `s = 1`; it rises in proportion to `s`. */ + hazard: number + /** Death is certain at this multiple of `maxAge`, so nothing is immortal. */ + ceiling: number +} + export interface HistoryConfig { /** Events retained in the bounded event log; older events are dropped. `0` retains none. */ maxEvents: number @@ -371,6 +390,7 @@ export interface WorldConfig { feeding: FeedingConfig predation: PredationConfig perception: PerceptionConfig + ageing: AgeingConfig observatory: ObservatoryConfig } @@ -398,6 +418,7 @@ export interface WorldConfigOverrides { } } perception?: Partial + ageing?: Partial } export interface WorldOptions { diff --git a/packages/renderer/src/pixi/PixiRenderer.ts b/packages/renderer/src/pixi/PixiRenderer.ts index 2f08ba9..d812ab1 100644 --- a/packages/renderer/src/pixi/PixiRenderer.ts +++ b/packages/renderer/src/pixi/PixiRenderer.ts @@ -123,6 +123,8 @@ export class PixiRenderer implements Renderer { private obstacleG = new Graphics() /** One flat line from each plant's hub to each of its nodes, and the buds growing back. */ private stemG = new Graphics() + /** The eggs (ADR 0027): flat shapes redrawn each scene. */ + private eggG = new Graphics() private trailG = new Graphics() private selectionG = new Graphics() private resources: PoolHost = { container: new Container(), pool: [] } @@ -191,6 +193,7 @@ export class PixiRenderer implements Renderer { this.obstacleG, this.stemG, this.resources.container, + this.eggG, this.bodies.container, this.trailG, this.selectionG @@ -336,6 +339,7 @@ export class PixiRenderer implements Renderer { this.hazardG.visible = layers.hazards this.obstacleG.visible = layers.obstacles this.resources.container.visible = layers.resources + this.eggG.visible = layers.eggs this.bodies.container.visible = layers.organisms this.motionOn = layers.motion this.trailG.visible = layers.trails @@ -739,6 +743,7 @@ export class PixiRenderer implements Renderer { this.drawHazards(frame) this.drawStems(frame) + this.drawEggs(frame) this.drawTrails(frame) this.drawSelection(frame) @@ -758,6 +763,37 @@ export class PixiRenderer implements Renderer { } } + /** + * Eggs (ADR 0027): a pale flat disc with a thin edge, a darker core that grows as it nears + * hatching, and a thin ring around one a parent is guarding. Never smaller than 1.6 px on screen. + */ + private drawEggs(frame: RenderSnapshot): void { + this.eggG.clear() + if (frame.eggs.length === 0) return + const zoom = this.camera.state.zoom + for (const egg of frame.eggs) { + const radius = Math.max(egg.radius, 1.6 / zoom) + this.eggG.circle(egg.x, egg.y, radius).fill({ color: 0xece3c8, alpha: 0.95 }) + this.eggG + .circle(egg.x, egg.y, Math.max(radius * 0.8 * egg.progress, 0.3 / zoom)) + .fill({ color: 0xc9a35a, alpha: 0.9 }) + this.eggG.circle(egg.x, egg.y, radius).stroke({ + width: 1, + color: 0x8a7a55, + alpha: 0.9, + pixelLine: true + }) + if (egg.guarded) { + this.eggG.circle(egg.x, egg.y, radius * 2.2).stroke({ + width: 1, + color: 0xe0b34a, + alpha: 0.7, + pixelLine: true + }) + } + } + } + /** * Plants (ADR 0021): one flat 1 px line from a hub to each of its nodes, and a small ring where a * node is growing back, as large as the share of it already grown. Flat, no fill, no glow. diff --git a/packages/renderer/src/snapshot.ts b/packages/renderer/src/snapshot.ts index a32063d..1cb05ee 100644 --- a/packages/renderer/src/snapshot.ts +++ b/packages/renderer/src/snapshot.ts @@ -58,6 +58,9 @@ function organismOf( * Maps an engine snapshot to what the renderer draws (roadmap 7.2). Pure: it reads the snapshot and * returns new objects, so nothing the renderer does can reach the engine. */ +/** An egg is drawn about as large as a piece of food, in world units. */ +const EGG_DRAW_RADIUS = 2 + export function buildRenderSnapshot(world: WorldSnapshot, context: RenderContext): RenderSnapshot { return { tick: world.tick, @@ -85,6 +88,15 @@ export function buildRenderSnapshot(world: WorldSnapshot, context: RenderContext ? {} : { parent: resource.parent ?? 0, slot: resource.slot, bud: resource.bud ?? null }) })), + // The eggs (ADR 0027): as wide as a piece of food, so no new size is invented. + eggs: world.eggs.map((egg) => ({ + id: egg.id, + x: egg.position.x, + y: egg.position.y, + radius: EGG_DRAW_RADIUS, + progress: egg.progress, + guarded: egg.guarded + })), hazards: world.hazards.map((hazard) => ({ id: hazard.id, kind: hazard.kind, diff --git a/packages/simulation/src/organisms/ageing.ts b/packages/simulation/src/organisms/ageing.ts new file mode 100644 index 0000000..2411c48 --- /dev/null +++ b/packages/simulation/src/organisms/ageing.ts @@ -0,0 +1,37 @@ +import type { AgeingConfig } from '@evo/contracts' + +/** The ages that set a creature's own senescence (its genes, not the world's baseline). */ +export interface AgeGenes { + readonly senescenceAge: number + readonly maxAge: number +} + +/** + * How far into old age a creature is (ADR 0027): `0` until its `senescenceAge`, `1` at its `maxAge`, + * and above 1 beyond it. A pure function of age and its own genes, never stored. + */ +export function senescenceOf(age: number, genes: AgeGenes): number { + if (age <= genes.senescenceAge) return 0 + return (age - genes.senescenceAge) / Math.max(genes.maxAge - genes.senescenceAge, 1) +} + +/** What metabolism costs now, as a multiple of what it did (exactly 1 with ageing off or in prime). */ +export function ageingCostFactor(ageing: AgeingConfig, age: number, genes: AgeGenes): number { + if (!ageing.enabled) return 1 + const s = senescenceOf(age, genes) + return s === 0 ? 1 : 1 + ageing.metabolismRise * Math.min(s, 2) +} + +/** The share of top speed kept now (exactly 1 with ageing off or in prime). */ +export function ageingSpeedFactor(ageing: AgeingConfig, age: number, genes: AgeGenes): number { + if (!ageing.enabled) return 1 + const s = senescenceOf(age, genes) + return s === 0 ? 1 : 1 - ageing.speedLoss * Math.min(s, 1) +} + +/** What the energy needed to reproduce is multiplied by now (exactly 1 with ageing off or in prime). */ +export function ageingFertilityFactor(ageing: AgeingConfig, age: number, genes: AgeGenes): number { + if (!ageing.enabled) return 1 + const s = senescenceOf(age, genes) + return s === 0 ? 1 : 1 + ageing.fertilityLoss * Math.min(s, 1) +} diff --git a/packages/simulation/src/organisms/reproductionReadiness.ts b/packages/simulation/src/organisms/reproductionReadiness.ts index 8bc1561..da49b3a 100644 --- a/packages/simulation/src/organisms/reproductionReadiness.ts +++ b/packages/simulation/src/organisms/reproductionReadiness.ts @@ -1,6 +1,7 @@ import type { WorldConfig } from '@evo/contracts' import type { EcologyModel } from '../ecology/EcologyModel' import type { OrganismState } from '../entities/OrganismStore' +import { ageingFertilityFactor } from './ageing' import { lifeStageFor } from './lifeStage' import { reproductionCostOf, reproductionThresholdOf } from './traits' @@ -36,8 +37,11 @@ export class ReproductionReadiness { * never less than the cost it would pay here. */ thresholdFor(organism: OrganismState, tick: number): number { - if (!this.terrainScales) return reproductionThresholdOf(organism.genome, this.config) - return Math.max(organism.genome.reproduction.minEnergy, this.costFor(organism, tick)) + const base = this.terrainScales + ? Math.max(organism.genome.reproduction.minEnergy, this.costFor(organism, tick)) + : reproductionThresholdOf(organism.genome, this.config) + // An old creature needs more energy to breed (ADR 0027); exactly 1 with ageing off. + return base * ageingFertilityFactor(this.config.ageing, organism.age, organism.genome.physical) } /** diff --git a/packages/simulation/src/systems/BrainSystem.ts b/packages/simulation/src/systems/BrainSystem.ts index d991345..0415be0 100644 --- a/packages/simulation/src/systems/BrainSystem.ts +++ b/packages/simulation/src/systems/BrainSystem.ts @@ -25,6 +25,7 @@ import { TWO_PI } from '../math/scalar' import { atan2, cos, sin } from '../math/trig' import { computeReward } from '../learning/RewardModel' import { lifeStageFor } from '../organisms/lifeStage' +import { ageingSpeedFactor } from '../organisms/ageing' import { factorsOf } from '../organisms/bodyFactors' import { maxEnergyOf, maxHealthOf, reproductionCostOf, sensorRadiusOf } from '../organisms/traits' import type { SeededRandom } from '../random/SeededRandom' @@ -94,7 +95,8 @@ export class BrainSystem { maxSpeed: this.config.organisms.maxSpeed * (juvenile ? juvenileSpeedScale : 1) * - factorsOf(organism.genome, this.config).speed + factorsOf(organism.genome, this.config).speed * + ageingSpeedFactor(this.config.ageing, organism.age, organism.genome.physical) } } diff --git a/packages/simulation/src/systems/DeathSystem.ts b/packages/simulation/src/systems/DeathSystem.ts index 39fabf7..2e1fb06 100644 --- a/packages/simulation/src/systems/DeathSystem.ts +++ b/packages/simulation/src/systems/DeathSystem.ts @@ -1,9 +1,11 @@ -import type { DeathCause, EntityId } from '@evo/contracts' +import type { AgeingConfig, DeathCause, EntityId } from '@evo/contracts' import type { LastBitten } from '../buffers/types' import type { OrganismState, OrganismStore } from '../entities/OrganismStore' import type { EventLog } from '../events/EventLog' import type { HistoryStore } from '../history/HistoryStore' import type { LineageStore } from '../lineage/LineageStore' +import { senescenceOf } from '../organisms/ageing' +import type { RandomSource } from '../random/RandomSource' import { NO_MIGRATION } from '../ecology/MigrationTracker' import type { MigrationRecorder } from '../ecology/MigrationTracker' import { NO_SPECIES } from '../species/SpeciesRegistry' @@ -27,7 +29,13 @@ export class DeathSystem { /** Present only with `predation.enabled` (ADR 0023): who bit whom, and for how many ticks a bite counts. */ private readonly predation?: { readonly lastBitten: LastBitten; readonly windowTicks: number }, /** Called for each creature that dies, after it has been removed (carcasses are left from here). */ - private readonly onDied?: (organism: OrganismState, cause: DeathCause, tick: number) => void + private readonly onDied?: (organism: OrganismState, cause: DeathCause, tick: number) => void, + /** Present only with `ageing.enabled` (ADR 0027): death of old age is a chance, not a cutoff. */ + private readonly ageing?: { + readonly config: AgeingConfig + readonly timestep: number + readonly random: RandomSource + } ) {} update(tick: number): void { @@ -43,8 +51,19 @@ export class DeathSystem { cause = 'starvation' } else if (organism.health <= 0) { cause = 'damage' - } else if (organism.age >= organism.genome.physical.maxAge) { - cause = 'age' + } else if (this.ageing === undefined) { + if (organism.age >= organism.genome.physical.maxAge) cause = 'age' + } else { + // Ageing (ADR 0027): no cutoff at `maxAge`; the chance of dying rises with how far past + // `senescenceAge` the creature is, one draw a tick for each old creature, and death is certain + // at `ceiling` times `maxAge`. + const { config, timestep, random } = this.ageing + const s = senescenceOf(organism.age, organism.genome.physical) + if (organism.age >= organism.genome.physical.maxAge * config.ceiling) { + cause = 'age' + } else if (s > 0 && random.float() < config.hazard * s * timestep) { + cause = 'age' + } } if (cause === null) continue // A creature that was bitten a moment ago and then starved or was worn down was killed by the diff --git a/packages/simulation/src/systems/MetabolismSystem.ts b/packages/simulation/src/systems/MetabolismSystem.ts index 78d7de7..9f529e7 100644 --- a/packages/simulation/src/systems/MetabolismSystem.ts +++ b/packages/simulation/src/systems/MetabolismSystem.ts @@ -4,6 +4,7 @@ import type { EcologyModel } from '../ecology/EcologyModel' import type { OrganismStore } from '../entities/OrganismStore' import type { EventLog } from '../events/EventLog' import { lifeStageFor } from '../organisms/lifeStage' +import { ageingCostFactor } from '../organisms/ageing' import { factorsOf } from '../organisms/bodyFactors' import { basalCostOf, learningCostOf, outlineDragFactor, sensorCostOf } from '../organisms/traits' @@ -55,6 +56,8 @@ export class MetabolismSystem { body.temperatureTolerance ))) * scale * + // An old creature burns more (ADR 0027); exactly 1 with ageing off or before senescence. + ageingCostFactor(this.config.ageing, organism.age, genome.physical) * dt const previous = organism.energy const healing = this.regen?.get(organism.id) ?? 0 diff --git a/packages/simulation/src/systems/MovementSystem.ts b/packages/simulation/src/systems/MovementSystem.ts index 3aa3655..a9add1f 100644 --- a/packages/simulation/src/systems/MovementSystem.ts +++ b/packages/simulation/src/systems/MovementSystem.ts @@ -6,6 +6,7 @@ import { clamp, wrapAngle } from '../math/scalar' import { cos, sin } from '../math/trig' import type { EcologyModel } from '../ecology/EcologyModel' import type { Obstacle, ObstacleField } from '../ecology/ObstacleField' +import { ageingSpeedFactor } from '../organisms/ageing' import { factorsOf } from '../organisms/bodyFactors' import { lifeStageFor } from '../organisms/lifeStage' import { bodyRadiusOf } from '../organisms/traits' @@ -126,7 +127,11 @@ export class MovementSystem { chew : baseMaxSpeed * chew // The parts decide how much of that speed forward and sideways thrust can deliver. - const scaledMaxSpeed = terrainSpeed * body.speed + const scaledMaxSpeed = + terrainSpeed * + body.speed * + // An old creature is slower (ADR 0027); exactly 1 with ageing off or before senescence. + ageingSpeedFactor(this.config.ageing, organism.age, genes) const speed = clamp(intent.thrust, 0, 1) * scaledMaxSpeed let vx = cos(heading) * speed let vy = sin(heading) * speed diff --git a/packages/simulation/src/world/World.ts b/packages/simulation/src/world/World.ts index 3fb8d4d..21d117e 100644 --- a/packages/simulation/src/world/World.ts +++ b/packages/simulation/src/world/World.ts @@ -487,7 +487,14 @@ export class World { fatherId: organism.pregnancy.fatherId }) } - } + }, + this.config.ageing.enabled + ? { + config: this.config.ageing, + timestep: this.config.timestep, + random: this.randomStreams.get('world') + } + : undefined ) this.events.beginTick() @@ -1063,7 +1070,7 @@ export class World { maxEnergy: maxEnergyOf(organism.genome, this.config), health: organism.health, maxHealth: maxHealthOf(organism.genome, this.config), - lifeStage: lifeStageFor(organism.age, this.config.organisms), + lifeStage: lifeStageFor(organism.age, organism.genome.physical), reproductionCooldownRemaining: organism.reproductionCooldownRemaining, gut: organism.gut, gutCapacity: this.config.feeding.enabled ? gutCapacityOf(organism.genome, this.config) : 0, diff --git a/packages/simulation/tests/lifecycle/ageing.test.ts b/packages/simulation/tests/lifecycle/ageing.test.ts new file mode 100644 index 0000000..e5ad6b0 --- /dev/null +++ b/packages/simulation/tests/lifecycle/ageing.test.ts @@ -0,0 +1,227 @@ +import { describe, expect, it } from 'vitest' +import { resolveWorldConfig } from '@evo/config' +import type { AgeingConfig, WorldConfigOverrides } from '@evo/contracts' +import { OrganismStore } from '../../src/entities/OrganismStore' +import { EventLog } from '../../src/events/EventLog' +import { HistoryStore } from '../../src/history/HistoryStore' +import { LineageStore } from '../../src/lineage/LineageStore' +import { + ageingCostFactor, + ageingFertilityFactor, + ageingSpeedFactor, + senescenceOf +} from '../../src/organisms/ageing' +import { ReproductionReadiness } from '../../src/organisms/reproductionReadiness' +import type { RandomSource } from '../../src/random/RandomSource' +import { DeathSystem } from '../../src/systems/DeathSystem' +import { MetabolismSystem } from '../../src/systems/MetabolismSystem' +import { World } from '../../src/index' +import { organismFor } from '../support/organism' + +// Ageing (ADR 0027): decline past `senescenceAge` and a chance of dying that rises with age, +// instead of a hard cutoff at `maxAge`. + +const AGES = { senescenceAge: 100, maxAge: 200 } +const ON: AgeingConfig = { + enabled: true, + metabolismRise: 0.5, + speedLoss: 0.3, + fertilityLoss: 0.5, + hazard: 0.04, + ceiling: 2 +} + +describe('senescence', () => { + it('is 0 until senescenceAge, 1 at maxAge and above 1 beyond it', () => { + expect(senescenceOf(0, AGES)).toBe(0) + expect(senescenceOf(100, AGES)).toBe(0) + expect(senescenceOf(150, AGES)).toBeCloseTo(0.5, 12) + expect(senescenceOf(200, AGES)).toBeCloseTo(1, 12) + expect(senescenceOf(300, AGES)).toBeCloseTo(2, 12) + }) + + it('never divides by zero when the two ages meet', () => { + expect(Number.isFinite(senescenceOf(500, { senescenceAge: 300, maxAge: 300 }))).toBe(true) + }) +}) + +describe('the decline', () => { + it('is exactly 1 with ageing off, whatever the age (negative)', () => { + const off = { ...ON, enabled: false } + for (const age of [0, 150, 400]) { + expect(ageingCostFactor(off, age, AGES)).toBe(1) + expect(ageingSpeedFactor(off, age, AGES)).toBe(1) + expect(ageingFertilityFactor(off, age, AGES)).toBe(1) + } + }) + + it('is exactly 1 in prime, with ageing on', () => { + expect(ageingCostFactor(ON, 100, AGES)).toBe(1) + expect(ageingSpeedFactor(ON, 100, AGES)).toBe(1) + expect(ageingFertilityFactor(ON, 100, AGES)).toBe(1) + }) + + it('costs more, slows and needs more energy to breed as a creature ages, within bounds', () => { + expect(ageingCostFactor(ON, 150, AGES)).toBeCloseTo(1.25, 12) + expect(ageingCostFactor(ON, 200, AGES)).toBeCloseTo(1.5, 12) + // The cost rise is capped at s = 2, speed and fertility at s = 1. + expect(ageingCostFactor(ON, 900, AGES)).toBeCloseTo(2, 12) + expect(ageingSpeedFactor(ON, 150, AGES)).toBeCloseTo(0.85, 12) + expect(ageingSpeedFactor(ON, 900, AGES)).toBeCloseTo(0.7, 12) + expect(ageingFertilityFactor(ON, 150, AGES)).toBeCloseTo(1.25, 12) + expect(ageingFertilityFactor(ON, 900, AGES)).toBeCloseTo(1.5, 12) + }) + + it('an old creature pays more in metabolism than a young one, and none extra with ageing off', () => { + const energyLoss = (enabled: boolean, age: number): number => { + const config = resolveWorldConfig({ + learning: { controller: 'reflex' }, + ageing: { enabled } + }) + const old = organismFor(config, 1, { energy: 50, age }) + const organisms = new OrganismStore() + organisms.add(old) + const before = old.energy + new MetabolismSystem(config, organisms, new EventLog(10), null).update(1) + return before - old.energy + } + const maxAge = organismFor(resolveWorldConfig(), 1).genome.physical.maxAge + const youngCost = energyLoss(true, 120) + expect(energyLoss(true, maxAge)).toBeGreaterThan(youngCost * 1.3) + // Negative: with ageing off an old creature costs what a prime one does. + expect(energyLoss(false, maxAge)).toBeCloseTo(energyLoss(false, 120), 12) + }) + + it('an old creature needs more energy to be ready to reproduce', () => { + const config = resolveWorldConfig({ ageing: { enabled: true } }) + const readiness = new ReproductionReadiness(config, null) + const genes = organismFor(config, 1).genome.physical + const prime = organismFor(config, 1, { age: genes.maturityAge + 1 }) + const old = organismFor(config, 2, { age: genes.maxAge }) + expect(readiness.thresholdFor(old, 0)).toBeGreaterThan(readiness.thresholdFor(prime, 0)) + const off = new ReproductionReadiness(resolveWorldConfig(), null) + expect(off.thresholdFor(old, 0)).toBe(off.thresholdFor(prime, 0)) + }) +}) + +describe('death of old age is a chance, not a cutoff', () => { + const config = resolveWorldConfig({ learning: { controller: 'reflex' } }) + + /** Runs the death system once over one creature of `age`; returns whether it died and the draws made. */ + function dies( + ageing: AgeingConfig | undefined, + age: number, + draw = 0.5 + ): { died: boolean; draws: number } { + const organisms = new OrganismStore() + const lineage = new LineageStore() + const creature = organismFor(config, 1, { age, energy: 50, health: 100 }) + organisms.add(creature) + lineage.register({ genomeId: creature.genome.id, parentGenomeIds: [], organismId: 1, tick: 0 }) + let draws = 0 + const random: RandomSource = { + float: () => { + draws += 1 + return draw + } + } as RandomSource + new DeathSystem( + organisms, + new EventLog(10), + new HistoryStore(10), + lineage, + undefined, + undefined, + undefined, + undefined, + ageing === undefined ? undefined : { config: ageing, timestep: config.timestep, random } + ).update(1) + return { died: !organisms.has(1), draws } + } + const { maxAge, senescenceAge } = organismFor(config, 1).genome.physical + + it('without ageing the creature dies at maxAge exactly, as before (negative)', () => { + expect(dies(undefined, maxAge - 0.01).died).toBe(false) + expect(dies(undefined, maxAge).died).toBe(true) + }) + + it('with ageing there is no cutoff at maxAge: a lucky draw survives it', () => { + expect(dies(ON, maxAge, 0.99).died).toBe(false) + }) + + it('an unlucky draw kills an old creature, and the chance rises with age', () => { + const mid = (senescenceAge + maxAge) / 2 + // hazard x s x dt: at the middle s = 0.5, so the chance a tick is 0.04 x 0.5 x 0.1. + expect(dies(ON, mid, 0.0019).died).toBe(true) + expect(dies(ON, mid, 0.0021).died).toBe(false) + expect(dies(ON, maxAge, 0.0039).died).toBe(true) + expect(dies(ON, maxAge, 0.0041).died).toBe(false) + }) + + it('draws nothing for a creature in its prime (negative)', () => { + expect(dies(ON, senescenceAge - 1, 0).draws).toBe(0) + expect(dies(ON, senescenceAge - 1, 0).died).toBe(false) + expect(dies(ON, senescenceAge + 1, 0.99).draws).toBe(1) + }) + + it('death is certain at ceiling times maxAge', () => { + expect(dies(ON, maxAge * ON.ceiling, 0.99).died).toBe(true) + expect(dies(ON, maxAge * ON.ceiling - 1, 0.99).died).toBe(false) + }) +}) + +describe('in a world', () => { + const SHORT: WorldConfigOverrides = { + organisms: { maxAge: 120, senescenceAge: 80, maturityAge: 30 } + } + + it('creatures outlive their maxAge with ageing on and never without it', () => { + const oldest = (enabled: boolean): number => { + const world = World.create({ + seed: 3, + config: { ...SHORT, ageing: { enabled, hazard: 0.005 } } + }) + let max = 0 + for (let t = 0; t < 2500; t++) { + world.step() + if (t % 50 === 0) { + for (const o of world.snapshot().organisms) max = Math.max(max, o.age / o.maxAge) + } + } + return max + } + expect(oldest(true)).toBeGreaterThan(1) + expect(oldest(false)).toBeLessThanOrEqual(1) + }) + + it('is deterministic and the same stepped or chunked', () => { + const config = { ...SHORT, ageing: { enabled: true } } + const a = World.create({ seed: 4, config }) + a.run(1500) + const b = World.create({ seed: 4, config }) + b.run(700) + b.run(800) + expect(b.stateHash()).toBe(a.stateHash()) + }) +}) + +describe('configuration', () => { + it('is off by default', () => { + expect(resolveWorldConfig().ageing.enabled).toBe(false) + }) + + it('rejects bad values and unknown keys', () => { + for (const ageing of [ + { enabled: 'yes' }, + { metabolismRise: -1 }, + { speedLoss: 1 }, + { fertilityLoss: -0.1 }, + { hazard: -1 }, + { ceiling: 1 }, + { cure: true } + ]) { + expect(() => resolveWorldConfig({ ageing: ageing as never })).toThrow() + } + expect(() => resolveWorldConfig({ ageing: { enabled: true, hazard: 0 } })).not.toThrow() + }) +}) diff --git a/packages/simulation/tests/probe/life.probe.ts b/packages/simulation/tests/probe/life.probe.ts new file mode 100644 index 0000000..2d6d93b --- /dev/null +++ b/packages/simulation/tests/probe/life.probe.ts @@ -0,0 +1,127 @@ +import { describe, it } from 'vitest' +import { appendFileSync, mkdirSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { mouthFormOf } from '@evo/contracts' +import { World } from '../../src/index' + +/** + * How the life cycle (ADR 0027) plays out: viability columns (extinct worlds, mean and lowest + * population, starved share of deaths) and the egg columns (laid, hatched, eaten, clutches lost, a + * parent defending, hatch share, the share of energy that came from eggs, the share of eggs that + * lay guarded, females and jaws at the end). A measurement, not a test. + * + * Environment: `LIFE_NAME` (label), `LIFE_CONFIG` (JSON overrides merged over the life cycle on), + * `LIFE_OFF=1` (control: sexes and eggs off, then `LIFE_CONFIG` as given), `LIFE_SEEDS` (default 1..8), + * `LIFE_TICKS` (default 30000). One line goes to `/evo-probe/life-.txt`. + */ +const NAME = process.env.LIFE_NAME ?? 'on' +const OFF = process.env.LIFE_OFF === '1' +const EXTRA = JSON.parse(process.env.LIFE_CONFIG ?? '{}') as Record +const SEEDS = (process.env.LIFE_SEEDS ?? '1,2,3,4,5,6,7,8').split(',').map(Number) +const TICKS = Number(process.env.LIFE_TICKS ?? 30_000) +const SAMPLE = 2_500 + +describe('life-cycle probe', () => { + it(`measures ${NAME}`, () => { + let extinct = 0 + let popSum = 0 + let lowest = Infinity + let starved = 0 + let deaths = 0 + let laid = 0 + let hatched = 0 + let eaten = 0 + let lost = 0 + let guarded = 0 + let eggEnergy = 0 + let consumed = 0 + let females = 0 + let creatures = 0 + let jawEnd = 0 + let seedsWithJaw = 0 + let guardedSamples = 0 + let eggSamples = 0 + let ms = 0 + let ticks = 0 + const perSeed: string[] = [] + for (const seed of SEEDS) { + const reproduction = OFF + ? { ...(EXTRA['reproduction'] ?? {}) } + : { + ...(EXTRA['reproduction'] ?? {}), + sexes: { enabled: true }, + eggs: { enabled: true, ...((EXTRA['reproduction'] ?? {}).eggs ?? {}) } + } + const world = World.create({ seed, config: { ...EXTRA, reproduction } as never }) + let sum = 0 + let samples = 0 + const started = performance.now() + for (let tick = 0; tick < TICKS; tick += SAMPLE) { + world.run(SAMPLE) + const snapshot = world.snapshot() + sum += snapshot.organisms.length + samples++ + lowest = Math.min(lowest, snapshot.organisms.length) + eggSamples += snapshot.eggs.length + guardedSamples += snapshot.eggs.filter((e) => e.guarded).length + } + ms += performance.now() - started + ticks += TICKS + const end = world.snapshot() + const m = end.metrics + if (world.isExtinct) extinct++ + popSum += sum / samples + starved += m.deathsByStarvation + deaths += m.deathsByStarvation + m.deathsByAge + m.deathsByDamage + m.deathsByPredation + laid += m.eggsLaid + hatched += m.eggsHatched + eaten += m.eggsEaten + lost += m.clutchesLost + consumed += m.energyConsumed + females += end.organisms.filter((o) => o.sex === 0).length + creatures += end.organisms.length + let jaws = 0 + for (const o of end.organisms) { + const parts = world.anatomyOf(o.id)?.anatomy.parts ?? [] + if ( + parts.some( + (p) => p.type === 'mouth' && p.functional && mouthFormOf(p.stats[2] as number) === 'jaw' + ) + ) { + jaws++ + } + } + jawEnd += jaws + if (jaws > 0) seedsWithJaw++ + perSeed.push(`${seed}:${world.isExtinct ? 'X' : Math.round(sum / samples)}/${jaws}j`) + } + void guarded + void eggEnergy + const n = SEEDS.length + const line = [ + NAME, + `seeds=${n}`, + `extinct=${extinct}`, + `pop=${(popSum / n).toFixed(1)}`, + `lowest=${lowest}`, + `starved=${((100 * starved) / Math.max(1, deaths)).toFixed(0)}%`, + `laid=${(laid / n).toFixed(0)}`, + `hatched=${(hatched / n).toFixed(0)}`, + `hatch%=${((100 * hatched) / Math.max(1, laid)).toFixed(0)}`, + `eaten=${(eaten / n).toFixed(1)}`, + `lost=${(lost / n).toFixed(1)}`, + `guarded%=${((100 * guardedSamples) / Math.max(1, eggSamples)).toFixed(0)}`, + `eggsNow=${(eggSamples / (n * (TICKS / SAMPLE))).toFixed(1)}`, + `females%=${((100 * females) / Math.max(1, creatures)).toFixed(0)}`, + `jawEnd=${(jawEnd / n).toFixed(1)}(${seedsWithJaw}/${n})`, + `tps=${((1000 * ticks) / ms).toFixed(0)}`, + perSeed.join(' ') + ].join(' ') + void consumed + const dir = join(tmpdir(), 'evo-probe') + mkdirSync(dir, { recursive: true }) + appendFileSync(join(dir, `life-${NAME}.txt`), line + '\n') + console.log(line) + }, 3_600_000) +}) diff --git a/packages/ui/src/Controls.tsx b/packages/ui/src/Controls.tsx index 0303e19..a351f83 100644 --- a/packages/ui/src/Controls.tsx +++ b/packages/ui/src/Controls.tsx @@ -12,6 +12,7 @@ const LAYER_LABELS: Readonly> = { hazards: 'Hazards', obstacles: 'Obstacles', resources: 'Food', + eggs: 'Eggs', organisms: 'Organisms', trails: 'Trails', selection: 'Selection and events', From a4777a0e1e12a7c5efdc3c00d57d92f52bcdf173 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 19:48:53 +0000 Subject: [PATCH 05/11] feat(life-cycle): mate choice, two heritable genes and mutual acceptance (ADR 0027) reproduction.mateChoice (off by default, needs two sexes): a creature looks at the nearest few ready partners of the other sex and takes the first that both accept. It scores a candidate (1 - preference) x condition + preference x difference (condition: spare energy over what the candidate needs to be ready; difference: genomic distance against the species threshold) and accepts if the score reaches choosiness x threshold; turning every candidate down costs searchCost energy and a retryDelay wait (failure reason 'rejected'). choosiness and preference are two new reproduction genes appended to the table (Genome.version 5), so they mutate and recombine like any other. A creature with choosiness 0 accepts anyone and the world is bit for bit the one without mate choice (tested). The gene table grows by two, so every founder's later genetics draws shift and every golden entry is regenerated here. With the life cycle off, nine scenarios (field, instant eating, noise food, one cluster, lush, no predation, no ecology, reflex) give snapshots identical to the code before the life-cycle work; a multi-cluster layout differs only through the shifted genetics stream (its founders differ, so the blend of their children depends on the draws). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Cn5qp4xBHxLnTrwReNXcf8 --- packages/config/src/defaults.ts | 12 + packages/config/src/genetics.ts | 5 + packages/config/src/validation.ts | 68 +++- packages/contracts/src/events.ts | 2 +- packages/contracts/src/genome.ts | 15 +- packages/contracts/src/index.ts | 1 + packages/contracts/src/world.ts | 30 +- .../simulation/src/genetics/GenomeFactory.ts | 2 +- .../src/genetics/GenomeValidation.ts | 2 +- .../src/systems/ReproductionSystem.ts | 87 ++++- packages/simulation/src/world/World.ts | 19 +- .../simulation/tests/genetics/factory.test.ts | 4 +- .../simulation/tests/golden/state-hashes.json | 88 ++--- .../tests/lifecycle/mate-choice.test.ts | 344 ++++++++++++++++++ .../tests/phase5-exit-criteria.test.ts | 3 +- packages/simulation/tests/world.test.ts | 9 +- 16 files changed, 617 insertions(+), 74 deletions(-) create mode 100644 packages/simulation/tests/lifecycle/mate-choice.test.ts diff --git a/packages/config/src/defaults.ts b/packages/config/src/defaults.ts index 05f2afa..db7fd1f 100644 --- a/packages/config/src/defaults.ts +++ b/packages/config/src/defaults.ts @@ -108,6 +108,16 @@ export const DEFAULT_WORLD_CONFIG: Readonly = deepFreeze({ guardRadius: 20, guardCost: 0.05, guardDamage: 5 + }, + // Off here; the founders' two genes sit at a mild taste (ADR 0027). + mateChoice: { + enabled: false, + choosiness: 0.3, + preference: 0.3, + threshold: 0.5, + searchCost: 0.5, + retryDelay: 2, + candidates: 4 } }, history: { maxEvents: 10_000, eventDetail: 'essential', maxHistoricalOrganisms: 10_000 }, @@ -482,6 +492,8 @@ export const DEFAULT_GENE_RANGES: Readonly> 'reproduction.offspringInvestment': range(6, 25), 'reproduction.cooldown': range(15, 120), 'reproduction.searchRadius': range(25, 100), + 'reproduction.choosiness': range(0, 1), + 'reproduction.preference': range(0, 1), 'learning.learningRate': range(0.001, 0.5, 0.1), 'learning.discountFactor': range(0, 1), 'learning.eligibilityTraceDecay': range(0, 1), diff --git a/packages/config/src/genetics.ts b/packages/config/src/genetics.ts index 484e6d9..edc94f3 100644 --- a/packages/config/src/genetics.ts +++ b/packages/config/src/genetics.ts @@ -75,6 +75,8 @@ export function geneBaselines(config: WorldConfig): Record { 'reproduction.offspringInvestment': reproduction.offspringInvestment, 'reproduction.cooldown': reproduction.cooldown, 'reproduction.searchRadius': reproduction.searchRadius, + 'reproduction.choosiness': reproduction.mateChoice.choosiness, + 'reproduction.preference': reproduction.mateChoice.preference, 'learning.learningRate': genetics.learning.learningRate, 'learning.discountFactor': genetics.learning.discountFactor, 'learning.eligibilityTraceDecay': genetics.learning.eligibilityTraceDecay, @@ -213,6 +215,9 @@ function baselineValues(root: PlainObject): Partial> { set('reproduction.offspringInvestment', numberAt(reproduction, 'offspringInvestment')) set('reproduction.cooldown', numberAt(reproduction, 'cooldown')) set('reproduction.searchRadius', numberAt(reproduction, 'searchRadius')) + const choice = isObject(reproduction) ? reproduction['mateChoice'] : undefined + set('reproduction.choosiness', numberAt(choice, 'choosiness')) + set('reproduction.preference', numberAt(choice, 'preference')) set('learning.learningRate', numberAt(learning, 'learningRate')) set('learning.discountFactor', numberAt(learning, 'discountFactor')) set('learning.eligibilityTraceDecay', numberAt(learning, 'eligibilityTraceDecay')) diff --git a/packages/config/src/validation.ts b/packages/config/src/validation.ts index 0b434d4..c4f6e82 100644 --- a/packages/config/src/validation.ts +++ b/packages/config/src/validation.ts @@ -97,6 +97,15 @@ const EGGS_KEYS = [ 'guardCost', 'guardDamage' ] +const MATE_CHOICE_KEYS = [ + 'enabled', + 'choosiness', + 'preference', + 'threshold', + 'searchCost', + 'retryDelay', + 'candidates' +] const REPRODUCTION_KEYS = [ 'minEnergy', 'offspringInvestment', @@ -105,7 +114,8 @@ const REPRODUCTION_KEYS = [ 'searchRadius', 'mateSenseRadius', 'sexes', - 'eggs' + 'eggs', + 'mateChoice' ] const HISTORY_KEYS = ['maxEvents', 'eventDetail', 'maxHistoricalOrganisms'] const OBSERVATORY_KEYS = ['enabled', 'sampleEvery', 'behaviourEvery', 'maxSamples'] @@ -392,6 +402,59 @@ export function validateWorldConfig(value: unknown): ValidationResult { } } + const choice = checkSection( + reproduction, + 'mateChoice', + MATE_CHOICE_KEYS, + errors, + 'reproduction.mateChoice' + ) + if (choice) { + if (typeof choice['enabled'] !== 'boolean') { + errors.push('reproduction.mateChoice.enabled must be a boolean') + } + for (const key of ['choosiness', 'preference'] as const) { + const value = checkNumber(choice, key, `reproduction.mateChoice.${key}`, {}, errors) + if (value !== undefined && (value < 0 || value > 1)) { + errors.push(`reproduction.mateChoice.${key} must be from 0 to 1`) + } + } + const threshold = checkNumber( + choice, + 'threshold', + 'reproduction.mateChoice.threshold', + {}, + errors + ) + if (threshold !== undefined && (threshold <= 0 || threshold > 1)) { + errors.push('reproduction.mateChoice.threshold must be greater than 0 and at most 1') + } + checkNumber( + choice, + 'searchCost', + 'reproduction.mateChoice.searchCost', + { nonnegative: true }, + errors + ) + checkNumber( + choice, + 'retryDelay', + 'reproduction.mateChoice.retryDelay', + { nonnegative: true }, + errors + ) + checkNumber( + choice, + 'candidates', + 'reproduction.mateChoice.candidates', + { integer: true, positive: true }, + errors + ) + if (choice['enabled'] === true && sexes && sexes['enabled'] !== true) { + errors.push('reproduction.mateChoice.enabled requires reproduction.sexes.enabled') + } + } + if ( investment !== undefined && overhead !== undefined && @@ -657,7 +720,8 @@ function mergeReproduction(base: object, override: unknown): unknown { ...base, ...override, sexes: mergeSection(defaults['sexes'] as object, override['sexes']), - eggs: mergeSection(defaults['eggs'] as object, override['eggs']) + eggs: mergeSection(defaults['eggs'] as object, override['eggs']), + mateChoice: mergeSection(defaults['mateChoice'] as object, override['mateChoice']) } } diff --git a/packages/contracts/src/events.ts b/packages/contracts/src/events.ts index 1c20ca3..55cdfca 100644 --- a/packages/contracts/src/events.ts +++ b/packages/contracts/src/events.ts @@ -148,7 +148,7 @@ export interface EnergyChangedEvent extends BaseEvent { * organism that's simply immature never generates one of these, the same way an organism that * finds no food never generates a failed `resource-consumed` (docs/decisions/0005). */ -export type ReproductionFailureReason = 'no-partner' | 'population-cap' +export type ReproductionFailureReason = 'no-partner' | 'population-cap' | 'rejected' /** Essential tier: not gated by `history.eventDetail`. Emitted starting in Phase 3. */ export interface ReproductionAttemptedEvent extends BaseEvent { diff --git a/packages/contracts/src/genome.ts b/packages/contracts/src/genome.ts index fe53275..610c951 100644 --- a/packages/contracts/src/genome.ts +++ b/packages/contracts/src/genome.ts @@ -30,6 +30,10 @@ export interface ReproductionGenes { readonly offspringInvestment: number readonly cooldown: number readonly searchRadius: number + /** How demanding it is of a mate, `[0, 1]` (ADR 0027): `0` accepts anyone, `1` only the best. Inert with mate choice off. */ + readonly choosiness: number + /** What it prizes in a mate, `[0, 1]` (ADR 0027): `0` condition (spare energy), `1` genetic difference. Inert with mate choice off. */ + readonly preference: number } /** Fixed brain dimensions shared by every organism in a world (topology does not evolve). */ @@ -64,10 +68,10 @@ export interface LearningGenes { /** Immutable. One per organism; a child's genome is built from both parents' genomes. */ export interface Genome { /** - * 3 since the parts act (ADR 0015): speed, turning, sensing and movement cost left the scalar + * 5 since mate choice (ADR 0027) added two reproduction genes. 3 since the parts act (ADR 0015): speed, turning, sensing and movement cost left the scalar * genes and come from the body. 2 added the `body` section (ADR 0012). */ - readonly version: 4 + readonly version: 5 readonly id: GenomeId /** Empty for founders; otherwise the two parents' genome ids, ascending. */ readonly parentIds: readonly GenomeId[] @@ -101,6 +105,8 @@ export type GenePath = | 'reproduction.offspringInvestment' | 'reproduction.cooldown' | 'reproduction.searchRadius' + | 'reproduction.choosiness' + | 'reproduction.preference' | 'learning.learningRate' | 'learning.discountFactor' | 'learning.eligibilityTraceDecay' @@ -151,7 +157,10 @@ export const GENE_DEFINITIONS: readonly GeneDefinition[] = [ { path: 'learning.explorationRate', kind: 'float' }, { path: 'learning.riskTolerance', kind: 'float' }, { path: 'learning.noveltyPreference', kind: 'float' }, - { path: 'learning.persistence', kind: 'float' } + { path: 'learning.persistence', kind: 'float' }, + // Mate choice (ADR 0027): appended, so every earlier gene keeps its place. + { path: 'reproduction.choosiness', kind: 'float' }, + { path: 'reproduction.preference', kind: 'float' } ] /** Bounds and mutation parameters of one gene. */ diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index ae02992..08e27ec 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -104,6 +104,7 @@ export type { ReproductionConfigOverrides, SexesConfig, EggsConfig, + MateChoiceConfig, HistoryConfig, ObservatoryConfig, WorldConfig, diff --git a/packages/contracts/src/world.ts b/packages/contracts/src/world.ts index a577f56..e4be8e6 100644 --- a/packages/contracts/src/world.ts +++ b/packages/contracts/src/world.ts @@ -296,6 +296,8 @@ export interface ReproductionConfig { sexes: SexesConfig /** Incubation, eggs and guarding (ADR 0027). Off: a child is born at conception, as before. */ eggs: EggsConfig + /** A partner has to accept too, and a creature has tastes (ADR 0027). Off: the nearest ready partner. */ + mateChoice: MateChoiceConfig } /** Two sexes (ADR 0027). A newborn's sex is one draw from the `reproduction` stream; founders alternate. */ @@ -323,10 +325,36 @@ export interface EggsConfig { guardDamage: number } +/** + * Mate choice (ADR 0027). A creature looks at the nearest `candidates` ready partners and takes the + * first that both of them accept. A creature scores a candidate `(1 - preference) x condition + + * preference x difference`, where condition is the candidate's spare energy over what it needs to be + * ready, and difference is how far apart the genomes are against the species threshold; it accepts if + * the score reaches `choosiness x threshold`. Refusing costs `searchCost` energy and a `retryDelay` wait. + */ +export interface MateChoiceConfig { + enabled: boolean + /** The founders' `choosiness` gene. */ + choosiness: number + /** The founders' `preference` gene. */ + preference: number + /** The score a fully choosy creature (`choosiness` 1) asks for, in `(0, 1]`. */ + threshold: number + /** Energy a creature pays each time it turns every candidate down. */ + searchCost: number + /** Seconds it waits before looking again after turning them all down. */ + retryDelay: number + /** How many of the nearest ready partners it looks at. */ + candidates: number +} + /** A partial reproduction section merged onto the defaults. */ -export type ReproductionConfigOverrides = Partial> & { +export type ReproductionConfigOverrides = Partial< + Omit +> & { sexes?: Partial eggs?: Partial + mateChoice?: Partial } /** diff --git a/packages/simulation/src/genetics/GenomeFactory.ts b/packages/simulation/src/genetics/GenomeFactory.ts index e7cb027..c8c2071 100644 --- a/packages/simulation/src/genetics/GenomeFactory.ts +++ b/packages/simulation/src/genetics/GenomeFactory.ts @@ -78,7 +78,7 @@ export function genomeFromParts(parts: GenomeParts): Genome { ;(groups[group] as Record)[name] = parts.vector[index] as number }) const genome = { - version: 4, + version: 5, id: parts.id, parentIds: [...parts.parentIds], ...groups, diff --git a/packages/simulation/src/genetics/GenomeValidation.ts b/packages/simulation/src/genetics/GenomeValidation.ts index 5788ae8..8d3ef8d 100644 --- a/packages/simulation/src/genetics/GenomeValidation.ts +++ b/packages/simulation/src/genetics/GenomeValidation.ts @@ -73,7 +73,7 @@ export function validateGenome( ): ValidationResult { const errors: string[] = [] - if (genome.version !== 4) errors.push(`unsupported genome version ${String(genome.version)}`) + if (genome.version !== 5) errors.push(`unsupported genome version ${String(genome.version)}`) if (!Number.isInteger(genome.id) || genome.id < 0) { errors.push(`genome id (${genome.id}) must be a nonnegative integer`) } else if (context.nextGenomeId !== undefined && genome.id >= context.nextGenomeId) { diff --git a/packages/simulation/src/systems/ReproductionSystem.ts b/packages/simulation/src/systems/ReproductionSystem.ts index cd17f43..c89af6a 100644 --- a/packages/simulation/src/systems/ReproductionSystem.ts +++ b/packages/simulation/src/systems/ReproductionSystem.ts @@ -57,7 +57,12 @@ export class ReproductionSystem { private readonly species: SpeciesTracker = NO_SPECIES, ecology: EcologyModel | null = null, /** The eggs in the world; they count against `maxPopulation` with the clutches being carried (ADR 0027). */ - private readonly eggs: EggStore = new EggStore() + private readonly eggs: EggStore = new EggStore(), + /** + * How different two genomes are, `0` (alike) to `1` (as far apart as two species), for mate choice + * (ADR 0027); without it difference counts for nothing. + */ + private readonly mateDistance?: (a: Genome, b: Genome) => number ) { this.unbounded = ecology !== null && ecology.clusters !== null this.readiness = new ReproductionReadiness(config, ecology) @@ -89,6 +94,28 @@ export class ReproductionSystem { }) } + /** Candidates looked at by one creature, reused between attempts. */ + private readonly candidates: { item: OrganismState; distanceSquared: number }[] = [] + + /** + * Whether `chooser` accepts `candidate` as a mate (ADR 0027): the candidate's score, `(1 - preference)` + * of its condition (spare energy over what it needs to be ready) plus `preference` of how different + * it is, has to reach `choosiness x threshold`. A creature with `choosiness` 0 accepts anyone. + */ + private accepts(chooser: OrganismState, candidate: OrganismState, tick: number): boolean { + const genes = chooser.genome.reproduction + if (genes.choosiness <= 0) return true + const needed = this.readiness.thresholdFor(candidate, tick) + const room = maxEnergyOf(candidate.genome, this.config) - needed + const condition = room > 0 ? clamp((candidate.energy - needed) / room, 0, 1) : 1 + const difference = + genes.preference > 0 && this.mateDistance !== undefined + ? this.mateDistance(chooser.genome, candidate.genome) + : 0 + const score = (1 - genes.preference) * condition + genes.preference * difference + return score >= genes.choosiness * this.config.reproduction.mateChoice.threshold + } + /** With `species.reproductiveIsolation`, only members of one species mate. */ private sameSpecies(a: OrganismState, b: OrganismState): boolean { if (!this.config.species.enabled || !this.config.species.reproductiveIsolation) return true @@ -102,6 +129,8 @@ export class ReproductionSystem { const { sexes, eggs: eggConfig } = this.config.reproduction const sexed = sexes.enabled + const choice = this.config.reproduction.mateChoice + const choosing = sexed && choice.enabled const eggsOn = eggConfig.enabled const initiators = this.organisms.values() @@ -135,17 +164,48 @@ export class ReproductionSystem { continue } - const partnerHit = this.organismIndex.nearestWhere( - { x: organism.x, y: organism.y }, - genome.reproduction.searchRadius, - (item) => - item.id !== organism.id && - (!sexed || item.sex !== organism.sex) && - this.sameSpecies(organism, item) && - !pairedIds.has(item.id) && - this.readiness.isReady(item, tick) - ) - if (!partnerHit) { + const eligible = (item: OrganismState): boolean => + item.id !== organism.id && + (!sexed || item.sex !== organism.sex) && + this.sameSpecies(organism, item) && + !pairedIds.has(item.id) && + this.readiness.isReady(item, tick) + const here = { x: organism.x, y: organism.y } + let partner: OrganismState | undefined + let turnedDown = false + if (choosing) { + // Mate choice (ADR 0027): look at the nearest few ready partners and take the first that + // both sides accept; turning them all down costs energy and a wait. + const found = this.candidates + found.length = 0 + this.organismIndex.scan(here, genome.reproduction.searchRadius, (item, distanceSquared) => { + if (eligible(item)) found.push({ item, distanceSquared }) + }) + found.sort((a, b) => a.distanceSquared - b.distanceSquared || a.item.id - b.item.id) + const looked = Math.min(found.length, choice.candidates) + for (let k = 0; k < looked; k++) { + const candidate = (found[k] as { item: OrganismState }).item + if (this.accepts(organism, candidate, tick) && this.accepts(candidate, organism, tick)) { + partner = candidate + break + } + } + turnedDown = partner === undefined && found.length > 0 + } else { + partner = this.organismIndex.nearestWhere( + here, + genome.reproduction.searchRadius, + eligible + )?.item + } + if (partner === undefined) { + if (turnedDown) { + organism.energy -= choice.searchCost + organism.reproductionCooldownRemaining = Math.max( + organism.reproductionCooldownRemaining, + choice.retryDelay + ) + } this.events.record({ type: 'reproduction-attempted', tick, @@ -153,12 +213,11 @@ export class ReproductionSystem { partnerId: null, childId: null, succeeded: false, - failureReason: 'no-partner' + failureReason: turnedDown ? 'rejected' : 'no-partner' }) continue } - const partner = partnerHit.item pairedIds.add(organism.id) pairedIds.add(partner.id) organism.energy -= this.readiness.costFor(organism, tick) diff --git a/packages/simulation/src/world/World.ts b/packages/simulation/src/world/World.ts index 21d117e..3266867 100644 --- a/packages/simulation/src/world/World.ts +++ b/packages/simulation/src/world/World.ts @@ -79,6 +79,7 @@ import { kindNamesOf, massScaleOf } from '../organisms/bodyFactors' import { planClusterFounders } from '../genetics/ClusterFounders' import type { FounderPlan } from '../genetics/ClusterFounders' import { createFounderGenome, genomeToVector } from '../genetics/GenomeFactory' +import { genomeDistance, weightedDistance } from '../genetics/GeneticDistance' import { GenomeRecombiner } from '../genetics/Recombination' import { HistoryStore } from '../history/HistoryStore' import { LineageStore } from '../lineage/LineageStore' @@ -444,7 +445,23 @@ export class World { this.events, this.speciesRegistry, this.ecology, - this.eggStore + this.eggStore, + this.config.reproduction.mateChoice.enabled + ? (a, b) => + Math.min( + 1, + weightedDistance( + genomeDistance( + a, + b, + this.geneSpecs, + this.config.genetics.brain.initialWeightStd, + this.bodySpecs + ), + this.config.species.distanceWeights + ) / Math.max(this.config.species.threshold, 1e-9) + ) + : undefined ) this.eggSystem = this.config.reproduction.eggs.enabled ? new EggSystem( diff --git a/packages/simulation/tests/genetics/factory.test.ts b/packages/simulation/tests/genetics/factory.test.ts index 4e0b860..c180f18 100644 --- a/packages/simulation/tests/genetics/factory.test.ts +++ b/packages/simulation/tests/genetics/factory.test.ts @@ -16,7 +16,7 @@ describe('buildGeneSpecs', () => { it('produces one spec per gene, in the canonical order', () => { const { specs } = fixture() expect(specs.map((spec) => spec.path)).toEqual(GENE_DEFINITIONS.map((d) => d.path)) - expect(specs).toHaveLength(18) + expect(specs).toHaveLength(20) }) it('takes baselines from the config fields the genes replace', () => { @@ -77,7 +77,7 @@ describe('founder genomes', () => { const f = fixture() const genome = founder(f, 0, 1) expect(genomeToVector(genome)).toEqual(f.specs.map((spec) => spec.baseline)) - expect(genome.version).toBe(4) + expect(genome.version).toBe(5) expect(genome.parentIds).toEqual([]) }) diff --git a/packages/simulation/tests/golden/state-hashes.json b/packages/simulation/tests/golden/state-hashes.json index 716f008..c8bc89c 100644 --- a/packages/simulation/tests/golden/state-hashes.json +++ b/packages/simulation/tests/golden/state-hashes.json @@ -30,7 +30,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 1000, - "expectedHash": "8f71809ee45b7b9dfcc83291648895e7" + "expectedHash": "2518f4cfb14ced68e6905d0fbf5c5360" }, { "name": "default-instant-eating-3k", @@ -61,7 +61,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 3000, - "expectedHash": "205f4d364e31c034964266634f1c7218" + "expectedHash": "df7535a5e6e3404d4ace5f1d6fb11249" }, { "name": "scenario-a-instant-eating-5k", @@ -102,7 +102,7 @@ } }, "steps": 5000, - "expectedHash": "fac0167fd79b9527c9752d6659f1c6e6" + "expectedHash": "c5e10adfa845734ba8d506dd8e27e65e" }, { "name": "scenario-a-foraging-5k", @@ -142,7 +142,7 @@ } }, "steps": 5000, - "expectedHash": "ce2828cb4db3716818d7c71d3c7478ba" + "expectedHash": "f7330c139d2662b27c2c0916a8f1ebb9" }, { "name": "scenario-b-extinction-20k", @@ -222,7 +222,7 @@ } }, "steps": 200, - "expectedHash": "29935eccf7614daf4a592ef466a751d4" + "expectedHash": "4f20daef8d6a6132fabf5fbc27753ff7" }, { "name": "zero-population-100", @@ -292,7 +292,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 100000, - "expectedHash": "b670887850be03e611c27ecd2a8bbbaf" + "expectedHash": "25fcd60a9660b673b5242e540f452689" }, { "name": "reflex-default-1k", @@ -331,7 +331,7 @@ } }, "steps": 1000, - "expectedHash": "f258aa73d70b4640fc7bdb606e70393b" + "expectedHash": "70e734ea1d6d6c5f9dbb82dc9d3381ad" }, { "name": "reflex-scenario-a-5k", @@ -450,7 +450,7 @@ } }, "steps": 100000, - "expectedHash": "ab4272d259b1016e699a296e55a1ba3c" + "expectedHash": "e5b52b43fb3b01294481736235100d56" }, { "name": "brain-hebbian-5k", @@ -490,7 +490,7 @@ } }, "steps": 5000, - "expectedHash": "3ce3a79e73fb8b4326b9ff968a54822b" + "expectedHash": "b9228f30a0301521a9e89f62ba18885f" }, { "name": "brain-learning-off-5k", @@ -530,7 +530,7 @@ } }, "steps": 5000, - "expectedHash": "5ff17b38b076f11521fc574aab2f607a" + "expectedHash": "43a0a7447fb3fa12910fe6c92fd3dc5f" }, { "name": "brain-random-prior-off-5k", @@ -601,7 +601,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 12000, - "expectedHash": "34e6421db6ba22622877967c590b5a7e" + "expectedHash": "a948a19d1eced1bbce9116ee46ef3d82" }, { "name": "ecology-reflex-8k", @@ -632,7 +632,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 8000, - "expectedHash": "c1565c19600cda506d694a827cd2c43d" + "expectedHash": "9e32ca41118c61ebd6afbceea81e6828" }, { "name": "ecology-lethal-hazards-3k", @@ -667,7 +667,7 @@ } }, "steps": 3000, - "expectedHash": "a67879bd25d324791b5713419f7ee361" + "expectedHash": "b479f3a30edefbb15e934cb5b284df84" }, { "name": "anatomy-on-evolving-6k", @@ -707,7 +707,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 6000, - "expectedHash": "f9bf7561dcf7025914e4d6920092463a" + "expectedHash": "0f330f3e60e0896a29356fe93c1460b0" }, { "name": "anatomy-on-reflex-4k", @@ -748,7 +748,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 4000, - "expectedHash": "3f7b824e58437e6cded90713448136d9" + "expectedHash": "32a847674a4593ba019bd04c35170da7" }, { "name": "clusters-small-6k", @@ -783,7 +783,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 6000, - "expectedHash": "dce98f47abb2dad02670fbee8c33bfd6" + "expectedHash": "db606f9b6714ac485b096e8c3e75480a" }, { "name": "clusters-small-reflex-4k", @@ -819,7 +819,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 4000, - "expectedHash": "fca48beeb235e035755e49a374f48e5a" + "expectedHash": "530838834a0807cb7bc9fe1bd16adb36" }, { "name": "archetypes-default-1k", @@ -849,7 +849,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 1000, - "expectedHash": "1a6154bcc6980f3385427f807de1c093" + "expectedHash": "5d2202c1c69d47df376be70193ab845a" }, { "name": "archetypes-ecology-12k", @@ -879,7 +879,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 12000, - "expectedHash": "1e5e7ffe9384bf2e61e2c9240f828208" + "expectedHash": "ebeac7f3b41ff95b3ba1fc84e18fcac2" }, { "name": "archetypes-reflex-8k", @@ -910,7 +910,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 8000, - "expectedHash": "abc12eaecff3c5de5cd2511b87e90d53" + "expectedHash": "5a57bef443cd4fa2f106690ec6699751" }, { "name": "archetypes-evolving-bodies-6k", @@ -949,7 +949,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 6000, - "expectedHash": "4794af4317c6cdd171bf7939d999c21d" + "expectedHash": "4f1a73efcecf95330496516efc30df4b" }, { "name": "archetype-forced-grazer-3k", @@ -981,7 +981,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 3000, - "expectedHash": "721b47c6c843ec9b99f2b8aaf7b9cbe4" + "expectedHash": "d65e58c5d3b5b2d9984e3a163213d230" }, { "name": "archetype-forced-fungus-scraper-3k", @@ -1013,7 +1013,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 3000, - "expectedHash": "471bd9bf3b446342aa6b07be1bde9fb7" + "expectedHash": "94ba369309c9e4f7a4d3ec1c3ba86c23" }, { "name": "archetype-forced-tank-3k", @@ -1043,7 +1043,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 3000, - "expectedHash": "a247ee5dafffbe33b5177f48e810ae9f" + "expectedHash": "32af631715cdaf5133c9b234aaa300ed" }, { "name": "noise-food-4k", @@ -1073,7 +1073,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 4000, - "expectedHash": "4ba0f0fa9cfb9ced70954216c1ba423c" + "expectedHash": "cb0c7b08e8f9d0182e16746c5f0b679e" }, { "name": "noise-reflex-3k", @@ -1104,7 +1104,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 3000, - "expectedHash": "49a124d2eea35f66a665953a81350af9" + "expectedHash": "590ea8ff33a5ec0e2dd4a83c47f4084b" }, { "name": "plants-6k", @@ -1134,7 +1134,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 6000, - "expectedHash": "633274a7923a3ef1ba0d4efcc2b0b04f" + "expectedHash": "6b1a4f76d2db861b62f0847c74eccdbd" }, { "name": "plants-noise-reflex-5k", @@ -1165,7 +1165,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 5000, - "expectedHash": "8c5aa335f11224a3006910dacbbc29ed" + "expectedHash": "369f3dc4299d405a9648dbfa2cc60d12" }, { "name": "plants-brain-evolving-8k", @@ -1198,7 +1198,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 8000, - "expectedHash": "3141079a4f55c7569ee981a4f6c44541" + "expectedHash": "086130764ea50cada377ed85a6d8c303" }, { "name": "food-default-1k", @@ -1209,7 +1209,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 1000, - "expectedHash": "668cd3e890fd9210fff83b877d3809f1" + "expectedHash": "7d6630e2622cb13620f755844ae07571" }, { "name": "food-default-ecology-12k", @@ -1220,7 +1220,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 12000, - "expectedHash": "421caebbbca6354f8c7877aa12b3559a" + "expectedHash": "91be0367534ff84d275200b96e175020" }, { "name": "food-default-reflex-8k", @@ -1232,7 +1232,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 8000, - "expectedHash": "21a234445828a0656a8402b1c8ee6e91" + "expectedHash": "8ca2517bd3ea2792496275776cc5b07f" }, { "name": "food-default-evolving-bodies-6k", @@ -1252,7 +1252,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 6000, - "expectedHash": "2f89d6efcf9200911c5d99ae0f93a3a7" + "expectedHash": "465fc2acb3e7d718f7c09840bbd2ad1e" }, { "name": "food-lush-4k", @@ -1268,7 +1268,7 @@ "ecology": { "obstacles": { "enabled": false } } }, "steps": 4000, - "expectedHash": "5b184f4bcdc372fe2bc4b540a374479d" + "expectedHash": "86e51b0d232675fdb223bf03b4468b44" }, { "name": "obstacles-default-1k", @@ -1278,7 +1278,7 @@ "anatomy": { "startingBody": { "groups": [] } } }, "steps": 1000, - "expectedHash": "54c302d9bafa86ef378e2ac9f230cce4" + "expectedHash": "88963b777e3146df110eb400abcff2fb" }, { "name": "obstacles-ecology-12k", @@ -1288,7 +1288,7 @@ "anatomy": { "startingBody": { "groups": [] } } }, "steps": 12000, - "expectedHash": "87ffc09317dae86c556a2663151e3f5e" + "expectedHash": "14d5f168770ba317a57079192f096aec" }, { "name": "obstacles-reflex-8k", @@ -1299,7 +1299,7 @@ "learning": { "controller": "reflex" } }, "steps": 8000, - "expectedHash": "e54088160f14df93fa3ede87383be314" + "expectedHash": "65e9584a52546bcb1ab6eecea5b8082c" }, { "name": "obstacles-evolving-bodies-6k", @@ -1318,7 +1318,7 @@ "genetics": { "mutationRateScale": 3 } }, "steps": 6000, - "expectedHash": "367a0055c7669406c1fb5ad515f8051f" + "expectedHash": "b9280cf509d498a0243c3c92af68d944" }, { "name": "obstacles-lush-4k", @@ -1333,28 +1333,28 @@ } }, "steps": 4000, - "expectedHash": "1cc62d2e15be89f8b1115afc1a6786f2" + "expectedHash": "3c52d9f3994e2fa03240bbb238171995" }, { "name": "predation-default-1k", "seed": 12345, "config": {}, "steps": 1000, - "expectedHash": "e8e0eb06f270958a6cb383f4d617af67" + "expectedHash": "a8e12a566e672251f9228be5eaaeb471" }, { "name": "predation-ecology-12k", "seed": 7, "config": {}, "steps": 12000, - "expectedHash": "7ed8b2be4de980be9fe9350485ff0cb5" + "expectedHash": "c659948d291cc9e6e570f92e65d6bfa7" }, { "name": "predation-reflex-8k", "seed": 3, "config": { "learning": { "controller": "reflex" } }, "steps": 8000, - "expectedHash": "1be318afaf35b3335173cd19e173ef82" + "expectedHash": "d5f2160cd4b7b9a125f1f198bee22930" }, { "name": "predation-evolving-bodies-6k", @@ -1371,7 +1371,7 @@ "genetics": { "mutationRateScale": 3 } }, "steps": 6000, - "expectedHash": "0be79e3f67ec55bd9a9341b000b086ae" + "expectedHash": "6bd7d4128a6f51d44737e571ad855b85" }, { "name": "predation-lush-4k", @@ -1384,7 +1384,7 @@ } }, "steps": 4000, - "expectedHash": "f7ea0143bb41ffaaa1ec8fade4f41478" + "expectedHash": "4cb76e70b10405b78f2fe2c97afa9aa7" }, { "name": "predation-hunters-only-3k", diff --git a/packages/simulation/tests/lifecycle/mate-choice.test.ts b/packages/simulation/tests/lifecycle/mate-choice.test.ts new file mode 100644 index 0000000..83cdf9a --- /dev/null +++ b/packages/simulation/tests/lifecycle/mate-choice.test.ts @@ -0,0 +1,344 @@ +import { describe, expect, it } from 'vitest' +import { resolveWorldConfig } from '@evo/config' +import { GENE_DEFINITIONS } from '@evo/contracts' +import type { GenePath, WorldConfigOverrides } from '@evo/contracts' +import { IdGenerator } from '../../src/entities/IdGenerator' +import { OrganismStore } from '../../src/entities/OrganismStore' +import type { OrganismState } from '../../src/entities/OrganismStore' +import { EventLog } from '../../src/events/EventLog' +import { buildGeneSpecs } from '../../src/genetics/GeneSpecs' +import { GenomeRecombiner } from '../../src/genetics/Recombination' +import { LineageStore } from '../../src/lineage/LineageStore' +import { SeededRandom } from '../../src/random/SeededRandom' +import { deriveStreamWords } from '../../src/random/streams' +import { SpatialHash } from '../../src/spatial/SpatialHash' +import { ReproductionSystem } from '../../src/systems/ReproductionSystem' +import { World } from '../../src/index' +import { organismFor, withGenes } from '../support/organism' + +// Mate choice (ADR 0027): a partner has to accept too, and a creature has tastes. + +const CHOICE: WorldConfigOverrides = { + learning: { controller: 'reflex' }, + reproduction: { sexes: { enabled: true }, mateChoice: { enabled: true } } +} + +interface Pair { + readonly events: EventLog + readonly organisms: OrganismStore + readonly initiator: OrganismState + readonly others: OrganismState[] + tick(): void +} + +type Genes = Partial> + +/** + * A ready female (id 1) with ready males at the given distances (ids 2, 3, ...), all with the genes + * and energy given. The female is the first to be looked at, so she is the initiator. + */ +function pair( + extra: WorldConfigOverrides, + options: { + initiator?: Genes + others?: { distance: number; genes?: Genes; energy?: number }[] + initiatorEnergy?: number + difference?: number + } = {} +): Pair { + const config = resolveWorldConfig({ + ...CHOICE, + ...extra, + reproduction: { + ...(CHOICE.reproduction as object), + ...(extra.reproduction as object | undefined) + } as never + }) + const initiator = withGenes( + organismFor(config, 1, { + x: 100, + y: 100, + age: 200, + energy: options.initiatorEnergy ?? 100, + sex: 0 + }), + { 'reproduction.choosiness': 0, 'reproduction.preference': 0, ...options.initiator } + ) + const others = (options.others ?? [{ distance: 5 }]).map((o, i) => + withGenes( + organismFor(config, 2 + i, { + x: 100 + o.distance, + y: 100, + age: 200, + energy: o.energy ?? 100, + sex: 1 + }), + { 'reproduction.choosiness': 0, 'reproduction.preference': 0, ...o.genes } + ) + ) + const organisms = new OrganismStore() + organisms.add(initiator) + for (const o of others) organisms.add(o) + const index = new SpatialHash(60, (o) => o) + index.rebuild(organisms.values()) + const lineage = new LineageStore() + for (const o of organisms.values()) { + lineage.register({ genomeId: o.genome.id, parentGenomeIds: [], organismId: o.id, tick: 0 }) + } + const genomeIds = new IdGenerator() + for (let i = 0; i < 100; i++) genomeIds.allocate() + const events = new EventLog(100) + const system = new ReproductionSystem( + config, + organisms, + index, + (() => { + const ids = new IdGenerator() + for (let i = 0; i < 20; i++) ids.allocate() + return ids + })(), + new GenomeRecombiner(buildGeneSpecs(config), config.genetics, () => genomeIds.allocate()), + new SeededRandom(deriveStreamWords(1, 'genetics')), + lineage, + new SeededRandom(deriveStreamWords(1, 'reproduction')), + events, + undefined, + undefined, + undefined, + () => options.difference ?? 0 + ) + return { + events, + organisms, + initiator, + others, + tick() { + events.beginTick() + system.update(1) + } + } +} + +/** What the female (id 1) tried; the males look too, afterwards, and are not what these tests ask about. */ +const attempts = (p: Pair) => + p.events.eventsThisTick().filter((e) => e.type === 'reproduction-attempted' && e.organismId === 1) + +describe('a creature that is not choosy accepts anyone', () => { + it('pairs with the nearest ready partner and a child is born', () => { + const p = pair({}) + p.tick() + expect(attempts(p)).toMatchObject([{ succeeded: true, partnerId: 2 }]) + expect(p.organisms.size).toBe(3) + }) +}) + +describe('choosiness and condition', () => { + // A fully choosy creature (choosiness 1) wants a score of `threshold` (0.5): a candidate with half + // its spare energy. One just ready (75 of 100, condition 0) is turned down, a full one is taken. + const choosy = { 'reproduction.choosiness': 1 } as Genes + + it('turns a poor candidate down, pays the search cost and waits, and nothing is born', () => { + const p = pair({}, { initiator: choosy, others: [{ distance: 5, energy: 75.5 }] }) + const cfg = resolveWorldConfig(CHOICE) + p.tick() + expect(attempts(p)).toMatchObject([{ succeeded: false, failureReason: 'rejected' }]) + expect(p.initiator.energy).toBeCloseTo(100 - cfg.reproduction.mateChoice.searchCost, 9) + expect(p.initiator.reproductionCooldownRemaining).toBe(cfg.reproduction.mateChoice.retryDelay) + expect(p.others[0]?.energy).toBe(75.5) + expect(p.organisms.size).toBe(2) + }) + + it('takes a candidate in full condition (negative)', () => { + const p = pair({}, { initiator: choosy, others: [{ distance: 5, energy: 100 }] }) + p.tick() + expect(attempts(p)).toMatchObject([{ succeeded: true, partnerId: 2 }]) + }) + + it('a candidate that is not choosy never costs the initiator anything when it is accepted', () => { + const p = pair({}, { others: [{ distance: 5, energy: 75.5 }] }) + const before = p.initiator.energy + p.tick() + // She paid the reproduction cost only, not a search cost. + const cost = p.initiator.energy + expect(attempts(p)).toMatchObject([{ succeeded: true }]) + expect(before - cost).toBeGreaterThan(10) + }) +}) + +describe('acceptance is mutual', () => { + it('a choosy partner can refuse a creature that would have taken it', () => { + // She is not choosy, and he is, and she is only just ready (condition 0). + const p = pair( + {}, + { + initiatorEnergy: 75.5, + others: [{ distance: 5, energy: 100, genes: { 'reproduction.choosiness': 1 } }] + } + ) + p.tick() + expect(attempts(p)).toMatchObject([{ succeeded: false, failureReason: 'rejected' }]) + }) + + it('both being easy to please pairs them (negative)', () => { + const p = pair({}, { initiatorEnergy: 75.5, others: [{ distance: 5, energy: 100 }] }) + p.tick() + expect(attempts(p)).toMatchObject([{ succeeded: true }]) + }) +}) + +describe('preference for difference', () => { + const wantsDifferent = { + 'reproduction.choosiness': 1, + 'reproduction.preference': 1 + } as Genes + + it('turns a clone down and takes a stranger', () => { + const clone = pair({}, { initiator: wantsDifferent, difference: 0 }) + clone.tick() + expect(attempts(clone)).toMatchObject([{ failureReason: 'rejected' }]) + const stranger = pair({}, { initiator: wantsDifferent, difference: 1 }) + stranger.tick() + expect(attempts(stranger)).toMatchObject([{ succeeded: true }]) + }) + + it('a creature with no taste for difference ignores it (negative)', () => { + const p = pair( + {}, + { initiator: { 'reproduction.choosiness': 1, 'reproduction.preference': 0 }, difference: 0 } + ) + p.tick() + expect(attempts(p)).toMatchObject([{ succeeded: true }]) + }) +}) + +describe('the search', () => { + const choosy = { 'reproduction.choosiness': 1 } as Genes + const poor = { distance: 5, energy: 75.5 } + const rich = { distance: 20, energy: 100 } + + it('looks at no more than `candidates` of the nearest', () => { + const one = pair( + { reproduction: { mateChoice: { enabled: true, candidates: 1 } } as never }, + { + initiator: choosy, + others: [poor, rich] + } + ) + one.tick() + expect(attempts(one)).toMatchObject([{ failureReason: 'rejected' }]) + const two = pair( + { reproduction: { mateChoice: { enabled: true, candidates: 2 } } as never }, + { + initiator: choosy, + others: [poor, rich] + } + ) + two.tick() + expect(attempts(two)).toMatchObject([{ succeeded: true, partnerId: 3 }]) + }) + + it('with nobody in range it is a plain failure with no cost (negative)', () => { + const p = pair({}, { initiator: choosy, others: [{ distance: 500 }] }) + p.tick() + expect(attempts(p)).toMatchObject([{ succeeded: false, failureReason: 'no-partner' }]) + expect(p.initiator.energy).toBe(100) + expect(p.initiator.reproductionCooldownRemaining).toBe(0) + }) + + it('with mate choice off the genes are ignored: a choosy creature takes the nearest', () => { + const p = pair( + { reproduction: { mateChoice: { enabled: false } } as never }, + { initiator: choosy, others: [poor] } + ) + p.tick() + expect(attempts(p)).toMatchObject([{ succeeded: true }]) + }) +}) + +describe('the genes', () => { + it('are the two last scalar genes, start at the configured tastes and stay in [0, 1]', () => { + const paths = GENE_DEFINITIONS.map((d) => d.path) + expect(paths.slice(-2)).toEqual(['reproduction.choosiness', 'reproduction.preference']) + const world = World.create({ seed: 2, config: CHOICE }) + expect(world.snapshot().organisms.length).toBeGreaterThan(0) + const founder = organismFor(resolveWorldConfig(CHOICE), 1).genome.reproduction + expect(founder.choosiness).toBeCloseTo(0.3, 12) + expect(founder.preference).toBeCloseTo(0.3, 12) + world.run(3000) + // The world validates itself every tick when asked: ranges are part of what is checked. + expect(world.validate().ok).toBe(true) + }) +}) + +describe('configuration', () => { + it('is off by default, and needs two sexes', () => { + expect(resolveWorldConfig().reproduction.mateChoice.enabled).toBe(false) + expect(() => resolveWorldConfig({ reproduction: { mateChoice: { enabled: true } } })).toThrow( + /requires reproduction.sexes.enabled/ + ) + }) + + it('rejects out-of-range tastes, costs and counts, and unknown keys', () => { + for (const mateChoice of [ + { choosiness: 1.1 }, + { preference: -0.1 }, + { threshold: 0 }, + { threshold: 1.5 }, + { searchCost: -1 }, + { retryDelay: -1 }, + { candidates: 0 }, + { candidates: 1.5 }, + { enabled: 'yes' }, + { taste: 1 } + ]) { + expect(() => resolveWorldConfig({ reproduction: { mateChoice } as never })).toThrow() + } + }) +}) + +describe('in a world', () => { + const FROZEN: WorldConfigOverrides = { + genetics: { mutationRateScale: 0, mutationStrengthScale: 0 } + } + + it('with every creature easy to please it is the world without mate choice, bit for bit', () => { + const run = (enabled: boolean): string => { + const world = World.create({ + seed: 5, + config: { + ...FROZEN, + reproduction: { + sexes: { enabled: true }, + mateChoice: { enabled, choosiness: 0, preference: 0 } + } + } + }) + world.run(2500) + expect(world.snapshot().metrics.reproductionSuccesses).toBeGreaterThan(3) + return world.stateHash() + } + expect(run(true)).toBe(run(false)) + }) + + it('choosy creatures turn partners down, and the world is deterministic and chunk-invariant', () => { + const config: WorldConfigOverrides = { + reproduction: { + sexes: { enabled: true }, + mateChoice: { enabled: true, choosiness: 0.9, preference: 0.5 } + } + } + const a = World.create({ seed: 6, config }) + let rejected = 0 + for (let t = 0; t < 3000; t++) { + a.step() + rejected += a.events + .eventsThisTick() + .filter((e) => e.type === 'reproduction-attempted' && e.failureReason === 'rejected').length + } + expect(rejected).toBeGreaterThan(0) + const b = World.create({ seed: 6, config }) + b.run(1000) + b.run(2000) + expect(b.stateHash()).toBe(a.stateHash()) + }) +}) diff --git a/packages/simulation/tests/phase5-exit-criteria.test.ts b/packages/simulation/tests/phase5-exit-criteria.test.ts index a48ca1a..da9cfda 100644 --- a/packages/simulation/tests/phase5-exit-criteria.test.ts +++ b/packages/simulation/tests/phase5-exit-criteria.test.ts @@ -20,7 +20,8 @@ describe('Phase 5 exit criteria', () => { }) it('organisms receive observations', () => { - for (const organism of alive) { + // A creature born in the very last tick has not decided yet, so it has not seen anything. + for (const organism of alive.filter((o) => o.age > 0)) { const brain = world.brainOf(organism.id)! expect(brain.observation).toHaveLength(OBSERVATION_SIZE) expect(brain.observation.every((value) => Number.isFinite(value))).toBe(true) diff --git a/packages/simulation/tests/world.test.ts b/packages/simulation/tests/world.test.ts index 3b7ff7f..3ca24b0 100644 --- a/packages/simulation/tests/world.test.ts +++ b/packages/simulation/tests/world.test.ts @@ -206,9 +206,12 @@ describe('scenario A: stable foraging (roadmap testing scenario A)', () => { // step two): founders draw 64 more weights from the `genetics` stream, which shifts every later // mutation. Measured on this seed: 29 / 47 / 18 before, 28 / 46 / 18 now; the reflex controller // ignores the weights, so nothing but the mutation draws moved. - expect(snapshot.population.active).toBe(28) - expect(snapshot.metrics.organismsBorn).toBe(46) - expect(snapshot.metrics.deathsByStarvation).toBe(18) + // And once more when mate choice added two reproduction genes (ADR 0027): two more genes mutate + // at every birth, so the draws that follow shift. Measured: 28 / 46 / 18 before, 27 / 47 / 20 now + // (mate choice is off, so the new genes do nothing; only the draws moved). + expect(snapshot.population.active).toBe(27) + expect(snapshot.metrics.organismsBorn).toBe(47) + expect(snapshot.metrics.deathsByStarvation).toBe(20) expect(snapshot.metrics.deathsByAge).toBe(0) expect(snapshot.population.extinctionTick).toBeNull() From f479e5af84b5e9f36f978f38184a0203930cfd66 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 20:53:15 +0000 Subject: [PATCH 06/11] feat(life-cycle): switch the life cycle on by default, measured (ADR 0027) Sexes, eggs, mate choice and ageing are on in the default world. 16 seeds x 30,000 ticks: no extinct world, mean population 51 (lowest 16 to 21), starved 60 to 64 percent of deaths, old age about a third, 98 to 99 percent of eggs hatch, a jaw lineage alive in 7 of 16 worlds. Reaching it took four breeding numbers: minEnergy 75 to 65, cooldown 45 to 30, search radius 50 to 75 and mating signal 250 to 350 (with half the creatures the wrong sex, the old values let 2 of 8 worlds go extinct); ageing hazard 0.02 (0.04 cost a world) and mate choice choosiness 0.8, preference 0.5, threshold 0.4, search cost 0.2 (the 0.3 tastes never turned anyone down). Every pinned golden entry now says what it was measured with (one sex, an instant birth, the old breeding numbers and gene baselines, ageing off) and all 50 reproduce their hashes unchanged: the proof that the flip is config only. Three new entries pin the new default world. The Classic and Clusters presets keep the old breeding and a hard lifespan; tests that pin numbers measured before the life cycle use the BEFORE_LIFE helper. The Statistics panel shows the egg totals once an egg has been laid, and the observatory counts an egg as flesh intake. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Cn5qp4xBHxLnTrwReNXcf8 --- docs/decisions/0027-life-cycle.md | 41 + docs/genetics/genome.md | 2 + docs/simulation/configuration.md | 224 +- docs/simulation/update-order.md | 4 +- packages/config/src/defaults.ts | 44 +- packages/config/src/presets.ts | 20 +- packages/contracts/tests/contracts.test.ts | 1 + .../src/observatory/ObservatoryRecorder.ts | 5 + .../simulation/tests/brain-system.test.ts | 3 +- .../tests/ecology/exit-criteria.test.ts | 3 +- .../simulation/tests/ecology/systems.test.ts | 3 +- .../simulation/tests/genes-in-systems.test.ts | 5 +- .../simulation/tests/golden/state-hashes.json | 2579 ++++++++++++++--- .../tests/learning/ablation.test.ts | 5 +- .../simulation/tests/lifecycle/ageing.test.ts | 8 +- .../tests/lifecycle/lifecycle.test.ts | 40 +- .../tests/lifecycle/mate-choice.test.ts | 26 +- packages/simulation/tests/probe/life.probe.ts | 27 +- .../tests/species/world-species.test.ts | 5 +- packages/simulation/tests/support/life.ts | 48 + packages/simulation/tests/support/phase3.ts | 4 +- packages/simulation/tests/systems.test.ts | 27 +- packages/simulation/tests/traits.test.ts | 5 +- .../simulation/tests/world-genomes.test.ts | 25 +- packages/simulation/tests/world.test.ts | 3 +- packages/ui/src/Overview.tsx | 20 + packages/ui/tests/ui.test.tsx | 15 + 27 files changed, 2649 insertions(+), 543 deletions(-) create mode 100644 docs/decisions/0027-life-cycle.md create mode 100644 packages/simulation/tests/support/life.ts diff --git a/docs/decisions/0027-life-cycle.md b/docs/decisions/0027-life-cycle.md new file mode 100644 index 0000000..b7ec5af --- /dev/null +++ b/docs/decisions/0027-life-cycle.md @@ -0,0 +1,41 @@ +# ADR 0027: A life cycle, two sexes, eggs, ageing and mate choice + +Status: accepted. Builds on [ADR 0005](0005-continuous-organism-ecology.md) (reproduction), [ADR 0006](0006-genetics-and-inheritance.md) (genes), [ADR 0010](0010-mate-seeking.md) (the mating signal) and [ADR 0023](0023-predation.md) (jaws). Hash schema 13, genome version 5. + +## Why + +After five measured null results on carnivory (ADRs 0023 step four, 0025, 0026 and the prey-eligibility experiment) the owner stopped chasing levers and asked for a feature: **instead of an instant birth, a short incubation, then an egg that matures and hatches**, and a **real overhaul of ageing and of how creatures pair up**, without forcing the best to breed (selection stays natural). Their decisions: **two sexes**; **parents guard eggs, and jaws can eat them**; **ageing is decline plus a chance of dying**; **mate choice is a heritable preference and mutual acceptance**. Everything ships in one PR, each part behind its own switch and measured on its own first. + +What the code did before: a child was a fully formed creature made in the tick the pair met, at their midpoint; the partner was the nearest ready creature in reach and had no say (99.8 percent of attempts failed with no partner in reach); a creature died by a hard cutoff at its `maxAge`; the `senescent` stage did nothing but dim a sprite. + +## The life cycle + +**Sexes** (`reproduction.sexes.enabled`). `OrganismState.sex` (0 female, 1 male). Founders alternate by index (no draw); a newborn's sex is one draw from the `reproduction` stream. Only a female and a male mate and the female is the mother. The mate sense (ADR 0010) and the partner search both require the other sex. + +**Eggs** (`reproduction.eggs`, needs sexes). Conception happens where the birth used to: both parents pay, cooldowns reset, and the child's genome is **recombined at once** (the same draws, in the same order, as an instant birth) and stored in the mother's pregnancy. She carries it for `incubation` seconds and pays `carryCost` a second on top of her metabolism; **if she dies first the clutch is lost** (`clutch-lost`). Then `EggSystem` lays one egg at her position (`egg-laid`) and, `hatch` seconds later, the egg becomes a creature with the stored genome, parents and the **mother's species at conception** (she may be dead), `egg-hatched` then `organism-born`, so births, generations and the birth effect work as before. Eggs and carried clutches **count against `maxPopulation`**. Ids come from the shared allocator at laying and at hatching, so they stay ascending. + +**Guarding and egg predation.** A living parent within `guardRadius` of its egg guards it (`guardCost` a second per egg). A bite at a guarded egg is **stopped**: the egg stays, the biter takes `guardDamage` health counted as a bite by the guard (so a death from it is a death by predation). An unguarded egg is **eaten whole** by any mouth with a flesh yield (a jaw), never by a mandible, a sprout or a parent: the egg is gone and the gut takes what it can hold of its energy at the trophic yield and the flesh yield; a full gut refuses it. A body that bites creatures sees eggs as prey (the existing prey input, so the innate hunting instinct drives it). A parent senses the way back to its own egg through the **existing `home` inputs** (observation slots 37 to 39, zero in the field layout): `present` grows from 0 at the guard radius to 1 at three times it, so **no observation or weight changes**. Eggs are drawn as flat pale discs that fill as they near hatching, with a ring when guarded, on an Eggs layer. + +## Ageing + +`ageing.enabled`. With `s` the share of the way from the creature's own `senescenceAge` to its own `maxAge` (above 1 beyond it): metabolism rises by `metabolismRise x min(s, 2)`, top speed falls by `speedLoss x min(s, 1)`, and the energy needed to breed rises by `fertilityLoss x min(s, 1)`. **There is no cutoff at `maxAge`**: a creature past `senescenceAge` dies of `age` with chance `hazard x s` a second (one draw per old creature per tick from the `world` stream, none in prime), and certainly at `ceiling x maxAge`. Off is the hard cutoff, exactly. The snapshot's `lifeStage` now uses the creature's own genes instead of the world's baseline (a latent bug: a creature with evolved ages showed the founder's stage). + +## Mate choice + +`reproduction.mateChoice` (needs sexes). Two new **genes**, `choosiness` and `preference` (both `[0, 1]`, appended to the gene table, so every earlier gene keeps its place; genome version 5). An initiator looks at the nearest `candidates` ready partners of the other sex and takes the first that **both** accept. A creature scores a candidate `(1 - preference) x condition + preference x difference`, where condition is the candidate's spare energy over what it needs to be ready (0 just ready, 1 full) and difference is the genomic distance over the species threshold (capped at 1); it accepts if the score reaches `choosiness x threshold`. A creature with `choosiness` 0 accepts anyone and the world is bit for bit the world without mate choice (tested). Turning every candidate down costs `searchCost` energy and a `retryDelay` wait (failure reason `rejected`). + +## Proof that the switches are switches + +With sexes, eggs, mate choice and ageing off, nine scenarios (field, instant eating, noise food, one cluster, lush, no predation, no ecology, the reflex controller; founder brains equal to the prior, mutation and learned inheritance frozen) give normalized snapshots, events and records **identical** to the code before this work, through births and deaths. A multi-cluster layout differs only through the shifted `genetics` stream (the two new genes: its founders differ, so the blend of their children depends on the draws), as in ADR 0025. The hash header and sample digests for schema 13 match the independent Python hasher. Goldens regenerated twice (hash schema 13 in the first commit; the two new genes in the mate-choice commit), each in the commit that caused it. + +## Measured + +RESULTS + +## Limits, said plainly + +- **Mate choice rarely decides anything here.** Most attempts fail because no ready creature of the other sex is in reach (the 99.8 percent of ADR 0005 is still the headline), so mutual acceptance only matters when a candidate is found. Tastes stay near where they start: there is no direct payoff for a choosy creature (the offspring's energy comes from a fixed investment), only the indirect one that a mate with spare energy has been a better forager. The mechanism is real and tested; its effect on the world is small and reported as measured, not claimed. +- **Guarding is only as good as the brain's wiring.** It reuses the home inputs so no weights change; a parent returns to its egg because the innate prior steers toward `home`, and the reflex controller does not guard at all (it has no home sense). +- **Eggs add an energy-rich stationary target, but jaws are rare**, so egg predation is a few eggs a world (reported). Whether eggs help carnivory persist is reported below, not assumed. +- Litter size is still 1; clutch size is a candidate gene for later. +- The life cycle changes the population dynamics enough that **every statistical gate that measures the default world was re-measured** and re-pinned with its measurement (listed in the PR), never by loosening what it asserts. diff --git a/docs/genetics/genome.md b/docs/genetics/genome.md index 60b0720..4a52c05 100644 --- a/docs/genetics/genome.md +++ b/docs/genetics/genome.md @@ -28,6 +28,8 @@ Founders start at the **baseline** (the existing `organisms.*` / `reproduction.* | `learning.riskTolerance` | float | 0.5 (`genetics.learning`) | 0 - 1 | 0.1 | 0.05 | scales the damage penalty (Phase 6: `1 - riskTolerance`) | | `learning.noveltyPreference` | float | 0.5 (`genetics.learning`) | 0 - 1 | 0.1 | 0.05 | scales the novelty reward (Phase 6) | | `learning.persistence` | float | 0.5 (`genetics.learning`) | 0 - 1 | 0.1 | 0.05 | Brain (exploration annealing) | +| `reproduction.choosiness` | float | 0.3 (`reproduction.mateChoice`) | 0 - 1 | 0.1 | 0.05 | Mate choice (how demanding of a partner; ADR 0027) | +| `reproduction.preference` | float | 0.3 (`reproduction.mateChoice`) | 0 - 1 | 0.1 | 0.05 | Mate choice (condition against difference; ADR 0027) | The ordering `maturityAge < senescenceAge < maxAge` is enforced by the operators: `senescenceAge` is declared `orderedAfter` `maturityAge`, and `maxAge` after `senescenceAge`, and mutation, recombination and repair raise such a gene's lower bound above the earlier gene (by a 1e-6 margin) even when the later gene itself did not mutate. Config validation requires each ordered gene's range maximum to exceed the earlier gene's, so there is always room. The default ranges of `maturityAge` and `senescenceAge` overlap (45 - 180 and 150 - 560) since ADR 0018, which nothing relies on being otherwise. diff --git a/docs/simulation/configuration.md b/docs/simulation/configuration.md index 03fa62b..2f8ac48 100644 --- a/docs/simulation/configuration.md +++ b/docs/simulation/configuration.md @@ -22,116 +22,120 @@ Seeds are validated separately with `validateSeed`: an integer in `[0, 429496729 Units: time is in **seconds** (one tick advances time by `timestep`), distance in world units, energy in arbitrary units. -| Field | Rule | Meaning | -| -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `timestep` | > 0 | Seconds of simulated time per tick | -| `maxPopulation` | integer, > 0 | Population ceiling (births are refused at the cap) | -| `extinctionPolicy` | `'stop'` (only value implemented) | What happens when the population reaches zero | -| `environment.width`, `.height` | > 0 | World rectangle Not 500 x 500 (the reference field), the field layout derives its terrain from the area (ADR 0021): region seed count and static hazard count scale with the area, the storm rate too, and the region lookup keeps its cell size; food supply, organism counts and the food pattern's patch size do not, so a bigger world is the same food and creatures spread thinner. At 500 x 500 nothing changes | -| `organisms.initialCount` | integer, >= 0, <= `maxPopulation` | Founders created at tick 0 | -| `organisms.initialEnergy` | > 0, <= `maxEnergy` | Founders' starting energy | -| `organisms.maxEnergy` | > 0 | Founder energy capacity (an organism's capacity scales with its body size gene); overflow is wasted | -| `organisms.radius` | > 0, < half the smaller world dimension | **Founder baseline** body radius | -| `organisms.maxSpeed` | >= 0 | **Founder baseline**, units per second | -| `organisms.maxTurnRate` | >= 0 | **Founder baseline**, radians per second | -| `organisms.sensorRadius` | > 0 | **Founder baseline** perception distance | -| `organisms.wanderJitter` | >= 0 | **Founder baseline** wander heading change, radians per second | -| `organisms.basalCost` | >= 0 | **Founder baseline** energy per second for being alive | -| `organisms.movementCost` | >= 0 | **Founder baseline** energy per second per squared unit of speed | -| `organisms.turningCost` | >= 0 | **Founder baseline** energy per second per squared radian turned | -| `organisms.sensorCost` | >= 0 | Energy per second for sensing at the baseline `sensorRadius` (scales with an organism's own radius) | -| `organisms.learningCost` | >= 0 | Metabolic cost per second at the baseline learning rate, charged while learning is enabled under the brain controller | -| `organisms.maturityAge` | > 0, < `senescenceAge` | **Founder baseline** seconds until a juvenile becomes mature | -| `organisms.senescenceAge` | > `maturityAge`, < `maxAge` | **Founder baseline** seconds until a mature organism becomes senescent | -| `organisms.maxAge` | > `senescenceAge` | **Founder baseline** seconds until death by age | -| `organisms.hue` | [0, 1) | **Founder baseline** hue in turns (cosmetic) | -| `organisms.juvenileSizeScale` | (0, 1] | Juvenile capture radius and energy capacity multiplier | -| `organisms.juvenileSpeedScale` | (0, 1] | Juvenile `maxSpeed` multiplier | -| `organisms.juvenileMetabolicScale` | (0, 1] | Juvenile metabolic cost multiplier | -| `resources.initialCount` | integer, >= 0, <= `maxCount` | Resources at tick 0 | -| `resources.maxCount` | integer, >= 0 | Cap on simultaneous resources | -| `resources.spawnRate` | >= 0 | Expected new resources per second | -| `resources.energyValue` | > 0 | Energy one resource provides | -| `resources.radius` | > 0, < half the smaller world dimension | Resource radius | -| `resources.region` | `null` or `{x, y, width, height}` inside the world | Restricts where resources spawn (Scenario D); `null` is the whole world with unchanged random draws | -| `resources.distribution` | `mode` `uniform`/`noise`; `scale` > 0; `contrast` 0-1; `floor` in (0, 1]; `turnover` >= 0 | How food is spread over the field (ADR 0021). `uniform`: every site equally likely, two draws a spawn, as before. `noise`: a smooth drifting pattern of patches (value noise in x, y and time, a pure function of the seed); a spawn draws eight candidate sites and keeps the first the pattern accepts, so the draw count never depends on the outcome. `scale` is the patch size in world units, `contrast` how much the patches stand out, `floor` the least likely a site is, `turnover` the seconds for the pattern to change by one feature (0 freezes it). Field layout only | -| `resources.plants` | `enabled`; `nodes` 1-6; `ring`, `hubEnergyScale`, `nodeEnergyScale` > 0; `hubHardness` >= 1; `regrowRate`, `photosynthesis`, `lifespan` >= 0; `maxPlants` >= 1 | Renewable plants (ADR 0021): with `enabled`, a spawn makes a hub joined to `nodes` nodes (`ring` food radii away), each a bitable food item. The hub regrows an eaten node from its store at `regrowRate` and gains `photosynthesis` a second up to `hubEnergyScale` times its kind's energy (where energy enters the world); eating the hub kills the plant and frees its nodes as free food; a plant withers after `lifespan` seconds (0: never). `spawnRate` then counts plants a second; `initialCount` and `maxCount` still count items. Field layout only (clusters keep free food) | -| `reproduction.minEnergy` | > 0 | **Founder baseline** energy required to attempt reproduction | -| `reproduction.offspringInvestment` | > 0 | **Founder baseline** energy each parent gives the child; `parent pays = investment * (1 + overheadFraction)` | -| `reproduction.overheadFraction` | >= 0 | Fraction of the investment lost in the transfer | -| `reproduction.cooldown` | >= 0 | **Founder baseline** seconds before a parent may reproduce again | -| `reproduction.mateSenseRadius` | > 0 | Distance at which an organism that is ready to reproduce senses other ready organisms (a mating signal, brain controller only; ADR 0010). Default 250 | -| `reproduction.searchRadius` | > 0 | **Founder baseline** distance within which a partner is sought | -| `history.maxEvents` | integer, >= 0 | Retained events (`0` keeps none) | -| `history.eventDetail` | `'essential'` or `'verbose'` | Whether per-tick movement and energy events are emitted | -| `history.maxHistoricalOrganisms` | integer, >= 0 | Retained historical organism records (ring buffer) | -| `genetics.mutationRateScale` | >= 0 | Multiplies every gene's mutation rate; `0` disables mutation | -| `genetics.mutationStrengthScale` | >= 0 | Multiplies every gene's mutation standard deviation | -| `genetics.blendAlpha` | >= 0 | Blend-crossover extension past the parents' values | -| `genetics.brain.hiddenSize`, `.memorySize` | integer, > 0 | Hidden and memory widths of the shared brain architecture. The input (48) and output (5) sizes are not config: they come from the `OBSERVATION_SIZE` and `ACTION_SIZE` constants in `@evo/contracts` | -| `genetics.brain.innatePrior` | boolean | Founders start from the hand-wired forager template plus noise (true) or from random weights (false) | -| `genetics.brain.initialWeightStd` | > 0 | Standard deviation of founders' random weights | -| `genetics.brain.weightMutationRate`, `.weightMutationStd` | rate in [0, 1], std >= 0 | Per-weight mutation probability and size | -| `genetics.learning.*` | learning rate > 0; discount, trace decay, exploration, risk, novelty, persistence in [0, 1] | Founder baseline learning genes | -| `genetics.learningInheritance.mode` | `'baldwinian'`, `'partial'` or `'lamarckian'` | How learned weights are inherited (wired in Phase 5) | -| `genetics.learningInheritance.fraction` | [0, 1] | Share of learning inherited in `'partial'` mode | -| `genetics.genes.` | optional `{min, max, mutationRate, mutationStd}` | Per-gene overrides of the default ranges and rates. A default edge that excludes the founder baseline is widened to include it; an explicit edge must contain the baseline; each life-stage gene's range max must exceed the previous one's | -| `learning.controller` | `'reflex'` or `'brain'` | `brain` (the default since Phase 5) runs the neural controller; `reflex` runs the Phase 4 hand-coded forager | -| `learning.enabled` | boolean | When false, weights are frozen but exploration noise continues | -| `learning.algorithm` | `'hebbian'` or `'actorCritic'` | How `delta` is computed; see docs/learning/brain.md | -| `learning.rewardWeights.feeding`, `.reproduction`, `.energyCost`, `.damage`, `.exploration` | >= 0 | Weights of the reward terms | -| `learning.weightLimit` | > 0 | Learned weights are clamped to +-this | -| `learning.baselineRate` | (0, 1] | Step of the running reward baseline (Hebbian) | -| `learning.valueRateScale` | > 0 | Critic step size relative to the learning-rate gene | -| `learning.foodHorizon` | > 0 | Seconds that map to 1 in the time-since-food observation | -| `environment.layout` | `field` or `clusters` | `field` (default): one bounded 500x500 rectangle. `clusters`: an unbounded world of circular clusters with void between them (ADR 0014; see [the cluster world](./clusters.md)) | -| `environment.clusters.*` | see [the cluster world](./clusters.md) | `count`, `radius`, `spacing`, `speciesPerCluster`, `organismsPerSpecies`, `patches`, `voidSpeedScale`, `voidVisibility`, `mateSignalCap`, `clusterSpread`, `speciesSpread`, `foodFloor`, `strandedFoodPerTick`; read only with the cluster layout | -| `anatomy.enabled` | boolean | `false`: body genes are inert (every genome carries the founder body, nothing mutates or draws from the `anatomy` stream). `true`: they recombine, mutate and inherit (ADR 0012) | -| `anatomy.structuralBudget`, `.bodyMass`, `.senseFloor` | > 0; > 0; (0, 1] | Total part `size` a body can carry (parts beyond it do not develop); mass of the body itself; sense range of an eyeless body as a fraction of the baseline | -| `anatomy.mutation.presenceRate`, `.typeRate`, `.parentRate`, `.continuousRate`, `.visualRate`, `.outlineRate` | [0, 1] | Chance per slot (or per gene) per birth that a part is gained or lost (default 0.01), that its type changes (0.01), that it moves to another parent (0.004), and per continuous, visual or outline gene (ADR 0016 addenda) | -| `anatomy.mutation.openTypes` | boolean | `true` (default): a type change jumps to any other part type, and a slot that wakes up takes a random type, size, placement and stats; `false`: the earlier behaviour (neighbour steps, latent genes), which with the old 0.004 rates reproduces every golden hash (ADR 0016 addendum) | -| `anatomy.mutation.continuousStd` | > 0 | Gaussian step of a continuous body gene as a fraction of its range | -| `anatomy.parts..mass`, `.upkeep`, `.strength` | >= 0; >= 0; > 0 | Per unit of part `size`: mass added, energy per second, and the capability coefficient, for each of the ten part types | -| `anatomy.effects` | `eyestalkLift`, `gyroTorque`, `lipidCapacity`, `pheromoneSignal`, `skeletonBudget` >= 0; `visionNarrowing` in [0, 1]; `pheromoneCap` >= 1 | What the newer parts do: the range gain of an eye on an eyestalk, a gyro's torque, a lipid store's energy capacity, a pheromone gland's signal and the most any body can reach, the structural budget a skeleton adds for the slots after it, and how much reach a narrower eye gains (ADR 0016) | -| `anatomy.mouthForms` | each of sprout, proboscis, mandible, radula, jaw: food kind name to yield >= 0; the mandible is exactly 1; with food kinds on every form lists every kind | Energy yield of each mouth form on each kind of food (a kind has to be listed for every form, 0 if the form cannot eat it: an unlisted kind used to count as 1, edible by everyone, ADR 0026); the mandible is the generalist and the founder's, so the founder is neutral (ADR 0017). A yield of 0 means the mouth neither bites nor sees that food: the **jaw is 0 on every plant** (ADR 0023 step three), so it lives on creatures and carrion | -| `feeding.enabled` | boolean | `true` (default): organisms bite food with a mouth, food has health and a gut digests it (ADR 0017); `false`: touching food eats it whole at once (the original rule, used by the Classic preset) | -| `feeding.biteRadius`, `feeding.biteCone` | > 0 (body radii); > 0, <= pi (radians, half-angle) | How far from a mouth a bite reaches, and the cone in front of it in which food can be bitten | -| `feeding.biteSize`, `feeding.biteInterval` | > 0 (energy); > 0 (seconds) | Food energy one bite takes at the founder's mouth (before the kind's `hardness`), and seconds between bites | -| `feeding.gutCapacity`, `feeding.absorption` | > 0 (energy); > 0 (energy per second) | What a founder-sized gut holds, and how fast it turns into body energy; stomachs and intestines scale them | -| `feeding.chewSlow` | (0, 1] | Speed multiplier while a bite is on cooldown, so a creature stays at its food | -| `observatory.enabled`, `.sampleEvery`, `.behaviourEvery`, `.maxSamples` | boolean; integers > 0 | The evolution observatory (ADR 0024): read-only indicators of whether the world is still changing, sampled every `sampleEvery` ticks (500), with each creature's motion observed every `behaviourEvery` (10) and at most `maxSamples` (1000) kept, oldest dropped. Never hashed; off does no work. See [evolution.md](../ecology/evolution.md) | -| `predation.enabled` | boolean | Creatures with a mouth that can bite creatures (a jaw) bite other creatures (ADR 0023); on by default since step two, and `false` is the world as it was. Needs `feeding.enabled` and `ecology.health.enabled` (so a world that turns either off turns this off too). Pinned off for the Classic, Clusters and Fixed bodies presets | -| `predation.biteDamage`, `.biteEnergy`, `.trophicYield`, `.maxPreyRatio`, `.attackWindow` | >= 0; > 0; (0, 1]; > 0; > 0 (seconds) | Health damage of a bite and energy a bite takes from the victim (both at the founder's gape, damage reduced by the victim's armor); the share of the energy taken that reaches the biter's gut (the rest is lost); the biggest prey as a multiple of the biter's body radius; how long after a bite a death by starvation or damage counts as predation | -| `predation.fleshYield.` | >= 0 each | What each mouth form yields from a creature; zero means that form never bites creatures (only the jaw is above zero by default) | -| `predation.carcass.enabled`, `.energyFraction`, `.minEnergy`, `.lifespan`, `.maxCount`, `.radius`, `.hardness` | boolean; (0, 1]; >= 0; >= 0 (seconds, 0 never rots); integer >= 0; > 0; > 0 | What a dead creature leaves where it died: a carrion food item worth this share of its energy and gut if at least `minEnergy`, up to `maxCount` on the field. With predation on, a `carrion` food kind is appended to the resource kinds (it never spawns by itself) | -| `predation.carcass.yields.` | >= 0 each | What each mouth form yields from a carcass, per unit bitten; 0 means the form neither bites nor sees carcasses. Default: **the jaw only (1.2)**, every other form 0 (ADR 0026); before that every form had a positive yield and jaws got 5 percent of the carrion | -| `perception.organismsBlockSight`, `perception.maxSightChecks` | boolean; whole number >= 1 | `true` (default): another creature's body hides what is behind it from a viewer, for food and for other creatures; at most this many candidates are checked for something in the way (ADR 0019). `false` is the transparent world of Phase 3 (the Classic preset). | -| `ecology.resourceKinds.kinds[].hardness` | > 0, default 1 | How many times harder than the baseline a kind is to bite: a bite takes `biteSize / hardness` | -| `anatomy.founderOutline`, `anatomy.outlineDrag` | outline: count 5-16, 16 radii 0.35-1, 16 angles 0-1; >= 0 | The outline every founder starts with, and the extra movement cost per unit of outline roughness above the founder's (ADR 0013); size and drag factors are exactly 1 for the founder outline | -| `anatomy.founder`, `anatomy.founderLook` | list of up to 12 parts; pattern, accentHue | The body plan every founder starts with (slot `i` is entry `i`; its total size must fit `structuralBudget`) and the founders' visual genes | -| `anatomy.starters`, `anatomy.startingBody` | list of named plans (name, description, parts, look, outline); `mode` `reference` or `archetypes`, `archetype` a name or null | The bodies a world can start with (ADR 0020). The founder plan above stays the reference every capability is measured against. In `archetypes` mode (the default) a world draws one starter with one draw from the `genetics` stream, always, and every founder starts with it; `archetype` forces one, and `groups` (`[{ archetype, share }]`, default one group of `hunter` at 0.1) starts `round(share x initialCount)` of the founders, evenly spread over their order, with another starter's body (no draw is spent, so every seed keeps its base body; `archetypes` mode only; names must be starters, each share in (0, 0.5], total at most 0.5). A starter with `pool: false` (the hunter) is never drawn as a base body. `classic`, `fixed-bodies` and `clusters` use `reference` | -| `species.distanceWeights.body` | >= 0 | Weight of the body plan in species distance (default 0.5, the largest: bodies are compared as bodies, and colour counts for nothing, ADR 0008 addendum) | -| `ecology.health.enabled` | boolean | `false` keeps every organism at full health and disables all damage | -| `ecology.health.maxHealth`, `.regenRate`, `.regenEnergyCost`, `.regenMinEnergyFraction` | > 0; >= 0; >= 0; [0, 1] | Health capacity at baseline size (scaled by body size); health regained per second; energy per health point regained; fraction of energy capacity needed to heal | -| `ecology.regions.enabled`, `.seedCount`, `.gridSize` | boolean; integer > 0; integer > 0 | Voronoi region map: points and lookup grid resolution | -| `ecology.regions.temperatureTolerance`, `.temperatureCost` | [0, 1]; >= 0 | Temperatures within the tolerance cost nothing; energy per second at excess one (quadratic) | -| `ecology.regions.types..movementScale`, `.visibility` | (0, 1] | Top speed and sensor radius multipliers for meadow, forest, wetland, desert, cave, volcanic | -| `ecology.regions.types..temperature`, `.hazardExposure`, `.reproductionScale` | [-1, 1]; >= 0; > 0 | Temperature offset, hazard damage multiplier, reproduction cost divisor | -| `ecology.seasons.enabled`, `.seasonLength` | boolean; > 0 | Seconds per season (four seasons: spring, summer, autumn, winter) | -| `ecology.seasons.seasons..regeneration`, `.hazardIntensity` | >= 0 | Resource spawn rate and hazard damage / storm rate multipliers | -| `ecology.seasons.seasons..movementScale`, `.visibility`, `.reproductionScale`, `.temperature` | (0, 1]; (0, 1]; > 0; [-1, 1] | Season multipliers and temperature offset | -| `ecology.hazards.enabled`, `.areaCount`, `.areaRadius`, `.areaDamage` | boolean; integer >= 0; > 0; >= 0 | Static damage areas (health damage per second) | -| `ecology.hazards.stormRate`, `.stormRadius`, `.stormDuration`, `.stormDamage` | >= 0; > 0; > 0; >= 0 | Expected storms per second, size, seconds a storm lasts, damage per second | -| `ecology.obstacles.enabled`, `.maxCoverage`, `.clearance` | boolean; in [0, 1); >= 0 | Static obstacles placed by biome at creation (ADR 0022): circles that block movement, sight or both. `maxCoverage` is the share of the field they may cover (placement stops there), `clearance` how far from the world's edge they stay. Field layout only; the cluster layout has none. With `enabled: false` nothing is drawn and nothing changes | -| `ecology.obstacles.kinds.` (`boulder`, `tree`, `ridge`, `pond`, `reeds`) | `recipe` `single`/`chain`/`cluster`; `blocksMovement`, `blocksSight` boolean; `radiusMin` <= `radiusMax`, both >= 6; `membersMin` <= `membersMax` integers >= 1 (1 for `single`); `density.` >= 0 | One kind of obstacle: how it is laid out (one circle, a row of overlapping circles, a tight cluster), what it blocks, how big a circle is, and the expected sites per 10,000 square units in each of the six biomes. The circle radius is at least 6 so a body (at most about 2 units a tick) cannot tunnel through. `kinds` merges per kind and `density` per region type | -| `ecology.resourceKinds.enabled`, `.kinds[]` | boolean; non-empty list | Resource kinds: `name`, `energyScale`, `radiusScale`, `spawnWeight`, `detectability` (0, 1], `toxicity`, `regions` (empty means everywhere). Replaced whole by an override | -| `ecology.migration.enabled`, `.dwellTime` | boolean; > 0 | Migration tracking; seconds outside the home region that count as having migrated (needs regions) | -| `species.enabled` | boolean | `false` disables the species registry (no species ids, empty queries) | -| `species.threshold` | [0, 1] | Largest weighted genetic distance at which a genome joins an existing species (inclusive) | -| `species.distanceWeights.physical`, `.metabolic`, `.behavioral`, `.reproduction`, `.learning`, `.brain` | >= 0, not all zero | Relative weight of each gene group in the species distance (normalized by their sum) | -| `species.sampleInterval` | integer, > 0 | Ticks between species population samples | -| `species.maxHistorySamples` | integer, >= 0 | Samples kept per species; the oldest are dropped | -| `species.reproductiveIsolation` | boolean | When true, organisms only reproduce with members of their own species (changes behavior; default false) | +| Field | Rule | Meaning | +| -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `timestep` | > 0 | Seconds of simulated time per tick | +| `maxPopulation` | integer, > 0 | Population ceiling (births are refused at the cap) | +| `extinctionPolicy` | `'stop'` (only value implemented) | What happens when the population reaches zero | +| `environment.width`, `.height` | > 0 | World rectangle Not 500 x 500 (the reference field), the field layout derives its terrain from the area (ADR 0021): region seed count and static hazard count scale with the area, the storm rate too, and the region lookup keeps its cell size; food supply, organism counts and the food pattern's patch size do not, so a bigger world is the same food and creatures spread thinner. At 500 x 500 nothing changes | +| `organisms.initialCount` | integer, >= 0, <= `maxPopulation` | Founders created at tick 0 | +| `organisms.initialEnergy` | > 0, <= `maxEnergy` | Founders' starting energy | +| `organisms.maxEnergy` | > 0 | Founder energy capacity (an organism's capacity scales with its body size gene); overflow is wasted | +| `organisms.radius` | > 0, < half the smaller world dimension | **Founder baseline** body radius | +| `organisms.maxSpeed` | >= 0 | **Founder baseline**, units per second | +| `organisms.maxTurnRate` | >= 0 | **Founder baseline**, radians per second | +| `organisms.sensorRadius` | > 0 | **Founder baseline** perception distance | +| `organisms.wanderJitter` | >= 0 | **Founder baseline** wander heading change, radians per second | +| `organisms.basalCost` | >= 0 | **Founder baseline** energy per second for being alive | +| `organisms.movementCost` | >= 0 | **Founder baseline** energy per second per squared unit of speed | +| `organisms.turningCost` | >= 0 | **Founder baseline** energy per second per squared radian turned | +| `organisms.sensorCost` | >= 0 | Energy per second for sensing at the baseline `sensorRadius` (scales with an organism's own radius) | +| `organisms.learningCost` | >= 0 | Metabolic cost per second at the baseline learning rate, charged while learning is enabled under the brain controller | +| `organisms.maturityAge` | > 0, < `senescenceAge` | **Founder baseline** seconds until a juvenile becomes mature | +| `organisms.senescenceAge` | > `maturityAge`, < `maxAge` | **Founder baseline** seconds until a mature organism becomes senescent | +| `organisms.maxAge` | > `senescenceAge` | **Founder baseline** seconds until death by age | +| `organisms.hue` | [0, 1) | **Founder baseline** hue in turns (cosmetic) | +| `organisms.juvenileSizeScale` | (0, 1] | Juvenile capture radius and energy capacity multiplier | +| `organisms.juvenileSpeedScale` | (0, 1] | Juvenile `maxSpeed` multiplier | +| `organisms.juvenileMetabolicScale` | (0, 1] | Juvenile metabolic cost multiplier | +| `resources.initialCount` | integer, >= 0, <= `maxCount` | Resources at tick 0 | +| `resources.maxCount` | integer, >= 0 | Cap on simultaneous resources | +| `resources.spawnRate` | >= 0 | Expected new resources per second | +| `resources.energyValue` | > 0 | Energy one resource provides | +| `resources.radius` | > 0, < half the smaller world dimension | Resource radius | +| `resources.region` | `null` or `{x, y, width, height}` inside the world | Restricts where resources spawn (Scenario D); `null` is the whole world with unchanged random draws | +| `resources.distribution` | `mode` `uniform`/`noise`; `scale` > 0; `contrast` 0-1; `floor` in (0, 1]; `turnover` >= 0 | How food is spread over the field (ADR 0021). `uniform`: every site equally likely, two draws a spawn, as before. `noise`: a smooth drifting pattern of patches (value noise in x, y and time, a pure function of the seed); a spawn draws eight candidate sites and keeps the first the pattern accepts, so the draw count never depends on the outcome. `scale` is the patch size in world units, `contrast` how much the patches stand out, `floor` the least likely a site is, `turnover` the seconds for the pattern to change by one feature (0 freezes it). Field layout only | +| `resources.plants` | `enabled`; `nodes` 1-6; `ring`, `hubEnergyScale`, `nodeEnergyScale` > 0; `hubHardness` >= 1; `regrowRate`, `photosynthesis`, `lifespan` >= 0; `maxPlants` >= 1 | Renewable plants (ADR 0021): with `enabled`, a spawn makes a hub joined to `nodes` nodes (`ring` food radii away), each a bitable food item. The hub regrows an eaten node from its store at `regrowRate` and gains `photosynthesis` a second up to `hubEnergyScale` times its kind's energy (where energy enters the world); eating the hub kills the plant and frees its nodes as free food; a plant withers after `lifespan` seconds (0: never). `spawnRate` then counts plants a second; `initialCount` and `maxCount` still count items. Field layout only (clusters keep free food) | +| `reproduction.minEnergy` | > 0 | **Founder baseline** energy required to attempt reproduction | +| `reproduction.offspringInvestment` | > 0 | **Founder baseline** energy each parent gives the child; `parent pays = investment * (1 + overheadFraction)` | +| `reproduction.overheadFraction` | >= 0 | Fraction of the investment lost in the transfer | +| `reproduction.cooldown` | >= 0 | **Founder baseline** seconds before a parent may reproduce again | +| `reproduction.mateSenseRadius` | > 0 | Distance at which an organism that is ready to reproduce senses other ready organisms (a mating signal, brain controller only; ADR 0010). Default 250 | +| `reproduction.searchRadius` | > 0 | **Founder baseline** distance within which a partner is sought | +| `reproduction.sexes.enabled` | boolean | `true`: two sexes (ADR 0027). Founders alternate female and male; a newborn's sex is one draw from the `reproduction` stream; only a female and a male mate and the female is the mother. `false`: any two ready creatures may (the Classic preset) | +| `reproduction.eggs.enabled`, `.incubation`, `.hatch`, `.carryCost`, `.guardRadius`, `.guardCost`, `.guardDamage` | boolean; seconds > 0 (incubation, hatch, guardRadius); >= 0 (the three costs) | The life cycle (ADR 0027): needs `sexes.enabled`. A conceived clutch is carried for `incubation` s (the female pays `carryCost` energy a second on top of her metabolism, and loses the clutch if she dies), then laid as an egg that hatches after `hatch` s into a creature with the stored genome and the mother's species. A parent within `guardRadius` of its egg guards it (`guardCost` a second per egg) and a bite at a guarded egg is stopped and costs the biter `guardDamage` health. Eggs and carried clutches count against `maxPopulation`. A flesh-eating mouth eats an unguarded egg whole | +| `reproduction.mateChoice.enabled`, `.choosiness`, `.preference`, `.threshold`, `.searchCost`, `.retryDelay`, `.candidates` | boolean; 0 - 1; 0 - 1; (0, 1]; >= 0; >= 0; whole number >= 1 | Mate choice (ADR 0027): needs `sexes.enabled`. A creature looks at the nearest `candidates` ready partners and takes the first both accept; it scores `(1 - preference) x condition + preference x difference` and accepts at `choosiness x threshold`. `choosiness` and `preference` are the founders' values of two genes. Turning every candidate down costs `searchCost` energy and a `retryDelay` s wait | +| `history.maxEvents` | integer, >= 0 | Retained events (`0` keeps none) | +| `history.eventDetail` | `'essential'` or `'verbose'` | Whether per-tick movement and energy events are emitted | +| `history.maxHistoricalOrganisms` | integer, >= 0 | Retained historical organism records (ring buffer) | +| `genetics.mutationRateScale` | >= 0 | Multiplies every gene's mutation rate; `0` disables mutation | +| `genetics.mutationStrengthScale` | >= 0 | Multiplies every gene's mutation standard deviation | +| `genetics.blendAlpha` | >= 0 | Blend-crossover extension past the parents' values | +| `genetics.brain.hiddenSize`, `.memorySize` | integer, > 0 | Hidden and memory widths of the shared brain architecture. The input (48) and output (5) sizes are not config: they come from the `OBSERVATION_SIZE` and `ACTION_SIZE` constants in `@evo/contracts` | +| `genetics.brain.innatePrior` | boolean | Founders start from the hand-wired forager template plus noise (true) or from random weights (false) | +| `genetics.brain.initialWeightStd` | > 0 | Standard deviation of founders' random weights | +| `genetics.brain.weightMutationRate`, `.weightMutationStd` | rate in [0, 1], std >= 0 | Per-weight mutation probability and size | +| `genetics.learning.*` | learning rate > 0; discount, trace decay, exploration, risk, novelty, persistence in [0, 1] | Founder baseline learning genes | +| `genetics.learningInheritance.mode` | `'baldwinian'`, `'partial'` or `'lamarckian'` | How learned weights are inherited (wired in Phase 5) | +| `genetics.learningInheritance.fraction` | [0, 1] | Share of learning inherited in `'partial'` mode | +| `genetics.genes.` | optional `{min, max, mutationRate, mutationStd}` | Per-gene overrides of the default ranges and rates. A default edge that excludes the founder baseline is widened to include it; an explicit edge must contain the baseline; each life-stage gene's range max must exceed the previous one's | +| `learning.controller` | `'reflex'` or `'brain'` | `brain` (the default since Phase 5) runs the neural controller; `reflex` runs the Phase 4 hand-coded forager | +| `learning.enabled` | boolean | When false, weights are frozen but exploration noise continues | +| `learning.algorithm` | `'hebbian'` or `'actorCritic'` | How `delta` is computed; see docs/learning/brain.md | +| `learning.rewardWeights.feeding`, `.reproduction`, `.energyCost`, `.damage`, `.exploration` | >= 0 | Weights of the reward terms | +| `learning.weightLimit` | > 0 | Learned weights are clamped to +-this | +| `learning.baselineRate` | (0, 1] | Step of the running reward baseline (Hebbian) | +| `learning.valueRateScale` | > 0 | Critic step size relative to the learning-rate gene | +| `learning.foodHorizon` | > 0 | Seconds that map to 1 in the time-since-food observation | +| `environment.layout` | `field` or `clusters` | `field` (default): one bounded 500x500 rectangle. `clusters`: an unbounded world of circular clusters with void between them (ADR 0014; see [the cluster world](./clusters.md)) | +| `environment.clusters.*` | see [the cluster world](./clusters.md) | `count`, `radius`, `spacing`, `speciesPerCluster`, `organismsPerSpecies`, `patches`, `voidSpeedScale`, `voidVisibility`, `mateSignalCap`, `clusterSpread`, `speciesSpread`, `foodFloor`, `strandedFoodPerTick`; read only with the cluster layout | +| `anatomy.enabled` | boolean | `false`: body genes are inert (every genome carries the founder body, nothing mutates or draws from the `anatomy` stream). `true`: they recombine, mutate and inherit (ADR 0012) | +| `anatomy.structuralBudget`, `.bodyMass`, `.senseFloor` | > 0; > 0; (0, 1] | Total part `size` a body can carry (parts beyond it do not develop); mass of the body itself; sense range of an eyeless body as a fraction of the baseline | +| `anatomy.mutation.presenceRate`, `.typeRate`, `.parentRate`, `.continuousRate`, `.visualRate`, `.outlineRate` | [0, 1] | Chance per slot (or per gene) per birth that a part is gained or lost (default 0.01), that its type changes (0.01), that it moves to another parent (0.004), and per continuous, visual or outline gene (ADR 0016 addenda) | +| `anatomy.mutation.openTypes` | boolean | `true` (default): a type change jumps to any other part type, and a slot that wakes up takes a random type, size, placement and stats; `false`: the earlier behaviour (neighbour steps, latent genes), which with the old 0.004 rates reproduces every golden hash (ADR 0016 addendum) | +| `anatomy.mutation.continuousStd` | > 0 | Gaussian step of a continuous body gene as a fraction of its range | +| `anatomy.parts..mass`, `.upkeep`, `.strength` | >= 0; >= 0; > 0 | Per unit of part `size`: mass added, energy per second, and the capability coefficient, for each of the ten part types | +| `anatomy.effects` | `eyestalkLift`, `gyroTorque`, `lipidCapacity`, `pheromoneSignal`, `skeletonBudget` >= 0; `visionNarrowing` in [0, 1]; `pheromoneCap` >= 1 | What the newer parts do: the range gain of an eye on an eyestalk, a gyro's torque, a lipid store's energy capacity, a pheromone gland's signal and the most any body can reach, the structural budget a skeleton adds for the slots after it, and how much reach a narrower eye gains (ADR 0016) | +| `anatomy.mouthForms` | each of sprout, proboscis, mandible, radula, jaw: food kind name to yield >= 0; the mandible is exactly 1; with food kinds on every form lists every kind | Energy yield of each mouth form on each kind of food (a kind has to be listed for every form, 0 if the form cannot eat it: an unlisted kind used to count as 1, edible by everyone, ADR 0026); the mandible is the generalist and the founder's, so the founder is neutral (ADR 0017). A yield of 0 means the mouth neither bites nor sees that food: the **jaw is 0 on every plant** (ADR 0023 step three), so it lives on creatures and carrion | +| `feeding.enabled` | boolean | `true` (default): organisms bite food with a mouth, food has health and a gut digests it (ADR 0017); `false`: touching food eats it whole at once (the original rule, used by the Classic preset) | +| `feeding.biteRadius`, `feeding.biteCone` | > 0 (body radii); > 0, <= pi (radians, half-angle) | How far from a mouth a bite reaches, and the cone in front of it in which food can be bitten | +| `feeding.biteSize`, `feeding.biteInterval` | > 0 (energy); > 0 (seconds) | Food energy one bite takes at the founder's mouth (before the kind's `hardness`), and seconds between bites | +| `feeding.gutCapacity`, `feeding.absorption` | > 0 (energy); > 0 (energy per second) | What a founder-sized gut holds, and how fast it turns into body energy; stomachs and intestines scale them | +| `feeding.chewSlow` | (0, 1] | Speed multiplier while a bite is on cooldown, so a creature stays at its food | +| `observatory.enabled`, `.sampleEvery`, `.behaviourEvery`, `.maxSamples` | boolean; integers > 0 | The evolution observatory (ADR 0024): read-only indicators of whether the world is still changing, sampled every `sampleEvery` ticks (500), with each creature's motion observed every `behaviourEvery` (10) and at most `maxSamples` (1000) kept, oldest dropped. Never hashed; off does no work. See [evolution.md](../ecology/evolution.md) | +| `predation.enabled` | boolean | Creatures with a mouth that can bite creatures (a jaw) bite other creatures (ADR 0023); on by default since step two, and `false` is the world as it was. Needs `feeding.enabled` and `ecology.health.enabled` (so a world that turns either off turns this off too). Pinned off for the Classic, Clusters and Fixed bodies presets | +| `predation.biteDamage`, `.biteEnergy`, `.trophicYield`, `.maxPreyRatio`, `.attackWindow` | >= 0; > 0; (0, 1]; > 0; > 0 (seconds) | Health damage of a bite and energy a bite takes from the victim (both at the founder's gape, damage reduced by the victim's armor); the share of the energy taken that reaches the biter's gut (the rest is lost); the biggest prey as a multiple of the biter's body radius; how long after a bite a death by starvation or damage counts as predation | +| `predation.fleshYield.` | >= 0 each | What each mouth form yields from a creature; zero means that form never bites creatures (only the jaw is above zero by default) | +| `predation.carcass.enabled`, `.energyFraction`, `.minEnergy`, `.lifespan`, `.maxCount`, `.radius`, `.hardness` | boolean; (0, 1]; >= 0; >= 0 (seconds, 0 never rots); integer >= 0; > 0; > 0 | What a dead creature leaves where it died: a carrion food item worth this share of its energy and gut if at least `minEnergy`, up to `maxCount` on the field. With predation on, a `carrion` food kind is appended to the resource kinds (it never spawns by itself) | +| `predation.carcass.yields.` | >= 0 each | What each mouth form yields from a carcass, per unit bitten; 0 means the form neither bites nor sees carcasses. Default: **the jaw only (1.2)**, every other form 0 (ADR 0026); before that every form had a positive yield and jaws got 5 percent of the carrion | +| `perception.organismsBlockSight`, `perception.maxSightChecks` | boolean; whole number >= 1 | `true` (default): another creature's body hides what is behind it from a viewer, for food and for other creatures; at most this many candidates are checked for something in the way (ADR 0019). `false` is the transparent world of Phase 3 (the Classic preset). | +| `ageing.enabled`, `.metabolismRise`, `.speedLoss`, `.fertilityLoss`, `.hazard`, `.ceiling` | boolean; >= 0; [0, 1); >= 0; >= 0; > 1 | Ageing (ADR 0027): with `s` the share of the way from a creature's `senescenceAge` to its `maxAge` (above 1 beyond it), metabolism rises by `metabolismRise x min(s, 2)`, top speed falls by `speedLoss x min(s, 1)`, the energy needed to breed rises by `fertilityLoss x min(s, 1)`, and the chance of dying is `hazard x s` a second, with no cutoff at `maxAge` and certain death at `ceiling x maxAge`. `false` is the hard cutoff at `maxAge` | +| `ecology.resourceKinds.kinds[].hardness` | > 0, default 1 | How many times harder than the baseline a kind is to bite: a bite takes `biteSize / hardness` | +| `anatomy.founderOutline`, `anatomy.outlineDrag` | outline: count 5-16, 16 radii 0.35-1, 16 angles 0-1; >= 0 | The outline every founder starts with, and the extra movement cost per unit of outline roughness above the founder's (ADR 0013); size and drag factors are exactly 1 for the founder outline | +| `anatomy.founder`, `anatomy.founderLook` | list of up to 12 parts; pattern, accentHue | The body plan every founder starts with (slot `i` is entry `i`; its total size must fit `structuralBudget`) and the founders' visual genes | +| `anatomy.starters`, `anatomy.startingBody` | list of named plans (name, description, parts, look, outline); `mode` `reference` or `archetypes`, `archetype` a name or null | The bodies a world can start with (ADR 0020). The founder plan above stays the reference every capability is measured against. In `archetypes` mode (the default) a world draws one starter with one draw from the `genetics` stream, always, and every founder starts with it; `archetype` forces one, and `groups` (`[{ archetype, share }]`, default one group of `hunter` at 0.1) starts `round(share x initialCount)` of the founders, evenly spread over their order, with another starter's body (no draw is spent, so every seed keeps its base body; `archetypes` mode only; names must be starters, each share in (0, 0.5], total at most 0.5). A starter with `pool: false` (the hunter) is never drawn as a base body. `classic`, `fixed-bodies` and `clusters` use `reference` | +| `species.distanceWeights.body` | >= 0 | Weight of the body plan in species distance (default 0.5, the largest: bodies are compared as bodies, and colour counts for nothing, ADR 0008 addendum) | +| `ecology.health.enabled` | boolean | `false` keeps every organism at full health and disables all damage | +| `ecology.health.maxHealth`, `.regenRate`, `.regenEnergyCost`, `.regenMinEnergyFraction` | > 0; >= 0; >= 0; [0, 1] | Health capacity at baseline size (scaled by body size); health regained per second; energy per health point regained; fraction of energy capacity needed to heal | +| `ecology.regions.enabled`, `.seedCount`, `.gridSize` | boolean; integer > 0; integer > 0 | Voronoi region map: points and lookup grid resolution | +| `ecology.regions.temperatureTolerance`, `.temperatureCost` | [0, 1]; >= 0 | Temperatures within the tolerance cost nothing; energy per second at excess one (quadratic) | +| `ecology.regions.types..movementScale`, `.visibility` | (0, 1] | Top speed and sensor radius multipliers for meadow, forest, wetland, desert, cave, volcanic | +| `ecology.regions.types..temperature`, `.hazardExposure`, `.reproductionScale` | [-1, 1]; >= 0; > 0 | Temperature offset, hazard damage multiplier, reproduction cost divisor | +| `ecology.seasons.enabled`, `.seasonLength` | boolean; > 0 | Seconds per season (four seasons: spring, summer, autumn, winter) | +| `ecology.seasons.seasons..regeneration`, `.hazardIntensity` | >= 0 | Resource spawn rate and hazard damage / storm rate multipliers | +| `ecology.seasons.seasons..movementScale`, `.visibility`, `.reproductionScale`, `.temperature` | (0, 1]; (0, 1]; > 0; [-1, 1] | Season multipliers and temperature offset | +| `ecology.hazards.enabled`, `.areaCount`, `.areaRadius`, `.areaDamage` | boolean; integer >= 0; > 0; >= 0 | Static damage areas (health damage per second) | +| `ecology.hazards.stormRate`, `.stormRadius`, `.stormDuration`, `.stormDamage` | >= 0; > 0; > 0; >= 0 | Expected storms per second, size, seconds a storm lasts, damage per second | +| `ecology.obstacles.enabled`, `.maxCoverage`, `.clearance` | boolean; in [0, 1); >= 0 | Static obstacles placed by biome at creation (ADR 0022): circles that block movement, sight or both. `maxCoverage` is the share of the field they may cover (placement stops there), `clearance` how far from the world's edge they stay. Field layout only; the cluster layout has none. With `enabled: false` nothing is drawn and nothing changes | +| `ecology.obstacles.kinds.` (`boulder`, `tree`, `ridge`, `pond`, `reeds`) | `recipe` `single`/`chain`/`cluster`; `blocksMovement`, `blocksSight` boolean; `radiusMin` <= `radiusMax`, both >= 6; `membersMin` <= `membersMax` integers >= 1 (1 for `single`); `density.` >= 0 | One kind of obstacle: how it is laid out (one circle, a row of overlapping circles, a tight cluster), what it blocks, how big a circle is, and the expected sites per 10,000 square units in each of the six biomes. The circle radius is at least 6 so a body (at most about 2 units a tick) cannot tunnel through. `kinds` merges per kind and `density` per region type | +| `ecology.resourceKinds.enabled`, `.kinds[]` | boolean; non-empty list | Resource kinds: `name`, `energyScale`, `radiusScale`, `spawnWeight`, `detectability` (0, 1], `toxicity`, `regions` (empty means everywhere). Replaced whole by an override | +| `ecology.migration.enabled`, `.dwellTime` | boolean; > 0 | Migration tracking; seconds outside the home region that count as having migrated (needs regions) | +| `species.enabled` | boolean | `false` disables the species registry (no species ids, empty queries) | +| `species.threshold` | [0, 1] | Largest weighted genetic distance at which a genome joins an existing species (inclusive) | +| `species.distanceWeights.physical`, `.metabolic`, `.behavioral`, `.reproduction`, `.learning`, `.brain` | >= 0, not all zero | Relative weight of each gene group in the species distance (normalized by their sum) | +| `species.sampleInterval` | integer, > 0 | Ticks between species population samples | +| `species.maxHistorySamples` | integer, >= 0 | Samples kept per species; the oldest are dropped | +| `species.reproductiveIsolation` | boolean | When true, organisms only reproduce with members of their own species (changes behavior; default false) | Cross-field rules also include: `reproduction.offspringInvestment * (1 + overheadFraction) <= reproduction.minEnergy`, and `2 * reproduction.offspringInvestment <= organisms.maxEnergy`. The gene table with default ranges is in [docs/genetics/genome.md](../genetics/genome.md); `organisms.*` and `reproduction.*` above are only the founder baseline, since each organism reads its traits from its own genome. diff --git a/docs/simulation/update-order.md b/docs/simulation/update-order.md index c294001..af992e4 100644 --- a/docs/simulation/update-order.md +++ b/docs/simulation/update-order.md @@ -65,8 +65,8 @@ Initial population and resources are created once in `World.create` (setup, not 7-feeding. **With `feeding.enabled` (the default, ADR 0017) interaction bites instead**: in ascending id, an organism with a working mouth, the intent to interact and a bite off cooldown bites the nearest food that lies within `feeding.biteRadius * body radius * reach` of a mouth (the mouth is a part, placed by its anchor and turned by the heading) and inside the cone `feeding.biteCone` in front of it. A bite removes `min(remaining, feeding.biteSize * biteSize factor / kind hardness, room in the gut)` from the food's `remaining`; the food stays until its last bite (then one `resource-consumed`); the chunk times the mouth form's yield for that kind goes into the organism's `gut`; a toxic kind writes its toxicity times the chunk's share of the item. A gut with room for less than half a bite refuses it. **Digestion** (new, right after) moves up to `feeding.absorption * absorption factor * dt` from the gut into energy, never beyond the room in the body. A bitten organism chews: movement is multiplied by `feeding.chewSlow` while its `biteCooldown` is above zero. **With `predation.enabled` (ADR 0023)** a mouth whose form has a flesh yield (the jaw) takes the nearer of that food and the nearest creature it could bite (not kin, alive, no bigger than `maxPreyRatio` of its own body, in reach and cone, no solid obstacle between): the victim's energy goes down by what was taken, the biter's gut up by that times the trophic and flesh yields, the victim's bite damage is written for the health stage with the attacker, and an `organism-bitten` event is recorded. With `feeding.enabled: false` the paragraph above (touch and take whole) runs unchanged. 7a. **Health** (Phase 6): in ascending id, damage is the sum of every hazard circle the organism is inside (`damagePerSecond * regionExposure * seasonIntensity * dt`) plus the toxin eaten; if there is any, health drops and one `organism-damaged` event is recorded; otherwise, if hurt and holding enough energy, it heals up to `regenRate * dt` and the energy cost is passed to metabolism. The damage also includes the bites the organism took this tick (already reduced by its armor), and the event then names the attacker. A no-op with health off. 8. **Metabolism**: `cost = (basalCost*sizeFactor + movementCost*speed² + turningCost*lastTurnMagnitude² + sensorCost) * juvenileMetabolicScale (if juvenile, else 1)` per unit time, plus `age += deltaTime`; since Phase 5 it also adds `learningCost` while learning is enabled under the brain controller (see [docs/learning/brain.md](../learning/brain.md)), and since Phase 6 `environmentalCost` (a quadratic charge for region and season temperature outside the comfortable band, see [docs/ecology/ecology.md](../ecology/ecology.md)) and the energy spent healing. The formula is explicit and unit-tested. -9. **Reproduction**: every organism's `reproductionCooldownRemaining` is first decremented by `deltaTime` (floored at zero); then organisms are processed in ascending id, each considered at most once as an initiator. An organism attempts only once it clears three silent gates (life stage is not `juvenile`, `reproductionCooldownRemaining <= 0`, `energy >=` its own `minEnergy` gene); organisms that don't clear the gates simply don't attempt, no event. An attempting organism is blocked by, in order: the population cap (`organisms.size >= maxPopulation`), then the lack of an eligible, not-yet-paired partner within the initiator's own `searchRadius` gene (a partner must itself clear the three gates by its own genes) - both produce a `reproduction-attempted` event with `succeeded: false`. On success, each parent pays `offspringInvestment * (1 + reproduction.overheadFraction)` and its cooldown resets to its own `cooldown` gene; the child's genome gets a new `GenomeId` and is built from both parents (the lower-id parent is "mother"): recombination (blend crossover for continuous genes, per-block segment crossover for brain weights) then mutation, drawing only from the `genetics` stream, with the child registered in the lineage store and then assigned a species (see [species.md](species.md); no randomness, no state change); the child starts at age 0, `energy = min(investmentA + investmentB, its own derived maxEnergy)`, near the parents' midpoint, with `parentIds` in ascending order. See ADR 0005 for the full algorithm. -10. **Death**: in ascending id; `energy <= 0` gives `starvation`, otherwise `health <= 0` gives `damage`, otherwise `age >= maxAge` (the organism's own gene) gives `age`; the organism is removed from the active store and a compact historical record is appended to the (bounded) history store in the same stage, its lineage record is marked dead (the record itself is never removed), and its species loses a member (a species with no members is marked extinct but kept). +9. **Reproduction**: every organism's `reproductionCooldownRemaining` is first decremented by `deltaTime` (floored at zero); then organisms are processed in ascending id, each considered at most once as an initiator. An organism attempts only once it clears three silent gates (life stage is not `juvenile`, `reproductionCooldownRemaining <= 0`, `energy >=` its own `minEnergy` gene); organisms that don't clear the gates simply don't attempt, no event. An attempting organism is blocked by, in order: the population cap (`organisms.size >= maxPopulation`), then the lack of an eligible, not-yet-paired partner within the initiator's own `searchRadius` gene (a partner must itself clear the three gates by its own genes) - both produce a `reproduction-attempted` event with `succeeded: false`. On success, each parent pays `offspringInvestment * (1 + reproduction.overheadFraction)` and its cooldown resets to its own `cooldown` gene; the child's genome gets a new `GenomeId` and is built from both parents (the lower-id parent is "mother"): recombination (blend crossover for continuous genes, per-block segment crossover for brain weights) then mutation, drawing only from the `genetics` stream, with the child registered in the lineage store and then assigned a species (see [species.md](species.md); no randomness, no state change); the child starts at age 0, `energy = min(investmentA + investmentB, its own derived maxEnergy)`, near the parents' midpoint, with `parentIds` in ascending order. See ADR 0005 for the full algorithm. **Life cycle (ADR 0027).** With `reproduction.sexes.enabled` a partner must be of the other sex and the female is the mother; the child's sex is one more draw from the `reproduction` stream. With `reproduction.eggs.enabled` the birth is deferred: conception recombines the child's genome at once (the same draws as an instant birth) and stores it in the mother's pregnancy, the cap counts carried clutches and eggs, and then, right after conception in the same stage, `EggSystem` lays every clutch that is due (an egg at the mother's position, ascending mother id), charges each guarding parent `guardCost`, and hatches every egg whose time has come (ascending egg id; the hatchling is created with the stored genome and the mother's species at conception, `egg-hatched` then `organism-born`). With `reproduction.mateChoice.enabled` the initiator looks at the nearest few ready partners and takes the first both accept; turning all of them down is a `rejected` failure that costs `searchCost` and a wait. +10. **Death**: in ascending id; `energy <= 0` gives `starvation`, otherwise `health <= 0` gives `damage`, otherwise `age >= maxAge` (the organism's own gene) gives `age` (with `ageing.enabled` there is no cutoff there: a creature past its `senescenceAge` dies of `age` with chance `ageing.hazard x s` a tick-second, one draw from the `world` stream each, and certainly at `ageing.ceiling x maxAge`; ADR 0027); a carrying mother who dies also emits `clutch-lost`; the organism is removed from the active store and a compact historical record is appended to the (bounded) history store in the same stage, its lineage record is marked dead (the record itself is never removed), and its species loses a member (a species with no members is marked extinct but kept). 11. **Metrics**: counters derived from this tick's events; sets `extinctionTick` the first tick the active population is zero (never cleared - reproduction cannot revive an empty population, since it always requires at least one existing organism as a parent). ## Life stages diff --git a/packages/config/src/defaults.ts b/packages/config/src/defaults.ts index db7fd1f..085f26d 100644 --- a/packages/config/src/defaults.ts +++ b/packages/config/src/defaults.ts @@ -92,16 +92,21 @@ export const DEFAULT_WORLD_CONFIG: Readonly = deepFreeze({ } }, reproduction: { - minEnergy: 75, + // Measured with the life cycle on (ADR 0027): 16 seeds x 30,000 ticks, no extinct world, mean + // population 51, lowest 16 to 21. The life cycle needs creatures to breed a little sooner + // (minEnergy 75 to 65, cooldown 45 to 30) and to find a partner of the other sex from farther off + // (search 50 to 75, mating signal 250 to 350): with half the creatures the wrong sex the old values + // let 2 of 8 worlds go extinct. + minEnergy: 65, offspringInvestment: 12.5, overheadFraction: 0.6, - cooldown: 45, - searchRadius: 50, - mateSenseRadius: 250, - // Off here; the life cycle (ADR 0027) is switched on in the measured commit. - sexes: { enabled: false }, + cooldown: 30, + searchRadius: 75, + mateSenseRadius: 350, + // Two sexes, a carried clutch, an egg and a hatchling (ADR 0027). + sexes: { enabled: true }, eggs: { - enabled: false, + enabled: true, incubation: 10, hatch: 20, carryCost: 0.1, @@ -109,13 +114,13 @@ export const DEFAULT_WORLD_CONFIG: Readonly = deepFreeze({ guardCost: 0.05, guardDamage: 5 }, - // Off here; the founders' two genes sit at a mild taste (ADR 0027). + // A partner has to accept too, and a creature has tastes (ADR 0027). mateChoice: { - enabled: false, - choosiness: 0.3, - preference: 0.3, - threshold: 0.5, - searchCost: 0.5, + enabled: true, + choosiness: 0.8, + preference: 0.5, + threshold: 0.4, + searchCost: 0.2, retryDelay: 2, candidates: 4 } @@ -452,13 +457,14 @@ export const DEFAULT_WORLD_CONFIG: Readonly = deepFreeze({ organismsBlockSight: true, maxSightChecks: 6 }, - // Ageing (ADR 0027): off here; switched on in the measured commit. + // Ageing (ADR 0027): a creature declines past its senescence age and faces a chance of dying that + // rises with age instead of a cutoff; about a third of deaths are now of old age. ageing: { - enabled: false, - metabolismRise: 0.5, - speedLoss: 0.3, - fertilityLoss: 0.5, - hazard: 0.04, + enabled: true, + metabolismRise: 0.3, + speedLoss: 0.2, + fertilityLoss: 0.3, + hazard: 0.02, ceiling: 2 } } satisfies WorldConfig) diff --git a/packages/config/src/presets.ts b/packages/config/src/presets.ts index 1729cce..e44ca35 100644 --- a/packages/config/src/presets.ts +++ b/packages/config/src/presets.ts @@ -15,6 +15,17 @@ export interface WorldPreset { * `balanced` is the default world and the one the engine is tuned and gated on. The others change * one thing each, so what they do is easy to see in the interface. */ +/** The breeding of the worlds that predate the life cycle: one sex, an instant birth, no mate choice (ADR 0027). */ +const OLD_REPRODUCTION = { + minEnergy: 75, + cooldown: 45, + searchRadius: 50, + mateSenseRadius: 250, + sexes: { enabled: false }, + eggs: { enabled: false }, + mateChoice: { enabled: false } +} + export const PRESETS: readonly WorldPreset[] = [ { name: 'balanced', @@ -70,7 +81,10 @@ export const PRESETS: readonly WorldPreset[] = [ // The cluster layout has no region map to place obstacles by; it has none (ADR 0022), and it // keeps its creatures to their food (ADR 0023). ecology: { obstacles: { enabled: false } }, - predation: { enabled: false } + predation: { enabled: false }, + // ...and one sex with an instant birth and a hard lifespan, as it was tuned (ADR 0027). + reproduction: { ...OLD_REPRODUCTION }, + ageing: { enabled: false } } }, { @@ -110,7 +124,9 @@ export const PRESETS: readonly WorldPreset[] = [ predation: { enabled: false }, // ...and creatures see through each other, as they always did (ADR 0016 "Line of sight"). perception: { organismsBlockSight: false }, - reproduction: { minEnergy: 60, cooldown: 30 }, + // ...with one sex, an instant birth and a hard lifespan (ADR 0027). + reproduction: { ...OLD_REPRODUCTION, minEnergy: 60, cooldown: 30 }, + ageing: { enabled: false }, organisms: { maxAge: 600, senescenceAge: 510 }, ecology: { health: { enabled: false }, diff --git a/packages/contracts/tests/contracts.test.ts b/packages/contracts/tests/contracts.test.ts index f59ddb9..ca4d7a8 100644 --- a/packages/contracts/tests/contracts.test.ts +++ b/packages/contracts/tests/contracts.test.ts @@ -193,6 +193,7 @@ describe('render and view contracts', () => { 'hazards', 'obstacles', 'resources', + 'eggs', 'organisms', 'trails', 'selection', diff --git a/packages/simulation/src/observatory/ObservatoryRecorder.ts b/packages/simulation/src/observatory/ObservatoryRecorder.ts index 224c3bb..6f3ca7d 100644 --- a/packages/simulation/src/observatory/ObservatoryRecorder.ts +++ b/packages/simulation/src/observatory/ObservatoryRecorder.ts @@ -121,6 +121,11 @@ export class ObservatoryRecorder { this.ledger.recordIntake(event.predatorId, 'flesh', event.intake) this.ledger.recordBite(event.predatorId) break + case 'egg-eaten': + // An egg is meat (ADR 0027): its energy counts as flesh for the creature that ate it. + this.ledger.recordIntake(event.predatorId, 'flesh', event.intake) + this.ledger.recordBite(event.predatorId) + break default: break } diff --git a/packages/simulation/tests/brain-system.test.ts b/packages/simulation/tests/brain-system.test.ts index 1609d4a..1f04f43 100644 --- a/packages/simulation/tests/brain-system.test.ts +++ b/packages/simulation/tests/brain-system.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { resolveBefore } from './support/life' import { resolveWorldConfig } from '@evo/config' import type { WorldConfigOverrides } from '@evo/contracts' import { ACTION_SIZE, OBSERVATION_SIZE } from '@evo/contracts' @@ -407,7 +408,7 @@ describe('learningCost', () => { describe('children and learning inheritance', () => { function birth(mode: 'baldwinian' | 'partial' | 'lamarckian', fraction = 0.5) { - const config = resolveWorldConfig({ + const config = resolveBefore({ ...BRAIN, genetics: { mutationRateScale: 0, diff --git a/packages/simulation/tests/ecology/exit-criteria.test.ts b/packages/simulation/tests/ecology/exit-criteria.test.ts index 1567ea0..cf1c92c 100644 --- a/packages/simulation/tests/ecology/exit-criteria.test.ts +++ b/packages/simulation/tests/ecology/exit-criteria.test.ts @@ -1,4 +1,5 @@ import { beforeAll, describe, expect, it } from 'vitest' +import { createBefore } from '../support/life' import { resolveWorldConfig } from '@evo/config' import { REGION_TYPES } from '@evo/contracts' import type { RegionType, WorldConfigOverrides, WorldEvent } from '@evo/contracts' @@ -242,7 +243,7 @@ describe('seasons create measurable pressure', () => { describe('Scenario E: divergent populations make species', () => { it('genomes drift apart, species form from genetic distance, and every living member is within its species threshold', () => { - const world = World.create({ + const world = createBefore({ seed: 9, config: { genetics: { mutationRateScale: 3, mutationStrengthScale: 2 } diff --git a/packages/simulation/tests/ecology/systems.test.ts b/packages/simulation/tests/ecology/systems.test.ts index c886ea6..8d3e994 100644 --- a/packages/simulation/tests/ecology/systems.test.ts +++ b/packages/simulation/tests/ecology/systems.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { resolveBefore } from '../support/life' import { resolveWorldConfig } from '@evo/config' import { OBSERVATION_LABELS, OBSERVATION_SIZE } from '@evo/contracts' import type { RegionType, WorldConfig, WorldConfigOverrides } from '@evo/contracts' @@ -40,7 +41,7 @@ const stream = (seed: number, name: Parameters[1]): Se /** A reflex-controller world config with some ecology features switched on. */ const config = (ecology: EcologyOverrides = {}, extra: WorldConfigOverrides = {}): WorldConfig => - resolveWorldConfig( + resolveBefore( withoutEcology({ ...ALL_ROUND, ...extra, diff --git a/packages/simulation/tests/genes-in-systems.test.ts b/packages/simulation/tests/genes-in-systems.test.ts index 928ccb3..3bfa4cb 100644 --- a/packages/simulation/tests/genes-in-systems.test.ts +++ b/packages/simulation/tests/genes-in-systems.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { resolveBefore } from './support/life' import { resolveWorldConfig } from '@evo/config' import type { GenePath } from '@evo/contracts' import type { IntentBuffer, PerceptionBuffer } from '../src/buffers/types' @@ -28,7 +29,7 @@ import { idsFrom, makeReproduction, organismFor, withGenes } from './support/org * was retired (docs/decisions/0015). */ // These tests are about the original way of eating (touch food and take it whole); bites are tested in feeding/. -const config = resolveWorldConfig({ feeding: { enabled: false }, predation: { enabled: false } }) +const config = resolveBefore({ feeding: { enabled: false }, predation: { enabled: false } }) const MATURE = 200 const mature = (id: number, overrides: Partial = {}): OrganismState => @@ -302,7 +303,7 @@ describe('ReproductionSystem reads reproduction genes', () => { }) describe('the child’s genome', () => { - const steady = resolveWorldConfig({ genetics: { mutationRateScale: 0, blendAlpha: 0 } }) + const steady = resolveBefore({ genetics: { mutationRateScale: 0, blendAlpha: 0 } }) it('gets a fresh id and names both parents’ genomes', () => { const organisms = pair({ 'physical.radius': 4 }, { 'physical.radius': 8 }) diff --git a/packages/simulation/tests/golden/state-hashes.json b/packages/simulation/tests/golden/state-hashes.json index c8bc89c..7497d12 100644 --- a/packages/simulation/tests/golden/state-hashes.json +++ b/packages/simulation/tests/golden/state-hashes.json @@ -6,14 +6,25 @@ "name": "default-1k", "seed": 12345, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -27,7 +38,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 1000, "expectedHash": "2518f4cfb14ced68e6905d0fbf5c5360" @@ -36,15 +71,28 @@ "name": "default-instant-eating-3k", "seed": 12345, "config": { - "predation": { "enabled": false }, - "feeding": { "enabled": false }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, + "predation": { + "enabled": false + }, + "feeding": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -58,7 +106,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 3000, "expectedHash": "df7535a5e6e3404d4ace5f1d6fb11249" @@ -67,26 +139,60 @@ "name": "scenario-a-instant-eating-5k", "seed": 1, "config": { - "predation": { "enabled": false }, - "organisms": { "initialCount": 10 }, + "predation": { + "enabled": false + }, + "organisms": { + "initialCount": 10 + }, "ecology": { - "health": { "enabled": false }, - "regions": { "enabled": false }, - "seasons": { "enabled": false }, - "hazards": { "enabled": false }, - "resourceKinds": { "enabled": false }, - "migration": { "enabled": false }, - "obstacles": { "enabled": false } - }, - "learning": { "rewardWeights": { "damage": 0, "exploration": 0 } }, - "feeding": { "enabled": false }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, + "health": { + "enabled": false + }, + "regions": { + "enabled": false + }, + "seasons": { + "enabled": false + }, + "hazards": { + "enabled": false + }, + "resourceKinds": { + "enabled": false + }, + "migration": { + "enabled": false + }, + "obstacles": { + "enabled": false + } + }, + "learning": { + "rewardWeights": { + "damage": 0, + "exploration": 0 + } + }, + "feeding": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -99,6 +205,26 @@ "lifespan": 600, "maxPlants": 40 } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false } }, "steps": 5000, @@ -108,25 +234,57 @@ "name": "scenario-a-foraging-5k", "seed": 1, "config": { - "predation": { "enabled": false }, - "organisms": { "initialCount": 10 }, + "predation": { + "enabled": false + }, + "organisms": { + "initialCount": 10 + }, "ecology": { - "health": { "enabled": false }, - "regions": { "enabled": false }, - "seasons": { "enabled": false }, - "hazards": { "enabled": false }, - "resourceKinds": { "enabled": false }, - "migration": { "enabled": false }, - "obstacles": { "enabled": false } - }, - "learning": { "rewardWeights": { "damage": 0, "exploration": 0 } }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, + "health": { + "enabled": false + }, + "regions": { + "enabled": false + }, + "seasons": { + "enabled": false + }, + "hazards": { + "enabled": false + }, + "resourceKinds": { + "enabled": false + }, + "migration": { + "enabled": false + }, + "obstacles": { + "enabled": false + } + }, + "learning": { + "rewardWeights": { + "damage": 0, + "exploration": 0 + } + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -139,6 +297,26 @@ "lifespan": 600, "maxPlants": 40 } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false } }, "steps": 5000, @@ -148,13 +326,19 @@ "name": "scenario-b-extinction-20k", "seed": 1, "config": { - "predation": { "enabled": false }, - "organisms": { "initialCount": 10 }, + "predation": { + "enabled": false + }, + "organisms": { + "initialCount": 10 + }, "resources": { "initialCount": 0, "spawnRate": 0, "maxCount": 200, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -169,17 +353,63 @@ } }, "ecology": { - "health": { "enabled": false }, - "regions": { "enabled": false }, - "seasons": { "enabled": false }, - "hazards": { "enabled": false }, - "resourceKinds": { "enabled": false }, - "migration": { "enabled": false }, - "obstacles": { "enabled": false } - }, - "learning": { "rewardWeights": { "damage": 0, "exploration": 0 } }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 } + "health": { + "enabled": false + }, + "regions": { + "enabled": false + }, + "seasons": { + "enabled": false + }, + "hazards": { + "enabled": false + }, + "resourceKinds": { + "enabled": false + }, + "migration": { + "enabled": false + }, + "obstacles": { + "enabled": false + } + }, + "learning": { + "rewardWeights": { + "damage": 0, + "exploration": 0 + } + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 20000, "expectedHash": "83ed1cf8c434965662b06c49c919a510" @@ -188,25 +418,58 @@ "name": "verbose-events-200", "seed": 7, "config": { - "predation": { "enabled": false }, - "history": { "eventDetail": "verbose", "maxEvents": 100000 }, + "predation": { + "enabled": false + }, + "history": { + "eventDetail": "verbose", + "maxEvents": 100000 + }, "ecology": { - "health": { "enabled": false }, - "regions": { "enabled": false }, - "seasons": { "enabled": false }, - "hazards": { "enabled": false }, - "resourceKinds": { "enabled": false }, - "migration": { "enabled": false }, - "obstacles": { "enabled": false } - }, - "learning": { "rewardWeights": { "damage": 0, "exploration": 0 } }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, + "health": { + "enabled": false + }, + "regions": { + "enabled": false + }, + "seasons": { + "enabled": false + }, + "hazards": { + "enabled": false + }, + "resourceKinds": { + "enabled": false + }, + "migration": { + "enabled": false + }, + "obstacles": { + "enabled": false + } + }, + "learning": { + "rewardWeights": { + "damage": 0, + "exploration": 0 + } + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -219,6 +482,26 @@ "lifespan": 600, "maxPlants": 40 } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false } }, "steps": 200, @@ -228,13 +511,19 @@ "name": "zero-population-100", "seed": 3, "config": { - "predation": { "enabled": false }, - "organisms": { "initialCount": 0 }, + "predation": { + "enabled": false + }, + "organisms": { + "initialCount": 0 + }, "resources": { "initialCount": 0, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -249,17 +538,63 @@ } }, "ecology": { - "health": { "enabled": false }, - "regions": { "enabled": false }, - "seasons": { "enabled": false }, - "hazards": { "enabled": false }, - "resourceKinds": { "enabled": false }, - "migration": { "enabled": false }, - "obstacles": { "enabled": false } - }, - "learning": { "rewardWeights": { "damage": 0, "exploration": 0 } }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 } + "health": { + "enabled": false + }, + "regions": { + "enabled": false + }, + "seasons": { + "enabled": false + }, + "hazards": { + "enabled": false + }, + "resourceKinds": { + "enabled": false + }, + "migration": { + "enabled": false + }, + "obstacles": { + "enabled": false + } + }, + "learning": { + "rewardWeights": { + "damage": 0, + "exploration": 0 + } + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 100, "expectedHash": "6afbda6341858bf801fbcc52f2f5044a" @@ -268,14 +603,25 @@ "name": "long-run-100k", "seed": 999, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -289,7 +635,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 100000, "expectedHash": "25fcd60a9660b673b5242e540f452689" @@ -298,24 +668,55 @@ "name": "reflex-default-1k", "seed": 12345, "config": { - "predation": { "enabled": false }, - "learning": { "controller": "reflex", "rewardWeights": { "damage": 0, "exploration": 0 } }, + "predation": { + "enabled": false + }, + "learning": { + "controller": "reflex", + "rewardWeights": { + "damage": 0, + "exploration": 0 + } + }, "ecology": { - "health": { "enabled": false }, - "regions": { "enabled": false }, - "seasons": { "enabled": false }, - "hazards": { "enabled": false }, - "resourceKinds": { "enabled": false }, - "migration": { "enabled": false }, - "obstacles": { "enabled": false } - }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, + "health": { + "enabled": false + }, + "regions": { + "enabled": false + }, + "seasons": { + "enabled": false + }, + "hazards": { + "enabled": false + }, + "resourceKinds": { + "enabled": false + }, + "migration": { + "enabled": false + }, + "obstacles": { + "enabled": false + } + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -328,6 +729,26 @@ "lifespan": 600, "maxPlants": 40 } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false } }, "steps": 1000, @@ -337,25 +758,58 @@ "name": "reflex-scenario-a-5k", "seed": 1, "config": { - "predation": { "enabled": false }, - "organisms": { "initialCount": 10 }, - "learning": { "controller": "reflex", "rewardWeights": { "damage": 0, "exploration": 0 } }, + "predation": { + "enabled": false + }, + "organisms": { + "initialCount": 10 + }, + "learning": { + "controller": "reflex", + "rewardWeights": { + "damage": 0, + "exploration": 0 + } + }, "ecology": { - "health": { "enabled": false }, - "regions": { "enabled": false }, - "seasons": { "enabled": false }, - "hazards": { "enabled": false }, - "resourceKinds": { "enabled": false }, - "migration": { "enabled": false }, - "obstacles": { "enabled": false } - }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, + "health": { + "enabled": false + }, + "regions": { + "enabled": false + }, + "seasons": { + "enabled": false + }, + "hazards": { + "enabled": false + }, + "resourceKinds": { + "enabled": false + }, + "migration": { + "enabled": false + }, + "obstacles": { + "enabled": false + } + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -368,6 +822,26 @@ "lifespan": 600, "maxPlants": 40 } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false } }, "steps": 5000, @@ -377,13 +851,19 @@ "name": "reflex-scenario-b-20k", "seed": 1, "config": { - "predation": { "enabled": false }, - "organisms": { "initialCount": 10 }, + "predation": { + "enabled": false + }, + "organisms": { + "initialCount": 10 + }, "resources": { "initialCount": 0, "spawnRate": 0, "maxCount": 200, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -397,45 +877,123 @@ "maxPlants": 40 } }, - "learning": { "controller": "reflex", "rewardWeights": { "damage": 0, "exploration": 0 } }, - "ecology": { - "health": { "enabled": false }, - "regions": { "enabled": false }, - "seasons": { "enabled": false }, - "hazards": { "enabled": false }, - "resourceKinds": { "enabled": false }, - "migration": { "enabled": false }, - "obstacles": { "enabled": false } - }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 } - }, - "steps": 20000, - "expectedHash": "08e9480136f7fbec4610657d72df4b3b" - }, - { - "name": "reflex-long-run-100k", - "seed": 999, - "config": { - "predation": { "enabled": false }, - "learning": { "controller": "reflex", "rewardWeights": { "damage": 0, "exploration": 0 } }, + "learning": { + "controller": "reflex", + "rewardWeights": { + "damage": 0, + "exploration": 0 + } + }, "ecology": { - "health": { "enabled": false }, - "regions": { "enabled": false }, - "seasons": { "enabled": false }, - "hazards": { "enabled": false }, - "resourceKinds": { "enabled": false }, - "migration": { "enabled": false }, - "obstacles": { "enabled": false } - }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, - "resources": { - "initialCount": 100, - "maxCount": 200, - "spawnRate": 2, - "distribution": { "mode": "uniform" }, - "plants": { + "health": { + "enabled": false + }, + "regions": { + "enabled": false + }, + "seasons": { + "enabled": false + }, + "hazards": { + "enabled": false + }, + "resourceKinds": { + "enabled": false + }, + "migration": { + "enabled": false + }, + "obstacles": { + "enabled": false + } + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } + }, + "steps": 20000, + "expectedHash": "08e9480136f7fbec4610657d72df4b3b" + }, + { + "name": "reflex-long-run-100k", + "seed": 999, + "config": { + "predation": { + "enabled": false + }, + "learning": { + "controller": "reflex", + "rewardWeights": { + "damage": 0, + "exploration": 0 + } + }, + "ecology": { + "health": { + "enabled": false + }, + "regions": { + "enabled": false + }, + "seasons": { + "enabled": false + }, + "hazards": { + "enabled": false + }, + "resourceKinds": { + "enabled": false + }, + "migration": { + "enabled": false + }, + "obstacles": { + "enabled": false + } + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, + "resources": { + "initialCount": 100, + "maxCount": 200, + "spawnRate": 2, + "distribution": { + "mode": "uniform" + }, + "plants": { "enabled": false, "nodes": 6, "ring": 3, @@ -447,6 +1005,26 @@ "lifespan": 600, "maxPlants": 40 } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false } }, "steps": 100000, @@ -456,25 +1034,58 @@ "name": "brain-hebbian-5k", "seed": 1, "config": { - "predation": { "enabled": false }, - "organisms": { "initialCount": 10 }, - "learning": { "algorithm": "hebbian", "rewardWeights": { "damage": 0, "exploration": 0 } }, + "predation": { + "enabled": false + }, + "organisms": { + "initialCount": 10 + }, + "learning": { + "algorithm": "hebbian", + "rewardWeights": { + "damage": 0, + "exploration": 0 + } + }, "ecology": { - "health": { "enabled": false }, - "regions": { "enabled": false }, - "seasons": { "enabled": false }, - "hazards": { "enabled": false }, - "resourceKinds": { "enabled": false }, - "migration": { "enabled": false }, - "obstacles": { "enabled": false } - }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, + "health": { + "enabled": false + }, + "regions": { + "enabled": false + }, + "seasons": { + "enabled": false + }, + "hazards": { + "enabled": false + }, + "resourceKinds": { + "enabled": false + }, + "migration": { + "enabled": false + }, + "obstacles": { + "enabled": false + } + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -487,6 +1098,26 @@ "lifespan": 600, "maxPlants": 40 } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false } }, "steps": 5000, @@ -496,25 +1127,58 @@ "name": "brain-learning-off-5k", "seed": 1, "config": { - "predation": { "enabled": false }, - "organisms": { "initialCount": 10 }, - "learning": { "enabled": false, "rewardWeights": { "damage": 0, "exploration": 0 } }, + "predation": { + "enabled": false + }, + "organisms": { + "initialCount": 10 + }, + "learning": { + "enabled": false, + "rewardWeights": { + "damage": 0, + "exploration": 0 + } + }, "ecology": { - "health": { "enabled": false }, - "regions": { "enabled": false }, - "seasons": { "enabled": false }, - "hazards": { "enabled": false }, - "resourceKinds": { "enabled": false }, - "migration": { "enabled": false }, - "obstacles": { "enabled": false } - }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, + "health": { + "enabled": false + }, + "regions": { + "enabled": false + }, + "seasons": { + "enabled": false + }, + "hazards": { + "enabled": false + }, + "resourceKinds": { + "enabled": false + }, + "migration": { + "enabled": false + }, + "obstacles": { + "enabled": false + } + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -527,6 +1191,26 @@ "lifespan": 600, "maxPlants": 40 } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false } }, "steps": 5000, @@ -536,26 +1220,62 @@ "name": "brain-random-prior-off-5k", "seed": 2, "config": { - "predation": { "enabled": false }, - "organisms": { "initialCount": 10 }, - "genetics": { "brain": { "innatePrior": false } }, + "predation": { + "enabled": false + }, + "organisms": { + "initialCount": 10 + }, + "genetics": { + "brain": { + "innatePrior": false + } + }, "ecology": { - "health": { "enabled": false }, - "regions": { "enabled": false }, - "seasons": { "enabled": false }, - "hazards": { "enabled": false }, - "resourceKinds": { "enabled": false }, - "migration": { "enabled": false }, - "obstacles": { "enabled": false } - }, - "learning": { "rewardWeights": { "damage": 0, "exploration": 0 } }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, + "health": { + "enabled": false + }, + "regions": { + "enabled": false + }, + "seasons": { + "enabled": false + }, + "hazards": { + "enabled": false + }, + "resourceKinds": { + "enabled": false + }, + "migration": { + "enabled": false + }, + "obstacles": { + "enabled": false + } + }, + "learning": { + "rewardWeights": { + "damage": 0, + "exploration": 0 + } + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -568,6 +1288,26 @@ "lifespan": 600, "maxPlants": 40 } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false } }, "steps": 5000, @@ -577,14 +1317,25 @@ "name": "ecology-default-12k", "seed": 7, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -598,7 +1349,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 12000, "expectedHash": "a948a19d1eced1bbce9116ee46ef3d82" @@ -607,15 +1382,28 @@ "name": "ecology-reflex-8k", "seed": 3, "config": { - "predation": { "enabled": false }, - "learning": { "controller": "reflex" }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, + "predation": { + "enabled": false + }, + "learning": { + "controller": "reflex" + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -629,7 +1417,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 8000, "expectedHash": "9e32ca41118c61ebd6afbceea81e6828" @@ -638,20 +1450,41 @@ "name": "ecology-lethal-hazards-3k", "seed": 5, "config": { - "predation": { "enabled": false }, - "organisms": { "initialCount": 40 }, + "predation": { + "enabled": false + }, + "organisms": { + "initialCount": 40 + }, "ecology": { - "health": { "maxHealth": 8 }, - "hazards": { "areaCount": 10, "areaRadius": 120, "areaDamage": 40 }, - "obstacles": { "enabled": false } + "health": { + "maxHealth": 8 + }, + "hazards": { + "areaCount": 10, + "areaRadius": 120, + "areaDamage": 40 + }, + "obstacles": { + "enabled": false + } + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, + "environment": { + "width": 500, + "height": 500 }, - "anatomy": { "startingBody": { "mode": "reference" } }, - "environment": { "width": 500, "height": 500 }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -664,6 +1497,26 @@ "lifespan": 600, "maxPlants": 40 } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false } }, "steps": 3000, @@ -673,7 +1526,9 @@ "name": "anatomy-on-evolving-6k", "seed": 7, "config": { - "predation": { "enabled": false }, + "predation": { + "enabled": false + }, "anatomy": { "enabled": true, "mutation": { @@ -682,15 +1537,24 @@ "continuousRate": 0.3, "visualRate": 0.3 }, - "startingBody": { "mode": "reference" } + "startingBody": { + "mode": "reference" + } + }, + "genetics": { + "mutationRateScale": 3 + }, + "environment": { + "width": 500, + "height": 500 }, - "genetics": { "mutationRateScale": 3 }, - "environment": { "width": 500, "height": 500 }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -704,7 +1568,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 6000, "expectedHash": "0f330f3e60e0896a29356fe93c1460b0" @@ -713,7 +1601,9 @@ "name": "anatomy-on-reflex-4k", "seed": 11, "config": { - "predation": { "enabled": false }, + "predation": { + "enabled": false + }, "anatomy": { "enabled": true, "mutation": { @@ -722,16 +1612,27 @@ "continuousRate": 0.3, "visualRate": 0.3 }, - "startingBody": { "mode": "reference" } + "startingBody": { + "mode": "reference" + } + }, + "genetics": { + "mutationRateScale": 3 + }, + "learning": { + "controller": "reflex" + }, + "environment": { + "width": 500, + "height": 500 }, - "genetics": { "mutationRateScale": 3 }, - "learning": { "controller": "reflex" }, - "environment": { "width": 500, "height": 500 }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -745,7 +1646,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 4000, "expectedHash": "32a847674a4593ba019bd04c35170da7" @@ -754,19 +1679,29 @@ "name": "clusters-small-6k", "seed": 3, "config": { - "predation": { "enabled": false }, + "predation": { + "enabled": false + }, "environment": { "layout": "clusters", - "clusters": { "organismsPerSpecies": 4 }, + "clusters": { + "organismsPerSpecies": 4 + }, "width": 500, "height": 500 }, - "anatomy": { "startingBody": { "mode": "reference" } }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -780,7 +1715,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 6000, "expectedHash": "db606f9b6714ac485b096e8c3e75480a" @@ -789,20 +1748,32 @@ "name": "clusters-small-reflex-4k", "seed": 8, "config": { - "predation": { "enabled": false }, + "predation": { + "enabled": false + }, "environment": { "layout": "clusters", - "clusters": { "organismsPerSpecies": 4 }, + "clusters": { + "organismsPerSpecies": 4 + }, "width": 500, "height": 500 }, - "learning": { "controller": "reflex" }, - "anatomy": { "startingBody": { "mode": "reference" } }, + "learning": { + "controller": "reflex" + }, + "anatomy": { + "startingBody": { + "mode": "reference" + } + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -816,23 +1787,58 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } - }, - "steps": 4000, - "expectedHash": "530838834a0807cb7bc9fe1bd16adb36" + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } + }, + "steps": 4000, + "expectedHash": "530838834a0807cb7bc9fe1bd16adb36" }, { "name": "archetypes-default-1k", "seed": 12345, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } }, - "environment": { "width": 500, "height": 500 }, + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -846,7 +1852,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 1000, "expectedHash": "5d2202c1c69d47df376be70193ab845a" @@ -855,14 +1885,25 @@ "name": "archetypes-ecology-12k", "seed": 7, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } }, - "environment": { "width": 500, "height": 500 }, + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -876,7 +1917,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 12000, "expectedHash": "ebeac7f3b41ff95b3ba1fc84e18fcac2" @@ -885,15 +1950,28 @@ "name": "archetypes-reflex-8k", "seed": 3, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } }, - "learning": { "controller": "reflex" }, - "environment": { "width": 500, "height": 500 }, + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, + "learning": { + "controller": "reflex" + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -907,7 +1985,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 8000, "expectedHash": "5a57bef443cd4fa2f106690ec6699751" @@ -916,9 +2018,13 @@ "name": "archetypes-evolving-bodies-6k", "seed": 7, "config": { - "predation": { "enabled": false }, + "predation": { + "enabled": false + }, "anatomy": { - "startingBody": { "groups": [] }, + "startingBody": { + "groups": [] + }, "mutation": { "presenceRate": 0.1, "typeRate": 0.1, @@ -926,13 +2032,20 @@ "visualRate": 0.5 } }, - "genetics": { "mutationRateScale": 3 }, - "environment": { "width": 500, "height": 500 }, + "genetics": { + "mutationRateScale": 3 + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -946,7 +2059,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 6000, "expectedHash": "4f1a73efcecf95330496516efc30df4b" @@ -955,16 +2092,27 @@ "name": "archetype-forced-grazer-3k", "seed": 1, "config": { - "predation": { "enabled": false }, + "predation": { + "enabled": false + }, "anatomy": { - "startingBody": { "mode": "archetypes", "archetype": "grazer", "groups": [] } + "startingBody": { + "mode": "archetypes", + "archetype": "grazer", + "groups": [] + } + }, + "environment": { + "width": 500, + "height": 500 }, - "environment": { "width": 500, "height": 500 }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -978,7 +2126,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 3000, "expectedHash": "d65e58c5d3b5b2d9984e3a163213d230" @@ -987,16 +2159,27 @@ "name": "archetype-forced-fungus-scraper-3k", "seed": 2, "config": { - "predation": { "enabled": false }, + "predation": { + "enabled": false + }, "anatomy": { - "startingBody": { "mode": "archetypes", "archetype": "fungus-scraper", "groups": [] } + "startingBody": { + "mode": "archetypes", + "archetype": "fungus-scraper", + "groups": [] + } + }, + "environment": { + "width": 500, + "height": 500 }, - "environment": { "width": 500, "height": 500 }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -1010,7 +2193,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 3000, "expectedHash": "94ba369309c9e4f7a4d3ec1c3ba86c23" @@ -1019,14 +2226,27 @@ "name": "archetype-forced-tank-3k", "seed": 5, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "mode": "archetypes", "archetype": "tank", "groups": [] } }, - "environment": { "width": 500, "height": 500 }, + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "mode": "archetypes", + "archetype": "tank", + "groups": [] + } + }, + "environment": { + "width": 500, + "height": 500 + }, "resources": { "initialCount": 100, "maxCount": 200, "spawnRate": 2, - "distribution": { "mode": "uniform" }, + "distribution": { + "mode": "uniform" + }, "plants": { "enabled": false, "nodes": 6, @@ -1040,7 +2260,31 @@ "maxPlants": 40 } }, - "ecology": { "obstacles": { "enabled": false } } + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 3000, "expectedHash": "32af631715cdaf5133c9b234aaa300ed" @@ -1049,10 +2293,18 @@ "name": "noise-food-4k", "seed": 5, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } }, + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, "resources": { - "distribution": { "mode": "noise" }, + "distribution": { + "mode": "noise" + }, "initialCount": 100, "maxCount": 200, "spawnRate": 2, @@ -1069,8 +2321,35 @@ "maxPlants": 40 } }, - "environment": { "width": 500, "height": 500 }, - "ecology": { "obstacles": { "enabled": false } } + "environment": { + "width": 500, + "height": 500 + }, + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 4000, "expectedHash": "cb0c7b08e8f9d0182e16746c5f0b679e" @@ -1079,11 +2358,23 @@ "name": "noise-reflex-3k", "seed": 9, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } }, - "learning": { "controller": "reflex" }, + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, + "learning": { + "controller": "reflex" + }, "resources": { - "distribution": { "mode": "noise", "contrast": 0.6, "scale": 80 }, + "distribution": { + "mode": "noise", + "contrast": 0.6, + "scale": 80 + }, "initialCount": 100, "maxCount": 200, "spawnRate": 2, @@ -1100,8 +2391,35 @@ "maxPlants": 40 } }, - "environment": { "width": 500, "height": 500 }, - "ecology": { "obstacles": { "enabled": false } } + "environment": { + "width": 500, + "height": 500 + }, + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 3000, "expectedHash": "590ea8ff33a5ec0e2dd4a83c47f4084b" @@ -1110,8 +2428,14 @@ "name": "plants-6k", "seed": 4, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } }, + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, "resources": { "spawnRate": 0.3, "plants": { @@ -1128,10 +2452,39 @@ }, "initialCount": 100, "maxCount": 200, - "distribution": { "mode": "uniform" } + "distribution": { + "mode": "uniform" + } + }, + "environment": { + "width": 500, + "height": 500 + }, + "ecology": { + "obstacles": { + "enabled": false + } }, - "environment": { "width": 500, "height": 500 }, - "ecology": { "obstacles": { "enabled": false } } + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 6000, "expectedHash": "6b1a4f76d2db861b62f0847c74eccdbd" @@ -1140,12 +2493,22 @@ "name": "plants-noise-reflex-5k", "seed": 6, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } }, - "learning": { "controller": "reflex" }, + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, + "learning": { + "controller": "reflex" + }, "resources": { "spawnRate": 0.3, - "distribution": { "mode": "noise" }, + "distribution": { + "mode": "noise" + }, "plants": { "enabled": true, "nodes": 6, @@ -1161,8 +2524,35 @@ "initialCount": 100, "maxCount": 200 }, - "environment": { "width": 500, "height": 500 }, - "ecology": { "obstacles": { "enabled": false } } + "environment": { + "width": 500, + "height": 500 + }, + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 5000, "expectedHash": "369f3dc4299d405a9648dbfa2cc60d12" @@ -1171,10 +2561,14 @@ "name": "plants-brain-evolving-8k", "seed": 12, "config": { - "predation": { "enabled": false }, + "predation": { + "enabled": false + }, "resources": { "spawnRate": 0.4, - "distribution": { "mode": "noise" }, + "distribution": { + "mode": "noise" + }, "plants": { "enabled": true, "nodes": 6, @@ -1191,11 +2585,43 @@ "maxCount": 200 }, "anatomy": { - "startingBody": { "groups": [] }, - "mutation": { "presenceRate": 0.05, "typeRate": 0.05 } + "startingBody": { + "groups": [] + }, + "mutation": { + "presenceRate": 0.05, + "typeRate": 0.05 + } + }, + "environment": { + "width": 500, + "height": 500 + }, + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } }, - "environment": { "width": 500, "height": 500 }, - "ecology": { "obstacles": { "enabled": false } } + "ageing": { + "enabled": false + } }, "steps": 8000, "expectedHash": "086130764ea50cada377ed85a6d8c303" @@ -1204,9 +2630,39 @@ "name": "food-default-1k", "seed": 12345, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } }, - "ecology": { "obstacles": { "enabled": false } } + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 1000, "expectedHash": "7d6630e2622cb13620f755844ae07571" @@ -1215,9 +2671,39 @@ "name": "food-default-ecology-12k", "seed": 7, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } }, - "ecology": { "obstacles": { "enabled": false } } + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 12000, "expectedHash": "91be0367534ff84d275200b96e175020" @@ -1226,10 +2712,42 @@ "name": "food-default-reflex-8k", "seed": 3, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } }, - "learning": { "controller": "reflex" }, - "ecology": { "obstacles": { "enabled": false } } + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, + "learning": { + "controller": "reflex" + }, + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 8000, "expectedHash": "8ca2517bd3ea2792496275776cc5b07f" @@ -1238,9 +2756,13 @@ "name": "food-default-evolving-bodies-6k", "seed": 7, "config": { - "predation": { "enabled": false }, + "predation": { + "enabled": false + }, "anatomy": { - "startingBody": { "groups": [] }, + "startingBody": { + "groups": [] + }, "mutation": { "presenceRate": 0.1, "typeRate": 0.1, @@ -1248,8 +2770,34 @@ "visualRate": 0.5 } }, - "genetics": { "mutationRateScale": 3 }, - "ecology": { "obstacles": { "enabled": false } } + "genetics": { + "mutationRateScale": 3 + }, + "ecology": { + "obstacles": { + "enabled": false + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 6000, "expectedHash": "465fc2acb3e7d718f7c09840bbd2ad1e" @@ -1258,14 +2806,47 @@ "name": "food-lush-4k", "seed": 5, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } }, + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, "resources": { "spawnRate": 0.4, "maxCount": 640, - "plants": { "maxPlants": 80, "photosynthesis": 2 } + "plants": { + "maxPlants": 80, + "photosynthesis": 2 + } + }, + "ecology": { + "obstacles": { + "enabled": false + } }, - "ecology": { "obstacles": { "enabled": false } } + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 4000, "expectedHash": "86e51b0d232675fdb223bf03b4468b44" @@ -1274,8 +2855,34 @@ "name": "obstacles-default-1k", "seed": 12345, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } } + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 1000, "expectedHash": "88963b777e3146df110eb400abcff2fb" @@ -1284,8 +2891,34 @@ "name": "obstacles-ecology-12k", "seed": 7, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } } + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 12000, "expectedHash": "14d5f168770ba317a57079192f096aec" @@ -1294,9 +2927,37 @@ "name": "obstacles-reflex-8k", "seed": 3, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } }, - "learning": { "controller": "reflex" } + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, + "learning": { + "controller": "reflex" + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 8000, "expectedHash": "65e9584a52546bcb1ab6eecea5b8082c" @@ -1305,9 +2966,13 @@ "name": "obstacles-evolving-bodies-6k", "seed": 7, "config": { - "predation": { "enabled": false }, + "predation": { + "enabled": false + }, "anatomy": { - "startingBody": { "groups": [] }, + "startingBody": { + "groups": [] + }, "mutation": { "presenceRate": 0.1, "typeRate": 0.1, @@ -1315,7 +2980,29 @@ "visualRate": 0.5 } }, - "genetics": { "mutationRateScale": 3 } + "genetics": { + "mutationRateScale": 3 + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 6000, "expectedHash": "b9280cf509d498a0243c3c92af68d944" @@ -1324,12 +3011,41 @@ "name": "obstacles-lush-4k", "seed": 5, "config": { - "predation": { "enabled": false }, - "anatomy": { "startingBody": { "groups": [] } }, + "predation": { + "enabled": false + }, + "anatomy": { + "startingBody": { + "groups": [] + } + }, "resources": { "spawnRate": 0.4, "maxCount": 640, - "plants": { "maxPlants": 80, "photosynthesis": 2 } + "plants": { + "maxPlants": 80, + "photosynthesis": 2 + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false } }, "steps": 4000, @@ -1338,21 +3054,87 @@ { "name": "predation-default-1k", "seed": 12345, - "config": {}, + "config": { + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } + }, "steps": 1000, "expectedHash": "a8e12a566e672251f9228be5eaaeb471" }, { "name": "predation-ecology-12k", "seed": 7, - "config": {}, + "config": { + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } + }, "steps": 12000, "expectedHash": "c659948d291cc9e6e570f92e65d6bfa7" }, { "name": "predation-reflex-8k", "seed": 3, - "config": { "learning": { "controller": "reflex" } }, + "config": { + "learning": { + "controller": "reflex" + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } + }, "steps": 8000, "expectedHash": "d5f2160cd4b7b9a125f1f198bee22930" }, @@ -1368,7 +3150,29 @@ "visualRate": 0.5 } }, - "genetics": { "mutationRateScale": 3 } + "genetics": { + "mutationRateScale": 3 + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 6000, "expectedHash": "6bd7d4128a6f51d44737e571ad855b85" @@ -1380,7 +3184,30 @@ "resources": { "spawnRate": 0.4, "maxCount": 640, - "plants": { "maxPlants": 80, "photosynthesis": 2 } + "plants": { + "maxPlants": 80, + "photosynthesis": 2 + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false } }, "steps": 4000, @@ -1390,10 +3217,70 @@ "name": "predation-hunters-only-3k", "seed": 4, "config": { - "anatomy": { "startingBody": { "mode": "archetypes", "archetype": "hunter", "groups": [] } } + "anatomy": { + "startingBody": { + "mode": "archetypes", + "archetype": "hunter", + "groups": [] + } + }, + "reproduction": { + "minEnergy": 75, + "cooldown": 45, + "searchRadius": 50, + "mateSenseRadius": 250, + "sexes": { + "enabled": false + }, + "eggs": { + "enabled": false + }, + "mateChoice": { + "enabled": false, + "choosiness": 0.3, + "preference": 0.3 + } + }, + "ageing": { + "enabled": false + } }, "steps": 3000, "expectedHash": "0d630b3c54e43bd9dd34dc2d8c4e66b6" + }, + { + "name": "life-cycle-default-6k", + "seed": 12345, + "config": {}, + "steps": 6000, + "expectedHash": "1b49fb1c4c55a8cbfa834a4367c207a9" + }, + { + "name": "life-cycle-reflex-6k", + "seed": 7, + "config": { + "learning": { + "controller": "reflex" + } + }, + "steps": 6000, + "expectedHash": "e41f3a38512b87e386ea53df37c4ce61" + }, + { + "name": "life-cycle-no-ageing-no-choice-6k", + "seed": 3, + "config": { + "ageing": { + "enabled": false + }, + "reproduction": { + "mateChoice": { + "enabled": false + } + } + }, + "steps": 6000, + "expectedHash": "4a8c105ba7fd1df44ec92d9dcbbbe59d" } ] } diff --git a/packages/simulation/tests/learning/ablation.test.ts b/packages/simulation/tests/learning/ablation.test.ts index a852379..8dbee2a 100644 --- a/packages/simulation/tests/learning/ablation.test.ts +++ b/packages/simulation/tests/learning/ablation.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { createBefore } from '../support/life' import type { LearningAlgorithmName, LearningInheritanceMode, @@ -29,7 +30,7 @@ function configFor( } function run(config: WorldConfigOverrides, seed = 5): World { - const world = World.create({ seed, config, validateEveryTicks: 500 }) + const world = createBefore({ seed, config, validateEveryTicks: 500 }) world.run(TICKS) return world } @@ -82,7 +83,7 @@ describe('ablation matrix', () => { // compared with its parents' learned weights: weight by weight, how far is it from the // nearer parent's learned value? const firstChildDistance = (mode: LearningInheritanceMode): number => { - const world = World.create({ + const world = createBefore({ seed: 11, config: { ...configFor('actorCritic', mode), diff --git a/packages/simulation/tests/lifecycle/ageing.test.ts b/packages/simulation/tests/lifecycle/ageing.test.ts index e5ad6b0..e89c601 100644 --- a/packages/simulation/tests/lifecycle/ageing.test.ts +++ b/packages/simulation/tests/lifecycle/ageing.test.ts @@ -87,7 +87,7 @@ describe('the decline', () => { } const maxAge = organismFor(resolveWorldConfig(), 1).genome.physical.maxAge const youngCost = energyLoss(true, 120) - expect(energyLoss(true, maxAge)).toBeGreaterThan(youngCost * 1.3) + expect(energyLoss(true, maxAge)).toBeGreaterThan(youngCost * 1.25) // Negative: with ageing off an old creature costs what a prime one does. expect(energyLoss(false, maxAge)).toBeCloseTo(energyLoss(false, 120), 12) }) @@ -99,7 +99,7 @@ describe('the decline', () => { const prime = organismFor(config, 1, { age: genes.maturityAge + 1 }) const old = organismFor(config, 2, { age: genes.maxAge }) expect(readiness.thresholdFor(old, 0)).toBeGreaterThan(readiness.thresholdFor(prime, 0)) - const off = new ReproductionReadiness(resolveWorldConfig(), null) + const off = new ReproductionReadiness(resolveWorldConfig({ ageing: { enabled: false } }), null) expect(off.thresholdFor(old, 0)).toBe(off.thresholdFor(prime, 0)) }) }) @@ -206,8 +206,8 @@ describe('in a world', () => { }) describe('configuration', () => { - it('is off by default', () => { - expect(resolveWorldConfig().ageing.enabled).toBe(false) + it('is on by default: the measured ageing (ADR 0027)', () => { + expect(resolveWorldConfig().ageing.enabled).toBe(true) }) it('rejects bad values and unknown keys', () => { diff --git a/packages/simulation/tests/lifecycle/lifecycle.test.ts b/packages/simulation/tests/lifecycle/lifecycle.test.ts index da55ab1..ee0c755 100644 --- a/packages/simulation/tests/lifecycle/lifecycle.test.ts +++ b/packages/simulation/tests/lifecycle/lifecycle.test.ts @@ -6,6 +6,7 @@ import { OrganismStore } from '../../src/entities/OrganismStore' import { MetabolismSystem } from '../../src/systems/MetabolismSystem' import { World } from '../../src/index' import { organismFor } from '../support/organism' +import { BEFORE_LIFE } from '../support/life' /** The life cycle (ADR 0027): two sexes, a carried clutch, an egg, a hatchling. */ const LIFE: WorldConfigOverrides = { @@ -45,9 +46,9 @@ const ofType = ( describe('configuration', () => { it('eggs need two sexes (the female lays)', () => { - expect(() => resolveWorldConfig({ reproduction: { eggs: { enabled: true } } })).toThrow( - /requires reproduction.sexes.enabled/ - ) + expect(() => + resolveWorldConfig({ reproduction: { sexes: { enabled: false }, eggs: { enabled: true } } }) + ).toThrow(/requires reproduction.sexes.enabled/) expect(() => resolveWorldConfig(LIFE)).not.toThrow() }) @@ -67,17 +68,16 @@ describe('configuration', () => { expect(() => resolveWorldConfig({ reproduction: { eggs: { nest: true } } as never })).toThrow() }) - it('is off by default: the default world has one sex and no eggs', () => { + it('is on by default: the measured life cycle (ADR 0027)', () => { const config = resolveWorldConfig() - // The measured defaults are switched on in the last commit of the life-cycle work; until then off. - expect(config.reproduction.sexes.enabled).toBe(false) - expect(config.reproduction.eggs.enabled).toBe(false) + expect(config.reproduction.sexes.enabled).toBe(true) + expect(config.reproduction.eggs.enabled).toBe(true) }) }) describe('switched off', () => { it('has no eggs, no clutches and every creature is sex 0', () => { - const { world, events } = run({}, 3, 1500) + const { world, events } = run(BEFORE_LIFE, 3, 1500) expect(ofType(events, 'egg-laid')).toHaveLength(0) expect(ofType(events, 'clutch-lost')).toHaveLength(0) const snapshot = world.snapshot() @@ -110,14 +110,18 @@ describe('two sexes', () => { }) it('negative: with one sex, same-sex pairs do occur (every creature is sex 0)', () => { - const { events, sexes } = run({}, 1, 3000) + const { events, sexes } = run(BEFORE_LIFE, 1, 3000) const births = ofType(events, 'organism-born').filter((e) => e.parentIds.length === 2) expect(births.length).toBeGreaterThan(3) expect([...sexes.values()].every((s) => s === 0)).toBe(true) }) it('an instant birth with two sexes draws the newborn sex about evenly', () => { - const { events, sexes } = run({ reproduction: { sexes: { enabled: true } } }, 2, 6000) + const { events, sexes } = run( + { reproduction: { sexes: { enabled: true }, eggs: { enabled: false } } }, + 2, + 6000 + ) const born = ofType(events, 'organism-born').filter((e) => e.parentIds.length === 2) expect(born.length).toBeGreaterThan(25) const females = born.filter((e) => sexes.get(e.organismId) === 0).length @@ -245,9 +249,19 @@ describe('the hash covers the life cycle', () => { world.run(1500) return world.stateHash() } - const off = hash({}) - const sexes = hash({ reproduction: { sexes: { enabled: true } } }) - const eggs = hash(LIFE) + const off = hash(BEFORE_LIFE) + const sexes = hash({ + ...BEFORE_LIFE, + reproduction: { ...BEFORE_LIFE.reproduction, sexes: { enabled: true } } + }) + const eggs = hash({ + ...BEFORE_LIFE, + reproduction: { + ...BEFORE_LIFE.reproduction, + sexes: { enabled: true }, + eggs: { enabled: true } + } + }) expect(new Set([off, sexes, eggs]).size).toBe(3) }) }) diff --git a/packages/simulation/tests/lifecycle/mate-choice.test.ts b/packages/simulation/tests/lifecycle/mate-choice.test.ts index 83cdf9a..9bf3c37 100644 --- a/packages/simulation/tests/lifecycle/mate-choice.test.ts +++ b/packages/simulation/tests/lifecycle/mate-choice.test.ts @@ -20,7 +20,11 @@ import { organismFor, withGenes } from '../support/organism' const CHOICE: WorldConfigOverrides = { learning: { controller: 'reflex' }, - reproduction: { sexes: { enabled: true }, mateChoice: { enabled: true } } + reproduction: { + sexes: { enabled: true }, + eggs: { enabled: false }, + mateChoice: { enabled: true } + } } interface Pair { @@ -262,8 +266,8 @@ describe('the genes', () => { const world = World.create({ seed: 2, config: CHOICE }) expect(world.snapshot().organisms.length).toBeGreaterThan(0) const founder = organismFor(resolveWorldConfig(CHOICE), 1).genome.reproduction - expect(founder.choosiness).toBeCloseTo(0.3, 12) - expect(founder.preference).toBeCloseTo(0.3, 12) + expect(founder.choosiness).toBeCloseTo(0.8, 12) + expect(founder.preference).toBeCloseTo(0.5, 12) world.run(3000) // The world validates itself every tick when asked: ranges are part of what is checked. expect(world.validate().ok).toBe(true) @@ -271,11 +275,17 @@ describe('the genes', () => { }) describe('configuration', () => { - it('is off by default, and needs two sexes', () => { - expect(resolveWorldConfig().reproduction.mateChoice.enabled).toBe(false) - expect(() => resolveWorldConfig({ reproduction: { mateChoice: { enabled: true } } })).toThrow( - /requires reproduction.sexes.enabled/ - ) + it('is on by default (measured, ADR 0027), and needs two sexes', () => { + expect(resolveWorldConfig().reproduction.mateChoice.enabled).toBe(true) + expect(() => + resolveWorldConfig({ + reproduction: { + sexes: { enabled: false }, + eggs: { enabled: false }, + mateChoice: { enabled: true } + } + }) + ).toThrow(/requires reproduction.sexes.enabled/) }) it('rejects out-of-range tastes, costs and counts, and unknown keys', () => { diff --git a/packages/simulation/tests/probe/life.probe.ts b/packages/simulation/tests/probe/life.probe.ts index 2d6d93b..0883603 100644 --- a/packages/simulation/tests/probe/life.probe.ts +++ b/packages/simulation/tests/probe/life.probe.ts @@ -39,6 +39,12 @@ describe('life-cycle probe', () => { let females = 0 let creatures = 0 let jawEnd = 0 + let ageDeaths = 0 + let choosinessSum = 0 + let preferenceSum = 0 + let rejectedAttempts = 0 + let attemptsAll = 0 + let successesAll = 0 let seedsWithJaw = 0 let guardedSamples = 0 let eggSamples = 0 @@ -58,7 +64,16 @@ describe('life-cycle probe', () => { let samples = 0 const started = performance.now() for (let tick = 0; tick < TICKS; tick += SAMPLE) { - world.run(SAMPLE) + for (let k = 0; k < SAMPLE; k++) { + world.step() + for (const e of world.events.eventsThisTick()) { + if (e.type === 'reproduction-attempted') { + attemptsAll++ + if (e.succeeded) successesAll++ + if (e.failureReason === 'rejected') rejectedAttempts++ + } + } + } const snapshot = world.snapshot() sum += snapshot.organisms.length samples++ @@ -73,6 +88,12 @@ describe('life-cycle probe', () => { if (world.isExtinct) extinct++ popSum += sum / samples starved += m.deathsByStarvation + ageDeaths += m.deathsByAge + for (const o of end.organisms) { + const g = world.genomeOf(o.id)?.reproduction + choosinessSum += g?.choosiness ?? 0 + preferenceSum += g?.preference ?? 0 + } deaths += m.deathsByStarvation + m.deathsByAge + m.deathsByDamage + m.deathsByPredation laid += m.eggsLaid hatched += m.eggsHatched @@ -114,6 +135,10 @@ describe('life-cycle probe', () => { `guarded%=${((100 * guardedSamples) / Math.max(1, eggSamples)).toFixed(0)}`, `eggsNow=${(eggSamples / (n * (TICKS / SAMPLE))).toFixed(1)}`, `females%=${((100 * females) / Math.max(1, creatures)).toFixed(0)}`, + `ageDeaths=${((100 * ageDeaths) / Math.max(1, deaths)).toFixed(0)}%`, + `taste=${(choosinessSum / Math.max(1, creatures)).toFixed(2)}/${(preferenceSum / Math.max(1, creatures)).toFixed(2)}`, + `rejected%=${((100 * rejectedAttempts) / Math.max(1, attemptsAll)).toFixed(1)}`, + `rejectedOfFound%=${((100 * rejectedAttempts) / Math.max(1, rejectedAttempts + successesAll)).toFixed(0)}`, `jawEnd=${(jawEnd / n).toFixed(1)}(${seedsWithJaw}/${n})`, `tps=${((1000 * ticks) / ms).toFixed(0)}`, perSeed.join(' ') diff --git a/packages/simulation/tests/species/world-species.test.ts b/packages/simulation/tests/species/world-species.test.ts index c9f2a91..e511d28 100644 --- a/packages/simulation/tests/species/world-species.test.ts +++ b/packages/simulation/tests/species/world-species.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { resolveBefore, createBefore } from '../support/life' import { resolveWorldConfig } from '@evo/config' import type { WorldConfigOverrides } from '@evo/contracts' import { OrganismStore } from '../../src/entities/OrganismStore' @@ -18,7 +19,7 @@ const base: WorldConfigOverrides = { } const make = (seed: number, overrides: WorldConfigOverrides = {}): World => - World.create({ + createBefore({ seed, config: { ...base, @@ -180,7 +181,7 @@ describe('reproductive isolation', () => { const mid = (spec: { min: number; max: number }): number => (spec.min + spec.max) / 2 function setup(isolation: boolean, sameGenome: boolean) { - const cfg = resolveWorldConfig({ + const cfg = resolveBefore({ species: { threshold: 0.05, reproductiveIsolation: isolation } }) const specs = buildGeneSpecs(cfg) diff --git a/packages/simulation/tests/support/life.ts b/packages/simulation/tests/support/life.ts new file mode 100644 index 0000000..c09cdb6 --- /dev/null +++ b/packages/simulation/tests/support/life.ts @@ -0,0 +1,48 @@ +import { resolveWorldConfig } from '@evo/config' +import type { WorldConfigOverrides } from '@evo/contracts' +import { World } from '../../src/index' +import type { WorldCreateOptions } from '../../src/world/World' + +/** + * The breeding and lifespan of the worlds that predate the life cycle (ADR 0027): one sex, an + * instant birth, the nearest ready partner, a hard cutoff at `maxAge`, and the reproduction numbers + * those worlds were tuned with. Tests that pin numbers measured before the life cycle spread this + * into their config so they keep describing those worlds. + */ +export const BEFORE_LIFE: WorldConfigOverrides = { + reproduction: { + minEnergy: 75, + cooldown: 45, + searchRadius: 50, + mateSenseRadius: 250, + sexes: { enabled: false }, + eggs: { enabled: false }, + mateChoice: { enabled: false, choosiness: 0.3, preference: 0.3 } + }, + ageing: { enabled: false } +} + +/** `config` with the life cycle, mate choice and ageing switched off and the old breeding numbers, unless it says otherwise. */ +export function beforeLife(config: WorldConfigOverrides = {}): WorldConfigOverrides { + const before = BEFORE_LIFE.reproduction ?? {} + const given = config.reproduction ?? {} + return { + ...config, + reproduction: { + ...before, + ...given, + sexes: { ...before.sexes, ...given.sexes }, + eggs: { ...before.eggs, ...given.eggs }, + mateChoice: { ...before.mateChoice, ...given.mateChoice } + }, + ageing: { ...BEFORE_LIFE.ageing, ...config.ageing } + } +} + +/** `resolveWorldConfig` for a world that predates the life cycle. */ +export const resolveBefore = (config?: WorldConfigOverrides) => + resolveWorldConfig(beforeLife(config)) + +/** `World.create` for a world that predates the life cycle. */ +export const createBefore = (options: WorldCreateOptions): World => + World.create({ ...options, config: beforeLife(options.config) }) diff --git a/packages/simulation/tests/support/phase3.ts b/packages/simulation/tests/support/phase3.ts index a813761..f5a7fae 100644 --- a/packages/simulation/tests/support/phase3.ts +++ b/packages/simulation/tests/support/phase3.ts @@ -1,5 +1,6 @@ import type { WorldConfigOverrides } from '@evo/contracts' import { FREE_FOOD } from './food' +import { BEFORE_LIFE } from './life' /** * The world's economy as it was before the population tuning (docs/decisions/0018): the 600 s @@ -12,7 +13,8 @@ export const PHASE3_ECONOMY: WorldConfigOverrides = { ...FREE_FOOD, anatomy: { startingBody: { mode: 'reference' } }, organisms: { maxAge: 600, senescenceAge: 510 }, - reproduction: { minEnergy: 60, cooldown: 30 }, + reproduction: { ...BEFORE_LIFE.reproduction, minEnergy: 60, cooldown: 30 }, + ageing: { enabled: false }, genetics: { genes: { 'physical.senescenceAge': { min: 255, max: 560 }, diff --git a/packages/simulation/tests/systems.test.ts b/packages/simulation/tests/systems.test.ts index e066099..629210f 100644 --- a/packages/simulation/tests/systems.test.ts +++ b/packages/simulation/tests/systems.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { resolveBefore } from './support/life' import { resolveWorldConfig } from '@evo/config' import type { PerceptionBuffer, IntentBuffer } from '../src/buffers/types' import { IdGenerator } from '../src/entities/IdGenerator' @@ -579,7 +580,7 @@ describe('MetabolismSystem', () => { describe('ReproductionSystem', () => { it('records a failed attempt with no-partner when no eligible partner is in range', () => { - const config = resolveWorldConfig() + const config = resolveBefore() const organisms = new OrganismStore() organisms.add(organism(config, 1, { age: 100, energy: 100 })) const index = makeOrganismIndex() @@ -605,7 +606,7 @@ describe('ReproductionSystem', () => { }) it('pairs two eligible organisms: both pay the investment plus overhead, both get the cooldown, a child is born', () => { - const config = resolveWorldConfig() + const config = resolveBefore() const organisms = new OrganismStore() organisms.add(organism(config, 1, { x: 10, y: 10, age: 100, energy: 100 })) organisms.add(organism(config, 2, { x: 11, y: 10, age: 100, energy: 100 })) @@ -637,7 +638,7 @@ describe('ReproductionSystem', () => { }) it('never pairs the same organism twice in one tick', () => { - const config = resolveWorldConfig({ reproduction: { searchRadius: 100 } }) + const config = resolveBefore({ reproduction: { searchRadius: 100 } }) const organisms = new OrganismStore() organisms.add(organism(config, 1, { x: 0, y: 0, age: 100, energy: 100 })) organisms.add(organism(config, 2, { x: 1, y: 0, age: 100, energy: 100 })) @@ -657,7 +658,7 @@ describe('ReproductionSystem', () => { }) it('does not let a juvenile initiate or be chosen as a partner', () => { - const config = resolveWorldConfig() + const config = resolveBefore() const organisms = new OrganismStore() organisms.add(organism(config, 1, { x: 0, y: 0, age: 1, energy: 100 })) organisms.add(organism(config, 2, { x: 1, y: 0, age: 100, energy: 100 })) @@ -679,7 +680,7 @@ describe('ReproductionSystem', () => { }) it('gates on a positive cooldown, silently, and decrements cooldowns by deltaTime each tick', () => { - const config = resolveWorldConfig({ timestep: 2 }) + const config = resolveBefore({ timestep: 2 }) const organisms = new OrganismStore() organisms.add(organism(config, 1, { age: 100, energy: 100, reproductionCooldownRemaining: 5 })) const index = makeOrganismIndex() @@ -694,7 +695,7 @@ describe('ReproductionSystem', () => { }) it('floors the decremented cooldown at zero rather than going negative', () => { - const config = resolveWorldConfig({ timestep: 2 }) + const config = resolveBefore({ timestep: 2 }) const organisms = new OrganismStore() organisms.add(organism(config, 1, { age: 100, energy: 100, reproductionCooldownRemaining: 1 })) const index = makeOrganismIndex() @@ -708,7 +709,7 @@ describe('ReproductionSystem', () => { }) it('rejects an attempt at the population cap without spending energy or a partner search', () => { - const config = resolveWorldConfig({ maxPopulation: 2, organisms: { initialCount: 2 } }) + const config = resolveBefore({ maxPopulation: 2, organisms: { initialCount: 2 } }) const organisms = new OrganismStore() organisms.add(organism(config, 1, { x: 0, y: 0, age: 100, energy: 100 })) organisms.add(organism(config, 2, { x: 1, y: 0, age: 100, energy: 100 })) @@ -744,7 +745,7 @@ describe('ReproductionSystem', () => { }) it('gates silently on energy below minEnergy', () => { - const config = resolveWorldConfig({ reproduction: { minEnergy: 60 } }) + const config = resolveBefore({ reproduction: { minEnergy: 60 } }) const organisms = new OrganismStore() organisms.add(organism(config, 1, { age: 100, energy: 59 })) const index = makeOrganismIndex() @@ -760,7 +761,7 @@ describe('ReproductionSystem', () => { describe('DeathSystem', () => { it('removes an organism that starved and records the cause', () => { - const config = resolveWorldConfig() + const config = resolveBefore() const organisms = new OrganismStore() organisms.add(organism(config, 1, { energy: 0, x: 3, y: 4 })) organisms.add(organism(config, 2, { energy: 50 })) @@ -784,7 +785,7 @@ describe('DeathSystem', () => { }) it('removes an organism that reached maxAge and records the cause', () => { - const config = resolveWorldConfig({ + const config = resolveBefore({ organisms: { maturityAge: 1, senescenceAge: 5, maxAge: 10 } }) const organisms = new OrganismStore() @@ -800,7 +801,7 @@ describe('DeathSystem', () => { }) it('leaves healthy organisms alone', () => { - const config = resolveWorldConfig({ organisms: { maxAge: 1000 } }) + const config = resolveBefore({ organisms: { maxAge: 1000 } }) const organisms = new OrganismStore() organisms.add(organism(config, 1, { energy: 1, age: 1 })) const events = new EventLog(10) @@ -810,7 +811,7 @@ describe('DeathSystem', () => { }) it('processes every organism even while removing some (ascending id order)', () => { - const config = resolveWorldConfig({ organisms: { maxAge: 1000 } }) + const config = resolveBefore({ organisms: { maxAge: 1000 } }) const organisms = new OrganismStore() organisms.add(organism(config, 1, { energy: 0 })) organisms.add(organism(config, 2, { energy: 50 })) @@ -822,7 +823,7 @@ describe('DeathSystem', () => { }) it('appends a historical record with the parent ids, birth tick, and death cause', () => { - const config = resolveWorldConfig() + const config = resolveBefore() const organisms = new OrganismStore() organisms.add(organism(config, 1, { energy: 0, parentIds: [7, 9], birthTick: 3 })) const events = new EventLog(10) diff --git a/packages/simulation/tests/traits.test.ts b/packages/simulation/tests/traits.test.ts index de76f34..24280b5 100644 --- a/packages/simulation/tests/traits.test.ts +++ b/packages/simulation/tests/traits.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { resolveBefore } from './support/life' import { resolveWorldConfig } from '@evo/config' import { basalCostOf, @@ -10,7 +11,7 @@ import { } from '../src/organisms/traits' import { organismFor, withGenes } from './support/organism' -const config = resolveWorldConfig() +const config = resolveBefore() const founder = organismFor(config, 1).genome describe('derived traits at the founder baseline equal their Phase 3 values exactly', () => { @@ -71,7 +72,7 @@ describe('capability is not free', () => { 'reproduction.offspringInvestment': 25 }).genome expect(reproductionCostOf(generous, config)).toBe(40) - const overheadFree = resolveWorldConfig({ reproduction: { overheadFraction: 0 } }) + const overheadFree = resolveBefore({ reproduction: { overheadFraction: 0 } }) expect(reproductionCostOf(generous, overheadFree)).toBe(25) }) }) diff --git a/packages/simulation/tests/world-genomes.test.ts b/packages/simulation/tests/world-genomes.test.ts index e44a913..4693315 100644 --- a/packages/simulation/tests/world-genomes.test.ts +++ b/packages/simulation/tests/world-genomes.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { createBefore } from './support/life' import { World } from '../src/index' import { genomeToVector } from '../src/genetics/GenomeFactory' import { withoutEcology } from './support/ecology' @@ -7,7 +8,7 @@ import { PHASE3_ECONOMY } from './support/phase3' /** The world wiring of genomes (docs/decisions/0006); Phase 3 behavior is pinned in world.test.ts. */ describe('founders carry genomes', () => { - const world = World.create({ seed: 1, config: { organisms: { initialCount: 5 } } }) + const world = createBefore({ seed: 1, config: { organisms: { initialCount: 5 } } }) const snapshot = world.snapshot() it('gives every founder its own genome, in birth order', () => { @@ -54,7 +55,7 @@ describe('founders carry genomes', () => { describe('config baselines reach the genes', () => { it('starts every founder at the configured baseline', () => { - const world = World.create({ + const world = createBefore({ seed: 3, config: { organisms: { initialCount: 4, basalCost: 0.6, radius: 3, hue: 0.2 }, @@ -72,7 +73,7 @@ describe('config baselines reach the genes', () => { }) it('reports the organism’s own radius gene in the snapshot', () => { - const world = World.create({ + const world = createBefore({ seed: 3, config: { ...REFERENCE_START, organisms: { initialCount: 2, radius: 4 } } }) @@ -81,7 +82,7 @@ describe('config baselines reach the genes', () => { }) describe('children get new genomes', () => { - const world = World.create({ + const world = createBefore({ seed: 42, config: { environment: { width: 100, height: 100 }, @@ -140,7 +141,7 @@ describe('children get new genomes', () => { }) describe('genome identity over a long run', () => { - const world = World.create({ + const world = createBefore({ seed: 1, validateEveryTicks: 250, config: { history: { maxEvents: 200_000 } } @@ -172,8 +173,8 @@ describe('genome identity over a long run', () => { describe('genomes are part of the state hash', () => { it('differs when only the founders’ brains differ', () => { - const a = World.create({ seed: 1, config: { organisms: { initialCount: 3 } } }) - const b = World.create({ + const a = createBefore({ seed: 1, config: { organisms: { initialCount: 3 } } }) + const b = createBefore({ seed: 1, config: { organisms: { initialCount: 3 }, genetics: { brain: { initialWeightStd: 0.5 } } } }) @@ -181,8 +182,8 @@ describe('genomes are part of the state hash', () => { }) it('is reproducible for the same seed and configuration', () => { - const a = World.create({ seed: 8, config: { organisms: { initialCount: 3 } } }) - const b = World.create({ seed: 8, config: { organisms: { initialCount: 3 } } }) + const a = createBefore({ seed: 8, config: { organisms: { initialCount: 3 } } }) + const b = createBefore({ seed: 8, config: { organisms: { initialCount: 3 } } }) a.run(300) b.run(300) expect(a.stateHash()).toBe(b.stateHash()) @@ -193,7 +194,7 @@ describe('heritable genomes build on, and do not disturb, Phase 3 dynamics', () // With mutation disabled every child blends identical parent genes, so only the brains differ // and nothing the simulation does depends on a brain yet: Phase 3's pinned Scenario A returns. it('reproduces Phase 3 Scenario A exactly when mutation is off', () => { - const world = World.create({ + const world = createBefore({ seed: 1, config: withoutEcology({ ...PHASE3_ECONOMY, @@ -218,7 +219,7 @@ describe('heritable genomes build on, and do not disturb, Phase 3 dynamics', () it('changes the trajectory when mutation is on', () => { const run = (genetics: object) => { - const world = World.create({ seed: 1, config: { organisms: { initialCount: 10 }, genetics } }) + const world = createBefore({ seed: 1, config: { organisms: { initialCount: 10 }, genetics } }) world.run(2000) return world.stateHash() } @@ -227,7 +228,7 @@ describe('heritable genomes build on, and do not disturb, Phase 3 dynamics', () }) describe('lineage over a run', () => { - const world = World.create({ + const world = createBefore({ seed: 1, validateEveryTicks: 250, config: { history: { maxEvents: 200_000 } } diff --git a/packages/simulation/tests/world.test.ts b/packages/simulation/tests/world.test.ts index 3ca24b0..4bf4ae7 100644 --- a/packages/simulation/tests/world.test.ts +++ b/packages/simulation/tests/world.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { createBefore } from './support/life' import { ConfigValidationError } from '@evo/config' import { ENGINE_VERSION, World } from '../src/index' import { withoutEcology } from './support/ecology' @@ -280,7 +281,7 @@ describe('scenario B: extinction (roadmap testing scenario B)', () => { describe('scenario C: reproduction (roadmap testing scenario C)', () => { // 2 mature organisms, high energy, a small world (so they're always within searchRadius). it('two eligible organisms reproduce: a child is born and both parents pay the cost', () => { - const world = World.create({ + const world = createBefore({ seed: 42, config: { environment: { width: 100, height: 100 }, diff --git a/packages/ui/src/Overview.tsx b/packages/ui/src/Overview.tsx index 1fc53a8..06246b0 100644 --- a/packages/ui/src/Overview.tsx +++ b/packages/ui/src/Overview.tsx @@ -112,6 +112,26 @@ export function StatsPanel({ view }: { view: ViewState }): React.JSX.Element {
Food eaten
{formatCount(metrics.resourcesConsumed)}
+ {metrics.eggsLaid > 0 && ( + <> +
+
Eggs laid
+
{formatCount(metrics.eggsLaid)}
+
+
+
Eggs hatched
+
{percent(metrics.eggsHatched, metrics.eggsLaid)}
+
+
+
Eggs eaten
+
{formatCount(metrics.eggsEaten)}
+
+
+
Clutches lost
+
{formatCount(metrics.clutchesLost)}
+
+ + )} ) diff --git a/packages/ui/tests/ui.test.tsx b/packages/ui/tests/ui.test.tsx index 156215d..401e20b 100644 --- a/packages/ui/tests/ui.test.tsx +++ b/packages/ui/tests/ui.test.tsx @@ -210,6 +210,21 @@ describe('components render', () => { expect(html).not.toContain(' { + const before = renderToStaticMarkup() + expect(before).not.toContain('Eggs laid') + const base = view() + const withEggs = view({ + metrics: { ...base.metrics, eggsLaid: 40, eggsHatched: 30, eggsEaten: 6, clutchesLost: 2 } + }) + const html = renderToStaticMarkup() + expect(html).toContain('Eggs laid') + expect(html).toContain('>40<') + expect(html).toContain('75%') // 30 of 40 hatched + expect(html).toContain('Eggs eaten') + expect(html).toContain('Clutches lost') + }) + it('death causes are rates per simulated minute over the recent window, with totals alongside', () => { const html = renderToStaticMarkup() // fixture: 12 starved, 4 aged, 2 damaged in the 120 s between the first and last sample From 1f2840ebb91587fcd8a2b2dd58e5085518b96227 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 21:15:54 +0000 Subject: [PATCH 07/11] fix(life-cycle): species are not state, so an egg's species is not hashed; re-pin two Phase 3 gates (ADR 0027) An egg and a carried clutch kept the mother's species, and the hash covered it, which made species part of the state: turning species off changed the 50,000-tick hash (species-long-run caught it). The species an egg will hatch into is still stored, and no longer hashed, as for every other use of species. The three golden entries of the new default world are regenerated for it; the 50 older entries never carried an egg and are unchanged. Two Phase 3 pins moved only because mate choice added two genes (every later mutation draw shifts): the scarce world of long-run-extinction goes extinct at 27,182 (was 19,582, seed 6), and long-run-population's seed 1 back half is 55 to 89 (was 25 to 46; seeds 2 to 6 stay at 25 to 48), so its limit is 100 against a maxPopulation of 1,000. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Cn5qp4xBHxLnTrwReNXcf8 --- docs/simulation/determinism.md | 2 +- packages/simulation/src/world/World.ts | 7 ++----- .../tests/determinism/long-run-extinction.test.ts | 6 ++++-- .../tests/determinism/long-run-population.test.ts | 5 ++++- packages/simulation/tests/golden/state-hashes.json | 6 +++--- 5 files changed, 14 insertions(+), 12 deletions(-) diff --git a/docs/simulation/determinism.md b/docs/simulation/determinism.md index 44d610b..7fac277 100644 --- a/docs/simulation/determinism.md +++ b/docs/simulation/determinism.md @@ -209,7 +209,7 @@ Introduced with the prey and threat senses (ADR 0023, step two). The metrics sec #### Version 13 (current, the life cycle) -Introduced with sexes, incubation and eggs (ADR 0027). Everything in version 12 is unchanged and a tail is appended after its predation counters: the four egg counters `eggsLaid`, `eggsHatched`, `eggsEaten`, `clutchesLost` (u32 each); then for every organism in ascending id order its `sex` (u8, `0` female, `1` male) and a boolean for a carried clutch followed, when carrying, by the clutch (the child's genome written exactly as an organism's is: ids, gene vector, brain, body genes; then the father's id u32, a boolean and u32 for the mother's species at conception, the egg's energy f64 and the lay tick f64); then the egg count (u32) and each egg in ascending id order (id u32, x f64, y f64, mother id u32, father id u32, species boolean and u32, energy f64, lay tick f64, hatch tick f64, then its genome). With sexes and eggs off the tail is four zero counters, a `0` and a `false` per organism and an egg count of zero, and the state before the tail is bit for bit the version 12 state. The header carries the new version, so every golden entry's hash moves (regenerated in the commit that caused it); the proof that nothing else moved is the equivalence harness: nine scenarios (field, instant eating, noise food, clusters, one cluster, lush, no predation, no ecology, the reflex controller) with founder brains equal to the prior and mutation frozen gave normalized snapshots, events and records **identical** to the previous commit through births and deaths with the life cycle off. The header and sample vectors below were recomputed with the independent Python hasher. +Introduced with sexes, incubation and eggs (ADR 0027). Everything in version 12 is unchanged and a tail is appended after its predation counters: the four egg counters `eggsLaid`, `eggsHatched`, `eggsEaten`, `clutchesLost` (u32 each); then for every organism in ascending id order its `sex` (u8, `0` female, `1` male) and a boolean for a carried clutch followed, when carrying, by the clutch (the child's genome written exactly as an organism's is: ids, gene vector, brain, body genes; then the father's id u32, the egg's energy f64 and the lay tick f64); then the egg count (u32) and each egg in ascending id order (id u32, x f64, y f64, mother id u32, father id u32, energy f64, lay tick f64, hatch tick f64, then its genome); the species an egg will hatch into is stored but not hashed, since species are a derived view. With sexes and eggs off the tail is four zero counters, a `0` and a `false` per organism and an egg count of zero, and the state before the tail is bit for bit the version 12 state. The header carries the new version, so every golden entry's hash moves (regenerated in the commit that caused it); the proof that nothing else moved is the equivalence harness: nine scenarios (field, instant eating, noise food, clusters, one cluster, lush, no predation, no ecology, the reflex controller) with founder brains equal to the prior and mutation frozen gave normalized snapshots, events and records **identical** to the previous commit through births and deaths with the life cycle off. The header and sample vectors below were recomputed with the independent Python hasher. `WorldConfig` is **not** part of the hash; golden tests pin their config explicitly. Fields for later phases are appended as new sections or new fields with a version bump. diff --git a/packages/simulation/src/world/World.ts b/packages/simulation/src/world/World.ts index 3266867..2e9db5b 100644 --- a/packages/simulation/src/world/World.ts +++ b/packages/simulation/src/world/World.ts @@ -1220,7 +1220,8 @@ export class World { // Schema v12 tail: the predation counters (docs/decisions/0023). hasher.writeUint32(metrics.deathsByPredation).writeUint32(metrics.predationBites) // Schema v13 tail: the life cycle (docs/decisions/0027): the egg counters, each creature's sex - // and carried clutch, and the eggs. All zero or empty with sexes and eggs off. + // and carried clutch, and the eggs. All zero or empty with sexes and eggs off. The species an egg + // will hatch into is not hashed: species are a derived view and never part of the state. hasher .writeUint32(metrics.eggsLaid) .writeUint32(metrics.eggsHatched) @@ -1234,8 +1235,6 @@ export class World { writeGenome(hasher, pregnancy.genome) hasher .writeUint32(pregnancy.fatherId) - .writeBoolean(pregnancy.speciesId !== null) - .writeUint32(pregnancy.speciesId ?? 0) .writeFloat64(pregnancy.energy) .writeFloat64(pregnancy.layTick) } @@ -1249,8 +1248,6 @@ export class World { .writeFloat64(egg.y) .writeUint32(egg.motherId) .writeUint32(egg.fatherId) - .writeBoolean(egg.speciesId !== null) - .writeUint32(egg.speciesId ?? 0) .writeFloat64(egg.energy) .writeFloat64(egg.layTick) .writeFloat64(egg.hatchTick) diff --git a/packages/simulation/tests/determinism/long-run-extinction.test.ts b/packages/simulation/tests/determinism/long-run-extinction.test.ts index 99d97c3..bea487f 100644 --- a/packages/simulation/tests/determinism/long-run-extinction.test.ts +++ b/packages/simulation/tests/determinism/long-run-extinction.test.ts @@ -69,6 +69,8 @@ describe('extinction over a long run', () => { // scarce world is a knife edge, measured over seeds 1 to 12 at 60,000 ticks: 7 go extinct (at // 14,130, 16,430, 19,582, 20,110, 23,431, 31,664 and 47,640) and 5 do not. The test is about // extinction, so it uses seed 6, which goes extinct at 19,582 with 28 successful births. + // It moved once more (ADR 0027): mate choice added two genes, so every later mutation draw + // shifts. Seed 6 still goes extinct, now at 27,182. learning: { controller: 'reflex' }, // Phase 3's way of eating: with bites (ADR 0017) nothing is wasted and this world no longer dies out. feeding: { enabled: false }, @@ -79,13 +81,13 @@ describe('extinction over a long run', () => { world.run(60_000) expect(world.isExtinct).toBe(true) - expect(world.snapshot().population.extinctionTick).toBe(19_582) + expect(world.snapshot().population.extinctionTick).toBe(27_182) expect(world.snapshot().metrics.reproductionSuccesses).toBeGreaterThan(0) world.run(40_000) expect(world.snapshot().population.active).toBe(0) - expect(world.snapshot().population.extinctionTick).toBe(19_582) + expect(world.snapshot().population.extinctionTick).toBe(27_182) expect(world.snapshot().organisms).toEqual([]) expect(world.validate()).toEqual({ ok: true, errors: [] }) }) diff --git a/packages/simulation/tests/determinism/long-run-population.test.ts b/packages/simulation/tests/determinism/long-run-population.test.ts index 874f988..0c60911 100644 --- a/packages/simulation/tests/determinism/long-run-population.test.ts +++ b/packages/simulation/tests/determinism/long-run-population.test.ts @@ -37,7 +37,10 @@ describe('long-run population', () => { // 40 until ADR 0016: parts anchored to the outline changed every body's mass and thrust, // and seed 1's back half moved from 15-40 to 25-46 (seeds 1 to 6 span 21-46). Still a // bounded band far below maxPopulation, with no collapse, so the claim is unchanged. - expect(active).toBeLessThanOrEqual(50) + // And again when mate choice added two genes (ADR 0027), which shifts every later mutation + // draw: seed 1's back half is now 55-89 (seeds 2 to 6 stay at 25-48), still far below + // maxPopulation (1,000) and nowhere near a collapse, so the limit is 100. + expect(active).toBeLessThanOrEqual(100) } expect(world.snapshot().metrics.reproductionSuccesses).toBeGreaterThan(0) expect(world.validate()).toEqual({ ok: true, errors: [] }) diff --git a/packages/simulation/tests/golden/state-hashes.json b/packages/simulation/tests/golden/state-hashes.json index 7497d12..90becb1 100644 --- a/packages/simulation/tests/golden/state-hashes.json +++ b/packages/simulation/tests/golden/state-hashes.json @@ -3253,7 +3253,7 @@ "seed": 12345, "config": {}, "steps": 6000, - "expectedHash": "1b49fb1c4c55a8cbfa834a4367c207a9" + "expectedHash": "7c69e82c652e7cfb05c5e3f6b7ebf67b" }, { "name": "life-cycle-reflex-6k", @@ -3264,7 +3264,7 @@ } }, "steps": 6000, - "expectedHash": "e41f3a38512b87e386ea53df37c4ce61" + "expectedHash": "7446d031818a1a7cfe8e98f13e40383e" }, { "name": "life-cycle-no-ageing-no-choice-6k", @@ -3280,7 +3280,7 @@ } }, "steps": 6000, - "expectedHash": "4a8c105ba7fd1df44ec92d9dcbbbe59d" + "expectedHash": "a202844ea17489c6b579abaabc4debea" } ] } From 74b92fa42c7de6a55420b27f0a6e925564244789 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 21:25:17 +0000 Subject: [PATCH 08/11] docs(life-cycle): ADR 0027 results and pointers from ADRs 0005, 0006 and 0010 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Cn5qp4xBHxLnTrwReNXcf8 --- .../0005-continuous-organism-ecology.md | 4 +++ .../0006-genetics-and-inheritance.md | 4 +++ docs/decisions/0010-mate-seeking.md | 4 +++ docs/decisions/0027-life-cycle.md | 34 ++++++++++++++++++- 4 files changed, 45 insertions(+), 1 deletion(-) diff --git a/docs/decisions/0005-continuous-organism-ecology.md b/docs/decisions/0005-continuous-organism-ecology.md index 2a5f18c..77636f7 100644 --- a/docs/decisions/0005-continuous-organism-ecology.md +++ b/docs/decisions/0005-continuous-organism-ecology.md @@ -154,3 +154,7 @@ Per-system unit tests for the new/changed `ReproductionSystem`, `MovementSystem` ## Rollback plan Each PR is independently revertable. If reproduction's population dynamics prove unstable or undesirable in practice, `ReproductionSystem.update()` can be reverted to a no-op (as it was engineered to be a real, swappable implementation, not a special case baked into `World`) while keeping the life-stage and history infrastructure, which are useful independent of whether reproduction is active. + +## Update (ADR 0027): a life cycle + +Reproduction is no longer always an instant birth between any two ready creatures. With the life cycle on (the default) there are two sexes, a conceived clutch is carried and laid as an egg that hatches after a delay, a partner has to accept too, and death of old age is a chance that rises with age rather than a cutoff. [ADR 0027](0027-life-cycle.md) has the design, the switches that restore this ADR's behaviour exactly, and the measurements. diff --git a/docs/decisions/0006-genetics-and-inheritance.md b/docs/decisions/0006-genetics-and-inheritance.md index 8146a86..eaae354 100644 --- a/docs/decisions/0006-genetics-and-inheritance.md +++ b/docs/decisions/0006-genetics-and-inheritance.md @@ -152,3 +152,7 @@ Pure-function unit tests mirror the roadmap's genetics list: mutation stays boun ## Rollback plan Each PR is independently revertable. The behavior-preserving PR (organisms carry genomes) can ship and stay even if inheritance is later disabled: setting `mutationRateScale` to `0` makes children blends of their parents without drift, and reverting only the "heritable genomes" PR restores genome-carrying organisms that copy a parent's genome. + +## Update (ADR 0027): two more genes + +Mate choice added two reproduction genes, `choosiness` and `preference`, appended to the gene table (genome version 5). See [ADR 0027](0027-life-cycle.md). diff --git a/docs/decisions/0010-mate-seeking.md b/docs/decisions/0010-mate-seeking.md index 80ee5ab..04ae727 100644 --- a/docs/decisions/0010-mate-seeking.md +++ b/docs/decisions/0010-mate-seeking.md @@ -73,3 +73,7 @@ The naive-steering experiment, the ready-gated sensor-range experiment, the rang - Causal ablation in a real world: under the brain controller, a 250 signal produces clearly more births than a signal of 1; under the reflex controller the signal changes nothing (identical state hash). - Removing the "only if I am ready" gate from perception fails the suite (checked by hand during development). - The equivalence harness (previous commit versus this one, reflex controller, mutation off, same food supply, 20 scenarios, snapshots every 250 ticks, the full event list and the historical records) gave identical digests in all 20: reflex dynamics are untouched; only genome contents, and therefore every golden hash, changed. + +## Update (ADR 0027) + +With two sexes the mating signal only points to a ready creature of the other sex, and its range in the default world is 350 (the life cycle needed a longer reach: [ADR 0027](0027-life-cycle.md)). diff --git a/docs/decisions/0027-life-cycle.md b/docs/decisions/0027-life-cycle.md index b7ec5af..08346a9 100644 --- a/docs/decisions/0027-life-cycle.md +++ b/docs/decisions/0027-life-cycle.md @@ -30,7 +30,39 @@ With sexes, eggs, mate choice and ageing off, nine scenarios (field, instant eat ## Measured -RESULTS +Probe: `tests/probe/life.probe.ts` (default world; 30,000 ticks unless said; every number is a mean over the seeds listed). + +**The first flip failed, and the cause was breeding, not the eggs.** With the life cycle on at the old breeding numbers, 2 of 8 worlds went extinct and the mean population fell from 55 (control, life cycle off, 4 seeds) to 24. 98 to 99 percent of eggs hatched, so the mechanism worked; half the creatures were the wrong sex and a pair is rarer. One lever at a time, on seeds 1, 3, 5, 7: search radius 50 to 75 alone (1 of 4 extinct, mean 29), mating signal 250 to 350 alone (2 of 4, mean 23), cooldown 45 to 30 alone (0 of 4, mean 41, lowest 7), all three (0 of 4, mean 51, lowest 19). On the other four seeds all three gave 53, lowest 17. + +**Then the other two parts, same method.** Ageing at hazard 0.04 plus mate choice cost a world (1 of 8 extinct); a lighter ageing (hazard 0.02, metabolism +30 percent, speed -20 percent, fertility cost +30 percent) did not. Mate choice at the first tastes (choosiness 0.3) turned nobody down (0.0 percent of attempts): it was a switch that did nothing, so the founders' tastes are 0.8 and 0.5, which turns down 12 to 28 percent of the attempts that found a partner. On the fragile seeds (3, 5, 6, 7, 8) lowering `minEnergy` from 75 to 65 was the best lever (mean 49, lowest 21, against 42 and lowest 5), while shorter incubation (5 s and 10 s) and still wider search radii did not help (one world died with the wider radii). + +**The shipped default** (breeding: `minEnergy` 65, `cooldown` 30, search radius 75, mating signal 350; ageing light; mate choice 0.8 and 0.5 with threshold 0.4 and search cost 0.2): + +| 16 seeds x 30,000 ticks | result | stated bar | +| ------------------------------------------ | ---------------- | ------------------- | +| extinct worlds | 0 | none | +| mean population (per 4 seeds) | 48 to 53 | 35 to 70 | +| lowest population | 16 to 21 | at least 10 | +| starved share of deaths | 60 to 64 percent | 35 to 70 percent | +| old age share of deaths | about 35 percent | (was about 0) | +| eggs that hatched | 98 to 99 percent | at least 70 percent | +| worlds with a jaw lineage alive at the end | 7 of 16 | reported | + +| 8 seeds x 100,000 ticks (including 3246115366) | result | +| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | +| extinct worlds | 0 | +| mean population | 55 (lowest 19 to 25) | +| starved share of deaths | 61 to 70 percent; old age 28 to 31 percent | +| eggs laid and hatched per world | about 3,300 laid; 92 to 99 percent hatched | +| clutches lost with a mother | 94 to 124 per world | +| eggs eaten per world | 7, 11, 67 and 263 (by pair of seeds); seed 1 about 500 | +| jaw lineage alive at 100,000 | **4 of 8 worlds** (seed 1: 40 of 41 creatures; seed 5: 13; seeds 2 and 6: 1 each); it was 1 or 2 of 8 before | +| tastes at the end | choosiness 0.73 to 0.88, preference 0.50 to 0.55 | +| ticks per second | 450 to 510 with four runs in parallel; the control was 509 | + +**What it says about carnivory, said plainly.** Eggs are a second, stationary meat source, and jaw lineages persist in twice as many worlds (4 of 8, from 1 or 2). They do so in the way this ADR's author did not want: in seed 1 the jaws fed on eggs (about 500 eaten) and are **40 of the 41 creatures at 100,000 ticks, a jaw monoculture**; the owner's earlier bar (jaws never above 40 percent of a population) is broken in that world and held in the other seven. This is reported, not required for the feature, and it is a pointer to the next lever (a jaw that also grazes, which the owner already named: multiple mouths). + +**Gates.** Every default-world statistical gate was run (all 17 determinism files and the unit suites) and two Phase 3 pins moved only because mate choice added two genes and so shifted every later mutation draw: the extinction tick of the scarce world (seed 6, 19,582 to 27,182) and the population band of seed 1 (back half 25 to 46 to 55 to 89; seeds 2 to 6 stay at 25 to 48), re-pinned with those measurements. All 50 older golden entries now say what they were measured with (one sex, an instant birth, the old breeding numbers, ageing off) and reproduce their old hashes exactly; three new entries pin the new default. ## Limits, said plainly From 28a44554fb917b7fed7b1e11fffbeb53b8f402c9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 21:25:25 +0000 Subject: [PATCH 09/11] docs(life-cycle): wording --- docs/decisions/0027-life-cycle.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/decisions/0027-life-cycle.md b/docs/decisions/0027-life-cycle.md index 08346a9..5db3a33 100644 --- a/docs/decisions/0027-life-cycle.md +++ b/docs/decisions/0027-life-cycle.md @@ -60,7 +60,7 @@ Probe: `tests/probe/life.probe.ts` (default world; 30,000 ticks unless said; eve | tastes at the end | choosiness 0.73 to 0.88, preference 0.50 to 0.55 | | ticks per second | 450 to 510 with four runs in parallel; the control was 509 | -**What it says about carnivory, said plainly.** Eggs are a second, stationary meat source, and jaw lineages persist in twice as many worlds (4 of 8, from 1 or 2). They do so in the way this ADR's author did not want: in seed 1 the jaws fed on eggs (about 500 eaten) and are **40 of the 41 creatures at 100,000 ticks, a jaw monoculture**; the owner's earlier bar (jaws never above 40 percent of a population) is broken in that world and held in the other seven. This is reported, not required for the feature, and it is a pointer to the next lever (a jaw that also grazes, which the owner already named: multiple mouths). +**What it says about carnivory, said plainly.** Eggs are a second, stationary meat source, and jaw lineages persist in twice as many worlds (4 of 8, from 1 or 2). They do so in a way nobody asked for: in seed 1 the jaws fed on eggs (about 500 eaten) and are **40 of the 41 creatures at 100,000 ticks, a jaw monoculture**; the owner's earlier bar (jaws never above 40 percent of a population) is broken in that world and held in the other seven. This is reported, not required for the feature, and it is a pointer to the next lever (a jaw that also grazes, which the owner already named: multiple mouths). **Gates.** Every default-world statistical gate was run (all 17 determinism files and the unit suites) and two Phase 3 pins moved only because mate choice added two genes and so shifted every later mutation draw: the extinction tick of the scarce world (seed 6, 19,582 to 27,182) and the population band of seed 1 (back half 25 to 46 to 55 to 89; seeds 2 to 6 stay at 25 to 48), re-pinned with those measurements. All 50 older golden entries now say what they were measured with (one sex, an instant birth, the old breeding numbers, ageing off) and reproduce their old hashes exactly; three new entries pin the new default. From a0332616496a23da02e74eaa33207b3601d18442 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 21:26:36 +0000 Subject: [PATCH 10/11] test: remove two imports the test typecheck flags Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Cn5qp4xBHxLnTrwReNXcf8 --- packages/simulation/tests/ecology/systems.test.ts | 1 - packages/simulation/tests/world-genomes.test.ts | 1 - 2 files changed, 2 deletions(-) diff --git a/packages/simulation/tests/ecology/systems.test.ts b/packages/simulation/tests/ecology/systems.test.ts index 8d3e994..d01ca95 100644 --- a/packages/simulation/tests/ecology/systems.test.ts +++ b/packages/simulation/tests/ecology/systems.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest' import { resolveBefore } from '../support/life' -import { resolveWorldConfig } from '@evo/config' import { OBSERVATION_LABELS, OBSERVATION_SIZE } from '@evo/contracts' import type { RegionType, WorldConfig, WorldConfigOverrides } from '@evo/contracts' import type { DamageBuffer, HazardBuffer, IntentBuffer, RegenBuffer } from '../../src/buffers/types' diff --git a/packages/simulation/tests/world-genomes.test.ts b/packages/simulation/tests/world-genomes.test.ts index 4693315..d4198e5 100644 --- a/packages/simulation/tests/world-genomes.test.ts +++ b/packages/simulation/tests/world-genomes.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from 'vitest' import { createBefore } from './support/life' -import { World } from '../src/index' import { genomeToVector } from '../src/genetics/GenomeFactory' import { withoutEcology } from './support/ecology' import { ALL_ROUND, REFERENCE_START } from './support/bodies' From 00d230f31f9211013aa6e6c9b23e8de73ff9be41 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 21:27:19 +0000 Subject: [PATCH 11/11] test(probe): lint-clean the life probe Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Cn5qp4xBHxLnTrwReNXcf8 --- packages/simulation/tests/probe/life.probe.ts | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/packages/simulation/tests/probe/life.probe.ts b/packages/simulation/tests/probe/life.probe.ts index 0883603..0816d9d 100644 --- a/packages/simulation/tests/probe/life.probe.ts +++ b/packages/simulation/tests/probe/life.probe.ts @@ -17,7 +17,9 @@ import { World } from '../../src/index' */ const NAME = process.env.LIFE_NAME ?? 'on' const OFF = process.env.LIFE_OFF === '1' -const EXTRA = JSON.parse(process.env.LIFE_CONFIG ?? '{}') as Record +const EXTRA = JSON.parse(process.env.LIFE_CONFIG ?? '{}') as { + reproduction?: { eggs?: object } & Record +} & Record const SEEDS = (process.env.LIFE_SEEDS ?? '1,2,3,4,5,6,7,8').split(',').map(Number) const TICKS = Number(process.env.LIFE_TICKS ?? 30_000) const SAMPLE = 2_500 @@ -33,9 +35,6 @@ describe('life-cycle probe', () => { let hatched = 0 let eaten = 0 let lost = 0 - let guarded = 0 - let eggEnergy = 0 - let consumed = 0 let females = 0 let creatures = 0 let jawEnd = 0 @@ -57,7 +56,7 @@ describe('life-cycle probe', () => { : { ...(EXTRA['reproduction'] ?? {}), sexes: { enabled: true }, - eggs: { enabled: true, ...((EXTRA['reproduction'] ?? {}).eggs ?? {}) } + eggs: { enabled: true, ...(EXTRA.reproduction?.eggs ?? {}) } } const world = World.create({ seed, config: { ...EXTRA, reproduction } as never }) let sum = 0 @@ -99,7 +98,6 @@ describe('life-cycle probe', () => { hatched += m.eggsHatched eaten += m.eggsEaten lost += m.clutchesLost - consumed += m.energyConsumed females += end.organisms.filter((o) => o.sex === 0).length creatures += end.organisms.length let jaws = 0 @@ -117,8 +115,6 @@ describe('life-cycle probe', () => { if (jaws > 0) seedsWithJaw++ perSeed.push(`${seed}:${world.isExtinct ? 'X' : Math.round(sum / samples)}/${jaws}j`) } - void guarded - void eggEnergy const n = SEEDS.length const line = [ NAME, @@ -143,7 +139,6 @@ describe('life-cycle probe', () => { `tps=${((1000 * ticks) / ms).toFixed(0)}`, perSeed.join(' ') ].join(' ') - void consumed const dir = join(tmpdir(), 'evo-probe') mkdirSync(dir, { recursive: true }) appendFileSync(join(dir, `life-${NAME}.txt`), line + '\n')