File size: 5,871 Bytes
57e1bdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Patch additions for Tier 1 integration in script.js

// 1. Replace the existing AI orchestration with Federation
document.addEventListener('DOMContentLoaded', () => {
    // Initialize Tier 1 systems
    window.wasmSecurity.init().then(() => {
        console.log('[TIER-1] WASM Security Core initialized');
    });

    // Register AI models for federation
    window.aiFederation.registerModel('deepseek', { type: 'deepseek', priority: 1 });
    window.aiFederation.registerModel('mistral', { type: 'mistral', priority: 2 });
    window.aiFederation.registerModel('llama', { type: 'llama', priority: 3 });
    window.aiFederation.registerModel('gemma', { type: 'local', priority: 4 });

    // 2. Replace generate button handler with Federated consensus
    const generateBtn = document.getElementById('generate-btn');
    if (generateBtn) {
        generateBtn.addEventListener('click', async () => {
            // Firewall check first
            const rateCheck = window.ironFirewall.checkRateLimit('API_CALL', 'generate');
            if (!rateCheck.allowed) {
                showToast(`Security: ${rateCheck.reason}. Wait ${rateCheck.retryAfter}s`, 'error');
                return;
            }

            const inputCheck = window.ironFirewall.sanitizeInput(
                document.getElementById('report-input').value
            );
            
            if (!inputCheck.safe) {
                showToast(`Security Violation: ${inputCheck.threats.join(', ')}`, 'error');
                return;
            }

            // Proceed with federated consensus
            try {
                generateBtn.disabled = true;
                generateBtn.innerHTML = '<i data-feather="loader"></i> Consensus Building...';
                
                const consensus = await window.aiFederation.proposeConsensus(
                    document.getElementById('report-input').value,
                    { timeout: 15000 }
                );

                if (consensus.status === 'CONSENSUS') {
                    displayConsensusResult(consensus);
                    window.federationBus.emit('NARRATIVE_GENERATED', consensus);
                } else {
                    showToast('Partial consensus - Review minority reports', 'warning');
                }
                
            } catch (err) {
                handleProductionError(err, 'Federation Consensus');
            } finally {
                generateBtn.disabled = false;
                generateBtn.innerHTML = '<i data-feather="cpu"></i> Initialize MEGA Federation';
            }
        });
    }

    // 3. Subscribe to system events
    window.federationBus.subscribe('SECURITY_THREAT', (payload) => {
        if (payload.score > 50) {
            document.body.style.filter = 'grayscale(0.5)';
        }
    });

    window.federationBus.subscribe('SYSTEM_LOCKDOWN', () => {
        document.getElementById('output-container').innerHTML = 
            '<div class="text-red-500 text-center text-2xl font-bold mt-20">🔒 SYSTEM LOCKED 🔒</div>';
    });

    // 4. Enhanced initCognitiveView with Federation
    const originalInitCognitive = window.initializeViewComponents;
    window.initializeViewComponents = function(viewName) {
        if (viewName === 'cognitive') {
            const cognitiveCore = document.getElementById('main-cognitive-core');
            if (cognitiveCore && !cognitiveCore._tier1) {
                cognitiveCore._tier1 = true;
                
                cognitiveCore.addEventListener('message-sent', async (e) => {
                    const query = e?.detail?.message;
                    
                    // Use federation instead of single model
                    const result = await window.aiFederation.proposeConsensus(query);
                    
                    // Display reasoning trace from all models
                    updateFederatedTrace(result);
                });
            }
        }
        if (originalInitCognitive) originalInitCognitive(viewName);
    };

    function updateFederatedTrace(consensus) {
        const container = document.getElementById('reasoning-trace');
        if (!container) return;

        const html = `
            <div class="mb-2 text-green-400 font-bold">CONSENSUS: ${Math.round(consensus.agreement * 100)}% Agreement</div>
            <div class="space-y-2">
                ${consensus.minorityReports.length > 0 ? 
                    `<div class="text-yellow-400 text-xs">⚠️ ${consensus.minorityReports.length} models dissented</div>` 
                    : '<div class="text-green-400 text-xs">✓ Unanimous agreement</div>'}
            </div>
            <div class="mt-2 text-xs text-slate-500">Latency: ${consensus.latency}ms | Hash: ${consensus.winningHash?.substring(0, 16)}...</div>
        `;
        
        container.innerHTML = html;
    }

    function displayConsensusResult(consensus) {
        const output = document.getElementById('output-container');
        if (output) {
            output.innerHTML = `
                <div class="border border-green-500/30 bg-green-900/10 p-4 rounded">
                    <div class="flex justify-between items-center mb-4">
                        <span class="text-green-400 font-bold">FEDERATED CONSENSUS</span>
                        <span class="text-xs text-slate-400">${consensus.latency}ms</span>
                    </div>
                    <div class="text-slate-300 text-sm leading-relaxed font-mono">
                        ${consensus.winningOutput}
                    </div>
                    <div class="mt-4 pt-4 border-t border-green-500/20 text-xs text-slate-500">
                        Models: ${window.aiFederation.models.size} | Agreement: ${Math.round(consensus.agreement * 100)}%
                    </div>
                </div>
            `;
        }
    }
});