-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmurmuration.js
More file actions
219 lines (193 loc) · 7.56 KB
/
Copy pathmurmuration.js
File metadata and controls
219 lines (193 loc) · 7.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
/**
* Murmuration — Main Simulation Engine
* Gnosquam Swarm World Sim — Zero Dependencies — Rule-Based
*
* Traits wired:
* ST-1 Trust Battery — dynamic earned authority
* ST-2 Grief Variable — behavioral modifier, three exits
* #14 Epigenetic Memory — successful patterns strengthen
* #3 Pheromone Trail — failed patterns decay
* #31 Echolocation — frequency controls sim resolution
* #32 Lateral Line — pressure triggers cascade
* #33 Electroreception — anomaly modulates reactivity
* #34 PitViper Divergence — disturbance signal to world env
* #16 Mantis Shrimp — 16-band filter controls spawn
*
* NOT FOR PUBLIC USE — internal Gnosquam tool only.
* Embed via boardroom protected route.
*/
window.MurmurationModules = window.MurmurationModules || {};
window.MurmurationModules.MurmurationSim = class MurmurationSim {
/**
* @param {HTMLCanvasElement} canvas
* @param {object} opts
* @param {number} opts.agentCount — default 80
* @param {function} opts.onLog — (msg, type) => void — hook for boardroom log panel
* @param {function} opts.onEmerge — (emergence) => void — hook for boardroom metrics panel
*/
constructor(canvas, opts = {}) {
this.canvas = canvas;
this.agentCount = opts.agentCount || 80;
this.onLog = opts.onLog || null;
this.onEmerge = opts.onEmerge || null;
// Sub-engines
this.world = null;
this.seedInjector = new window.MurmurationModules.SeedInjector();
this.interactionEngine = new window.MurmurationModules.InteractionEngine();
this.evolutionEngine = new window.MurmurationModules.EvolutionEngine();
this.extractor = new window.MurmurationModules.EmergenceExtractor();
this.isRunning = false;
this.animationId = null;
this.timeStep = 1; // default — overridden by EcholocationFrequency
// Wire global logLine so sub-modules can emit
const self = this;
window.logLine = (msg, type = 'sys') => {
if (self.onLog) self.onLog(msg, type);
};
}
// ── Lifecycle ────────────────────────────────────────────────────────────
/**
* Initialize world with fresh agents.
* Safe to call repeatedly — stops any running sim first.
*/
init(agentCount) {
this.stop();
this.agentCount = agentCount || this.agentCount;
const w = this.canvas.width;
const h = this.canvas.height;
this.world = new window.MurmurationModules.World(w, h, this.agentCount);
this._draw();
if (window.logLine) {
window.logLine(`// World initialized — ${this.agentCount} agents — waiting for RUN`, 'sys');
}
return this;
}
start() {
if (!this.world) this.init();
this.isRunning = true;
const loop = () => {
if (!this.isRunning) return;
this._step();
this._draw();
const emergence = this.extract();
if (this.onEmerge) this.onEmerge(emergence);
this.animationId = requestAnimationFrame(loop);
};
loop();
return this;
}
stop() {
this.isRunning = false;
if (this.animationId) {
cancelAnimationFrame(this.animationId);
this.animationId = null;
}
return this;
}
reset() {
this.stop();
this.world = null;
const ctx = this.canvas.getContext('2d');
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
if (window.logLine) window.logLine('// Murmuration reset', 'sys');
return this;
}
// ── Single tick — callable externally for step-through mode ─────────────
tick() {
if (!this.world) return null;
this._step();
this._draw();
return this.extract();
}
// ── Seed injection ───────────────────────────────────────────────────────
/**
* Inject bio-trait signals directly.
* @param {object} signals — { PitViperDivergence, ElectroreceptionAnomaly, ... }
*/
inject(signals = {}) {
if (!this.world) return this;
this.seedInjector.inject(this.world, signals);
// EcholocationFrequency controls sim resolution
if (signals.EcholocationFrequency !== undefined) {
this.timeStep = Math.max(0.1, Math.min(3, signals.EcholocationFrequency * 3));
}
const active = Object.entries(signals)
.filter(([, v]) => v > 0)
.map(([k, v]) => `${k.replace(/Divergence|Anomaly|Pressure|Frequency|16Bands/g, '')}=${v.toFixed(2)}`)
.join(' ');
if (window.logLine) {
window.logLine(`▶ INJECT — ${active || 'all signals zero'} — watch emergence ↑`, 'seed');
}
return this;
}
// ── Emergence data ───────────────────────────────────────────────────────
extract() {
if (!this.world) return null;
return this.extractor.extract(this.world);
}
/**
* Snapshot for external systems (boardroom, n8n, Council).
* Serializable — no DOM refs.
*/
snapshot() {
const em = this.extract();
if (!em) return null;
return {
time: this.world.time,
agentCount: this.world.agents.length,
activeCount: this.world.agents.filter(a => !a.seppukuDone && !a.isSentinel).length,
prediction: em.prediction,
confidence: em.confidence,
consensus: em.consensus,
divergence: em.divergence,
stability: em.stability,
clusters: em.clusters,
cascadeVelocity: em.cascadeVelocity,
avgTrust: em.avgTrust,
highTrustCount: em.highTrustCount,
lowTrustCount: em.lowTrustCount,
avgGrief: em.avgGrief,
grievingCount: em.grievingCount,
crisisCount: em.crisisCount,
seppukuCount: em.seppukuCount,
dishonoredCount: em.dishonoredCount,
hasSentinel: em.hasSentinel,
sentinelId: em.sentinelId,
wisdomCount: em.wisdomCount,
env: { ...this.world.env },
ts: Date.now()
};
}
// ── Private ──────────────────────────────────────────────────────────────
_step() {
this.interactionEngine.computeInteractions(this.world);
this.world.advanceStep();
this.evolutionEngine.evolve(this.world);
}
_draw() {
if (this.world) this.world.draw(this.canvas.getContext('2d'));
}
};
// ── Top-level factory — used by boardroom embed ──────────────────────────
/**
* Mount Murmuration onto a canvas element.
* Returns the MurmurationSim instance for external control.
*
* Usage:
* const sim = Murmuration.mount('canvas', { onLog, onEmerge });
* sim.init(80).start();
*/
window.Murmuration = {
mount(canvasId, opts = {}) {
const canvas = typeof canvasId === 'string'
? document.getElementById(canvasId)
: canvasId;
if (!canvas) throw new Error(`Murmuration.mount: canvas '${canvasId}' not found`);
const sim = new window.MurmurationModules.MurmurationSim(canvas, opts);
window._murmurationInstance = sim;
return sim;
},
/** Get the running instance (for console access) */
get instance() { return window._murmurationInstance || null; }
};