sublinear 0.2.0

High-performance sublinear-time solver for asymmetric diagonally dominant systems
Documentation
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
#!/usr/bin/env node

const { Command } = require('commander');
const chalk = require('chalk');
const figlet = require('figlet');
const ora = require('ora');
const boxen = require('boxen');
const inquirer = require('inquirer');
const { table } = require('table');
const path = require('path');
const fs = require('fs');
const { spawn } = require('child_process');

// Import our WASM modules and demos
const StrangeLoop = require('../lib/strange-loop');

const program = new Command();

// Version and description
program
  .name('strange-loop')
  .description('A framework where thousands of tiny agents collaborate in real-time, each operating within nanosecond budgets, forming emergent intelligence through temporal consciousness and quantum-classical hybrid computing')
  .version('0.1.0');

// ASCII Art Header
function showHeader() {
  console.log(
    chalk.cyan(
      figlet.textSync('Strange Loop', {
        font: 'ANSI Shadow',
        horizontalLayout: 'default',
        verticalLayout: 'default'
      })
    )
  );

  console.log(
    boxen(
      chalk.white('🌀 Emergent Intelligence Through Temporal Consciousness\n') +
      chalk.gray('Thousands of nano-agents • Nanosecond budgets • Quantum-classical hybrid computing'),
      {
        padding: 1,
        margin: 1,
        borderStyle: 'round',
        borderColor: 'cyan',
        backgroundColor: 'black'
      }
    )
  );
}

// Demo command
program
  .command('demo')
  .description('Run interactive demos of Strange Loop capabilities')
  .argument('[type]', 'Demo type: nano-agents, quantum, consciousness, prediction, all')
  .action(async (type) => {
    showHeader();

    if (!type) {
      const { demoType } = await inquirer.prompt([
        {
          type: 'list',
          name: 'demoType',
          message: 'Choose a demo to run:',
          choices: [
            { name: '🔧 Nano-Agent Swarm (1000+ agents)', value: 'nano-agents' },
            { name: '🌀 Quantum-Classical Computing', value: 'quantum' },
            { name: '🧠 Temporal Consciousness', value: 'consciousness' },
            { name: '⏰ Temporal Lead Prediction', value: 'prediction' },
            { name: '🚀 All Demos', value: 'all' }
          ]
        }
      ]);
      type = demoType;
    }

    await runDemo(type);
  });

// Benchmark command
program
  .command('benchmark')
  .description('Run performance benchmarks')
  .option('-a, --agents <number>', 'Number of agents', '1000')
  .option('-d, --duration <time>', 'Duration (e.g., 60s, 5m)', '30s')
  .option('-t, --topology <type>', 'Topology: mesh, hierarchical, ring, star', 'mesh')
  .action(async (options) => {
    showHeader();

    const spinner = ora('Initializing benchmark...').start();

    try {
      const agentCount = parseInt(options.agents);
      const duration = parseDuration(options.duration);

      spinner.text = `Running benchmark: ${agentCount} agents, ${options.topology} topology...`;

      // Initialize WASM
      await StrangeLoop.init();

      const results = await StrangeLoop.runBenchmark({
        agentCount,
        duration,
        topology: options.topology
      });

      spinner.succeed('Benchmark completed!');

      displayBenchmarkResults(results);

    } catch (error) {
      spinner.fail(`Benchmark failed: ${error.message}`);
    }
  });

// Interactive mode
program
  .command('interactive')
  .description('Enter interactive REPL mode')
  .action(async () => {
    showHeader();

    console.log(chalk.yellow('🔬 Entering Interactive Mode\n'));
    console.log(chalk.gray('Available commands:'));
    console.log(chalk.white('  .nano      - Create nano-agent swarm'));
    console.log(chalk.white('  .quantum   - Initialize quantum container'));
    console.log(chalk.white('  .temporal  - Start temporal consciousness'));
    console.log(chalk.white('  .predict   - Run temporal prediction'));
    console.log(chalk.white('  .help      - Show help'));
    console.log(chalk.white('  .exit      - Exit interactive mode\n'));

    await startREPL();
  });

