conscious-agent
v3.0.0
Published
Self-referential structure-learning system — agents that learn by inhabiting worlds
Maintainers
Readme
conscious-agent
An executable model of Donald Hoffman's conscious-agent formalism — in Node.js.
Build self-referential agents that learn by inhabiting worlds. Zero external dependencies.
For AI coding assistants: A
SKILL.mdfile lives in.context/SKILL.mdwith patterns for complex use cases (multi-agent networks, live data feeding, debugging). opencode and compatible tools load it automatically.
const { ConsciousAgent } = require('conscious-agent');
const { CoinTossWorld } = require('conscious-agent/worlds');
const world = new CoinTossWorld(4);
const agent = new ConsciousAgent({ agentId: 'my_agent', world });
const outputs = agent.run(1000);
console.log(`"I" locked: ${agent.isILocked}`);Installation
npm install conscious-agent # once publishedor directly From Git
npm install github:ben42-01/hoffman-agentsOr from source:
cd hoffman-agents-node
npm link # or copy src/ into your projectQuick Start
Single agent in a coin-toss world
const { ConsciousAgent } = require('conscious-agent');
const { CoinTossWorld } = require('conscious-agent/worlds');
const world = new CoinTossWorld(3);
const agent = new ConsciousAgent({ agentId: 'coin_agent', world });
for (let i = 0; i < 500; i++) {
const output = agent.step();
if (output.iLocked) {
console.log(`I locked at step ${output.step}`);
break;
}
}Custom Markov world
const { ConsciousAgent, WorldBuilder } = require('conscious-agent');
const data = Array.from({ length: 500 }, () => [Math.random(), Math.random(), Math.random()]);
const world = new WorldBuilder()
.addFeature('temp', 'minmax', 4)
.addFeature('humidity', 'minmax', 4)
.addFeature('pressure', 'minmax', 4)
.build(data);
const agent = new ConsciousAgent({ agentId: 'weather_agent', world });
const outputs = agent.run(1000);Build world from JSON data (v2.1)
const { buildWorldFromDataFrame } = require('conscious-agent');
const rows = [
{ temperature: 23.5, humidity: 65, pressure: 1013 },
{ temperature: 24.1, humidity: 63, pressure: 1011 },
// ...
];
const world = buildWorldFromDataFrame(rows);
// Auto-detects numeric columns, or pass explicit feature specsPredict next state (v2.1)
const prediction = agent.predictNext();
if (prediction) {
console.log(`Expecting state ${prediction.stateId} (conf: ${prediction.confidence.toFixed(2)})`);
const top3 = prediction.topK(3);
}Combine two agents
const { combine } = require('conscious-agent');
const a = new ConsciousAgent({ agentId: 'agent_a', world });
const b = new ConsciousAgent({ agentId: 'agent_b', world });
a.run(500);
b.run(500);
const combined = combine(a, b);
console.log(`Combined agent: ${combined.agentId}, level: ${combined.cycleLevel}`);Multi-agent network
const { AgentNetwork } = require('conscious-agent');
const network = new AgentNetwork({ nAgents: 10, seed: 42 });
const states = network.run(100);
console.log(`Avg prediction error: ${network.avgPredictionError().toFixed(3)}`);Save and load
const { saveAgent, loadAgent, cloneAgent } = require('conscious-agent/io');
const path = saveAgent(agent, './souls');
const loaded = loadAgent(path);
const cloned = cloneAgent(agent, 'experiment_clone');Public API
// Core classes
const { ConsciousAgent, World, WorldBuilder } = require('conscious-agent');
const { SimpleWorld, ExperienceSpace, Prediction } = require('conscious-agent');
// World factories
const { CoinTossWorld, SelfWorld, Normalizer, FeatureSpec } = require('conscious-agent/worlds');
const { buildWorldFromDataFrame } = require('conscious-agent');
// IO
const { saveAgent, loadAgent, cloneAgent, loadLatest, clone } = require('conscious-agent/io');
// Multi-agent
const { AgentNetwork, Topology, InteractionCycle, combine } = require('conscious-agent');
// Core components
const { TraceBuffer, TraceEvent, ExperienceTrie, TrieNode } = require('conscious-agent');
const { MetaTrie, MetaStateSnapshot, SelfTokenState, ExperienceLexicon, LexiconEntry } = require('conscious-agent');
// Utilities
const { strangeLoopScore, computeSelfReferenceScore, populationReferenceScore } = require('conscious-agent');
const { prune, traceDistance, mergeSimilarPaths, inventToken, isInventedToken } = require('conscious-agent');
const { SharedMeaningTracker, EnvironmentState, sequenceToStateId } = require('conscious-agent');
// v2.1 — Predict next state
agent.predictNext(); // → Prediction { stateId, stateLabel, confidence, topK(n) }
prediction.topK(3); // top 3 alternatives with confidence
// v2.1 — Config-driven construction
ConsciousAgent.fromConfig('id', { agent: { selfToken: { lockThreshold: 0.3 } } });
// v2.1 — Topology introspection
topology.getConnectionStrength(0, 1); // query connection weight
topology.maybeAddConnection(0, 5); // add link probabilistically
topology.getAgentObservers(3); // who observes agent 3?
// v2.0 — Agent mode control
agent.setMode('frozen'); // deterministic projection, no trie/meta updates
agent.thaw(); // back to learning mode
agent.refreeze(); // back to frozen
// v2.0 — Memory & lifecycle
agent.clearMemory(); // reset trace buffer + counters, preserve trie/lexicon
agent.injectObservation(worldState); // push new data mid-run without reset
// v2.0 — Metrics & introspection
agent.metrics; // { predictionError, iLocked, loopDepth, outputTokens }
network.getMetrics(); // { agentCount, meanPredictionError, iLockRate, ... }
network.getAgentMetrics(id); // individual agent's metrics snapshot
trie.getStats(); // { nodeCount, maxDepth, meanVisitCount, depthDistribution }
trie.exportNodes(3); // all paths with visitCount >= 3
trie.getDominantPaths(5); // top 5 most-visited paths
// v2.0 — Batch stepping
network.stepAll(worldState); // step all agents with same world state
network.agentList; // agents as an ordered array
// v2.0 — Action space
output.actionDistribution; // { token: probability, ... } — full distribution
new ConsciousAgent({ allowableTokens: ['I', 'notice'] }); // constrain output
agent.setAllowableTokens(['I', 'notice', 'familiar']);
// v2.0 — Composition
combine(a, b, c); // n-ary combination (3+ agents)
fuse(combined); // decompose back into constituents
// v2.0 — TraceBuffer
traceBuffer.resize(100); // dynamic window resizing
// v2.0 — Trie compression
prune(trie, 5); // remove nodes with < 5 visits
traceDistance(pathA, pathB); // edit distance with transition-aware cost
mergeSimilarPaths(trie, matrix, 0.15); // merge paths within thresholdSelf-Modelling
Agents contain four self-modelling mechanisms. They are mechanisms; whether any of them amounts to self-awareness is not something the code can establish.
| Mechanism | Type | What it does |
|-----------|------|-------------|
| MetaTrie | Built-in | A Markov chain over the agent's own coarse self-observations |
| SelfTokenState ("I") | Built-in | Locks when that chain has a stable attractor; unlocks when it dissolves |
| strangeLoopScore | Built-in | Counts self-reference in output tokens (mostly reflects time in the core output mode) |
| SelfWorld | Optional wrapper | Feeds the agent's internal metrics back into its perception |
SelfWorld
SelfWorld is a world wrapper that lets the agent perceive its own internal state alongside external data. The agent's trie learns transitions over composite states of (world + self).
const inner = new SimpleWorld({ nStates: 10 });
const agent = new ConsciousAgent({
agentId: 'self_aware',
world: new SelfWorld(inner, (self) => ({
sp: self.experience.selfToken.stationaryProb,
pe: self.meanPredictionError,
})),
});
agent.run(1000);Each step, the agent's WorldState contains both 'world' and 'self' sequences. The agent discovers patterns like "when my prediction error is high and the world shows pattern X, the next state tends to be Y."
→ What these mechanisms do and do not show: docs/SELF_AWARENESS.md
How It Works
Every ConsciousAgent has an experience space — four interconnected structures:
- TraceBuffer — short-term memory: the last N state transitions
- ExperienceTrie — long-term world model: compressed prefix tree over observed state sequences
- MetaTrie — self-model: a Markov chain over the agent's own coarse self-observations
- SelfTokenState ("I") — identity: locks onto a stable attractor of the self-model
The agent cycles through perception → meta-observation → decision (generate output tokens via the decision kernel D).
The "I" locks when the agent's self-observation chain has a clear, stable attractor: enough data, aperiodic, one state well above the uniform baseline, currently occupied. It unlocks with hysteresis when the attractor dissolves. It fires in worlds with structure and not in noise. agent.ergodicStats() reports the criteria, and agent.toFormal() exports the learned kernels as a (X, G, P, D, A, N) tuple. The mathematics is in docs/MATHEMATICAL_MODEL.md.
Version 3 changed the math (see RELEASE_NOTES_v3.0.0.md). Pass { mathVersion: 'legacy' } to reproduce 2.x behaviour exactly, and seed: 1 for reproducible runs, identical across Node and Python.
Experiments
The examples/ directory holds experiments, each with controls. Highlights:
- 13 Bell test through the headset: correlations produced by a conscious-agent network behind spacetime; best CHSH = 2 + 2·δ(Qᵏ) (
npm run examples:bellThroughTheHeadset) - 14 Spacetime in the headset: an observer recovers dimension from experience; ⊗ adds dimensions and interaction binds them (
npm run examples:spacetimeInTheHeadset) - 15 Time in the traces: Hoffman's trace chains; per-observer clocks and an observer-dependent arrow of time (
npm run examples:timeInTheTraces) - 16 Trace logic and decorated permutations: Hoffman's map to the positive Grassmannian's combinatorics, checked against the paper; trace logic's structure; mass and speed proposals stress-tested (
npm run examples:traceLogic) - 17 Quantum agents: kernels as quantum channels; combined agents reach exactly 2√2; Markov agents as the decohered limit (
npm run examples:quantumAgents) - 18 Relativity at infinity: as n → ∞ an agent's clock converges to Einstein's proper time; a light cone needs memory (
npm run examples:relativityAtInfinity) - 02 Quantum signature?: why an earlier "quantum-like" signature was an artifact
- 05 Self-reference ablation and 12 ergodic diagnostics: the "I" lock tracks structure
Documentation
MATHEMATICAL_MODEL.md · Q_AND_A.md (results, limitations, corrections) · COMPONENT_DEFINITIONS.md · CONSCIOUS_AGENTS_VISUAL_GUIDE.md · SELF_AWARENESS.md · GLOSSARY.md · CONSCIOUS_AGENTS_THEORY.md (design document)
Requirements
- Node.js >= 18
- No external dependencies
License
MIT
