Evolution
Grazers, omnivores and hunters evolve diet, armour and weapons, and compete for one world.
Build log
Status
Not started. This log is written by Claude Code during the cloud session that builds the demo, then lightly edited.
The brief
The prompt the session received, verbatim, and a link to the cloud session and PR.
Approach
What was chosen and why. Alternatives considered. Anything reused from open source, with license and link.
Timeline
Short dated entries as the work progressed: what was tried, what broke, what fixed it.
Numbers
Rough wall-clock time, number of turns, tokens or cost if known, bundle size, frames per second on a laptop and a phone.
What I would do next
Known gaps, stretch goals, ideas.
Original spec
Evolution
Build an evolving ecosystem in projects/evolution/demo/, following the demo contract in CLAUDE.md.
Three founding species compete in a shared world. Each creature has a neural brain and a heritable genome that includes diet, offence and defence. Visitors watch which species, and which strategy, wins.
This spec is the complete brief. Where it gives a number, use it as the starting value. Where it is silent,
do what the base does. Record every deviation and every tuned value in BUILD-LOG.md.
Goal
A live, in-browser ecosystem that runs on the visitor’s device. Plant-eaters, omnivores and meat-eaters gain energy from base resources (plants) and by eating each other. Population pressures follow from those energy flows:
- boom and bust cycles
- starvation
- crowding
- an offence-versus-defence arms race, where both traits cost energy to maintain
The visitor should be able to answer two questions:
- Which founding species is winning?
- Which strategy is winning: herbivory, omnivory or carnivory? And is the arms race favouring offence or defence?
The visitor should also be able to inspect any creature: its genome, its brains and what it is doing.
Base code
Base: casaisdev/primordial, MIT, © 2026 Martín Casais, commit
c891c061febd7c1f094d0fd4795d47e9ae58e739.
Port its framework-free simulation core from sim/:
World.ts,Organism.ts,Genome.ts,Brain.ts,Food.tsSpatialGrid.ts,rng.ts,stepCadence.ts,density.ts,telemetry.tstypes.ts,render.ts,sim.worker.ts,protocol.ts
Drop everything else: the Next.js app/, components/ and hooks/, React, and Tailwind.
The rule: wherever this spec does not say otherwise, keep the base’s behaviour, constants, order of operations and RNG-draw order. Read the base, not your memory of ecosystem sims. The base’s balance is the product of extensive tuning; its README section “The tuning war” explains why each mechanism exists. Read it before changing anything.
Licensing:
- Every ported file starts with a comment naming the source and the commit, and carries the full MIT notice.
BUILD-LOG.mdcredits the base with its link and commit, and states roughly what fraction of the final code is ported.
Ideas only, no code copied. Credit each of these in BUILD-LOG.md:
- codevalley/preylife (BSD-2): a failed attack costs energy.
- Wilensky’s NetLogo Wolf Sheep Predation (CC BY-NC-SA, so no code): the classic predator–prey framing.
- The research basis for the diet trade-off and refuges: Chubaty et al. 2013 (evolution of omnivory), and Brose, Williams & Martinez 2006.
No new npm dependencies. The base’s tests use Vitest; convert them to node:test (see Tests).
What the base does, kept unchanged
Use these as your map of the base:
- Food: discrete food particles of four kinds (small, lean, rich, dense), each with energy, radius and
spawn weight. They respawn at
foodSpawnRateper tick up tofoodCap, with a 2× spawn grace for the first 600 ticks. The world is bounded, 3072 × 3072, and organisms bounce off the edges. - Genome: five physical traits in [0,1] (
speed,size,vision,energyEfficiency,reproductionRate), spent against a total budget, plus brain weights. Mutation is Gaussian, with mean regression and budget rebalancing. - Phenotype: derived from the genome once, then cached (
phenotypeFromGenome). It covers speed, vision, eat radius, energy gain, upkeep, reproduction threshold, and offspring ratio, age and cooldown. - Brain: a 5→6→2 tanh network with 50 weights (
Brain.ts). - Foraging: fully brain-driven steering toward food, with the inputs listed in
Organism.tick. - Fleeing: a hard-coded flee from the nearest visible threat overrides foraging.
- Hunting: a hybrid. Hard-coded pursuit of the nearest visible prey is the floor. The hunting brain modulates it within ±15% turn and 0.85–1.15× speed, and also nudges wandering when nothing is in sight.
- Hunter tuning: the base’s predator constants:
- predator speed bonus 1.4
- vision grace for early generations
- wander speed multiplier
- reproduction energy bonus 55
- minimum reproduction age 120
- a “hunt score” that shortens the breeding cooldown
- zeroed brains for seeded hunters
- Life cycle: senescence (randomised lifespan, with drain rising after 60% of it), death at zero energy, and reproduction costs.
- Population control:
- plant-eater births taper with crowding, as
1 − crowd³ - meat-eater numbers are capped at a fixed ratio of plant-eaters
- meat-eaters reproduce first in the birth loop
- total population is capped at
maxPopulation - mutation is adaptive: 4× the rate when genetic diversity falls below a threshold
- plant-eater births taper with crowding, as
- Rescue floors: clones of the best survivor, with light mutation, are spawned when a population nears
zero. They are disabled by
allowExtinction. - Architecture: the simulation and rendering live in a Web Worker drawing to an
OffscreenCanvas; the main thread only forwards input and receives a slimViewState. - Determinism: seeded mulberry32. The same seed gives a bit-identical run.
- Speed cadence: fractional and integer speeds, plus MAX mode under a per-frame time budget
(
stepCadence.ts).
What changes
1. Three founding species, and diet as a gene
The base’s species: 'prey' | 'predator' is replaced by two fields:
founder: 0 | 1 | 2 (Grazers, Omnivores, Hunters):
- Inherited unchanged from parent to child.
- Used for colour, for charts (“which species is winning”), for rescue floors, and for the no-cannibalism rule.
diet: a new genome trait in [0,1], where 0 means only plants and 1 means only meat.
- It is outside the trait budget.
- It mutates slowly: Gaussian with σ equal to 0.25 × the base trait σ. With probability 0.01 per birth, it instead jumps by ±0.15 (sign chosen at random). Clamp to [0,1].
- Mean regression (the base’s
MEAN_REGRESSION) does not apply to diet. If it did, a hunter lineage would drift out of the carnivore range within about 40 births. - Mutation draw order is fixed:
- The seven budget traits, in the base’s loop, in this order: speed, size, vision, energyEfficiency, reproductionRate, offence, defence. Mean regression and rebalancing apply to these.
- Diet: one Gaussian draw, then one draw for the jump check, then one draw for the sign only if the jump fires.
- The forage brain weights, then the hunt brain weights.
- Role is derived from diet, for behaviour gating and for charts (“which strategy is winning”):
- herbivore:
diet < 0.33 - omnivore:
0.33 ≤ diet ≤ 0.67 - carnivore:
diet > 0.67
- herbivore:
Founding values:
| Founder | Founding diet | Initial count (desktop / phone) | Initial genome |
|---|---|---|---|
| Grazers | 0.10 | 160 / 100 | Base randomGenome |
| Omnivores | 0.50 | 50 / 30 | Base randomGenome |
| Hunters | 0.90 | 10 / 8 | Base newPredatorGenome (zeroed hunt brain) |
Founding offence and defence: each is the table value plus a Gaussian with σ 0.05, clamped.
- Draw them after the five base traits.
- Set them before
rebalanceBudgetruns, so the budget always holds. The rebalanced values may differ slightly from the table.
| Founder | Offence | Defence |
|---|---|---|
| Grazers | 0.15 | 0.35 |
| Omnivores | 0.45 | 0.45 |
| Hunters | 0.65 | 0.20 |
Founding start energy: Grazers and Omnivores use initialEnergy. Hunters use initialEnergy × 0.6, as in the
base.
Diet efficiency. These factors scale what a creature gets from each food source. Founders at their founding diet reproduce the base’s numbers exactly, with factor 1.0:
plantFactor(d) = min(1.17, ((1 − d) / 0.9) ^ 1.5), which multiplies the basefoodGainForresult.meatFactor(d) = min(1.17, (d / 0.9) ^ 1.5), which multiplies the base predation gain (prey.energy × PREDATION_GAIN).- The exponent 1.5 favours specialists. An omnivore at 0.5 gets about 0.41 of each, which gives it a niche but not dominance.
2. Two brains
Each genome carries two brains, each with the base’s shape (5→6→2, 50 weights):
forageBrain: driven exactly as the base drives prey foraging.huntBrain: driven exactly as the base drives predator hunting and wandering.
Mutation magnitude follows the base: forage brains use scale 8; hunt brains use scale 2. Draw the forage weights first, then the hunt weights, so the draw order is fixed.
Seeding: Hunters get a zeroed huntBrain, as in the base. Every other brain starts random, as in the base.
3. Behaviour: choose a mode each tick, then run the base’s code path for it
Each tick, every organism picks exactly one mode, in this priority order. Every organism always gets a mode.
-
Flee. It flees when a threat is within its vision radius. A threat is an organism that meets all of these:
- it is of a different founder
- it was in hunt mode on the previous tick
- it is not satiated
catchProbability(threat, self) ≥ 0.3catchProbability(threat, self) > catchProbability(self, threat)
Store each organism’s previous mode on the organism, so this stays deterministic.
Run the base prey flee path: steer away from the nearest threat at full speed.
- Creatures do not flee from foragers.
- Well-armoured creatures, and stronger fighters, do not flee from weak attackers. This is how defence pays off behaviourally.
- Without the last two conditions, omnivores and hunters would each count as a threat to the other, and would flee each other instead of hunting.
-
Hunt. Considered when diet is at least 0.33 and the organism is not satiated. A satiated organism counts as having no target.
- A target is a visible organism of a different founder, not killed earlier this tick.
- The chosen target is the one with the highest meat score:
meatFactor(d) × target.energy × PREDATION_GAIN × catchProbability(self, target) / (dist + 20). Ties go to the lowest id. - Compute the plant score:
plantFactor(d) × food.energy × FOOD_GAIN_BASE_MULT / (dist + 20), for the nearest visible food, or 0 if there is none. - Hunt if the meat score is greater than the plant score. Run the base predator pursuit path toward the
target, with the
huntBrainmodulation and the 1.4 speed bonus.
-
Otherwise:
- Diet above 0.67: the base predator wander path, with the
huntBrain. - Diet 0.67 or below: forage, the base prey foraging path with the
forageBrain.
- Diet above 0.67: the base predator wander path, with the
Forced flee: an organism that just survived a failed attack flees from the attacker’s position on its next tick, even if the threat test would not pick that attacker.
Tick order:
- Organisms tick in array order: one pass, not prey first and then predators as in the base.
- An organism killed earlier in the tick is skipped, and is left out of every later target and threat list.
- Brain inputs:
- The forage brain’s neighbour input counts organisms of every founder within 100, using the base’s
NEIGHBOR_RADIUS. - The hunt brain’s neighbour input counts the targets in its query.
- The forage brain’s neighbour input counts organisms of every founder within 100, using the base’s
Other per-tick rules:
- Upkeep, senescence, edge bounce and death are applied once per tick, as in the base.
- Record the chosen mode, plus the target or threat position, so the inspector can display them.
- Spatial grids: replace the base’s separate prey and predator grids with one organism grid of the same cell
size, plus the food grid. Query radii:
- hunting and fleeing: the organism’s vision, at most
PREY_QUERY_RADIUS(540) - food:
FOOD_QUERY_CAP(170), as in the base
- hunting and fleeing: the organism’s vision, at most
4. Offence, defence and the catch rule
New genome traits: offence and defence, both in [0,1], inside the trait budget.
- Seven traits now share the budget.
- Scale the budget bounds by 7/5:
- initial budget: [3.08, 4.06]
- mutation budget: [2.52, 4.48]
Costs:
- Upkeep: add
offence² × 0.60 + defence² × 0.60to the bracketed sum inenergyCostPerTick. The squared terms make extremes expensive and keep the arms race bounded. - Speed: defence slows its owner. Multiply
moveSpeedby(1 − defence × 0.25).
Catch probability:
sizeRatio = sqrt((0.5 + attacker.size) / (0.5 + target.size))
P = 1 / (1 + exp(−((attacker.offence × sizeRatio − target.defence) / 0.15)))
P ×= (target inside a thicket) ? 0.4 : 1
With the founding traits and equal sizes, a hunter against a grazer gives P = σ(2.0) ≈ 0.88, close to the base’s certain catch. Each step of trait drift then matters.
Attempt rule. This replaces the base’s certain catch on contact:
- An attempt happens on contact, using the base’s contact distance (
PREDATOR_EAT_RADIUS + eatRadius). - Draw one RNG value per attempt.
- Success:
- the target is killed
- the attacker gains
target.energy × PREDATION_GAIN × meatFactor(attacker.diet), capped atMAX_ENERGY - the hunt score is bumped, as in the base
- the attacker becomes satiated for 30 ticks: it cannot hunt, and it is not a threat. This is a new handling-time stabiliser.
- Failure:
- the target loses 4 energy and the attacker loses 2
- the attacker cannot attempt again for 15 ticks
- the target gets a free flee on its next tick: it is forced into flee mode even if the threat test fails
- One attempt per attacker per tick.
- No same-founder attacks. This prevents collapse into cannibalism.
5. Population control, generalised
Apply the base’s rules by role, recomputed each tick from diet:
| Base rule | Applies to |
|---|---|
Birth taper 1 − crowd³ (crowd = plant-eaters ÷ maxPopulation) |
Herbivores and omnivores. Count them together as plant-eaters |
Ratio cap PREDATOR_PREY_RATIO = 0.28 |
Carnivores, against the count of herbivores plus omnivores |
| Breed first | Carnivores |
| Predator reproduction energy bonus, minimum reproduction age, hunt-score cooldown cut | Organisms with diet ≥ 0.33. Base prey rules apply otherwise |
| Generation counter | Counted on herbivore births, as in the base. The generation mark advances by the sum of the founders’ initial counts |
Diversity and stats:
- Determinism fix. The base updates
lastDiversity, which switches on 4× adaptive mutation, only insidebuildSnapshot(). That makes a run depend on how often frames are drawn, so the same seed would not reproduce in the page and the harness.- Compute diversity inside
World.step(), at everytick % 10 == 0. buildSnapshot()must not change any simulation state.
- Compute diversity inside
- What diversity measures: only the 5 base traits, and only across herbivore-role organisms. Founders differ in offence, defence and diet on purpose, so including them would keep diversity permanently high and the adaptive mutation would never fire.
SimStatsmapping:organismsmeans herbivores plus omnivores.predatorsmeans carnivores.- Add per-founder and per-role counts.
- Update the telemetry labels to match.
6. Thickets (refuges)
- At reset, place 6 thicket circles of radius 140.
- Centres are at least 400 apart, measured centre to centre, and at least 200 from the edges.
- Place them with a separate RNG,
mulberry32(seed ^ 0x9e3779b9), with up to 200 tries per thicket. - The separate RNG means toggling thickets does not shift the main random stream.
- Inside a thicket, catch probability is ×0.4.
- Food spawns there normally.
- Render thickets as soft dark-green blobs under everything else.
- A settings toggle turns thickets off; it takes effect on reset.
7. Rescue floors (“immigration”)
There is one floor per founder, applied when allowExtinction is false:
| Founder | Floor | Rule |
|---|---|---|
| Grazers | 18 | As the base prey floor: checked every tick |
| Omnivores | 10 | As the base predator net: from tick 1200, every 200 ticks, only while herbivores plus omnivores number at least 150 |
| Hunters | 8 | Same as Omnivores |
Deliberate differences from the base’s rescue code:
- The base prey floor requires
preyCount > 0, so it never fires at zero. Here the Grazer floor also fires at zero. - The base predator net requires at least 250 prey. Here the threshold is 150 herbivores plus omnivores, because the plant-eating population is split.
- As in the base, a founder whose initial count is 0 never gets immigrants.
- Omnivore and Hunter rescues mutate with
config.mutationRate, as the base predator rescue does, not the adaptive rate. Use brain scale 2 for the hunt brain and 8 for the forage brain.
Who gets spawned:
- A light mutation of the founder’s best surviving member, judged by
accumulatedFitness, as in the base. - If that founder has no survivors, its founding genome as defined in section 1. Hunters get a zeroed hunt brain.
Visibility:
- Every spawn is an
immigrationevent, counted per founder. - Draw it as a distinct ring.
- Show it in the charts as a marker.
8. Phone configuration
The phone configuration applies when matchMedia('(pointer: coarse)') matches or the container is under 600
px wide:
maxPopulation450foodCap2000foodSpawnRate22- the initial counts from the table in section 1
The world stays 3072 × 3072; the camera fits it to the screen. These starting values must pass the tuning gate, which runs both configurations.
Tuning gate (do this before any UI work)
The changes above will disturb the base’s balance. Expect to tune.
The harness
Write a headless harness, demo/tools/tune.ts, run with:
node --experimental-strip-types projects/evolution/demo/tools/tune.ts --seeds 20 --ticks 30000 --config desktop|phone
- It imports
Worlddirectly, with no worker and no DOM. - Every module it imports must use erasable TypeScript only:
- no
enum,namespaceor constructor parameter properties import typefor types- explicit
.tsimport extensions
- no
- The base already uses only erasable syntax. Under Node it fails only because its imports have no
.tsextensions; add them and it runs. There is no other problem to hunt for. - Files that import
node:modules begin with// @ts-nocheck.astro checktype-checks every file and@types/nodeis not installed. Do not add@types/node.
What it reports, per seed
- Survival: minimum population of each founder and each role.
- Immigration: immigration births as a percentage of all births, per founder.
- Cycles: the number of Hunter-population peaks.
- Sample the Hunter count every 10 ticks.
- Smooth it with a 200-tick moving average.
- Prominence = (peak − the higher of the two surrounding minima) ÷ peak.
- A peak counts if its prominence is at least 0.25, its height is at least 12, and it is at least 500 ticks from the previous counted peak.
- Winner at the end: the founder and the role with the largest share of total energy (biomass).
- Arms race: the change in mean offence and mean defence for each founder.
It also prints a summary table, which goes into BUILD-LOG.md.
Pass criteria (both configurations)
- In at least 18 of 20 seeds, every founder is alive at every tick.
- Immigration is under 10% of births for every founder, in at least 18 of 20 seeds.
- At least 3 Hunter cycles per 30,000 ticks, in at least 15 of 20 seeds.
- Median ticks per second headless is at least 1.0× the unchanged base
Worldon the same machine. Measure the base once, record both numbers, and fix any regression. The base itself manages about 350–400 ticks per second in a 4-core container.
Running it:
- Run seeds in parallel with
node:child_process, one per core. - Screen candidate settings with 6 seeds × 10,000 ticks.
- Run the full 20 × 30,000 only to confirm a candidate. One full run of both configurations is about 1.2 million ticks.
Tuning
- Allowed knobs, in this order:
meatFactor/plantFactorcaps and exponent- satiation and failure costs
- the offence/defence upkeep weights
- the founding offence/defence values
- the floors’ cadence
- the thicket count and radius
- the initial counts
- Change base constants only as a last resort, and record why.
- Log each tuning round (what changed, and the pass/fail numbers) in
BUILD-LOG.md. - Report, don’t force, the outcome distribution: which founder or role wins across seeds. Any mix is acceptable, and a varied one is more interesting.
- If the gate cannot be met within a reasonable effort (about a third of the session), stop and write the
best result and the failure mode in
BUILD-LOG.md. Then continue with the UI using the best configuration, and flag it in the PR.
Page and UI
Layout
mount(container) creates a root (tabindex=0) containing:
- A
.demo-controlsbar:- Play/Pause
- speed: 0.25, 0.5, 1, 2, 4 and MAX, as in the base
- Reset, which starts a new random seed
- the seed as editable text; Enter resets with that seed
- the active configuration (“desktop” or “phone”) next to the seed. The same seed runs differently under each configuration, and a narrow desktop window gets the phone one.
- Settings
- The stage: the canvas the worker draws to, transferred with
transferControlToOffscreen.- It fills the width.
- Its height is
max(60vh, 420px); on phones it is55vh. - The stage is sized by CSS, never by the canvas, so the
ResizeObservercannot loop.
- A side panel on wide screens, stacked below the stage on phones. It holds:
- Status: tick, generation, total population, and a “Winning” readout. This shows the founder with the largest biomass share averaged over the last 1,000 ticks, its role mix, and a trend arrow.
- Charts: see Charts.
- Inspector: shown when a creature is selected.
- Settings sheet, applied on Reset:
- mutation rate, food spawn rate, food cap and max population (the base’s
CONFIG_BOUNDS) - initial count per founder
- allow extinction (default off)
- thickets (default on)
- mutation rate, food spawn rate, food cap and max population (the base’s
- Explainer, below everything, in plain prose:
- what a creature is (its seven traits, plus diet and two brains)
- how energy flows: plants, then eaters, with losses
- the catch rule in words
- why traits cost energy
- what immigration is and why it exists
- how to read the charts
- credits
Charts
Draw these in Canvas 2D, with no library. Sample every 10 ticks into a ring of 1,000 points, so the window is the last 10,000 ticks.
- Population by founder: a stacked area chart, with immigration markers.
- A toggle switches the stack to by role (herbivore, omnivore, carnivore).
- Arms race: mean offence and mean defence per founder over time. Six lines: solid for offence, dashed for defence, coloured by founder.
- Diet distribution: a histogram of the current population’s diet, 20 bins, stacked by founder.
- Offence vs defence: a scatter plot of the current population, coloured by founder and shaped by role.
Rendering
Port render.ts, then make these changes:
Colour by founder:
| Founder | Colour |
|---|---|
| Grazers | #5ee0a0 |
| Omnivores | #f5c76a |
| Hunters | #ff6b6b |
Shape by role, so the colours remain readable for colourblind visitors:
- herbivore: circle
- omnivore: rounded square
- carnivore: triangle pointing along the heading
Other drawing:
- Satiated organisms: a small inner dot.
- Events: keep the base’s predation and birth event flashes, and add an immigration ring.
- Background: thickets are drawn under everything else.
- Selected organism: draw its vision radius, plus a line to its current target or threat, coloured by mode (forage, hunt or flee). This is the original spec’s “draw its sensors”.
Inspector
Shown when a creature is clicked (the base’s hit-testing in the worker):
- Identity: founder, role, current mode, generation, age, lifespan, energy, kills and offspring.
- Genome: a bar for each of the 7 budget traits plus diet.
- Phenotype: speed, vision, upkeep per tick, and catch probability against each other founder. Each founder is represented by its median offence, defence and size.
- Brains: both drawn as small node diagrams, with edges coloured by sign and widened by magnitude.
Extend ViewState with these fields.
Worker to main-thread data
The charts and the inspector are drawn on the main thread.
- Chart samples:
World.steprecords them at everytick % 10 == 0: counts by founder and by role, mean offence and defence by founder, biomass by founder, and immigration events.- The worker posts only the new samples since the last post, at most 4 times a second.
- Per-organism data for the histogram and the scatter plot: diet, offence, defence, founder and role.
- Post it as a transferable
Float32Array, at most 4 times a second. - Keep
ViewStateitself slim.
- Post it as a transferable
Input
Port the base’s pointer, wheel, keyboard and pan/zoom handling, with these changes:
- Listen on the root and canvas, never on
windowordocument. - Pinch-zoom on touch, using two pointers.
- Add a
zoomAt {fx, fy, factor}message to the protocol; the base’szoomByalways zooms about the centre. - Set
touch-action: noneon the canvas. - A second pointer cancels any drag.
- Add a
- Tap to select.
- Remove every listener in cleanup.
Fallback
If OffscreenCanvas or transferControlToOffscreen is unavailable, run the same simulation on the main
thread with requestAnimationFrame.
The base can’t be reused for this as it stands:
- The camera, hit-testing and speed cadence all live as module-level state in
sim.worker.ts. sim.worker.tsregisters its message listener as soon as the file loads.
So restructure it:
- Move the worker’s logic into
sim/host.ts, exportingcreateSimHost(post). sim.worker.tsbecomes a thin wrapper that callscreateSimHostand wiresselfmessages to it.- The fallback calls
createSimHostdirectly on the main thread. - In
render.ts, type the context asCanvasRenderingContext2D | OffscreenCanvasRenderingContext2D, soastro checkaccepts both paths.
Worker loading
new Worker(new URL('./sim/sim.worker.ts', import.meta.url), { type: 'module' })
Verify the worker is emitted by npm run build.
Lifecycle
mount returns a cleanup function that:
- terminates the worker
- cancels any animation frame
- disconnects observers
- removes listeners
- empties the container
Also:
- Pause when off-screen (
IntersectionObserversends a pause message). - With
prefers-reduced-motion, start paused and forward the setting to the worker, as the base does.
Files
projects/evolution/demo/
index.ts mount(), DOM, controls, panels, worker or fallback wiring
sim/ ported core + changes (World, Organism, Genome, Brain, Food, SpatialGrid, rng,
stepCadence, density, telemetry, types, render, protocol)
sim/host.ts createSimHost(post): camera, hit-testing, cadence, loop (from the base's worker)
sim/sim.worker.ts thin wrapper around createSimHost
ui/charts.ts ui/inspector.ts ui/settings.ts
tools/tune.ts headless tuning harness (// @ts-nocheck)
tests/*.test.ts node:test (// @ts-nocheck)
Tests
Convert the base’s Vitest suites to node:test with node:assert/strict:
genomeorganismfoodspatialGridworld.invariantsworld.reproducibilityworld.no-extinction, extended to all three founders
Run them with:
node --experimental-strip-types --test projects/evolution/demo/tests/<file>.test.ts
Give one file path per run, or a shell glob that expands to file paths.
Add these new tests:
- Diet factors: both are exactly 1.0 at their founding diets.
- Trait budget: holds with 7 traits.
- Catch probability: symmetric limits, and the thicket factor applies.
- Satiated organisms: never hunt and are never threats.
- No cannibalism: organisms never attack their own founder.
- Immigration: fires only below its floor.
- Determinism: the same seed gives an identical snapshot after 2,000 ticks with every new mechanic active.
project.json
Update:
| Field | Value |
|---|---|
tagline |
“Grazers, omnivores and hunters evolve diet, armour and weapons, and compete for one world.” |
description |
Describe the three founders, the evolving diet and the offence/defence arms race |
tags |
["simulation", "neural-net", "ecology"] |
status |
building at start, live when done |
Leave the other fields alone.
Build order
Branch from main after the design PR containing this spec has merged. Commit after each step, and keep
BUILD-LOG.md current.
- Port the core unchanged, with the base tests converted to
node:test. Check: the tests pass, and a seed reproduces bit for bit. - Mount, worker, render and controls, still with the base’s two species. Check: it runs in the page, speeds work, and resize behaves.
- Founders, diet, two brains and mode selection. Check: new tests pass.
- Offence, defence, the catch rule, satiation, thickets and immigration. Check: new tests pass.
- The tuning harness and the gate. Record every round. Check: the gate passes, or a documented best result exists.
- Charts, status and the “Winning” readout.
- Inspector, sensors and touch pinch-zoom.
- Settings, explainer, phone layout, screenshot and build log. Run
npm run checkandnpm run build, then set status tolive.
Cut list, in this order:
- The offence-vs-defence scatter plot.
- The diet histogram.
- Brain diagrams in the inspector (keep the trait bars).
- Pinch-zoom (keep the base’s zoom buttons and keyboard controls).
Never cut the tuning gate, the population and arms-race charts, the “Winning” readout or the fallback.
Out of scope:
- the original spec’s hall of fame, genome save/load and fitness-per-generation chart (there is no fitness function)
- sound
- WebGPU
- saving runs
Acceptance checklist
-
npm run checkandnpm run buildpass. No new npm dependencies. The PR changes onlyprojects/evolution/. - All converted base tests and all new tests pass, run with the commands above.
- The tuning gate passes on both configurations, or the shortfall is documented. The
BUILD-LOG.mdtable shows, per configuration: survival, the immigration percentage, cycles, the winner distribution, the arms-race drift and ticks per second. - The same seed reproduces the same run, both in the page (enter the seed and Reset) and in the harness.
- Founder colours and role shapes render. Thickets, satiation dots, immigration rings and selected-organism sensors are visible.
- Both population chart modes, the arms-race chart and the “Winning” readout update live. The diet histogram and scatter plot update unless cut.
- The inspector shows identity, genome, phenotype (including catch probabilities) and both brains, unless cut.
- Settings apply on Reset. “Allow extinction” really allows extinction.
- At least 60 fps on a laptop at 1× with the population at the desktop cap. Record what you measured in the container, labelled “headless”.
- The phone layout works at 375×667. Tap-select works, and pinch-zoom works unless cut.
- The fallback path runs when
OffscreenCanvasis disabled. Test by forcing the fallback with a dev query flag,?nooffscreen. - Cleanup terminates the worker and removes listeners. No console errors.
- The MIT notice is in the ported files.
BUILD-LOG.mdcredits Primordial with its commit, and credits Preylife, Wilensky and the papers as ideas. -
media/has a screenshot.