Primordial Soup
An agent-based simulation exploring whether genuine learning can emerge from simple chemistry rather than statistical optimization.
The Question
If you were going to build a better AI, how would you do it? Not by training on corpora or optimizing loss functions, but by starting from a single cell in a simple environment and letting it learn from first principles. Primordial Soup is an attempt to take that question seriously.
The simulation places agents in a small, dynamic environment and gives them minimal internal machinery. There are no reward signals, no gradient descent, no objective functions. Instead, agents accumulate chemical states that encode their history, and the pressure of that history — its inadequacies, its patterns, its texture — drives behavioral change. The hypothesis is that learning emerges not from directed search but from the pressure of accumulated inadequacy: the growing weight of experience that doesn't fit the agent's current way of operating.
The Environment
A 41x31 grid — a "puddle" — with four corners that exert environmental effects: poison, restoration, sunlight, and moisture. These effects follow quadratic distance falloff with sinusoidal variation, so the landscape is non-uniform and position matters.
Three overlapping seasonal cycles drive the environment:
- Poison/restore oscillates on a 100-tick full season
- Sunlight on a 50-tick half season
- Moisture on a 25-tick quarter season
The cycles use diagonal corner-pair oscillation with smooth sinusoidal transitions, creating interference patterns that repeat every 200 ticks. The landscape breathes — corners pass through neutral at crossover points, and the combined effect at any position is genuinely complex despite the simple generating rules.
Critically, the environment maintains a hidden variable stack. Variables like seasonal phase exist and causally affect what the agent experiences, but agents don't know about them until their own internal dynamics trigger discovery. Some hidden variables are genuinely informative (seasonal phase predicts environmental change). Others are red herrings (moon phase correlates with nothing useful). The agent has to figure out which is which.
Two Species
Daffodil — Memory Without a Brain
The simpler species, inspired by research on Stentor roeseli — a single-celled organism that demonstrates learning without neural structures. If a protozoan can learn, the mechanism can't require a brain.
A Daffodil has four chemical concentrations that serve simultaneously as its internal state, its drives, and its memory:
- Curiosity (c) — a growth hormone, produced by sunlight and moisture
- Survival (s) — a stress hormone, produced by environmental change
- Inertia (i) — a damage marker, produced by resource deficit and poison
- Habit (h) — structural adaptation, slow accumulation inhibited by surprise
These four chemicals form a single behavioral axis via the ratio (c * h) / (s * i). High ratio means conditions are favorable — disperse, reproduce. Mid-range means orient — the Daffodil physically leans along one of the environment's two diagonal corner-pair axes, adjusting its effective sunlight capture. Very low ratio triggers last-gasp dispersal: terminal, desperate reproduction, which is biologically real behavior in stressed plants.
The key insight is that these chemical levels are the memory. There is no episodic record, no memory bank. Current concentrations encode the integral of recent history. A daffodil doesn't "remember" Tuesday's drought — it carries the chemical residue of things having gotten worse, encoded as hormone gradients. The four chemicals forming two ratios mirrors the structure of DNA's four bases forming two pairs: meaning emerges from pairing and relationship, not from individual components.
Orientation is a discoverable behavior: before the Daffodil discovers that direction matters (through the same inquiry pipeline that discovers seasonal variables), it orients randomly. After discovery, a rising ratio trend causes it to lean toward its nearest corner pair (growth investment), while a falling trend causes it to lean away (protective posture). Two Daffodils at the same position with different chemical histories will orient differently — the chemical memory produces observable, directional, differentiated behavior without any brain or environmental awareness beyond "am I getting better or worse."
Daffodils compete for resources through a density system — local crowding reduces effective sunlight and moisture, creating self-regulating population dynamics (steady state around 92 living individuals).
PrimordialMan — The Full Architecture
The more complex species, with a proper brain, episodic memory, and the full learning pipeline.
Five internal state variables (deliberately constrained — the cognitive bottleneck hypothesis suggests that limitation is generative, forcing compression and abstraction):
- Vitality, Hunger, Curiosity, Satisfaction, Sociability
Four drives used in action selection:
- Curiosity, Survival, Inertia, Habit
Action selection uses the formula score = (c/s) - (i/h), where each term is weighted per-action. Division prevents any single variable from dominating. Positive scores indicate instinct-led behavior; negative scores indicate behavior-led (learned pattern) behavior. Final selection uses softmax with temperature modulated by curiosity — more uncertain agents explore more.
Episodic memory stores (action, qualifiers, sensory context) mapped to observed deltas in vitality, hunger, and curiosity. Each memory tracks per-dimension convergence and divergence — the agent develops selective trust, believing a memory's vitality prediction even if its hunger prediction is unreliable. Memories decay through non-use, but reliable memories (high convergence) decay more slowly. Encoding is probabilistic, triggered by stress and novelty — a mutation analogy where difficult or surprising moments are more likely to be recorded.
Sensory context anchors memories to the perceptual conditions under which they formed. Each tick, the agent collects binned measurements from its learned senses — density readings at various radii, environmental conditions, species-specific measurements — and stores this as a flat context snapshot alongside each memory. When retrieving memories, sensory context similarity serves as the primary proximity signal: memories formed in perceptually similar conditions carry more weight. This grounds memory retrieval in environmental reality rather than internal drive state, reflecting the principle that outcomes matter more than mood for behavioral learning.
Generalizations emerge when clusters of episodic memories for the same action show consistent outcome patterns. The system groups memories by qualifier combinations, relaxes one qualifier at a time, and checks whether the remaining group agrees on the sign of each outcome dimension. When five or more memories consistently agree — "moving at speed 4 costs vitality regardless of direction" — a generalization crystallizes with an initial reinforcement factor reflecting the group's consistency. Every subsequent observation either confirms (RF grows slowly) or contradicts (RF erodes faster) the generalization. Contradictions weigh more than confirmations — it's easier to lose trust than to build it. Generalizations that erode below a threshold are abandoned entirely. Those that survive feed back into action scoring at a weaker weight than episodic memories, and into prediction when no relevant episodic memories exist.
Collation is a metacognitive action where the agent re-examines its own memories to discover which environmental conditions actually matter. Rather than treating all sensory context equally, collation partitions memories by individual context keys — sunlight, season, density — and checks whether the partitions show different outcome patterns. When they do, that key is promoted from passive context to an active qualifier on the action: "MOVE at speed 1, season=low" becomes a distinct memory from "MOVE at speed 1, season=high". The existing convergence/divergence machinery then tracks whether the distinction is predictive. Collation is weighted toward high curiosity and gated by a per-agent cooldown (30-100 ticks), creating population-level diversity in cognitive strategy.
Epigenetic inheritance preserves knowledge across generations. Before an agent is culled, its high-confidence generalizations are deposited into a species-level pool. Newly spawned agents inherit the top generalizations at a discounted reinforcement factor, along with automatic promotion of any qualifiers (internal, external, and sensory) the generalizations depend on. An inherited agent arrives knowing that "high speed costs vitality regardless of direction" and already possessing the speed and distance qualifiers that would normally require hundreds of ticks of inquiry to discover.
Satisfaction dynamics provide the meta-epistemic signal: not "are my predictions right?" (that's curiosity) but "is my worldview holding up?" Satisfaction tracks generalization reinforcement — when an agent's generalizations are confirmed by observations, satisfaction rises; when they're eroded, it falls. This creates a genuinely independent axis from curiosity. High satisfaction dampens epistemic rise (things are working, less urgency to explore). Low satisfaction amplifies it and makes collation more attractive (worldview crumbling, need to reorganize). Satisfaction gates reproduction — an agent must have validated knowledge worth passing on. It also governs respawn eligibility: dead agents are only respawned if their satisfaction exceeds neutral, ensuring that agents with unvalidated knowledge are replaced by fresh spawns with epigenetic inheritance rather than recycled indefinitely.
Inquiry — How Agents Discover What They Don't Know
This is the mechanism that distinguishes the simulation from a fixed-representation learning system.
When an agent's predictions persistently fail to improve — when epistemic health detects stagnant or worsening prediction error — the agent enters inquiry mode. This is not a search over a predefined hypothesis space. It's a three-way event:
- The agent's internal dynamics signal that its current representation is inadequate
- The environment surfaces a variable from its hidden stack
- The agent gains the ability to perceive that variable going forward
After discovery, existing memories are remapped to include the new dimension (prior memories get null for the newly discovered variable). The agent then tracks whether the new variable actually reduces prediction divergence. Useful variables (like seasonal phase) show convergence over time. Useless variables (like moon phase) show persistent divergence and are effectively learned to be irrelevant.
For Daffodils, this is currently implemented: agents discover rain (moisture cycle phase) and sun_season (sunlight cycle phase) as binary hidden variables. After discovery, their chemical ratio history is partitioned by the new variable's value — separate trend lines for wet vs. dry, bright vs. dim. Approximately 90% of agents discover both variables within 600 ticks. Agents sitting on symmetry axes, where seasonal variation cancels out, rarely discover — which is exactly right, since for them the variable genuinely doesn't matter.
What's Built
- Seasonal environment with three overlapping cycles and interference patterns
- Daffodil chemical memory with ratio-based behavioral axis and phototropic orientation (ORIENT action)
- Daffodil inquiry: two-priority discovery pipeline — sense qualifiers (rain, sun_season, season) partition chemical memory via bitmask, action qualifier (direction) switches orientation from random to trend-informed
- Density-dependent resource competition and population self-regulation
- Bitmask-indexed ratio history that partitions on discovered variables
- Seedling inheritance of discovered variables and memory topology
- Perception layer with discoverable senses and qualifiers (shared across species)
- Sensory context collection, binning, and context-anchored memory retrieval
- PrimordialMan with episodic memory, convergence/divergence tracking, and probabilistic encoding
- Generalization system with reinforcement factor dynamics and erosion under contradiction
- PrimordialMan inquiry — four-branch epistemic pipeline (sense qualifiers, sense promotion, action qualifiers, action promotion) triggered by stagnant prediction error
- Collation — metacognitive action discovering which sensory features discriminate action outcomes, promoting them to qualifiers with immediate generalization formation
- SkillMeta abstraction — per-species metadata for skills with cooldown support and extensibility
- Epigenetic generalization inheritance — species-level knowledge pool, pre-cull deposit, spawn-time inheritance with full qualifier promotion cascade
- Satisfaction dynamics — meta-epistemic signal tracking generalization reinforcement, coupling with curiosity, gating reproduction and respawn eligibility
- Reproduction — courtship-based social action with health/knowledge/satisfaction thresholds, mate quality evaluation, complementary parental knowledge inheritance, carrying capacity gating
- Multi-signal memory encoding — top 5 buffer entries reinforce existing memories, only first unrepresented entry creates a new memory
- Ecological carrying capacity with sinusoidal per-species population waves
- Cross-species interaction: PM grazing pressure on Daffodils, Daffodil proximity benefit for PMs
- Context-aware action scoring — external qualifiers (discovered via collation) are fixed to currently perceived values during scoring rather than enumerating all possible environmental states, reducing MOVE scoring from 4,320 combinations (with 3 external qualifiers) back to 160
- Generalization cap (60 per agent) with lowest-RF eviction and action-indexed retrieval
- Generalization prohibition — abandoned generalizations leave signatures that prevent the same overly-broad claim from re-forming, driving the system toward more specific, higher-dimensional patterns
- Position (x, y) as sensory context — tertile-binned coordinates flow through COLLATE, enabling spatial discrimination in generalizations
- Population floor — species populations maintained at minimum 50% of carrying capacity, ensuring sufficient density for social interaction
- Birthplace modulation — PM initial state shaped by local conditions at spawn: Daffodil density boosts vitality/hunger, PM isolation boosts sociability, positive corner effects boost satisfaction, negative boost curiosity. Creates the comparative advantage between agents needed for viable trade.
- Social economy tracking — full funnel stats for OFFER and REQUEST actions (attempts, spatial failures, negotiation failures, successes), with trade flow tracking (what items exchanged, quantities, direction)
- Curiosity dynamics driven by epistemic accuracy — accurate predictions reduce curiosity, poor predictions raise it, replacing the old constant-upward-pressure model that pinned curiosity at ceiling
- CLI trial runner with progress bar, periodic mid-run state persistence (every 5K ticks), and SIGUSR1 signal handler for on-demand snapshots
- PM lifecycle tracking — all-time death causes, lifespan distribution, satisfaction and generalization counts at death
- CLI state analysis report with section flags (--population, --daffodil, --lifecycle, --social, --memory, --generalizations, --prohibitions, --events), deduplicated generalizations, prohibition content analysis
- FORAGE action — active foraging tied to Daffodil density and rain cycle, discoverable through inquiry
- Action delta visibility — tick pipeline restructured so action effects (trade deltas, effort costs) are captured in memory alongside environmental deltas. Previously invisible, blocking social action learning.
- Premature generalization — agents with low satisfaction can form generalizations from 2-3 agreeing memories at discounted RF. Higher consistency required (0.7 vs 0.6). Wrong guesses die fast; correct ones confirm normally.
- Dead agent skip in tickAll — performance fix, only living agents instantiated each tick. ~35% time savings at 50K.
- Generalization-at-death distribution in trial report
- Canvas-based browser visualization with offscreen gradient caching
- State persistence across sessions
What's Ahead
- Experience-derived trade valuations — Static weights in
evaluateExchangeDeltas()prevent comparative advantage. Agents with reliable vitality production should value vitality less in trade. Generalization predictions could inform trade pricing. This is the primary blocker for the OFFER economy (0 successes across 70K+ attempts). - Close the reproduction loop — Satisfaction has breached the 0.4 gate (max 0.556) but simultaneous fitness across all criteria has not yet co-occurred with REPRODUCE selection. The satisfaction normalization by generalization count may need revisiting.
- Prohibition inheritance — Negative knowledge (prohibited generalization signatures) through the epigenetic pool. Needs a confidence mechanism — frequency of prohibition across agents is one candidate.
- Proto-language — Tokens as compressed names for generalizations. The emergence sequence: full generalization transmission, then token proposal, then token-first communication, then propagation, then semantic drift. Grammar pressure arises from the need to disambiguate.
- Deeper hidden variable stacks — Both environmental and agent-side. Agents have properties they don't know about, discoverable through inquiry when matching environmental stressors surface them.
Expectations
This project is exploratory and the expectations should be calibrated accordingly.
What we are fairly confident will work: agents developing distinct behavioral signatures from identical starting conditions (Daffodils already do this); inquiry expanding representational capacity in response to genuine predictive inadequacy (implemented and working for both species); density-mediated population self-regulation (implemented and stable); generalizations emerging naturally from convergent memory clusters (implemented — agents reliably form rules like "high speed costs vitality regardless of direction"); epigenetic inheritance measurably accelerating descendant development (implemented — inherited agents start with pre-promoted qualifiers and environmental knowledge that would take hundreds of ticks to discover independently).
What is emerging and promising: generalization prohibition is driving qualitatively richer knowledge — agents learn speed discrimination (speed:1 costs 7x less vitality than speed:3), directional preferences (moving west at distance 1 is net positive), spatial awareness (y=high is costly, y=low is favorable), and social rules (offering curiosity during low season has specific costs, requesting satisfaction costs vitality). The prohibition regime produces a 3:1 ratio of negative to positive knowledge, and the negative knowledge prevents re-formation of overly-broad claims, forcing progressive specification. Satisfaction has breached the 0.4 reproduction gate (max 0.556), though simultaneous fitness across all criteria has not yet co-occurred. Action delta visibility — making action effects visible to the memory system — produced the largest single improvement, unlocking social action learning that was previously impossible.
What we think is plausible but unproven: that the reproduction loop will close as generalization quality improves; that OFFER/REQUEST will produce non-trivial exchange patterns at current PM density (maintained at 50% of carrying capacity); that proto-language tokens will emerge from the need to compress and transmit generalizations efficiently.
What would be genuinely surprising and is the real aspiration: proto-language emergence with measurable semantic drift; traceable knowledge genealogies across generations; population-level strategy diversity maintained without explicit diversity mechanisms. These are the outcomes that would suggest the architecture captures something structural about learning rather than just producing interesting-looking dynamics.
The simulation is not trying to produce artificial general intelligence or compete with modern ML. It is asking a narrower and (we think) more interesting question: whether the specific mechanisms of chemical memory, ratio-based behavioral modulation, and inquiry-driven representational expansion are sufficient to produce learning that looks qualitatively different from optimization — learning that carries the texture of its own history and changes not because a gradient points downhill but because accumulated experience becomes unbearable in its inadequacy.
Tech Stack
PHP 8.2, Laravel 12, Vue.js 3, Vite, SQLite. State persistence via JSON snapshots. Browser visualization via HTML5 Canvas.
Running
# Install dependencies
composer install && npm install
# Set up environment
cp .env.example .env && php artisan key:generate
# Run in browser
npm run dev
php artisan serve
# Run headless trial (with progress bar)
php artisan simulation:trial --ticks=1000 --summary --progress
# Analyze results
php artisan simulation:report