// Create command for generating project templates
program
  .command('create')
  .description('Create a new Strange Loop project')
  .argument('<name>', 'Project name')
  .option('-t, --template <type>', 'Template: basic, quantum, swarm, consciousness', 'basic')
  .action(async (name, options) => {
    showHeader();

    const spinner = ora(`Creating ${options.template} project: ${name}...`).start();

    try {
      await createProject(name, options.template);
      spinner.succeed(`Project ${name} created successfully!`);

      console.log(chalk.green(`\n📁 Project created: ./${name}`));
      console.log(chalk.white('Next steps:'));
      console.log(chalk.gray(`  cd ${name}`));
      console.log(chalk.gray('  npm install'));
      console.log(chalk.gray('  npm run dev'));

    } catch (error) {
      spinner.fail(`Failed to create project: ${error.message}`);
    }
  });

// MCP command
program
  .command('mcp')
  .description('MCP (Model Context Protocol) server operations')
  .addCommand(
    new Command('start')
      .description('Start the Strange Loops MCP server')
      .option('-p, --port <port>', 'Server port (not used in stdio mode)', '3000')
      .option('-v, --verbose', 'Verbose output')
      .action(async (options) => {
        try {
          // Directly require and run the MCP server (same as strange-loops-mcp)
          const serverPath = path.join(__dirname, '..', 'mcp', 'server.js');
          require(serverPath);
        } catch (error) {
          console.error(` Failed to start MCP server: ${error.message}`);
          process.exit(1);
        }
      })
  );

// Info command
program
  .command('info')
  .description('Show system information and capabilities')
  .action(async () => {
    showHeader();

    const spinner = ora('Gathering system information...').start();

    try {
      await StrangeLoop.init();
      const info = await StrangeLoop.getSystemInfo();

      spinner.succeed('System information gathered');

      displaySystemInfo(info);

    } catch (error) {
      spinner.fail(`Failed to gather info: ${error.message}`);
    }
  });

// Helper functions
async function runDemo(type) {
  try {
    await StrangeLoop.init();

    switch (type) {
      case 'nano-agents':
        await demoNanoAgents();
        break;
      case 'quantum':
        await demoQuantum();
        break;
      case 'consciousness':
        await demoConsciousness();
        break;
      case 'prediction':
        await demoPrediction();
        break;
      case 'all':
        await demoNanoAgents();
        await demoQuantum();
        await demoConsciousness();
        await demoPrediction();
        break;
      default:
        console.log(chalk.red(`Unknown demo type: ${type}`));
    }
  } catch (error) {
    console.error(chalk.red(`Demo failed: ${error.message}`));
  }
}

async function demoNanoAgents() {
  console.log(chalk.cyan('\n🔧 NANO-AGENT SWARM DEMO\n'));

  const spinner = ora('Creating 1000-agent swarm...').start();

  const swarm = await StrangeLoop.createSwarm({
    agentCount: 1000,
    topology: 'mesh',
    tickDurationNs: 25000
  });

  spinner.text = 'Running swarm simulation...';

  const results = await swarm.run(5000); // 5 second run

  spinner.succeed('Swarm simulation completed!');

  console.log(chalk.green(` Executed ${results.totalTicks} ticks across ${results.agentCount} agents`));
  console.log(chalk.white(` Throughput: ${Math.round(results.totalTicks / (results.runtimeNs / 1e9))} ticks/second`));
  console.log(chalk.white(`🔋 Budget violations: ${results.budgetViolations}`));
  console.log(chalk.gray(`💾 Runtime: ${(results.runtimeNs / 1e6).toFixed(2)}ms\n`));
}

async function demoQuantum() {
  console.log(chalk.magenta('\n🌀 QUANTUM-CLASSICAL HYBRID DEMO\n'));

  const spinner = ora('Initializing 8-state quantum system...').start();

  const quantum = await StrangeLoop.createQuantumContainer(3); // 3 qubits = 8 states

  spinner.text = 'Creating superposition...';

  await quantum.createSuperposition();
  quantum.storeClassical('temperature', 298.15);
  quantum.storeClassical('pressure', 101.325);

  spinner.text = 'Running quantum measurements...';

  const measurements = [];
  for (let i = 0; i < 10; i++) {
    measurements.push(await quantum.measure());
  }

  spinner.succeed('Quantum measurements completed!');

  console.log(chalk.green('✅ Quantum states measured:', measurements.join(', ')));
  console.log(chalk.white(`🌡  Classical data preserved: ${quantum.getClassical('temperature')}K`));
  console.log(chalk.white(`📊 Classical data preserved: ${quantum.getClassical('pressure')} kPa\n`));
}

