UNPKG

universal-life-protocol-core

Version:

Revolutionary AI framework implementing living, conscious digital reality with meta-cognitive reasoning, attention economics, and autonomous learning

213 lines 8.78 kB
import { CryptoUtil } from './crypto.js'; import { existsSync, readFileSync, writeFileSync } from 'fs'; // Import new modules import { CrtModule } from './crt-module.js'; import { CtlConsensus } from './ctl-consensus.js'; import { CepEngine } from './cep-engine.js'; import { ClarionMduAgent } from './clarion-mdu-agent.js'; const log = (peerId, message, color) => { const timestamp = new Date().toISOString().split('T')[1].split('.')[0]; console.log(`[${timestamp}][${peerId.slice(-6)}] ${message}`); }; export class CuePeer { stateFilePath; credentialId; privateKey; // MODIFIED STATE MANAGEMENT to support Phase 1 enhancements entityStates = new Map(); // NEW MODULE INTEGRATIONS for Phase 2 & 3 ctl; cep; agent; eventBroadcastCallback; constructor(stateFilePath) { this.stateFilePath = stateFilePath; const { publicKey, privateKey } = this.loadOrGenerateIdentity(); this.credentialId = publicKey; this.privateKey = privateKey; this.cep = new CepEngine(); this.setupCepRules(); log(this.credentialId, `Peer identity loaded/generated.`); } loadOrGenerateIdentity() { if (existsSync(this.stateFilePath)) { const stateData = JSON.parse(readFileSync(this.stateFilePath, 'utf-8')); // Re-hydrate the Map from the saved array if (stateData.entityStates) { this.entityStates = new Map(stateData.entityStates); } return { publicKey: stateData.credentialId, privateKey: stateData.privateKey }; } const { publicKey, privateKey } = CryptoUtil.generateKeyPair(); return { publicKey, privateKey }; } saveState() { const state = { credentialId: this.credentialId, privateKey: this.privateKey, // Convert Map to array for JSON serialization entityStates: Array.from(this.entityStates.entries()), }; writeFileSync(this.stateFilePath, JSON.stringify(state, null, 2)); } setupCepRules() { const resonanceRule = { id: 'harmonic-resonance-rule', pattern: (event) => event.type === 'STATE_CHANGED', action: (matchedEvents) => { const stateChangeEvent = matchedEvents[matchedEvents.length - 1]; const { entityId } = stateChangeEvent.payload; const entityState = this.entityStates.get(entityId); if (entityState && CrtModule.checkHarmonicResonance(entityState.multiDomainState, ['daily', 'weekly'])) { const resonanceEvent = { type: 'HARMONIC_RESONANCE_TRIGGER', level: 'GROUP', payload: { entityId: entityId, resonantDomains: ['daily', 'weekly'] }, timestamp: Date.now() }; log(this.credentialId, `[CEP] Harmonic Resonance Detected for entity ${entityId}!`); this.broadcast(resonanceEvent); } } }; this.cep.registerRule(resonanceRule); } // --- Core Simulation & Protocol Methods --- initializeCtl(validatorIds) { this.ctl = new CtlConsensus(validatorIds); log(this.credentialId, 'CTL Consensus module initialized.'); } runCtlConsensusRound(roundSeed) { if (!this.ctl) { log(this.credentialId, 'CTL not initialized.'); return; } log(this.credentialId, `[CTL] Running new consensus round with seed: ${roundSeed}`); const quorum = this.ctl.getActivatedQuorum(roundSeed); if (quorum) { const event = { type: 'CTL_QUORUM_ACTIVATED', level: 'GROUP', payload: { quorum: [...quorum], roundSeed }, timestamp: Date.now() }; log(this.credentialId, `[CTL] Consensus Quorum Activated: Validators ${[...quorum].map(q => q.slice(-6)).join(', ')}`); this.broadcast(event); } else { log(this.credentialId, '[CTL] Failed to activate a quorum this round.'); } } hostAgent(agentId) { this.agent = new ClarionMduAgent(agentId, this); this.initializeEntity(agentId); log(this.credentialId, `Peer is now hosting agent ${agentId}.`); } runAgentDecision(agentId) { if (!this.agent || this.agent.id !== agentId) return; const agentState = this.entityStates.get(agentId); if (!agentState) return; // For simulation, we create a dummy weighted state const weightedState = { L: agentState.currentL, A: agentState.multiDomainState.get('default')?.A || 0, B: agentState.multiDomainState.get('default')?.B || 7, w: Math.random() * 10 // Dummy weight }; const possibleActions = ['explore', 'exploit', 'reconfigure']; const action = this.agent.decideNextAction(weightedState, possibleActions); // Simulate outcome and learning const reward = Math.random() > 0.5 ? 5 : -1; const nextL = agentState.currentL + (Math.random() > 0.9 ? 1 : 0); // Chance of L-transition const nextA = (weightedState.A + 1) % weightedState.B; const nextState = { ...weightedState, L: nextL, A: nextA, w: weightedState.w + reward }; this.agent.learnFromExperience(weightedState, action, reward, nextState); const event = { type: 'AGENT_ACTION', level: 'LOCAL', payload: { agentId, action, reward, state: weightedState }, timestamp: Date.now() }; this.broadcast(event); } initializeEntity(entityId, domains = { 'default': 7, 'daily': 24, 'weekly': 7 }) { if (this.entityStates.has(entityId)) return; const multiDomainState = new Map(); for (const [name, base] of Object.entries(domains)) { multiDomainState.set(name, { A: 0, B: base }); } const state = { entityId, currentL: 0, multiDomainState, baseHistory: [] }; this.entityStates.set(entityId, state); log(this.credentialId, `Initialized new entity: ${entityId}`); } updateEntityState(entityId) { const entityState = this.entityStates.get(entityId); if (!entityState) return; for (const [domain, state] of entityState.multiDomainState.entries()) { state.A = (state.A + 1) % state.B; if (state.A === 0) { // L-transition for this domain log(this.credentialId, `Entity ${entityId} completed a cycle in domain '${domain}'.`); if (domain === 'default') { entityState.currentL += 1; entityState.baseHistory.push(state.B); } } } this.entityStates.set(entityId, entityState); const event = { type: 'STATE_CHANGED', level: 'LOCAL', payload: { entityId, newState: { L: entityState.currentL, A: entityState.multiDomainState.get('default')?.A } }, timestamp: Date.now() }; this.broadcast(event); this.saveState(); } // --- Networking --- sign(payload) { const payloadStr = JSON.stringify(payload); return { payload, sourceCredentialId: this.credentialId, signature: CryptoUtil.sign(payloadStr, this.privateKey) }; } broadcast(event) { // Process event through CEP engine this.cep.processEvent(event); // Call external broadcast callback if set if (this.eventBroadcastCallback) { this.eventBroadcastCallback(event); } } setBroadcastCallback(callback) { this.eventBroadcastCallback = callback; } processIncomingEvent(signedEvent) { const payloadStr = JSON.stringify(signedEvent.payload); if (!CryptoUtil.verify(payloadStr, signedEvent.signature, signedEvent.sourceCredentialId)) { log(this.credentialId, `Invalid signature from ${signedEvent.sourceCredentialId.slice(-6)}`); return false; } log(this.credentialId, `Received valid event '${signedEvent.payload.type}' from ${signedEvent.sourceCredentialId.slice(-6)}`); this.cep.processEvent(signedEvent.payload); return true; } // --- Getters for testing --- getEntityStates() { return new Map(this.entityStates); } getCepEngine() { return this.cep; } getAgent() { return this.agent; } } //# sourceMappingURL=cue-peer.js.map