ruvector/examples/edge-net/sim/src/report.ts
rUv 383c791101 feat(edge-net): add Pi-Key crypto, lifecycle simulation, optimizations
- Add Pi-Key WASM cryptographic module with mathematical constant sizing
  - Pi-sized (314 bits/40 bytes) identity keys
  - Euler-sized (271 bits/34 bytes) session keys
  - Phi-sized (161 bits/21 bytes) genesis keys
  - Ed25519 signing + AES-256-GCM encryption

- Add comprehensive TypeScript lifecycle simulation (sim/)
  - 6 source files, 1,420 lines
  - Validates all 4 phases: Genesis → Growth → Maturation → Independence
  - Economic sustainability and phase transition testing

- Performance optimizations
  - FxHashMap for 30-50% faster lookups in evolution/mod.rs
  - VecDeque for O(1) front removal
  - Batched Q-learning updates in security/mod.rs
  - Fixed borrow checker error in process_batch_updates()

- Add benchmarks and documentation
  - BENCHMARKS.md with performance metrics
  - PERFORMANCE_OPTIMIZATIONS.md with details
  - docs/FINAL_REPORT.md comprehensive summary

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-01 01:29:11 +00:00

246 lines
8.2 KiB
TypeScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Report Generation
* Generates comprehensive JSON reports of simulation results
*/
import { writeFileSync } from 'fs';
import { Network } from './network.js';
import { MetricsCollector, PhaseMetrics } from './metrics.js';
export interface SimulationReport {
metadata: {
timestamp: string;
simulationVersion: string;
duration: number;
totalTicks: number;
};
configuration: {
genesisNodeCount: number;
targetNodeCount: number;
nodesPerTick: number;
taskGenerationRate: number;
baseTaskReward: number;
};
summary: {
phasesCompleted: number;
totalPassed: boolean;
phasesPassed: number;
phasesTotal: number;
finalNodeCount: number;
finalPhase: string;
};
phases: {
[key: string]: PhaseMetrics;
};
finalState: {
nodeCount: number;
genesisNodes: any;
economy: any;
network: any;
topPerformers: any[];
};
validation: {
overallPassed: boolean;
criticalIssues: string[];
warnings: string[];
successes: string[];
};
}
export class ReportGenerator {
private network: Network;
private metrics: MetricsCollector;
private startTime: number;
constructor(network: Network, metrics: MetricsCollector) {
this.network = network;
this.metrics = metrics;
this.startTime = Date.now();
}
/**
* Generate comprehensive simulation report
*/
public generateReport(): SimulationReport {
const endTime = Date.now();
const stats = this.network.getStats();
const allMetrics = this.metrics.getAllMetrics();
const overallSuccess = this.metrics.getOverallSuccess();
// Organize metrics by phase
const phaseMetrics: { [key: string]: PhaseMetrics } = {};
allMetrics.forEach(m => {
phaseMetrics[m.phase] = m;
});
// Get top performing nodes
const topPerformers = this.getTopPerformers(10);
// Collect validation issues
const validation = this.collectValidation(allMetrics);
const report: SimulationReport = {
metadata: {
timestamp: new Date().toISOString(),
simulationVersion: '1.0.0',
duration: endTime - this.startTime,
totalTicks: this.network.currentTick,
},
configuration: {
genesisNodeCount: this.network.config.genesisNodeCount,
targetNodeCount: this.network.config.targetNodeCount,
nodesPerTick: this.network.config.nodesPerTick,
taskGenerationRate: this.network.config.taskGenerationRate,
baseTaskReward: this.network.config.baseTaskReward,
},
summary: {
phasesCompleted: allMetrics.length,
totalPassed: overallSuccess.passed,
phasesPassed: overallSuccess.totalPassed,
phasesTotal: overallSuccess.totalPhases,
finalNodeCount: stats.nodeCount,
finalPhase: this.network.currentPhase,
},
phases: phaseMetrics,
finalState: {
nodeCount: stats.nodeCount,
genesisNodes: stats.genesisNodes,
economy: stats.economy,
network: stats.network,
topPerformers,
},
validation,
};
return report;
}
/**
* Get top performing nodes
*/
private getTopPerformers(count: number): any[] {
const cells = Array.from(this.network.cells.values());
return cells
.sort((a, b) => {
const scoreA = a.metrics.energyEarned - a.metrics.energySpent;
const scoreB = b.metrics.energyEarned - b.metrics.energySpent;
return scoreB - scoreA;
})
.slice(0, count)
.map(cell => ({
id: cell.id.substring(0, 8),
type: cell.type,
netEnergy: cell.metrics.energyEarned - cell.metrics.energySpent,
tasksCompleted: cell.metrics.tasksCompleted,
successRate: (cell.metrics.successRate * 100).toFixed(1) + '%',
connections: cell.connectedCells.size,
fitnessScore: cell.getFitnessScore().toFixed(3),
}));
}
/**
* Collect all validation issues
*/
private collectValidation(allMetrics: PhaseMetrics[]): {
overallPassed: boolean;
criticalIssues: string[];
warnings: string[];
successes: string[];
} {
const criticalIssues: string[] = [];
const warnings: string[] = [];
const successes: string[] = [];
allMetrics.forEach(metrics => {
if (!metrics.validation.passed) {
criticalIssues.push(`${metrics.phase.toUpperCase()} phase failed validation`);
}
metrics.validation.reasons.forEach(reason => {
if (reason.startsWith('✓')) {
successes.push(`${metrics.phase}: ${reason}`);
} else if (reason.includes('too low') || reason.includes('insufficient')) {
warnings.push(`${metrics.phase}: ${reason}`);
} else {
criticalIssues.push(`${metrics.phase}: ${reason}`);
}
});
});
return {
overallPassed: criticalIssues.length === 0,
criticalIssues,
warnings,
successes,
};
}
/**
* Save report to file
*/
public saveReport(filepath: string): void {
const report = this.generateReport();
writeFileSync(filepath, JSON.stringify(report, null, 2), 'utf-8');
console.log(`\n📄 Report saved to: ${filepath}`);
}
/**
* Print summary to console
*/
public printSummary(): void {
const report = this.generateReport();
console.log('\n╔════════════════════════════════════════════════════════════╗');
console.log('║ EDGE-NET LIFECYCLE SIMULATION REPORT ║');
console.log('╚════════════════════════════════════════════════════════════╝\n');
console.log('📊 SUMMARY:');
console.log(` Duration: ${(report.metadata.duration / 1000).toFixed(2)}s`);
console.log(` Total Ticks: ${report.metadata.totalTicks.toLocaleString()}`);
console.log(` Final Nodes: ${report.summary.finalNodeCount.toLocaleString()}`);
console.log(` Final Phase: ${report.summary.finalPhase.toUpperCase()}`);
console.log(` Phases Passed: ${report.summary.phasesPassed}/${report.summary.phasesTotal}`);
console.log(` Overall Result: ${report.summary.totalPassed ? '✅ PASSED' : '❌ FAILED'}\n`);
console.log('📈 PHASE RESULTS:');
Object.entries(report.phases).forEach(([phase, metrics]) => {
const icon = metrics.validation.passed ? '✅' : '❌';
console.log(` ${icon} ${phase.toUpperCase()}:`);
console.log(` Nodes: ${metrics.nodeCount.start.toLocaleString()}${metrics.nodeCount.end.toLocaleString()}`);
console.log(` Energy: ${metrics.energy.netEnergy.toFixed(2)} rUv (${metrics.energy.sustainability.toFixed(2)}x sustainable)`);
console.log(` Tasks: ${metrics.network.tasksCompleted.toLocaleString()} completed`);
console.log(` Success Rate: ${(metrics.network.avgSuccessRate * 100).toFixed(1)}%`);
});
console.log('\n🏆 TOP PERFORMERS:');
report.finalState.topPerformers.slice(0, 5).forEach((node, i) => {
console.log(` ${i + 1}. ${node.id} (${node.type})`);
console.log(` Net Energy: ${node.netEnergy.toFixed(2)} rUv | Tasks: ${node.tasksCompleted} | Success: ${node.successRate}`);
});
if (report.validation.criticalIssues.length > 0) {
console.log('\n🚨 CRITICAL ISSUES:');
report.validation.criticalIssues.forEach(issue => {
console.log(`${issue}`);
});
}
if (report.validation.warnings.length > 0) {
console.log('\n⚠ WARNINGS:');
report.validation.warnings.slice(0, 5).forEach(warning => {
console.log(` ⚠️ ${warning}`);
});
if (report.validation.warnings.length > 5) {
console.log(` ... and ${report.validation.warnings.length - 5} more warnings`);
}
}
console.log('\n✅ SUCCESSES:');
report.validation.successes.slice(0, 10).forEach(success => {
console.log(` ${success}`);
});
console.log('\n╚════════════════════════════════════════════════════════════╝\n');
}
}