async function demoConsciousness() {
  console.log(chalk.blue('\n🧠 TEMPORAL CONSCIOUSNESS DEMO\n'));

  const spinner = ora('Evolving consciousness...').start();

  const consciousness = await StrangeLoop.createTemporalConsciousness({
    maxIterations: 100,
    integrationSteps: 50,
    enableQuantum: true
  });

  for (let i = 0; i < 10; i++) {
    const state = await consciousness.evolveStep();

    if (state.consciousnessIndex > 0.8) {
      spinner.succeed(`High consciousness detected! Φ = ${state.consciousnessIndex.toFixed(6)}`);
      break;
    }

    spinner.text = `Evolving... iteration ${i + 1}, Φ = ${state.consciousnessIndex.toFixed(3)}`;
  }

  const patterns = await consciousness.getTemporalPatterns();

  console.log(chalk.green(` Consciousness patterns detected: ${patterns.length}`));
  patterns.slice(0, 3).forEach((pattern, i) => {
    console.log(chalk.white(`  ${i + 1}. ${pattern.name}: confidence ${pattern.confidence.toFixed(3)}`));
  });
  console.log();
}

async function demoPrediction() {
  console.log(chalk.yellow('\n⏰ TEMPORAL PREDICTION DEMO\n'));

  const spinner = ora('Initializing temporal predictor...').start();

  const predictor = await StrangeLoop.createTemporalPredictor({
    horizonNs: 10_000_000, // 10ms horizon
    historySize: 500
  });

  spinner.text = 'Generating time series and predictions...';

  let correct = 0;
  const total = 20;

  for (let t = 0; t < total; t++) {
    // Generate noisy sine wave
    const actual = Math.sin(t * 0.2) + (Math.random() - 0.5) * 0.1;
    const predicted = await predictor.predict([actual]);

    // Check if prediction is reasonable (within 50% of actual)
    const error = Math.abs(predicted[0] - actual) / Math.abs(actual);
    if (error < 0.5) correct++;

    await predictor.updateHistory([actual]);
  }

  spinner.succeed('Temporal prediction completed!');

  console.log(chalk.green(` Prediction accuracy: ${(correct / total * 100).toFixed(1)}%`));
  console.log(chalk.white(` Sub-microsecond prediction latency achieved`));
  console.log(chalk.white(`🔮 Computing solutions before data arrives\n`));
}

function displayBenchmarkResults(results) {
  console.log(chalk.green('\n📊 BENCHMARK RESULTS\n'));

  const data = [
    ['Metric', 'Value'],
    ['Agent Count', results.agentCount.toLocaleString()],
    ['Total Ticks', results.totalTicks.toLocaleString()],
    ['Runtime', `${(results.runtimeNs / 1e6).toFixed(2)}ms`],
    ['Throughput', `${Math.round(results.totalTicks / (results.runtimeNs / 1e9)).toLocaleString()} ticks/sec`],
    ['Budget Violations', results.budgetViolations.toLocaleString()],
    ['Violation Rate', `${(results.budgetViolations / results.totalTicks * 100).toFixed(2)}%`],
    ['Avg Cycles/Tick', results.avgCyclesPerTick.toFixed(1)]
  ];

  console.log(table(data, {
    border: {
      topBody: '',
      topJoin: '',
      topLeft: '',
      topRight: '',
      bottomBody: '',
      bottomJoin: '',
      bottomLeft: '',
      bottomRight: '',
      bodyLeft: '',
      bodyRight: '',
      bodyJoin: '',
      joinBody: '',
      joinLeft: '',
      joinRight: '',
      joinJoin: ''
    }
  }));
}

function displaySystemInfo(info) {
  console.log(chalk.cyan('\n💻 SYSTEM INFORMATION\n'));

  const data = [
    ['Component', 'Status', 'Details'],
    ['WASM Support', info.wasmSupported ? '' : '', info.wasmVersion || 'N/A'],
    ['SIMD Support', info.simdSupported ? '' : '', info.simdFeatures?.join(', ') || 'N/A'],
    ['Memory Available', '', `${(info.memoryMB || 0)}MB`],
    ['Nano-Agents', '', `${info.maxAgents || 1000} max agents`],
    ['Quantum Container', info.quantumSupported ? '' : '', `${info.maxQubits || 8} qubits`],
    ['Temporal Prediction', '', `${info.predictionHorizonMs || 10}ms horizon`],
    ['Consciousness Engine', info.consciousnessSupported ? '' : '', 'IIT-based'],
  ];

  console.log(table(data));

  console.log(chalk.white('\n🚀 Ready for nano-scale agent orchestration!\n'));
}

