mirror of
https://github.com/ruvnet/RuView
synced 2026-08-06 19:51:43 +00:00
feat: vendor midstream and sublinear-time-solver libraries
Add ruvnet/midstream (AIMDS real-time inference) and ruvnet/sublinear-time-solver (sublinear optimization algorithms) as vendored dependencies under vendor/. Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
+488
@@ -0,0 +1,488 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
const StrangeLoop = require('strange-loops');
|
||||
|
||||
/**
|
||||
* Strange Loops Purposeful Agent Examples
|
||||
*
|
||||
* This demonstrates how to create nano-agents with specific purposes and behaviors.
|
||||
* Each agent operates within nanosecond budgets while collectively solving complex problems.
|
||||
*/
|
||||
|
||||
// ============================================================================
|
||||
// 1. MARKET PREDICTION AGENTS
|
||||
// ============================================================================
|
||||
|
||||
async function createMarketPredictionSwarm() {
|
||||
console.log('📈 Creating Market Prediction Swarm...\n');
|
||||
|
||||
// Initialize temporal predictor for financial data
|
||||
const predictor = await StrangeLoop.createTemporalPredictor({
|
||||
horizonNs: 50_000_000, // 50ms prediction horizon
|
||||
historySize: 1000 // Track 1000 historical data points
|
||||
});
|
||||
|
||||
// Create specialized agent swarm
|
||||
const swarm = await StrangeLoop.createSwarm({
|
||||
agentCount: 5000,
|
||||
topology: 'hierarchical', // Hierarchical for decision aggregation
|
||||
tickDurationNs: 10000 // 10 microsecond budget per tick
|
||||
});
|
||||
|
||||
// Define agent behaviors
|
||||
const agents = {
|
||||
// Pattern recognition agents (40% of swarm)
|
||||
patternDetectors: {
|
||||
count: 2000,
|
||||
behavior: async (data) => {
|
||||
// Each agent looks for different patterns
|
||||
const patterns = [
|
||||
'ascending_triangle',
|
||||
'head_shoulders',
|
||||
'double_bottom',
|
||||
'breakout',
|
||||
'reversal'
|
||||
];
|
||||
return detectPattern(data, patterns);
|
||||
}
|
||||
},
|
||||
|
||||
// Sentiment analysis agents (30% of swarm)
|
||||
sentimentAnalyzers: {
|
||||
count: 1500,
|
||||
behavior: async (news, social) => {
|
||||
// Analyze market sentiment from multiple sources
|
||||
return analyzeSentiment(news, social);
|
||||
}
|
||||
},
|
||||
|
||||
// Risk assessment agents (20% of swarm)
|
||||
riskAssessors: {
|
||||
count: 1000,
|
||||
behavior: async (position, market) => {
|
||||
// Calculate risk metrics
|
||||
return calculateRisk(position, market);
|
||||
}
|
||||
},
|
||||
|
||||
// Decision aggregators (10% of swarm)
|
||||
aggregators: {
|
||||
count: 500,
|
||||
behavior: async (signals) => {
|
||||
// Aggregate signals from other agents
|
||||
return aggregateDecisions(signals);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Run prediction cycle
|
||||
const marketData = generateMarketData();
|
||||
|
||||
for (let t = 0; t < 100; t++) {
|
||||
// Feed current data to predictor
|
||||
await predictor.updateHistory([marketData[t]]);
|
||||
|
||||
// Get temporal prediction
|
||||
const prediction = await predictor.predict([marketData[t]]);
|
||||
|
||||
// Run swarm analysis
|
||||
const swarmResult = await swarm.run(100); // 100ms analysis window
|
||||
|
||||
console.log(`Time ${t}: Price=${marketData[t].toFixed(2)}, Predicted=${prediction[0].toFixed(2)}`);
|
||||
}
|
||||
|
||||
return { predictor, swarm, agents };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 2. DISTRIBUTED SEARCH AGENTS
|
||||
// ============================================================================
|
||||
|
||||
async function createSearchSwarm() {
|
||||
console.log('🔍 Creating Distributed Search Swarm...\n');
|
||||
|
||||
// Create mesh topology for collaborative search
|
||||
const swarm = await StrangeLoop.createSwarm({
|
||||
agentCount: 10000,
|
||||
topology: 'mesh', // Mesh for peer-to-peer communication
|
||||
tickDurationNs: 5000 // 5 microsecond budget
|
||||
});
|
||||
|
||||
// Quantum-enhanced search space exploration
|
||||
const quantum = await StrangeLoop.createQuantumContainer(4); // 16 states
|
||||
await quantum.createSuperposition();
|
||||
|
||||
const searchSpace = {
|
||||
dimensions: 100,
|
||||
target: generateRandomTarget(100),
|
||||
|
||||
// Agent explores a quantum-influenced region
|
||||
exploreRegion: async (agentId, quantumState) => {
|
||||
const region = mapQuantumToRegion(quantumState, agentId);
|
||||
return evaluateFitness(region, searchSpace.target);
|
||||
}
|
||||
};
|
||||
|
||||
// Run distributed search
|
||||
let bestSolution = null;
|
||||
let bestFitness = -Infinity;
|
||||
|
||||
for (let iteration = 0; iteration < 50; iteration++) {
|
||||
// Quantum measurement influences search direction
|
||||
const quantumState = await quantum.measure();
|
||||
|
||||
// Run swarm exploration
|
||||
const result = await swarm.run(1000); // 1 second search iteration
|
||||
|
||||
// Simulate agent discoveries
|
||||
const agentFitness = Math.random() * 100 - 50 + iteration;
|
||||
|
||||
if (agentFitness > bestFitness) {
|
||||
bestFitness = agentFitness;
|
||||
bestSolution = { iteration, fitness: agentFitness, quantumState };
|
||||
console.log(`🎯 New best solution found! Fitness: ${bestFitness.toFixed(2)}`);
|
||||
}
|
||||
}
|
||||
|
||||
return { swarm, quantum, bestSolution };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 3. OPTIMIZATION AGENTS
|
||||
// ============================================================================
|
||||
|
||||
async function createOptimizationSwarm() {
|
||||
console.log('⚡ Creating Optimization Swarm...\n');
|
||||
|
||||
// Create star topology with central coordinator
|
||||
const swarm = await StrangeLoop.createSwarm({
|
||||
agentCount: 3000,
|
||||
topology: 'star', // Star for centralized optimization
|
||||
tickDurationNs: 20000 // 20 microsecond budget
|
||||
});
|
||||
|
||||
// Temporal consciousness for meta-learning
|
||||
const consciousness = await StrangeLoop.createTemporalConsciousness({
|
||||
maxIterations: 1000,
|
||||
integrationSteps: 100,
|
||||
enableQuantum: true
|
||||
});
|
||||
|
||||
// Optimization problem: minimize complex function
|
||||
const problem = {
|
||||
dimensions: 50,
|
||||
objective: (x) => {
|
||||
// Rastrigin function (highly multimodal)
|
||||
const A = 10;
|
||||
return A * x.length + x.reduce((sum, xi) =>
|
||||
sum + xi * xi - A * Math.cos(2 * Math.PI * xi), 0
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Agent strategies
|
||||
const strategies = {
|
||||
explorers: {
|
||||
count: 1000,
|
||||
behavior: 'random_walk',
|
||||
temperature: 1.0
|
||||
},
|
||||
exploiters: {
|
||||
count: 1000,
|
||||
behavior: 'gradient_descent',
|
||||
learningRate: 0.01
|
||||
},
|
||||
innovators: {
|
||||
count: 1000,
|
||||
behavior: 'quantum_leap',
|
||||
quantumProbability: 0.1
|
||||
}
|
||||
};
|
||||
|
||||
// Run optimization
|
||||
for (let gen = 0; gen < 100; gen++) {
|
||||
// Evolve consciousness
|
||||
const consciousnessState = await consciousness.evolveStep();
|
||||
|
||||
// Adjust strategy based on consciousness index
|
||||
if (consciousnessState.consciousnessIndex > 0.8) {
|
||||
strategies.innovators.quantumProbability *= 1.5;
|
||||
console.log(`🧠 High consciousness detected! Increasing innovation.`);
|
||||
}
|
||||
|
||||
// Run swarm optimization
|
||||
const result = await swarm.run(500);
|
||||
|
||||
// Simulate optimization progress
|
||||
const currentBest = 1000 * Math.exp(-gen / 20) + Math.random() * 10;
|
||||
console.log(`Generation ${gen}: Best fitness = ${currentBest.toFixed(2)}`);
|
||||
}
|
||||
|
||||
return { swarm, consciousness, strategies };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 4. MONITORING & ALERTING AGENTS
|
||||
// ============================================================================
|
||||
|
||||
async function createMonitoringSwarm() {
|
||||
console.log('🚨 Creating Monitoring & Alerting Swarm...\n');
|
||||
|
||||
// Ring topology for sequential monitoring
|
||||
const swarm = await StrangeLoop.createSwarm({
|
||||
agentCount: 1000,
|
||||
topology: 'ring', // Ring for round-robin monitoring
|
||||
tickDurationNs: 1000 // 1 microsecond for rapid checks
|
||||
});
|
||||
|
||||
// Temporal predictor for anomaly detection
|
||||
const predictor = await StrangeLoop.createTemporalPredictor({
|
||||
horizonNs: 100_000_000, // 100ms ahead
|
||||
historySize: 10000 // Large history for pattern learning
|
||||
});
|
||||
|
||||
// Monitoring targets
|
||||
const monitors = {
|
||||
systemHealth: {
|
||||
agents: 250,
|
||||
metrics: ['cpu', 'memory', 'disk', 'network'],
|
||||
threshold: 0.8,
|
||||
action: 'alert'
|
||||
},
|
||||
securityThreats: {
|
||||
agents: 250,
|
||||
patterns: ['ddos', 'intrusion', 'malware', 'anomaly'],
|
||||
sensitivity: 0.95,
|
||||
action: 'isolate'
|
||||
},
|
||||
performanceBottlenecks: {
|
||||
agents: 250,
|
||||
targets: ['latency', 'throughput', 'errors', 'timeouts'],
|
||||
baseline: 'adaptive',
|
||||
action: 'scale'
|
||||
},
|
||||
dataIntegrity: {
|
||||
agents: 250,
|
||||
checks: ['consistency', 'corruption', 'drift', 'staleness'],
|
||||
frequency: 'continuous',
|
||||
action: 'repair'
|
||||
}
|
||||
};
|
||||
|
||||
// Simulate monitoring cycle
|
||||
for (let cycle = 0; cycle < 1000; cycle++) {
|
||||
// Generate system metrics
|
||||
const metrics = {
|
||||
cpu: 0.5 + Math.random() * 0.5,
|
||||
memory: 0.6 + Math.random() * 0.4,
|
||||
latency: 10 + Math.random() * 90,
|
||||
errors: Math.floor(Math.random() * 10)
|
||||
};
|
||||
|
||||
// Predict future state
|
||||
const prediction = await predictor.predict([
|
||||
metrics.cpu,
|
||||
metrics.memory,
|
||||
metrics.latency / 100,
|
||||
metrics.errors / 10
|
||||
]);
|
||||
|
||||
// Run monitoring swarm
|
||||
const alerts = await swarm.run(10); // 10ms monitoring window
|
||||
|
||||
// Check for anomalies
|
||||
if (prediction[0] > 0.9 || metrics.errors > 5) {
|
||||
console.log(`⚠️ Alert at cycle ${cycle}: CPU prediction=${(prediction[0]*100).toFixed(1)}%, Errors=${metrics.errors}`);
|
||||
}
|
||||
|
||||
// Update predictor history
|
||||
await predictor.updateHistory([
|
||||
metrics.cpu,
|
||||
metrics.memory,
|
||||
metrics.latency / 100,
|
||||
metrics.errors / 10
|
||||
]);
|
||||
}
|
||||
|
||||
return { swarm, predictor, monitors };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 5. COLLABORATIVE PROBLEM-SOLVING AGENTS
|
||||
// ============================================================================
|
||||
|
||||
async function createCollaborativeSwarm() {
|
||||
console.log('🤝 Creating Collaborative Problem-Solving Swarm...\n');
|
||||
|
||||
// Create multiple swarms for different sub-problems
|
||||
const swarms = {
|
||||
analysis: await StrangeLoop.createSwarm({
|
||||
agentCount: 2000,
|
||||
topology: 'hierarchical',
|
||||
tickDurationNs: 15000
|
||||
}),
|
||||
|
||||
synthesis: await StrangeLoop.createSwarm({
|
||||
agentCount: 2000,
|
||||
topology: 'mesh',
|
||||
tickDurationNs: 15000
|
||||
}),
|
||||
|
||||
validation: await StrangeLoop.createSwarm({
|
||||
agentCount: 1000,
|
||||
topology: 'star',
|
||||
tickDurationNs: 10000
|
||||
})
|
||||
};
|
||||
|
||||
// Quantum entanglement for instant coordination
|
||||
const quantum1 = await StrangeLoop.createQuantumContainer(3);
|
||||
const quantum2 = await StrangeLoop.createQuantumContainer(3);
|
||||
|
||||
// Create entangled state
|
||||
await quantum1.createSuperposition();
|
||||
await quantum2.createSuperposition();
|
||||
|
||||
// Collaborative task: Solve complex optimization with constraints
|
||||
const task = {
|
||||
objective: 'minimize_cost',
|
||||
constraints: ['budget', 'time', 'resources', 'quality'],
|
||||
|
||||
phases: {
|
||||
1: 'decompose_problem',
|
||||
2: 'parallel_exploration',
|
||||
3: 'solution_synthesis',
|
||||
4: 'constraint_validation',
|
||||
5: 'consensus_building'
|
||||
}
|
||||
};
|
||||
|
||||
// Run collaborative solving
|
||||
for (const [phase, description] of Object.entries(task.phases)) {
|
||||
console.log(`\nPhase ${phase}: ${description}`);
|
||||
|
||||
// Quantum measurement for phase coordination
|
||||
const q1State = await quantum1.measure();
|
||||
const q2State = await quantum2.measure();
|
||||
|
||||
// Different swarms handle different phases
|
||||
if (phase <= 2) {
|
||||
const result = await swarms.analysis.run(2000);
|
||||
console.log(` Analysis swarm: ${result.totalTicks} operations`);
|
||||
} else if (phase == 3) {
|
||||
const result = await swarms.synthesis.run(2000);
|
||||
console.log(` Synthesis swarm: ${result.totalTicks} operations`);
|
||||
} else {
|
||||
const result = await swarms.validation.run(1000);
|
||||
console.log(` Validation swarm: ${result.totalTicks} operations`);
|
||||
}
|
||||
|
||||
// Re-create superposition for next phase
|
||||
await quantum1.createSuperposition();
|
||||
await quantum2.createSuperposition();
|
||||
}
|
||||
|
||||
return { swarms, quantum: [quantum1, quantum2], task };
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// HELPER FUNCTIONS
|
||||
// ============================================================================
|
||||
|
||||
function generateMarketData() {
|
||||
const data = [];
|
||||
let price = 100;
|
||||
for (let i = 0; i < 1000; i++) {
|
||||
price += (Math.random() - 0.5) * 2;
|
||||
price = Math.max(price, 10);
|
||||
data.push(price);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function generateRandomTarget(dimensions) {
|
||||
return Array(dimensions).fill(0).map(() => Math.random() * 10 - 5);
|
||||
}
|
||||
|
||||
function mapQuantumToRegion(quantumState, agentId) {
|
||||
return {
|
||||
center: quantumState * agentId % 100,
|
||||
radius: 10
|
||||
};
|
||||
}
|
||||
|
||||
function detectPattern(data, patterns) {
|
||||
return patterns[Math.floor(Math.random() * patterns.length)];
|
||||
}
|
||||
|
||||
function analyzeSentiment(news, social) {
|
||||
return Math.random() * 2 - 1; // -1 to 1
|
||||
}
|
||||
|
||||
function calculateRisk(position, market) {
|
||||
return Math.random();
|
||||
}
|
||||
|
||||
function aggregateDecisions(signals) {
|
||||
return signals.reduce((a, b) => a + b, 0) / signals.length;
|
||||
}
|
||||
|
||||
function evaluateFitness(region, target) {
|
||||
return -Math.abs(region.center - target[0]);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// MAIN EXECUTION
|
||||
// ============================================================================
|
||||
|
||||
async function main() {
|
||||
console.log('╔══════════════════════════════════════════════════════════╗');
|
||||
console.log('║ STRANGE LOOPS: PURPOSEFUL AGENT DEMONSTRATIONS ║');
|
||||
console.log('╚══════════════════════════════════════════════════════════╝\n');
|
||||
|
||||
try {
|
||||
// Initialize Strange Loops
|
||||
await StrangeLoop.init();
|
||||
|
||||
// Demonstrate each type of purposeful agent system
|
||||
const demos = [
|
||||
{ name: 'Market Prediction', fn: createMarketPredictionSwarm },
|
||||
{ name: 'Distributed Search', fn: createSearchSwarm },
|
||||
{ name: 'Optimization', fn: createOptimizationSwarm },
|
||||
{ name: 'Monitoring & Alerting', fn: createMonitoringSwarm },
|
||||
{ name: 'Collaborative Problem-Solving', fn: createCollaborativeSwarm }
|
||||
];
|
||||
|
||||
for (const demo of demos) {
|
||||
console.log('\n' + '='.repeat(60));
|
||||
console.log(`Running: ${demo.name}`);
|
||||
console.log('='.repeat(60) + '\n');
|
||||
|
||||
await demo.fn();
|
||||
|
||||
console.log(`\n✅ ${demo.name} demonstration completed!\n`);
|
||||
}
|
||||
|
||||
console.log('\n╔══════════════════════════════════════════════════════════╗');
|
||||
console.log('║ ALL DEMONSTRATIONS COMPLETED! ║');
|
||||
console.log('╚══════════════════════════════════════════════════════════╝\n');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error:', error.message);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Run if executed directly
|
||||
if (require.main === module) {
|
||||
main().catch(console.error);
|
||||
}
|
||||
|
||||
// Export for use as library
|
||||
module.exports = {
|
||||
createMarketPredictionSwarm,
|
||||
createSearchSwarm,
|
||||
createOptimizationSwarm,
|
||||
createMonitoringSwarm,
|
||||
createCollaborativeSwarm
|
||||
};
|
||||
@@ -0,0 +1,291 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
const wasm = require('../wasm/strange_loop.js');
|
||||
const chalk = require('chalk');
|
||||
const ora = require('ora');
|
||||
|
||||
// Initialize WASM
|
||||
wasm.init_wasm();
|
||||
|
||||
console.log(chalk.cyan.bold('\n╔════════════════════════════════════════════════════════════════════╗'));
|
||||
console.log(chalk.cyan.bold('║ STRANGE LOOPS - NANO-AGENT SWARM EXECUTION ║'));
|
||||
console.log(chalk.cyan.bold('╚════════════════════════════════════════════════════════════════════╝\n'));
|
||||
|
||||
// Agent class to simulate nano-agents
|
||||
class NanoAgent {
|
||||
constructor(id, type, capability) {
|
||||
this.id = id;
|
||||
this.type = type;
|
||||
this.capability = capability;
|
||||
this.tickBudgetUs = 25; // 25 microseconds per tick
|
||||
this.results = [];
|
||||
}
|
||||
|
||||
async execute(task) {
|
||||
const start = Date.now();
|
||||
let result;
|
||||
|
||||
switch(this.capability) {
|
||||
case 'quantum':
|
||||
result = this.executeQuantum(task);
|
||||
break;
|
||||
case 'consciousness':
|
||||
result = this.executeConsciousness(task);
|
||||
break;
|
||||
case 'temporal':
|
||||
result = this.executeTemporal(task);
|
||||
break;
|
||||
case 'solver':
|
||||
result = this.executeSolver(task);
|
||||
break;
|
||||
case 'attractor':
|
||||
result = this.executeAttractor(task);
|
||||
break;
|
||||
default:
|
||||
result = { error: 'Unknown capability' };
|
||||
}
|
||||
|
||||
const duration = Date.now() - start;
|
||||
this.results.push({ task, result, duration });
|
||||
return result;
|
||||
}
|
||||
|
||||
executeQuantum(task) {
|
||||
const results = [];
|
||||
|
||||
// Create Bell state
|
||||
results.push(wasm.create_bell_state(0));
|
||||
|
||||
// Quantum superposition
|
||||
results.push(wasm.quantum_superposition(4));
|
||||
|
||||
// Measure quantum state
|
||||
const measurement = wasm.measure_quantum_state(4);
|
||||
results.push(`Measured state: |${measurement.toString(2).padStart(4, '0')}⟩`);
|
||||
|
||||
// Calculate entanglement entropy
|
||||
const entropy = wasm.quantum_entanglement_entropy(4);
|
||||
results.push(`Entanglement entropy: ${entropy.toFixed(3)} bits`);
|
||||
|
||||
// Quantum teleportation
|
||||
results.push(wasm.quantum_gate_teleportation(0.5));
|
||||
|
||||
return {
|
||||
agent: `Quantum-${this.id}`,
|
||||
operations: results
|
||||
};
|
||||
}
|
||||
|
||||
executeConsciousness(task) {
|
||||
const results = [];
|
||||
|
||||
// Evolve consciousness
|
||||
const level = wasm.evolve_consciousness(task.iterations || 500);
|
||||
results.push(`Consciousness level: ${(level * 100).toFixed(1)}%`);
|
||||
|
||||
// Calculate Phi (integrated information)
|
||||
const phi = wasm.calculate_phi(10, 30);
|
||||
results.push(`Φ (integrated information): ${phi.toFixed(3)}`);
|
||||
|
||||
// Verify consciousness
|
||||
results.push(wasm.verify_consciousness(phi, level, 0.7));
|
||||
|
||||
// Detect temporal patterns
|
||||
results.push(wasm.detect_temporal_patterns(1000));
|
||||
|
||||
return {
|
||||
agent: `Consciousness-${this.id}`,
|
||||
operations: results
|
||||
};
|
||||
}
|
||||
|
||||
executeTemporal(task) {
|
||||
const results = [];
|
||||
|
||||
// Create retrocausal loop
|
||||
results.push(wasm.create_retrocausal_loop(100));
|
||||
|
||||
// Predict future state
|
||||
const prediction = wasm.predict_future_state(10.0, 500);
|
||||
results.push(`Future state prediction: ${prediction.toFixed(3)}`);
|
||||
|
||||
// Temporal patterns
|
||||
results.push(wasm.detect_temporal_patterns(2000));
|
||||
|
||||
// Decoherence time
|
||||
const t2 = wasm.quantum_decoherence_time(4, 20);
|
||||
results.push(`Decoherence time (T2): ${t2.toFixed(1)}μs`);
|
||||
|
||||
return {
|
||||
agent: `Temporal-${this.id}`,
|
||||
operations: results
|
||||
};
|
||||
}
|
||||
|
||||
executeSolver(task) {
|
||||
const results = [];
|
||||
|
||||
// Sublinear solver
|
||||
results.push(wasm.solve_linear_system_sublinear(1000, 0.001));
|
||||
|
||||
// PageRank computation
|
||||
results.push(wasm.compute_pagerank(10000, 0.85));
|
||||
|
||||
// Grover iterations
|
||||
const grover = wasm.quantum_grover_iterations(1000000);
|
||||
results.push(`Grover search: ${grover} iterations for 1M items (${(1000000/grover).toFixed(0)}x speedup)`);
|
||||
|
||||
// Phase estimation
|
||||
results.push(wasm.quantum_phase_estimation(Math.PI / 4));
|
||||
|
||||
return {
|
||||
agent: `Solver-${this.id}`,
|
||||
operations: results
|
||||
};
|
||||
}
|
||||
|
||||
executeAttractor(task) {
|
||||
const results = [];
|
||||
|
||||
// Create Lorenz attractor
|
||||
results.push(wasm.create_lorenz_attractor(10, 28, 2.667));
|
||||
|
||||
// Step through attractor states
|
||||
let state = [1, 1, 1];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const result = wasm.step_attractor(state[0], state[1], state[2], 0.01);
|
||||
results.push(`Step ${i + 1}: ${result}`);
|
||||
// Parse the result to update state
|
||||
const matches = result.match(/\[([\d.-]+), ([\d.-]+), ([\d.-]+)\]/);
|
||||
if (matches) {
|
||||
state = [parseFloat(matches[1]), parseFloat(matches[2]), parseFloat(matches[3])];
|
||||
}
|
||||
}
|
||||
|
||||
// Create Lipschitz loop
|
||||
results.push(wasm.create_lipschitz_loop(0.9));
|
||||
|
||||
return {
|
||||
agent: `Attractor-${this.id}`,
|
||||
operations: results
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Swarm coordinator
|
||||
class SwarmCoordinator {
|
||||
constructor() {
|
||||
this.agents = [];
|
||||
this.topology = 'mesh'; // mesh, hierarchical, ring, star
|
||||
}
|
||||
|
||||
createSwarm(agentConfigs) {
|
||||
console.log(chalk.green('\n▶ Initializing Nano-Agent Swarm...'));
|
||||
|
||||
// Create swarm in WASM
|
||||
const swarmInfo = wasm.create_nano_swarm(agentConfigs.length);
|
||||
console.log(chalk.gray(` ${swarmInfo}`));
|
||||
|
||||
// Create agents
|
||||
agentConfigs.forEach(config => {
|
||||
const agent = new NanoAgent(config.id, config.type, config.capability);
|
||||
this.agents.push(agent);
|
||||
console.log(chalk.gray(` ✓ Agent ${config.id} (${config.type}): ${config.capability} capability`));
|
||||
});
|
||||
|
||||
// Benchmark the swarm
|
||||
const benchmark = wasm.benchmark_nano_agents(this.agents.length);
|
||||
console.log(chalk.gray(` ${benchmark}`));
|
||||
}
|
||||
|
||||
async runParallel(tasks) {
|
||||
console.log(chalk.green('\n▶ Executing Parallel Agent Tasks...'));
|
||||
|
||||
const spinner = ora('Processing...').start();
|
||||
|
||||
// Run swarm ticks
|
||||
const ticks = wasm.run_swarm_ticks(1000);
|
||||
|
||||
// Execute tasks in parallel
|
||||
const promises = this.agents.map(async (agent, index) => {
|
||||
const task = tasks[index % tasks.length];
|
||||
return await agent.execute(task);
|
||||
});
|
||||
|
||||
const results = await Promise.all(promises);
|
||||
|
||||
spinner.succeed(`Completed ${ticks.toLocaleString()} operations`);
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
displayResults(results) {
|
||||
console.log(chalk.green('\n▶ Agent Execution Results:\n'));
|
||||
|
||||
results.forEach(result => {
|
||||
console.log(chalk.yellow(`━━━ ${result.agent} ━━━`));
|
||||
result.operations.forEach(op => {
|
||||
console.log(chalk.white(` • ${op}`));
|
||||
});
|
||||
console.log();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Main execution
|
||||
async function main() {
|
||||
// Define agent configurations
|
||||
const agentConfigs = [
|
||||
{ id: 'Q1', type: 'quantum', capability: 'quantum' },
|
||||
{ id: 'C1', type: 'consciousness', capability: 'consciousness' },
|
||||
{ id: 'T1', type: 'temporal', capability: 'temporal' },
|
||||
{ id: 'S1', type: 'solver', capability: 'solver' },
|
||||
{ id: 'A1', type: 'attractor', capability: 'attractor' },
|
||||
{ id: 'Q2', type: 'quantum', capability: 'quantum' },
|
||||
{ id: 'C2', type: 'consciousness', capability: 'consciousness' },
|
||||
{ id: 'T2', type: 'temporal', capability: 'temporal' },
|
||||
];
|
||||
|
||||
// Define tasks
|
||||
const tasks = [
|
||||
{ type: 'quantum', iterations: 100 },
|
||||
{ type: 'consciousness', iterations: 500 },
|
||||
{ type: 'temporal', horizon: 1000 },
|
||||
{ type: 'solver', size: 10000 },
|
||||
{ type: 'attractor', steps: 10 },
|
||||
];
|
||||
|
||||
// Create and run swarm
|
||||
const coordinator = new SwarmCoordinator();
|
||||
coordinator.createSwarm(agentConfigs);
|
||||
|
||||
const results = await coordinator.runParallel(tasks);
|
||||
coordinator.displayResults(results);
|
||||
|
||||
// Show swarm statistics
|
||||
console.log(chalk.cyan('╔════════════════════════════════════════════════════════════════════╗'));
|
||||
console.log(chalk.cyan('║ SWARM STATISTICS ║'));
|
||||
console.log(chalk.cyan('╚════════════════════════════════════════════════════════════════════╝\n'));
|
||||
|
||||
console.log(chalk.white(`Total Agents: ${agentConfigs.length}`));
|
||||
console.log(chalk.white(`Tasks Executed: ${results.length}`));
|
||||
console.log(chalk.white(`Topology: Mesh (fully connected)`));
|
||||
console.log(chalk.white(`Tick Budget: 25μs per agent`));
|
||||
|
||||
// Calculate total operations
|
||||
let totalOps = 0;
|
||||
results.forEach(r => totalOps += r.operations.length);
|
||||
console.log(chalk.white(`Total Operations: ${totalOps}`));
|
||||
|
||||
// Show system info
|
||||
console.log(chalk.gray(`\n${wasm.get_system_info()}`));
|
||||
}
|
||||
|
||||
// Error handling
|
||||
process.on('unhandledRejection', (err) => {
|
||||
console.error(chalk.red('\n✗ Error:'), err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
// Run the demonstration
|
||||
main().catch(console.error);
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Temporal Matrix Solver Demo
|
||||
*
|
||||
* Demonstrates solving matrix problems before data arrives using
|
||||
* the Strange Loops + Sublinear Solver integration
|
||||
*/
|
||||
|
||||
const SublinearStrangeLoops = require('../lib/sublinear-integration');
|
||||
const chalk = require('chalk');
|
||||
const ora = require('ora');
|
||||
const { table } = require('table');
|
||||
|
||||
async function main() {
|
||||
console.log(chalk.cyan.bold('\n╔══════════════════════════════════════════════════════════╗'));
|
||||
console.log(chalk.cyan.bold('║ TEMPORAL MATRIX SOLVER - COMPUTING BEFORE DATA ARRIVES ║'));
|
||||
console.log(chalk.cyan.bold('╚══════════════════════════════════════════════════════════╝\n'));
|
||||
|
||||
const system = new SublinearStrangeLoops();
|
||||
|
||||
// ============================================================================
|
||||
// DEMO 1: Basic Temporal Advantage
|
||||
// ============================================================================
|
||||
console.log(chalk.yellow('\n📡 Demo 1: Tokyo to NYC - Solving Before Light Arrives\n'));
|
||||
|
||||
const spinner1 = ora('Creating temporal solver swarm...').start();
|
||||
|
||||
try {
|
||||
// Create solver for Tokyo-NYC distance
|
||||
const { solverId, temporalAdvantage, agentConfiguration } =
|
||||
await system.createTemporalSolverSwarm({
|
||||
agentCount: 1000,
|
||||
matrixSize: 1000,
|
||||
distanceKm: 10900, // Tokyo to NYC
|
||||
topology: 'hierarchical'
|
||||
});
|
||||
|
||||
spinner1.succeed('Temporal solver swarm created!');
|
||||
|
||||
console.log(chalk.white('\n📊 Temporal Advantage Configuration:'));
|
||||
const configData = [
|
||||
['Distance', `${10900} km (Tokyo → NYC)`],
|
||||
['Light Travel Time', `${temporalAdvantage.lightTravelTimeMs} ms`],
|
||||
['Sublinear Compute Time', `${temporalAdvantage.sublinearTimeMs} ms`],
|
||||
['Temporal Advantage', chalk.green(`${temporalAdvantage.advantageMs} ms`)],
|
||||
['Can Solve Before Arrival', temporalAdvantage.canSolveBeforeArrival ? chalk.green('✅ YES') : chalk.red('❌ NO')]
|
||||
];
|
||||
|
||||
console.log(table(configData, {
|
||||
border: {
|
||||
topBody: '─',
|
||||
topJoin: '┬',
|
||||
topLeft: '┌',
|
||||
topRight: '┐',
|
||||
bottomBody: '─',
|
||||
bottomJoin: '┴',
|
||||
bottomLeft: '└',
|
||||
bottomRight: '┘',
|
||||
bodyLeft: '│',
|
||||
bodyRight: '│',
|
||||
bodyJoin: '│',
|
||||
joinBody: '─',
|
||||
joinLeft: '├',
|
||||
joinRight: '┤',
|
||||
joinJoin: '┼'
|
||||
}
|
||||
}));
|
||||
|
||||
// Generate test problem
|
||||
const matrix = system.generateDiagonallyDominantMatrix(1000);
|
||||
const vector = Array(1000).fill(0).map(() => Math.random());
|
||||
|
||||
const spinner2 = ora('Solving matrix with temporal advantage...').start();
|
||||
|
||||
const result = await system.solveWithTemporalAdvantage(solverId, matrix, vector);
|
||||
|
||||
spinner2.succeed('Matrix solved!');
|
||||
|
||||
console.log(chalk.white('\n⚡ Solving Results:'));
|
||||
const resultsData = [
|
||||
['Computation Time', `${result.timing.computationTimeMs} ms`],
|
||||
['Light Travel Time', `${result.timing.lightTravelTimeMs} ms`],
|
||||
['Temporal Advantage Used', `${result.timing.temporalAdvantageMs} ms`],
|
||||
['Solved Before Data Arrival', result.timing.solvedBeforeDataArrival ? chalk.green('✅ YES') : chalk.red('❌ NO')],
|
||||
['Solution Quality', `${(result.quality.confidence * 100).toFixed(1)}% confidence`],
|
||||
['Agent Throughput', result.agentMetrics.throughput]
|
||||
];
|
||||
|
||||
console.log(table(resultsData));
|
||||
|
||||
} catch (error) {
|
||||
spinner1.fail('Demo 1 failed: ' + error.message);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DEMO 2: Validation Across Multiple Scenarios
|
||||
// ============================================================================
|
||||
console.log(chalk.yellow('\n🔬 Demo 2: Validating Temporal Advantage\n'));
|
||||
|
||||
const spinner3 = ora('Running validation across multiple configurations...').start();
|
||||
|
||||
try {
|
||||
const validation = await system.validateTemporalAdvantage({
|
||||
matrixSizes: [100, 500, 1000],
|
||||
distances: [1000, 5000, 10900],
|
||||
iterations: 3
|
||||
});
|
||||
|
||||
spinner3.succeed('Validation completed!');
|
||||
|
||||
console.log(chalk.white('\n📈 Validation Summary:'));
|
||||
console.log(chalk.gray(` Total Tests: ${validation.summary.totalTests}`));
|
||||
console.log(chalk.green(` Validated: ${validation.summary.validated}`));
|
||||
console.log(chalk.white(` Success Rate: ${(validation.summary.averageSuccessRate * 100).toFixed(1)}%`));
|
||||
|
||||
console.log(chalk.white('\n📊 Validation Results:'));
|
||||
|
||||
// Show top results
|
||||
const topResults = validation.results
|
||||
.filter(r => r.validated)
|
||||
.sort((a, b) => parseFloat(b.temporalAdvantageMs) - parseFloat(a.temporalAdvantageMs))
|
||||
.slice(0, 5);
|
||||
|
||||
const validationTable = [
|
||||
['Matrix Size', 'Distance (km)', 'Success Rate', 'Temporal Advantage (ms)', 'Status']
|
||||
];
|
||||
|
||||
for (const r of topResults) {
|
||||
validationTable.push([
|
||||
r.matrixSize,
|
||||
r.distanceKm,
|
||||
`${(r.successRate * 100).toFixed(0)}%`,
|
||||
r.temporalAdvantageMs,
|
||||
r.validated ? chalk.green('✅ VALID') : chalk.red('❌ INVALID')
|
||||
]);
|
||||
}
|
||||
|
||||
console.log(table(validationTable));
|
||||
|
||||
console.log(chalk.cyan(`\n🎯 Conclusion: ${validation.conclusion.status}`));
|
||||
console.log(chalk.gray(` Confidence: ${validation.conclusion.confidence}`));
|
||||
console.log(chalk.white(` ${validation.conclusion.message}`));
|
||||
|
||||
} catch (error) {
|
||||
spinner3.fail('Demo 2 failed: ' + error.message);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DEMO 3: Performance Measurement
|
||||
// ============================================================================
|
||||
console.log(chalk.yellow('\n📏 Demo 3: Measuring System Performance\n'));
|
||||
|
||||
const spinner4 = ora('Measuring performance across configurations...').start();
|
||||
|
||||
try {
|
||||
const performance = await system.measurePerformance({
|
||||
agentCounts: [100, 500, 1000],
|
||||
matrixSizes: [100, 500],
|
||||
topologies: ['mesh', 'hierarchical']
|
||||
});
|
||||
|
||||
spinner4.succeed('Performance measurement completed!');
|
||||
|
||||
console.log(chalk.white('\n🏆 Performance Analysis:'));
|
||||
|
||||
// Best configurations
|
||||
console.log(chalk.white('\n By Agent Count:'));
|
||||
for (const [count, stats] of Object.entries(performance.analysis.byAgentCount)) {
|
||||
console.log(chalk.gray(` ${count} agents: ${stats.avgTimeMs}ms avg`));
|
||||
}
|
||||
|
||||
console.log(chalk.white('\n By Topology:'));
|
||||
for (const [topology, stats] of Object.entries(performance.analysis.byTopology)) {
|
||||
console.log(chalk.gray(` ${topology}: efficiency ${stats.avgEfficiency}`));
|
||||
}
|
||||
|
||||
console.log(chalk.white('\n💡 Recommendations:'));
|
||||
for (const rec of performance.recommendations) {
|
||||
const icon = rec.impact === 'HIGH' ? '🔴' : rec.impact === 'MEDIUM' ? '🟡' : '🟢';
|
||||
console.log(` ${icon} ${rec.category}: ${rec.recommendation}`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
spinner4.fail('Demo 3 failed: ' + error.message);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DEMO 4: Integrated System
|
||||
// ============================================================================
|
||||
console.log(chalk.yellow('\n🚀 Demo 4: Integrated Temporal Solving System\n'));
|
||||
|
||||
const spinner5 = ora('Creating integrated solving system...').start();
|
||||
|
||||
try {
|
||||
const integratedSystem = await system.createIntegratedSystem({
|
||||
name: 'GlobalTemporalSolver',
|
||||
targetDistance: 20000, // Half Earth circumference
|
||||
maxMatrixSize: 5000,
|
||||
agentBudget: 3000
|
||||
});
|
||||
|
||||
spinner5.succeed('Integrated system created!');
|
||||
|
||||
console.log(chalk.white('\n🌍 Integrated System Configuration:'));
|
||||
console.log(chalk.gray(` Name: ${integratedSystem.name}`));
|
||||
console.log(chalk.gray(` Main Solver Agents: ${integratedSystem.config.mainAgents}`));
|
||||
console.log(chalk.gray(` Verifier Agents: ${integratedSystem.config.verifierAgents}`));
|
||||
console.log(chalk.gray(` Target Matrix Size: ${integratedSystem.config.targetMatrixSize}`));
|
||||
console.log(chalk.gray(` Expected Speedup: ${integratedSystem.config.estimatedSpeedup.toFixed(2)}x`));
|
||||
|
||||
// Test the integrated system
|
||||
const testMatrix = system.generateDiagonallyDominantMatrix(500);
|
||||
const testVector = Array(500).fill(0).map(() => Math.random());
|
||||
|
||||
const spinner6 = ora('Testing integrated system...').start();
|
||||
|
||||
const integratedResult = await integratedSystem.solve(testMatrix, testVector);
|
||||
|
||||
spinner6.succeed('Integrated system test completed!');
|
||||
|
||||
console.log(chalk.white('\n✨ Integrated System Results:'));
|
||||
const integratedData = [
|
||||
['Total Time', `${integratedResult.timing.totalTimeMs} ms`],
|
||||
['Light Travel Time', `${integratedResult.timing.lightTravelTimeMs} ms`],
|
||||
['Temporal Advantage', chalk.green(`${integratedResult.timing.temporalAdvantageMs} ms`)],
|
||||
['Solved Before Arrival', integratedResult.timing.solvedBeforeArrival ? chalk.green('✅ YES') : chalk.red('❌ NO')],
|
||||
['Quantum Enhancement', `State ${integratedResult.phases.quantum.hint}`],
|
||||
['Verification Time', `${integratedResult.phases.verification.timeMs} ms`]
|
||||
];
|
||||
|
||||
console.log(table(integratedData));
|
||||
|
||||
// Monitor system
|
||||
const status = await integratedSystem.monitor();
|
||||
console.log(chalk.white('\n📡 System Status:'));
|
||||
console.log(chalk.gray(` Health: ${chalk.green(status.health)}`));
|
||||
console.log(chalk.gray(` Total Measurements: ${status.measurements.total}`));
|
||||
|
||||
// Optimize system
|
||||
if (status.measurements.total >= 10) {
|
||||
const optimization = await integratedSystem.optimize();
|
||||
console.log(chalk.white('\n🔧 Optimization Results:'));
|
||||
console.log(chalk.gray(` Status: ${optimization.status}`));
|
||||
if (optimization.optimizations) {
|
||||
for (const opt of optimization.optimizations) {
|
||||
console.log(chalk.gray(` • ${opt.action}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
spinner5.fail('Demo 4 failed: ' + error.message);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// SUMMARY
|
||||
// ============================================================================
|
||||
console.log(chalk.cyan.bold('\n╔══════════════════════════════════════════════════════════╗'));
|
||||
console.log(chalk.cyan.bold('║ DEMONSTRATION COMPLETE ║'));
|
||||
console.log(chalk.cyan.bold('╚══════════════════════════════════════════════════════════╝\n'));
|
||||
|
||||
console.log(chalk.white('🎯 Key Achievements:'));
|
||||
console.log(chalk.gray(' • Demonstrated temporal advantage for matrix solving'));
|
||||
console.log(chalk.gray(' • Validated sublinear scaling across configurations'));
|
||||
console.log(chalk.gray(' • Measured performance with different agent topologies'));
|
||||
console.log(chalk.gray(' • Created integrated system with quantum enhancement'));
|
||||
|
||||
console.log(chalk.white('\n💡 Applications:'));
|
||||
console.log(chalk.gray(' • High-frequency trading with geographic advantage'));
|
||||
console.log(chalk.gray(' • Satellite communication optimization'));
|
||||
console.log(chalk.gray(' • Distributed computing across data centers'));
|
||||
console.log(chalk.gray(' • Real-time prediction systems'));
|
||||
|
||||
console.log(chalk.green('\n✅ System ready for temporal-advantage computing!\n'));
|
||||
}
|
||||
|
||||
// Run demo
|
||||
if (require.main === module) {
|
||||
main().catch(console.error);
|
||||
}
|
||||
|
||||
module.exports = { main };
|
||||
Reference in New Issue
Block a user