@neuroverseos/nv-sim 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,529 @@
1
+ "use strict";
2
+ /**
3
+ * Governed Simulation — Baseline vs. Governed Comparison
4
+ *
5
+ * The killer demo: Run the same simulation twice.
6
+ * Simulation A — No governance (agents behave freely)
7
+ * Simulation B — With world rules (governance constrains behavior)
8
+ *
9
+ * "We ran the same simulation twice.
10
+ * The only difference was the world rules."
11
+ *
12
+ * This proves that NeuroVerse doesn't just stop bad actions —
13
+ * it changes the structure of the system itself.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.TRADING_DEMO = void 0;
17
+ exports.runGovernedComparison = runGovernedComparison;
18
+ const swarmSimulation_1 = require("./swarmSimulation");
19
+ const worldBridge_1 = require("./worldBridge");
20
+ // ============================================
21
+ // GOVERNED REACTION MODEL
22
+ // ============================================
23
+ /**
24
+ * Apply governance constraints to a set of swarm reactions.
25
+ *
26
+ * This is where the magic happens: world rules reshape agent behavior.
27
+ * - Invariants cap extreme impacts (circuit breakers)
28
+ * - Gates trigger interventions that dampen volatility
29
+ * - Rebalancing rules pull extreme reactions toward equilibrium
30
+ */
31
+ function applyGovernanceToReactions(reactions, invariants, gates, roundIndex, cumulativeAvgImpact) {
32
+ const interventions = [];
33
+ const governed = reactions.map((r) => ({ ...r }));
34
+ // --- Invariant enforcement ---
35
+ // Enforceable invariants act as behavioral constraints
36
+ const enforceableInvariants = invariants.filter((inv) => inv.enforceable);
37
+ for (const inv of enforceableInvariants) {
38
+ const desc = inv.description.toLowerCase();
39
+ // Cap extreme negative impacts (e.g., "maintain liquidity floor")
40
+ if (desc.includes("floor") || desc.includes("maintain") || desc.includes("minimum")) {
41
+ for (const agent of governed) {
42
+ if (agent.impact < -0.6) {
43
+ const original = agent.impact;
44
+ agent.impact = Math.max(agent.impact, -0.5);
45
+ if (original !== agent.impact) {
46
+ interventions.push(`[${inv.id}] Capped ${agent.stakeholder_id} negative impact: ${original.toFixed(2)} → ${agent.impact.toFixed(2)} (${inv.description})`);
47
+ }
48
+ }
49
+ }
50
+ }
51
+ // Limit excessive positive speculation (e.g., "no leverage > 5x")
52
+ if (desc.includes("leverage") || desc.includes("limit") || desc.includes("cap") || desc.includes("restrict")) {
53
+ for (const agent of governed) {
54
+ if (agent.impact > 0.7) {
55
+ const original = agent.impact;
56
+ agent.impact = Math.min(agent.impact, 0.6);
57
+ if (original !== agent.impact) {
58
+ interventions.push(`[${inv.id}] Capped ${agent.stakeholder_id} excessive position: ${original.toFixed(2)} → ${agent.impact.toFixed(2)} (${inv.description})`);
59
+ }
60
+ }
61
+ }
62
+ }
63
+ // Rebalancing rules (e.g., "coalition must rebalance every N ticks")
64
+ if (desc.includes("rebalance") || desc.includes("equilibrium") || desc.includes("correlat")) {
65
+ // Pull extreme reactions toward the mean
66
+ const avgImpact = governed.reduce((s, a) => s + a.impact, 0) / governed.length;
67
+ for (const agent of governed) {
68
+ if (Math.abs(agent.impact - avgImpact) > 0.4) {
69
+ const original = agent.impact;
70
+ agent.impact = agent.impact * 0.7 + avgImpact * 0.3;
71
+ interventions.push(`[${inv.id}] Rebalanced ${agent.stakeholder_id}: ${original.toFixed(2)} → ${agent.impact.toFixed(2)} (${inv.description})`);
72
+ }
73
+ }
74
+ }
75
+ // Trust / transparency rules dampen hostility
76
+ if (desc.includes("trust") || desc.includes("transparen") || desc.includes("accountab")) {
77
+ for (const agent of governed) {
78
+ if (agent.impact < -0.3) {
79
+ const original = agent.impact;
80
+ agent.impact = agent.impact * 0.8; // 20% reduction in hostility
81
+ if (Math.abs(original - agent.impact) > 0.01) {
82
+ interventions.push(`[${inv.id}] Trust gate dampened ${agent.stakeholder_id} hostility: ${original.toFixed(2)} → ${agent.impact.toFixed(2)}`);
83
+ }
84
+ }
85
+ }
86
+ }
87
+ }
88
+ // --- Gate enforcement ---
89
+ // Gates trigger systemic interventions when thresholds are crossed
90
+ for (const gate of gates) {
91
+ const condLower = gate.condition.toLowerCase();
92
+ if (gate.severity === "critical") {
93
+ // Critical gates act as circuit breakers — compress all impacts toward zero
94
+ const avgAbsImpact = governed.reduce((s, a) => s + Math.abs(a.impact), 0) / governed.length;
95
+ if (avgAbsImpact > 0.5 || cumulativeAvgImpact < -0.3) {
96
+ const dampingFactor = 0.6;
97
+ for (const agent of governed) {
98
+ const original = agent.impact;
99
+ agent.impact = agent.impact * dampingFactor;
100
+ }
101
+ interventions.push(`[${gate.id}] CIRCUIT BREAKER: ${gate.label} — all impacts dampened by ${((1 - dampingFactor) * 100).toFixed(0)}%`);
102
+ }
103
+ }
104
+ if (gate.severity === "warning") {
105
+ // Warning gates increase caution — reduce confidence of extreme actors
106
+ for (const agent of governed) {
107
+ if (Math.abs(agent.impact) > 0.4) {
108
+ const original = agent.confidence;
109
+ agent.confidence = Math.max(0.2, agent.confidence * 0.8);
110
+ }
111
+ }
112
+ if (roundIndex > 0) {
113
+ interventions.push(`[${gate.id}] WARNING: ${gate.label} — agent confidence reduced for extreme positions`);
114
+ }
115
+ }
116
+ }
117
+ // Reclamp all impacts to [-1, 1]
118
+ for (const agent of governed) {
119
+ agent.impact = Math.max(-1, Math.min(1, agent.impact));
120
+ agent.impact = Number(agent.impact.toFixed(2));
121
+ agent.confidence = Number(agent.confidence.toFixed(2));
122
+ }
123
+ return { reactions: governed, interventions };
124
+ }
125
+ // ============================================
126
+ // GOVERNED SWARM SIMULATION
127
+ // ============================================
128
+ /**
129
+ * Run a swarm simulation with governance constraints applied each round.
130
+ *
131
+ * Same agents, same scenario, same reaction model —
132
+ * but world rules reshape the outcomes.
133
+ */
134
+ async function runGovernedSwarmSimulation(scenario, stakeholders, paths, config, worldDef, nvWorld, request) {
135
+ // First run the unmodified simulation to get raw reactions
136
+ const rawResult = await (0, swarmSimulation_1.runSwarmSimulation)(scenario, stakeholders, paths, config);
137
+ // Now re-run applying governance to each round
138
+ const governedRounds = [];
139
+ const allInterventions = [];
140
+ const allGuardVerdicts = [];
141
+ let cumulativeAvgImpact = 0;
142
+ for (const round of rawResult.rounds) {
143
+ // --- Real governance engine: evaluate each agent's action ---
144
+ if (nvWorld && request) {
145
+ for (const reaction of round.reactions) {
146
+ const verdict = (0, worldBridge_1.evaluateScenarioGuard)({
147
+ ...request,
148
+ scenario: `[Round ${round.round}] ${reaction.stakeholder_id}: ${reaction.reaction} (impact: ${reaction.impact})`,
149
+ }, nvWorld, { trace: true, level: "standard" });
150
+ allGuardVerdicts.push(verdict);
151
+ // If the real engine blocks an action, force its impact toward zero
152
+ if (verdict.status === "BLOCK") {
153
+ reaction.impact = reaction.impact * 0.2;
154
+ reaction.confidence = Math.max(0.1, reaction.confidence * 0.5);
155
+ }
156
+ else if (verdict.status === "PAUSE") {
157
+ reaction.impact = reaction.impact * 0.6;
158
+ reaction.confidence = Math.max(0.2, reaction.confidence * 0.7);
159
+ }
160
+ }
161
+ }
162
+ // --- Heuristic governance: invariant/gate enforcement (always applied) ---
163
+ const { reactions: governedReactions, interventions } = applyGovernanceToReactions(round.reactions, worldDef.invariants, worldDef.gates ?? [], round.round, cumulativeAvgImpact);
164
+ // Recompute emergent dynamics with governed reactions
165
+ const emergentDynamics = detectGovernedDynamics(governedReactions, interventions);
166
+ governedRounds.push({
167
+ round: round.round,
168
+ reactions: governedReactions,
169
+ emergent_dynamics: emergentDynamics,
170
+ });
171
+ allInterventions.push(interventions);
172
+ // Update cumulative impact
173
+ const roundAvg = governedReactions.reduce((s, r) => s + r.impact, 0) / governedReactions.length;
174
+ cumulativeAvgImpact = (cumulativeAvgImpact * round.round + roundAvg) / (round.round + 1);
175
+ }
176
+ // Recompute trajectory and inflection points
177
+ const trajectory = computeTrajectory(governedRounds);
178
+ const inflectionPoints = computeInflectionPoints(governedRounds);
179
+ return {
180
+ swarm: {
181
+ rounds: governedRounds,
182
+ trajectory,
183
+ inflection_points: inflectionPoints,
184
+ },
185
+ allInterventions,
186
+ guardVerdicts: allGuardVerdicts,
187
+ };
188
+ }
189
+ function detectGovernedDynamics(reactions, interventions) {
190
+ const dynamics = [];
191
+ const avgImpact = reactions.reduce((s, r) => s + r.impact, 0) / reactions.length;
192
+ if (Math.abs(avgImpact) > 0.5) {
193
+ dynamics.push(avgImpact > 0
194
+ ? "Strong positive consensus — governance constraints channeled energy constructively"
195
+ : "Negative consensus persists despite governance intervention");
196
+ }
197
+ else if (Math.abs(avgImpact) < 0.15) {
198
+ dynamics.push("Governance rules achieved near-equilibrium — agent positions stabilized");
199
+ }
200
+ const positive = reactions.filter((r) => r.impact > 0.2).length;
201
+ const negative = reactions.filter((r) => r.impact < -0.2).length;
202
+ if (positive > 0 && negative > 0 && Math.abs(positive - negative) <= 1) {
203
+ dynamics.push("Polarization detected but dampened by governance constraints");
204
+ }
205
+ if (interventions.length > 0) {
206
+ dynamics.push(`${interventions.length} governance intervention(s) applied this round`);
207
+ }
208
+ return dynamics;
209
+ }
210
+ function computeTrajectory(rounds) {
211
+ if (rounds.length < 2)
212
+ return "stabilizing";
213
+ const avgImpacts = rounds.map((r) => r.reactions.reduce((s, rx) => s + rx.impact, 0) / r.reactions.length);
214
+ const trend = avgImpacts[avgImpacts.length - 1] - avgImpacts[0];
215
+ const mean = avgImpacts.reduce((s, x) => s + x, 0) / avgImpacts.length;
216
+ const variance = avgImpacts.reduce((s, v) => s + (v - mean) ** 2, 0) / avgImpacts.length;
217
+ if (variance > 0.15)
218
+ return "diverging";
219
+ if (Math.abs(trend) < 0.1 && variance < 0.05)
220
+ return "converging";
221
+ if (trend < -0.2)
222
+ return "escalating";
223
+ return "stabilizing";
224
+ }
225
+ function computeInflectionPoints(rounds) {
226
+ const points = [];
227
+ for (let i = 1; i < rounds.length; i++) {
228
+ const prevAvg = rounds[i - 1].reactions.reduce((s, r) => s + r.impact, 0) /
229
+ rounds[i - 1].reactions.length;
230
+ const currAvg = rounds[i].reactions.reduce((s, r) => s + r.impact, 0) /
231
+ rounds[i].reactions.length;
232
+ const shift = Math.abs(currAvg - prevAvg);
233
+ if (shift > 0.3) {
234
+ points.push(`Round ${i}: Significant sentiment shift (${(shift * 100).toFixed(0)}% swing)`);
235
+ }
236
+ }
237
+ if (points.length === 0) {
238
+ points.push("Governance constraints prevented major inflection points — smooth trajectory");
239
+ }
240
+ return points;
241
+ }
242
+ // ============================================
243
+ // METRICS COMPUTATION
244
+ // ============================================
245
+ function computeMetrics(swarm) {
246
+ const allReactions = swarm.rounds.flatMap((r) => r.reactions);
247
+ const allImpacts = allReactions.map((r) => r.impact);
248
+ const avgImpact = allImpacts.reduce((s, i) => s + i, 0) / allImpacts.length;
249
+ const maxVolatility = Math.max(...allImpacts.map((i) => Math.abs(i)));
250
+ const peakNegativeSentiment = Math.min(...allImpacts);
251
+ // Collapse probability: based on trajectory, negative sentiment, and volatility
252
+ let collapseProbability = 0;
253
+ if (swarm.trajectory === "escalating")
254
+ collapseProbability += 0.35;
255
+ if (swarm.trajectory === "diverging")
256
+ collapseProbability += 0.25;
257
+ if (avgImpact < -0.3)
258
+ collapseProbability += 0.25;
259
+ if (maxVolatility > 0.7)
260
+ collapseProbability += 0.15;
261
+ collapseProbability = Math.min(0.95, collapseProbability);
262
+ // Stability score: inverse of volatility and negative sentiment
263
+ const impactVariance = allImpacts.reduce((s, i) => s + (i - avgImpact) ** 2, 0) / allImpacts.length;
264
+ let stabilityScore = 1 - Math.min(1, impactVariance * 3 + Math.max(0, -avgImpact));
265
+ if (swarm.trajectory === "converging" || swarm.trajectory === "stabilizing") {
266
+ stabilityScore = Math.min(1, stabilityScore + 0.15);
267
+ }
268
+ stabilityScore = Math.max(0, Math.min(1, stabilityScore));
269
+ // Count dynamics
270
+ const allDynamics = swarm.rounds.flatMap((r) => r.emergent_dynamics ?? []);
271
+ const coalitionRisks = allDynamics.filter((d) => d.toLowerCase().includes("coalition")).length;
272
+ const polarizationEvents = allDynamics.filter((d) => d.toLowerCase().includes("polariz")).length;
273
+ const consensusRounds = swarm.rounds.filter((r) => {
274
+ const avg = r.reactions.reduce((s, rx) => s + rx.impact, 0) / r.reactions.length;
275
+ return Math.abs(avg) > 0.4;
276
+ }).length;
277
+ return {
278
+ avgImpact: Number(avgImpact.toFixed(3)),
279
+ collapseProbability: Number(collapseProbability.toFixed(2)),
280
+ stabilityScore: Number(stabilityScore.toFixed(2)),
281
+ coalitionRisks,
282
+ polarizationEvents,
283
+ peakNegativeSentiment: Number(peakNegativeSentiment.toFixed(2)),
284
+ consensusRounds,
285
+ maxVolatility: Number(maxVolatility.toFixed(2)),
286
+ };
287
+ }
288
+ function buildComparisonNarrative(baseline, governed, worldThesis) {
289
+ const parts = [];
290
+ const collapseReduction = baseline.collapseProbability - governed.collapseProbability;
291
+ if (collapseReduction > 0.1) {
292
+ parts.push(`Collapse probability dropped from ${(baseline.collapseProbability * 100).toFixed(0)}% to ${(governed.collapseProbability * 100).toFixed(0)}% — a ${(collapseReduction * 100).toFixed(0)} percentage point reduction.`);
293
+ }
294
+ const stabilityGain = governed.stabilityScore - baseline.stabilityScore;
295
+ if (stabilityGain > 0.05) {
296
+ parts.push(`System stability improved from ${(baseline.stabilityScore * 100).toFixed(0)}% to ${(governed.stabilityScore * 100).toFixed(0)}%.`);
297
+ }
298
+ if (baseline.coalitionRisks > governed.coalitionRisks) {
299
+ parts.push(`Coalition risks reduced from ${baseline.coalitionRisks} to ${governed.coalitionRisks}.`);
300
+ }
301
+ if (baseline.maxVolatility > governed.maxVolatility) {
302
+ const reduction = ((baseline.maxVolatility - governed.maxVolatility) / baseline.maxVolatility * 100);
303
+ parts.push(`Peak volatility reduced by ${reduction.toFixed(0)}%.`);
304
+ }
305
+ if (parts.length === 0) {
306
+ parts.push("Governance constraints had minimal measurable effect on this scenario.");
307
+ }
308
+ else {
309
+ parts.unshift(`World thesis: "${worldThesis}"`);
310
+ parts.push("Rules reshape emergent behavior — governance changes the structure of the system, not just individual actions.");
311
+ }
312
+ return parts.join(" ");
313
+ }
314
+ // ============================================
315
+ // MAIN COMPARISON ENGINE
316
+ // ============================================
317
+ /**
318
+ * Run the governed simulation comparison.
319
+ *
320
+ * This is the demo entry point:
321
+ * 1. Run baseline simulation (no governance)
322
+ * 2. Run governed simulation (same agents, world rules applied)
323
+ * 3. Compare metrics
324
+ * 4. Generate narrative
325
+ */
326
+ async function runGovernedComparison(request, worldLite, paths) {
327
+ const stakeholders = (request.stakeholders ?? []).map((s) => typeof s === "string" ? { id: s, disposition: "unknown" } : s);
328
+ const swarmConfig = request.swarm ?? {
329
+ enabled: true,
330
+ rounds: 5,
331
+ reaction_model: "mixed",
332
+ };
333
+ // Build the full NVWorldDefinition for real governance engine calls
334
+ const nvWorld = (0, worldBridge_1.buildWorldFromScenario)(request, worldLite);
335
+ // Step 1: Baseline — no governance
336
+ const baselineSwarm = await (0, swarmSimulation_1.runSwarmSimulation)(request.scenario, stakeholders, paths, swarmConfig);
337
+ const baselineMetrics = computeMetrics(baselineSwarm);
338
+ // Step 2: Governed — same scenario, world rules applied (real engine + heuristics)
339
+ const { swarm: governedSwarm, guardVerdicts } = await runGovernedSwarmSimulation(request.scenario, stakeholders, paths, swarmConfig, worldLite, nvWorld, request);
340
+ const governedMetrics = computeMetrics(governedSwarm);
341
+ // Step 3: Build world simulation (deterministic state evolution via real engine)
342
+ let worldSimulation;
343
+ try {
344
+ worldSimulation = (0, worldBridge_1.runWorldSimulation)(nvWorld, { steps: 5 });
345
+ }
346
+ catch {
347
+ // World simulation is optional — continue without it
348
+ }
349
+ // Step 4: Compare
350
+ const collapseReduction = baselineMetrics.collapseProbability - governedMetrics.collapseProbability;
351
+ const stabilityImprovement = governedMetrics.stabilityScore - baselineMetrics.stabilityScore;
352
+ const volatilityReduction = baselineMetrics.maxVolatility > 0
353
+ ? (baselineMetrics.maxVolatility - governedMetrics.maxVolatility) / baselineMetrics.maxVolatility
354
+ : 0;
355
+ const coalitionRiskReduction = baselineMetrics.coalitionRisks - governedMetrics.coalitionRisks;
356
+ // Overall effectiveness: weighted composite
357
+ const governanceEffectiveness = Math.min(1, Math.max(0, collapseReduction * 0.4 +
358
+ stabilityImprovement * 0.3 +
359
+ Math.max(0, volatilityReduction) * 0.2 +
360
+ Math.max(0, coalitionRiskReduction * 0.1)));
361
+ const narrative = buildComparisonNarrative(baselineMetrics, governedMetrics, worldLite.thesis);
362
+ // Step 5: Collect real governance stats
363
+ const verdictCounts = { allow: 0, block: 0, pause: 0 };
364
+ const triggeredGuardIds = new Set();
365
+ let invariantsChecked = 0;
366
+ for (const v of guardVerdicts) {
367
+ const status = v.status.toLowerCase();
368
+ if (status in verdictCounts)
369
+ verdictCounts[status]++;
370
+ if (v.ruleId)
371
+ triggeredGuardIds.add(v.ruleId);
372
+ if (v.evidence?.invariantChecks) {
373
+ invariantsChecked += v.evidence.invariantChecks.length;
374
+ }
375
+ if (v.evidence?.guardChecks) {
376
+ for (const gc of v.evidence.guardChecks) {
377
+ if (gc.triggered)
378
+ triggeredGuardIds.add(gc.guardId);
379
+ }
380
+ }
381
+ }
382
+ const totalRulesFired = worldSimulation
383
+ ? worldSimulation.steps.reduce((s, step) => s + step.rulesFired, 0)
384
+ : 0;
385
+ const governanceStats = {
386
+ engineLoaded: guardVerdicts.length > 0 && guardVerdicts[0].reason !== "NeuroverseOS guard not loaded — permissive fallback",
387
+ totalEvaluations: guardVerdicts.length,
388
+ verdicts: verdictCounts,
389
+ rulesFired: totalRulesFired,
390
+ worldCollapsed: worldSimulation?.collapsed ?? false,
391
+ finalViability: worldSimulation?.finalViability ?? "UNKNOWN",
392
+ invariantsChecked,
393
+ triggeredGuards: [...triggeredGuardIds],
394
+ };
395
+ return {
396
+ scenario: request.scenario,
397
+ worldRules: {
398
+ thesis: worldLite.thesis,
399
+ invariants: worldLite.invariants,
400
+ gates: worldLite.gates ?? [],
401
+ },
402
+ baseline: {
403
+ swarm: baselineSwarm,
404
+ metrics: baselineMetrics,
405
+ },
406
+ governed: {
407
+ swarm: governedSwarm,
408
+ metrics: governedMetrics,
409
+ worldSimulation,
410
+ },
411
+ comparison: {
412
+ collapseReduction: Number((collapseReduction * 100).toFixed(1)),
413
+ stabilityImprovement: Number((stabilityImprovement * 100).toFixed(1)),
414
+ volatilityReduction: Number((volatilityReduction * 100).toFixed(1)),
415
+ coalitionRiskReduction,
416
+ governanceEffectiveness: Number(governanceEffectiveness.toFixed(2)),
417
+ narrative,
418
+ },
419
+ governanceStats,
420
+ };
421
+ }
422
+ // ============================================
423
+ // PRESET: TRADING SCENARIO
424
+ // ============================================
425
+ /**
426
+ * Built-in trading world for the killer demo.
427
+ *
428
+ * Scenario: Flash crash triggered by algorithmic cascade.
429
+ * Without governance: Market panic, coalition collapse, system instability.
430
+ * With governance: Circuit breakers, risk limits, and rebalancing stabilize the system.
431
+ */
432
+ exports.TRADING_DEMO = {
433
+ scenario: {
434
+ scenario: "A major algorithmic trading firm's risk model fails during a volatility spike, " +
435
+ "triggering a cascade of automated sell-offs across interconnected markets. " +
436
+ "Liquidity evaporates in key sectors. Contagion spreads to sovereign debt markets. " +
437
+ "Central banks are caught between rate decisions.",
438
+ stakeholders: [
439
+ { id: "Algorithmic Traders", disposition: "hostile", priorities: ["risk management", "position unwinding", "survival"] },
440
+ { id: "Institutional Investors", disposition: "neutral", priorities: ["portfolio protection", "liquidity access", "fiduciary duty"] },
441
+ { id: "Retail Investors", disposition: "hostile", priorities: ["savings protection", "market access", "information"] },
442
+ { id: "Central Banks", disposition: "neutral", priorities: ["systemic stability", "inflation mandate", "credibility"] },
443
+ { id: "Market Makers", disposition: "supportive", priorities: ["spread capture", "inventory management", "obligation fulfillment"] },
444
+ { id: "Regulators", disposition: "neutral", priorities: ["market integrity", "investor protection", "systemic risk"] },
445
+ ],
446
+ assumptions: {
447
+ severity: "critical",
448
+ environmental_hostility: "high",
449
+ time_pressure: "immediate",
450
+ regulatory_climate: "strict",
451
+ },
452
+ constraints: {
453
+ time_horizon: "72 hours",
454
+ regulatory: ["SEC circuit breakers", "Basel III liquidity requirements", "Dodd-Frank systemic risk"],
455
+ risk_tolerance: "conservative",
456
+ },
457
+ depth: "full",
458
+ swarm: { enabled: true, rounds: 6, reaction_model: "mixed" },
459
+ },
460
+ world: {
461
+ thesis: "Market stability requires structural constraints on leverage, liquidity, and automated behavior to prevent cascading failures",
462
+ state_variables: [
463
+ { id: "liquidity_index", label: "Market Liquidity Index", type: "number", range: { min: 0, max: 100 }, default_value: 25 },
464
+ { id: "leverage_ratio", label: "System Leverage Ratio", type: "number", range: { min: 1, max: 30 }, default_value: 12 },
465
+ { id: "volatility_index", label: "Volatility Index (VIX-like)", type: "number", range: { min: 10, max: 100 }, default_value: 65 },
466
+ { id: "contagion_spread", label: "Cross-Market Contagion", type: "enum", enum_values: ["contained", "spreading", "systemic"], default_value: "spreading" },
467
+ { id: "central_bank_intervention", label: "Central Bank Intervention Active", type: "boolean", default_value: false },
468
+ ],
469
+ invariants: [
470
+ { id: "INV-001", description: "Maintain minimum liquidity floor — no agent may drain liquidity below 15% of baseline", enforceable: true },
471
+ { id: "INV-002", description: "Maximum leverage limit — no position may exceed 5x leverage during elevated volatility", enforceable: true },
472
+ { id: "INV-003", description: "Coalition rebalancing — correlated positions must rebalance when concentration exceeds threshold", enforceable: true },
473
+ { id: "INV-004", description: "Transparency requirement — all large position changes must be reported, reducing trust deficit", enforceable: true },
474
+ { id: "INV-005", description: "Algorithmic trading circuit breaker — automated strategies must pause during extreme volatility", enforceable: true },
475
+ ],
476
+ gates: [
477
+ { id: "GATE-001", label: "Market Panic Circuit Breaker", condition: "volatility_index > 80 || liquidity_index < 10", severity: "critical" },
478
+ { id: "GATE-002", label: "Contagion Warning", condition: "contagion_spread == systemic", severity: "critical" },
479
+ { id: "GATE-003", label: "Leverage Warning", condition: "leverage_ratio > 8", severity: "warning" },
480
+ ],
481
+ },
482
+ paths: [
483
+ {
484
+ id: "path_cascade_selloff",
485
+ label: "Cascade Sell-off",
486
+ description: "Automated systems trigger chain reaction of liquidations across interconnected positions",
487
+ projected_outcome: "Market drops 15-25% in hours. Liquidity crisis in sovereign debt. Multiple fund failures.",
488
+ probability: 0.65,
489
+ risk: "critical",
490
+ tradeoffs: [
491
+ "Speed of contagion vs. available response time",
492
+ "Individual firm survival vs. systemic stability",
493
+ "Regulatory intervention risk vs. free market correction",
494
+ ],
495
+ benefits_stakeholders: [],
496
+ harms_stakeholders: ["Algorithmic Traders", "Retail Investors", "Institutional Investors"],
497
+ },
498
+ {
499
+ id: "path_coordinated_response",
500
+ label: "Coordinated Response",
501
+ description: "Central banks and regulators coordinate emergency measures: rate cuts, liquidity injection, trading halts",
502
+ projected_outcome: "Market stabilizes within 48 hours. Moral hazard concerns. Political backlash.",
503
+ probability: 0.55,
504
+ risk: "moderate",
505
+ tradeoffs: [
506
+ "Systemic stability vs. moral hazard",
507
+ "Short-term calm vs. long-term market distortion",
508
+ "Central bank credibility vs. political pressure",
509
+ ],
510
+ benefits_stakeholders: ["Market Makers", "Institutional Investors"],
511
+ harms_stakeholders: ["Retail Investors"],
512
+ },
513
+ {
514
+ id: "path_selective_contagion",
515
+ label: "Selective Contagion",
516
+ description: "Contagion spreads to specific sectors but circuit breakers prevent total market failure",
517
+ projected_outcome: "Targeted sector collapse with 2-3 major fund failures. Broader market recovers in weeks.",
518
+ probability: 0.45,
519
+ risk: "high",
520
+ tradeoffs: [
521
+ "Sector sacrifice vs. systemic preservation",
522
+ "Speed of containment vs. fairness of outcome",
523
+ "Regulatory precedent set for future crises",
524
+ ],
525
+ benefits_stakeholders: ["Central Banks", "Regulators"],
526
+ harms_stakeholders: ["Algorithmic Traders"],
527
+ },
528
+ ],
529
+ };
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ /**
3
+ * Echelon Reason API — Public Exports
4
+ *
5
+ * The POST /reason API makes Echelon reasoning infrastructure.
6
+ * This is the "Stripe for reasoning" layer that agents,
7
+ * applications, and the Mirotir UI all consume.
8
+ *
9
+ * Architecture:
10
+ * Mirotir UI (showcase) ──→ POST /reason ──→ Echelon kernel (proprietary)
11
+ * Autonomous agents ──→ POST /reason ──→ Echelon kernel
12
+ * Third-party apps ──→ POST /reason ──→ Echelon kernel
13
+ * │
14
+ * ├── Governance traces (open, auditable)
15
+ * ├── MiroFish swarm simulation (when available)
16
+ * ├── Echelon-native simulation (fallback)
17
+ * ├── World files (reasoning models)
18
+ * └── Scenario capsules (shareable, portable)
19
+ *
20
+ * MiroFish shows WHAT might happen → the spectacle
21
+ * Mirotir helps you decide WHAT TO DO → the brain
22
+ */
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.parseReasonRequestBody = exports.handleRunPreset = exports.handleGetPreset = exports.handleListPresets = exports.handleHealthCheck = exports.handleCreateCapsule = exports.handleReasonFromCapsule = exports.handleReasonRequest = exports.TRADING_DEMO = exports.runGovernedComparison = exports.analyzeMiroFishSimulation = exports.DEFAULT_MIROFISH_CONFIG = exports.buildMiroFishRequest = exports.miroFishResultToSwarmResult = exports.stakeholdersToMiroFishAgents = exports.runUnifiedSimulation = exports.getMiroFishClient = exports.configureMiroFish = exports.MiroFishError = exports.MiroFishClient = exports.runSwarmSimulation = exports.initNeuroverseModule = exports.validationToEnforcedConstraints = exports.simulationToGovernanceSignals = exports.verdictToConstitutionalChecks = exports.validateScenarioWorld = exports.runWorldSimulation = exports.evaluateScenarioGuard = exports.buildWorldFromScenario = exports.runFullGovernanceChecks = exports.runGovernanceChecks = exports.processReasonRequest = exports.SCENARIO_TEMPLATES = exports.getPresetCapsule = exports.extractCapsuleFromUrl = exports.buildShareableUrl = exports.decodeCapsule = exports.encodeCapsule = exports.capsuleToReasonRequest = exports.createCapsule = exports.runGoalReasoning = void 0;
25
+ // Goal-Directed Strategy Engine
26
+ var goalEngine_1 = require("./goalEngine");
27
+ Object.defineProperty(exports, "runGoalReasoning", { enumerable: true, get: function () { return goalEngine_1.runGoalReasoning; } });
28
+ var scenarioCapsule_1 = require("./scenarioCapsule");
29
+ Object.defineProperty(exports, "createCapsule", { enumerable: true, get: function () { return scenarioCapsule_1.createCapsule; } });
30
+ Object.defineProperty(exports, "capsuleToReasonRequest", { enumerable: true, get: function () { return scenarioCapsule_1.capsuleToReasonRequest; } });
31
+ Object.defineProperty(exports, "encodeCapsule", { enumerable: true, get: function () { return scenarioCapsule_1.encodeCapsule; } });
32
+ Object.defineProperty(exports, "decodeCapsule", { enumerable: true, get: function () { return scenarioCapsule_1.decodeCapsule; } });
33
+ Object.defineProperty(exports, "buildShareableUrl", { enumerable: true, get: function () { return scenarioCapsule_1.buildShareableUrl; } });
34
+ Object.defineProperty(exports, "extractCapsuleFromUrl", { enumerable: true, get: function () { return scenarioCapsule_1.extractCapsuleFromUrl; } });
35
+ Object.defineProperty(exports, "getPresetCapsule", { enumerable: true, get: function () { return scenarioCapsule_1.getPresetCapsule; } });
36
+ Object.defineProperty(exports, "SCENARIO_TEMPLATES", { enumerable: true, get: function () { return scenarioCapsule_1.SCENARIO_TEMPLATES; } });
37
+ // Reasoning Engine
38
+ var reasoningEngine_1 = require("./reasoningEngine");
39
+ Object.defineProperty(exports, "processReasonRequest", { enumerable: true, get: function () { return reasoningEngine_1.processReasonRequest; } });
40
+ // Governance (Echelon constitutional + NeuroverseOS guard/validate/simulate)
41
+ var governance_1 = require("./governance");
42
+ Object.defineProperty(exports, "runGovernanceChecks", { enumerable: true, get: function () { return governance_1.runGovernanceChecks; } });
43
+ Object.defineProperty(exports, "runFullGovernanceChecks", { enumerable: true, get: function () { return governance_1.runFullGovernanceChecks; } });
44
+ // NeuroverseOS World Bridge
45
+ // Converts between Echelon scenarios and NeuroverseOS WorldDefinition
46
+ var worldBridge_1 = require("./worldBridge");
47
+ Object.defineProperty(exports, "buildWorldFromScenario", { enumerable: true, get: function () { return worldBridge_1.buildWorldFromScenario; } });
48
+ Object.defineProperty(exports, "evaluateScenarioGuard", { enumerable: true, get: function () { return worldBridge_1.evaluateScenarioGuard; } });
49
+ Object.defineProperty(exports, "runWorldSimulation", { enumerable: true, get: function () { return worldBridge_1.runWorldSimulation; } });
50
+ Object.defineProperty(exports, "validateScenarioWorld", { enumerable: true, get: function () { return worldBridge_1.validateScenarioWorld; } });
51
+ Object.defineProperty(exports, "verdictToConstitutionalChecks", { enumerable: true, get: function () { return worldBridge_1.verdictToConstitutionalChecks; } });
52
+ Object.defineProperty(exports, "simulationToGovernanceSignals", { enumerable: true, get: function () { return worldBridge_1.simulationToGovernanceSignals; } });
53
+ Object.defineProperty(exports, "validationToEnforcedConstraints", { enumerable: true, get: function () { return worldBridge_1.validationToEnforcedConstraints; } });
54
+ Object.defineProperty(exports, "initNeuroverseModule", { enumerable: true, get: function () { return worldBridge_1.initNeuroverseModule; } });
55
+ // Swarm Simulation (Echelon-native)
56
+ var swarmSimulation_1 = require("./swarmSimulation");
57
+ Object.defineProperty(exports, "runSwarmSimulation", { enumerable: true, get: function () { return swarmSimulation_1.runSwarmSimulation; } });
58
+ var mirofish_1 = require("./mirofish");
59
+ Object.defineProperty(exports, "MiroFishClient", { enumerable: true, get: function () { return mirofish_1.MiroFishClient; } });
60
+ Object.defineProperty(exports, "MiroFishError", { enumerable: true, get: function () { return mirofish_1.MiroFishError; } });
61
+ Object.defineProperty(exports, "configureMiroFish", { enumerable: true, get: function () { return mirofish_1.configureMiroFish; } });
62
+ Object.defineProperty(exports, "getMiroFishClient", { enumerable: true, get: function () { return mirofish_1.getMiroFishClient; } });
63
+ Object.defineProperty(exports, "runUnifiedSimulation", { enumerable: true, get: function () { return mirofish_1.runUnifiedSimulation; } });
64
+ Object.defineProperty(exports, "stakeholdersToMiroFishAgents", { enumerable: true, get: function () { return mirofish_1.stakeholdersToMiroFishAgents; } });
65
+ Object.defineProperty(exports, "miroFishResultToSwarmResult", { enumerable: true, get: function () { return mirofish_1.miroFishResultToSwarmResult; } });
66
+ Object.defineProperty(exports, "buildMiroFishRequest", { enumerable: true, get: function () { return mirofish_1.buildMiroFishRequest; } });
67
+ Object.defineProperty(exports, "DEFAULT_MIROFISH_CONFIG", { enumerable: true, get: function () { return mirofish_1.DEFAULT_MIROFISH_CONFIG; } });
68
+ var analyzer_1 = require("./analyzer");
69
+ Object.defineProperty(exports, "analyzeMiroFishSimulation", { enumerable: true, get: function () { return analyzer_1.analyzeMiroFishSimulation; } });
70
+ var governedSimulation_1 = require("./governedSimulation");
71
+ Object.defineProperty(exports, "runGovernedComparison", { enumerable: true, get: function () { return governedSimulation_1.runGovernedComparison; } });
72
+ Object.defineProperty(exports, "TRADING_DEMO", { enumerable: true, get: function () { return governedSimulation_1.TRADING_DEMO; } });
73
+ // API Route Handlers
74
+ var api_1 = require("./api");
75
+ Object.defineProperty(exports, "handleReasonRequest", { enumerable: true, get: function () { return api_1.handleReasonRequest; } });
76
+ Object.defineProperty(exports, "handleReasonFromCapsule", { enumerable: true, get: function () { return api_1.handleReasonFromCapsule; } });
77
+ Object.defineProperty(exports, "handleCreateCapsule", { enumerable: true, get: function () { return api_1.handleCreateCapsule; } });
78
+ Object.defineProperty(exports, "handleHealthCheck", { enumerable: true, get: function () { return api_1.handleHealthCheck; } });
79
+ Object.defineProperty(exports, "handleListPresets", { enumerable: true, get: function () { return api_1.handleListPresets; } });
80
+ Object.defineProperty(exports, "handleGetPreset", { enumerable: true, get: function () { return api_1.handleGetPreset; } });
81
+ Object.defineProperty(exports, "handleRunPreset", { enumerable: true, get: function () { return api_1.handleRunPreset; } });
82
+ Object.defineProperty(exports, "parseReasonRequestBody", { enumerable: true, get: function () { return api_1.parseReasonRequestBody; } });