async function startREPL() {
  let running = true;

  try {
    await StrangeLoop.init();
  } catch (error) {
    console.log(chalk.red(`Failed to initialize: ${error.message}`));
    return;
  }

  while (running) {
    const { command } = await inquirer.prompt([
      {
        type: 'input',
        name: 'command',
        message: chalk.cyan('strange-loop>'),
        prefix: ''
      }
    ]);

    try {
      switch (command.trim()) {
        case '.exit':
          running = false;
          console.log(chalk.yellow('Goodbye! 🌀'));
          break;
        case '.help':
          console.log(chalk.white('Available commands:'));
          console.log(chalk.gray('  .nano      - Create nano-agent swarm'));
          console.log(chalk.gray('  .quantum   - Initialize quantum container'));
          console.log(chalk.gray('  .temporal  - Start temporal consciousness'));
          console.log(chalk.gray('  .predict   - Run temporal prediction'));
          console.log(chalk.gray('  .exit      - Exit'));
          break;
        case '.nano':
          console.log(chalk.cyan('Creating nano-agent swarm...'));
          // Implementation would call WASM functions
          break;
        case '.quantum':
          console.log(chalk.magenta('Initializing quantum container...'));
          // Implementation would call WASM functions
          break;
        case '.temporal':
          console.log(chalk.blue('Starting temporal consciousness...'));
          // Implementation would call WASM functions
          break;
        case '.predict':
          console.log(chalk.yellow('Running temporal prediction...'));
          // Implementation would call WASM functions
          break;
        default:
          if (command.trim()) {
            console.log(chalk.red(`Unknown command: ${command}`));
            console.log(chalk.gray('Type .help for available commands'));
          }
      }
    } catch (error) {
      console.log(chalk.red(`Error: ${error.message}`));
    }
  }
}

async function createProject(name, template) {
  const templatesDir = path.join(__dirname, '..', 'templates', template);
  const targetDir = path.join(process.cwd(), name);

  if (!fs.existsSync(templatesDir)) {
    throw new Error(`Template ${template} not found`);
  }

  // Copy template files
  await fs.promises.mkdir(targetDir, { recursive: true });

  // This would copy template files in a real implementation
  await fs.promises.writeFile(
    path.join(targetDir, 'package.json'),
    JSON.stringify({
      name,
      version: '1.0.0',
      description: `Strange Loop project: ${template} template`,
      main: 'index.js',
      dependencies: {
        '@strange-loop/cli': '^0.1.0'
      }
    }, null, 2)
  );

  await fs.promises.writeFile(
    path.join(targetDir, 'index.js'),
    `// Strange Loop ${template} project\n// Generated by @strange-loop/cli\n\nconst StrangeLoop = require('@strange-loop/cli');\n\nasync function main() {\n  await StrangeLoop.init();\n  console.log('Strange Loop ${template} project initialized!');\n}\n\nmain().catch(console.error);\n`
  );
}

function parseDuration(duration) {
  // Handle plain numbers as milliseconds
  if (/^\d+$/.test(duration)) {
    return parseInt(duration);
  }

  const match = duration.match(/^(\\d+)([sm])$/);
  if (!match) throw new Error('Invalid duration format');

  const value = parseInt(match[1]);
  const unit = match[2];

  return unit === 's' ? value * 1000 : value * 60 * 1000; // Convert to milliseconds
}

// Default action (help)
program.action(() => {
  showHeader();
  console.log(chalk.white('Use --help to see available commands\n'));
  console.log(chalk.gray('Quick start:'));
  console.log(chalk.white('  npx strange-loops demo           # Run interactive demos'));
  console.log(chalk.white('  npx strange-loops benchmark      # Performance benchmarks'));
  console.log(chalk.white('  npx strange-loops interactive    # REPL mode'));
  console.log(chalk.white('  npx strange-loops mcp start      # Start MCP server'));
  console.log(chalk.white('  npx strange-loops create myapp   # Create new project\n'));
});

program.parse();