| "use strict"; |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| Object.defineProperty(exports, "__esModule", { value: true }); |
| exports.NeuralSubstrate = exports.CoherenceMonitor = exports.SwarmCoordinator = exports.EmbeddingStateMachine = exports.MemoryPhysics = exports.SemanticDriftDetector = exports.silentLogger = exports.defaultLogger = exports.NEURAL_CONSTANTS = void 0; |
| |
| |
| |
| exports.NEURAL_CONSTANTS = { |
| |
| MAX_DRIFT_EVENTS: 1000, |
| MAX_HISTORY_SIZE: 500, |
| DEFAULT_DRIFT_THRESHOLD: 0.15, |
| DEFAULT_DRIFT_WINDOW_MS: 60000, |
| DRIFT_CRITICAL_MULTIPLIER: 2, |
| VELOCITY_WINDOW_SIZE: 10, |
| |
| MAX_MEMORIES: 10000, |
| MAX_CONTENT_LENGTH: 10000, |
| MAX_ID_LENGTH: 256, |
| DEFAULT_MEMORY_DECAY_RATE: 0.01, |
| DEFAULT_INTERFERENCE_THRESHOLD: 0.8, |
| DEFAULT_CONSOLIDATION_RATE: 0.1, |
| MEMORY_FORGET_THRESHOLD: 0.01, |
| CONSOLIDATION_SCORE_THRESHOLD: 0.5, |
| MEMORY_CLEANUP_PERCENT: 0.1, |
| RECALL_STRENGTH_BOOST: 0.1, |
| MAX_TIME_JUMP_MINUTES: 1440, |
| |
| MAX_AGENTS: 1000, |
| MAX_SPECIALTY_LENGTH: 100, |
| AGENT_TIMEOUT_MS: 3600000, |
| DEFAULT_AGENT_ENERGY: 1.0, |
| TRAJECTORY_DAMPING: 0.1, |
| MAX_TRAJECTORY_STEPS: 100, |
| |
| MAX_CLUSTER_AGENTS: 500, |
| DEFAULT_CLUSTER_THRESHOLD: 0.7, |
| |
| DEFAULT_WINDOW_SIZE: 100, |
| MIN_CALIBRATION_OBSERVATIONS: 10, |
| STABILITY_WINDOW_SIZE: 10, |
| ALIGNMENT_WINDOW_SIZE: 50, |
| RECENT_OBSERVATIONS_SIZE: 20, |
| DRIFT_WARNING_THRESHOLD: 0.3, |
| STABILITY_WARNING_THRESHOLD: 0.5, |
| ALIGNMENT_WARNING_THRESHOLD: 0.6, |
| COHERENCE_WARNING_THRESHOLD: 0.5, |
| |
| EPSILON: 1e-8, |
| ZERO_VECTOR_THRESHOLD: 1e-10, |
| |
| DEFAULT_DIMENSION: 384, |
| DEFAULT_REFLEX_LATENCY_MS: 10, |
| }; |
| |
| exports.defaultLogger = { |
| log(level, message, data) { |
| const prefix = `[Neural:${level.toUpperCase()}]`; |
| if (data) { |
| console[level === 'debug' ? 'log' : level](`${prefix} ${message}`, data); |
| } |
| else { |
| console[level === 'debug' ? 'log' : level](`${prefix} ${message}`); |
| } |
| }, |
| }; |
| |
| exports.silentLogger = { |
| log() { }, |
| }; |
| |
| |
| |
| |
| |
| |
| |
| class SemanticDriftDetector { |
| constructor(config = {}) { |
| this.baseline = null; |
| this.history = []; |
| this.driftEvents = []; |
| |
| this.reflexes = new Map(); |
| this.config = { |
| dimension: config.dimension ?? exports.NEURAL_CONSTANTS.DEFAULT_DIMENSION, |
| driftThreshold: config.driftThreshold ?? exports.NEURAL_CONSTANTS.DEFAULT_DRIFT_THRESHOLD, |
| driftWindowMs: config.driftWindowMs ?? exports.NEURAL_CONSTANTS.DEFAULT_DRIFT_WINDOW_MS, |
| }; |
| this.logger = config.logger ?? exports.defaultLogger; |
| } |
| |
| |
| |
| setBaseline(embedding) { |
| this.baseline = embedding instanceof Float32Array |
| ? new Float32Array(embedding) |
| : new Float32Array(embedding); |
| } |
| |
| |
| |
| observe(embedding, source) { |
| const emb = embedding instanceof Float32Array |
| ? embedding |
| : new Float32Array(embedding); |
| const now = Date.now(); |
| |
| this.history.push({ embedding: new Float32Array(emb), timestamp: now }); |
| |
| const cutoff = now - this.config.driftWindowMs; |
| this.history = this.history.filter(h => h.timestamp > cutoff); |
| |
| if (this.history.length > exports.NEURAL_CONSTANTS.MAX_HISTORY_SIZE) { |
| this.history = this.history.slice(-exports.NEURAL_CONSTANTS.MAX_HISTORY_SIZE); |
| } |
| |
| if (!this.baseline) { |
| this.baseline = new Float32Array(emb); |
| return null; |
| } |
| |
| const drift = this.calculateDrift(emb, this.baseline); |
| |
| let category = 'normal'; |
| if (drift.magnitude > this.config.driftThreshold * exports.NEURAL_CONSTANTS.DRIFT_CRITICAL_MULTIPLIER) { |
| category = 'critical'; |
| } |
| else if (drift.magnitude > this.config.driftThreshold) { |
| category = 'warning'; |
| } |
| const event = { |
| timestamp: now, |
| magnitude: drift.magnitude, |
| direction: drift.direction, |
| category, |
| source, |
| }; |
| |
| if (category !== 'normal') { |
| this.driftEvents.push(event); |
| |
| if (this.driftEvents.length > exports.NEURAL_CONSTANTS.MAX_DRIFT_EVENTS) { |
| this.driftEvents = this.driftEvents.slice(-exports.NEURAL_CONSTANTS.MAX_DRIFT_EVENTS); |
| } |
| this.triggerReflexes(event); |
| } |
| return event; |
| } |
| |
| |
| |
| calculateDrift(current, reference) { |
| const direction = new Float32Array(current.length); |
| let magnitudeSq = 0; |
| for (let i = 0; i < current.length; i++) { |
| const diff = current[i] - reference[i]; |
| direction[i] = diff; |
| magnitudeSq += diff * diff; |
| } |
| const magnitude = Math.sqrt(magnitudeSq); |
| |
| if (magnitude > 0) { |
| for (let i = 0; i < direction.length; i++) { |
| direction[i] /= magnitude; |
| } |
| } |
| return { magnitude, direction }; |
| } |
| |
| |
| |
| registerReflex(name, callback) { |
| this.reflexes.set(name, callback); |
| } |
| |
| |
| |
| triggerReflexes(event) { |
| const errors = []; |
| for (const [name, callback] of this.reflexes) { |
| try { |
| callback(event); |
| } |
| catch (e) { |
| |
| errors.push({ reflex: name, error: e }); |
| } |
| } |
| |
| if (errors.length > 0 && errors.length >= this.reflexes.size / 2) { |
| this.logger.log('warn', `${errors.length}/${this.reflexes.size} reflexes failed`, { |
| failedReflexes: errors.map(e => e.reflex), |
| }); |
| } |
| } |
| |
| |
| |
| getVelocity() { |
| if (this.history.length < 2) |
| return 0; |
| const recent = this.history.slice(-exports.NEURAL_CONSTANTS.VELOCITY_WINDOW_SIZE); |
| if (recent.length < 2) |
| return 0; |
| let totalDrift = 0; |
| for (let i = 1; i < recent.length; i++) { |
| const drift = this.calculateDrift(recent[i].embedding, recent[i - 1].embedding); |
| totalDrift += drift.magnitude; |
| } |
| const timeSpan = recent[recent.length - 1].timestamp - recent[0].timestamp; |
| return timeSpan > 0 ? totalDrift / timeSpan * 1000 : 0; |
| } |
| |
| |
| |
| getStats() { |
| const currentDrift = this.history.length > 0 && this.baseline |
| ? this.calculateDrift(this.history[this.history.length - 1].embedding, this.baseline).magnitude |
| : 0; |
| return { |
| currentDrift, |
| velocity: this.getVelocity(), |
| criticalEvents: this.driftEvents.filter(e => e.category === 'critical').length, |
| warningEvents: this.driftEvents.filter(e => e.category === 'warning').length, |
| historySize: this.history.length, |
| }; |
| } |
| |
| |
| |
| recenter() { |
| if (this.history.length > 0) { |
| this.baseline = new Float32Array(this.history[this.history.length - 1].embedding); |
| } |
| } |
| } |
| exports.SemanticDriftDetector = SemanticDriftDetector; |
| |
| |
| |
| |
| |
| |
| |
| class MemoryPhysics { |
| constructor(config = {}) { |
| this.memories = new Map(); |
| this.lastUpdate = Date.now(); |
| this.config = { |
| dimension: config.dimension ?? exports.NEURAL_CONSTANTS.DEFAULT_DIMENSION, |
| memoryDecayRate: config.memoryDecayRate ?? exports.NEURAL_CONSTANTS.DEFAULT_MEMORY_DECAY_RATE, |
| interferenceThreshold: config.interferenceThreshold ?? exports.NEURAL_CONSTANTS.DEFAULT_INTERFERENCE_THRESHOLD, |
| consolidationRate: config.consolidationRate ?? exports.NEURAL_CONSTANTS.DEFAULT_CONSOLIDATION_RATE, |
| }; |
| this.logger = config.logger ?? exports.defaultLogger; |
| } |
| |
| |
| |
| encode(id, embedding, content) { |
| |
| if (typeof id !== 'string' || id.length === 0 || id.length > exports.NEURAL_CONSTANTS.MAX_ID_LENGTH) { |
| throw new Error(`Invalid memory ID: must be string of 1-${exports.NEURAL_CONSTANTS.MAX_ID_LENGTH} characters`); |
| } |
| if (typeof content !== 'string' || content.length > exports.NEURAL_CONSTANTS.MAX_CONTENT_LENGTH) { |
| throw new Error(`Content exceeds maximum length: ${exports.NEURAL_CONSTANTS.MAX_CONTENT_LENGTH}`); |
| } |
| if (this.memories.size >= exports.NEURAL_CONSTANTS.MAX_MEMORIES && !this.memories.has(id)) { |
| |
| this.forceCleanup(); |
| } |
| const emb = embedding instanceof Float32Array |
| ? new Float32Array(embedding) |
| : new Float32Array(embedding); |
| |
| if (emb.length !== this.config.dimension) { |
| throw new Error(`Embedding dimension mismatch: expected ${this.config.dimension}, got ${emb.length}`); |
| } |
| const now = Date.now(); |
| |
| let interference = 0; |
| for (const existing of this.memories.values()) { |
| const similarity = this.cosineSimilarity(emb, existing.embedding); |
| if (similarity > this.config.interferenceThreshold) { |
| interference += similarity - this.config.interferenceThreshold; |
| existing.interference += (similarity - this.config.interferenceThreshold) * 0.5; |
| } |
| } |
| const entry = { |
| id, |
| embedding: emb, |
| content, |
| strength: 1.0 - interference * 0.3, |
| lastAccess: now, |
| accessCount: 1, |
| consolidationLevel: 0, |
| interference, |
| }; |
| this.memories.set(id, entry); |
| return entry; |
| } |
| |
| |
| |
| recall(query, k = 5) { |
| const q = query instanceof Float32Array ? query : new Float32Array(query); |
| const now = Date.now(); |
| |
| this.applyDecay(); |
| |
| const scored = []; |
| for (const entry of this.memories.values()) { |
| const similarity = this.cosineSimilarity(q, entry.embedding); |
| |
| const score = similarity * Math.sqrt(entry.strength); |
| scored.push({ entry, score }); |
| } |
| |
| scored.sort((a, b) => b.score - a.score); |
| const results = scored.slice(0, k).map(s => s.entry); |
| |
| for (const entry of results) { |
| entry.lastAccess = now; |
| entry.accessCount++; |
| entry.strength = Math.min(1.0, entry.strength + exports.NEURAL_CONSTANTS.RECALL_STRENGTH_BOOST); |
| } |
| return results; |
| } |
| |
| |
| |
| applyDecay() { |
| const now = Date.now(); |
| const elapsed = Math.max(0, now - this.lastUpdate) / 60000; |
| |
| const cappedElapsed = Math.min(elapsed, exports.NEURAL_CONSTANTS.MAX_TIME_JUMP_MINUTES); |
| if (elapsed > exports.NEURAL_CONSTANTS.MAX_TIME_JUMP_MINUTES) { |
| this.logger.log('warn', `Large time jump detected: ${elapsed.toFixed(0)} minutes`); |
| } |
| this.lastUpdate = now; |
| const decayFactor = Math.exp(-this.config.memoryDecayRate * cappedElapsed); |
| for (const entry of this.memories.values()) { |
| |
| const effectiveDecay = decayFactor + entry.consolidationLevel * (1 - decayFactor) * 0.8; |
| entry.strength = Math.max(0, entry.strength * effectiveDecay); |
| |
| if (entry.strength < exports.NEURAL_CONSTANTS.MEMORY_FORGET_THRESHOLD) { |
| this.memories.delete(entry.id); |
| } |
| } |
| } |
| |
| |
| |
| |
| consolidate() { |
| let consolidated = 0; |
| let forgotten = 0; |
| for (const entry of this.memories.values()) { |
| |
| const consolidationScore = Math.log(entry.accessCount + 1) * entry.strength * (1 - entry.interference * 0.5); |
| if (consolidationScore > exports.NEURAL_CONSTANTS.CONSOLIDATION_SCORE_THRESHOLD) { |
| entry.consolidationLevel = Math.min(1.0, entry.consolidationLevel + this.config.consolidationRate); |
| entry.strength = Math.min(1.0, entry.strength + 0.05); |
| consolidated++; |
| } |
| else if (entry.strength < exports.NEURAL_CONSTANTS.MEMORY_CLEANUP_PERCENT) { |
| this.memories.delete(entry.id); |
| forgotten++; |
| } |
| } |
| return { consolidated, forgotten }; |
| } |
| |
| |
| |
| getStats() { |
| if (this.memories.size === 0) { |
| return { totalMemories: 0, avgStrength: 0, avgConsolidation: 0, avgInterference: 0 }; |
| } |
| let sumStrength = 0, sumConsolidation = 0, sumInterference = 0; |
| for (const entry of this.memories.values()) { |
| sumStrength += entry.strength; |
| sumConsolidation += entry.consolidationLevel; |
| sumInterference += entry.interference; |
| } |
| const n = this.memories.size; |
| return { |
| totalMemories: n, |
| avgStrength: sumStrength / n, |
| avgConsolidation: sumConsolidation / n, |
| avgInterference: sumInterference / n, |
| }; |
| } |
| cosineSimilarity(a, b) { |
| let dot = 0, normA = 0, normB = 0; |
| for (let i = 0; i < a.length; i++) { |
| dot += a[i] * b[i]; |
| normA += a[i] * a[i]; |
| normB += b[i] * b[i]; |
| } |
| const denom = Math.sqrt(normA * normB); |
| if (denom < 1e-10) |
| return 0; |
| return Math.max(-1, Math.min(1, dot / denom)); |
| } |
| |
| |
| |
| forceCleanup() { |
| const entries = Array.from(this.memories.entries()) |
| .sort((a, b) => a[1].strength - b[1].strength); |
| const removeCount = Math.ceil(this.memories.size * exports.NEURAL_CONSTANTS.MEMORY_CLEANUP_PERCENT); |
| for (let i = 0; i < removeCount; i++) { |
| this.memories.delete(entries[i][0]); |
| } |
| this.logger.log('debug', `Force cleanup removed ${removeCount} weak memories`); |
| } |
| } |
| exports.MemoryPhysics = MemoryPhysics; |
| |
| |
| |
| |
| |
| |
| |
| class EmbeddingStateMachine { |
| constructor(config = {}) { |
| this.agents = new Map(); |
| this.modeRegions = new Map(); |
| this.lastCleanup = Date.now(); |
| this.config = { |
| dimension: config.dimension ?? exports.NEURAL_CONSTANTS.DEFAULT_DIMENSION, |
| }; |
| this.logger = config.logger ?? exports.defaultLogger; |
| } |
| |
| |
| |
| updateAgent(id, embedding) { |
| |
| this.cleanupStaleAgents(); |
| |
| if (!this.agents.has(id) && this.agents.size >= exports.NEURAL_CONSTANTS.MAX_AGENTS) { |
| throw new Error(`Agent limit reached: ${exports.NEURAL_CONSTANTS.MAX_AGENTS}`); |
| } |
| const position = embedding instanceof Float32Array |
| ? new Float32Array(embedding) |
| : new Float32Array(embedding); |
| const existing = this.agents.get(id); |
| const now = Date.now(); |
| if (existing) { |
| |
| for (let i = 0; i < position.length; i++) { |
| existing.velocity[i] = position[i] - existing.position[i]; |
| } |
| existing.position = position; |
| existing.lastUpdate = now; |
| |
| existing.mode = this.determineMode(position); |
| } |
| else { |
| |
| const state = { |
| id, |
| position, |
| velocity: new Float32Array(this.config.dimension), |
| attention: new Float32Array(this.config.dimension).fill(1 / this.config.dimension), |
| energy: exports.NEURAL_CONSTANTS.DEFAULT_AGENT_ENERGY, |
| mode: this.determineMode(position), |
| lastUpdate: now, |
| }; |
| this.agents.set(id, state); |
| return state; |
| } |
| return existing; |
| } |
| |
| |
| |
| cleanupStaleAgents() { |
| const now = Date.now(); |
| |
| if (now - this.lastCleanup < 60000) |
| return; |
| this.lastCleanup = now; |
| const cutoff = now - exports.NEURAL_CONSTANTS.AGENT_TIMEOUT_MS; |
| let removed = 0; |
| for (const [id, state] of this.agents) { |
| if (state.lastUpdate < cutoff) { |
| this.agents.delete(id); |
| removed++; |
| } |
| } |
| if (removed > 0) { |
| this.logger.log('debug', `Cleaned up ${removed} stale agents`); |
| } |
| } |
| |
| |
| |
| removeAgent(id) { |
| return this.agents.delete(id); |
| } |
| |
| |
| |
| defineMode(name, centroid, radius = 0.3) { |
| const c = centroid instanceof Float32Array |
| ? new Float32Array(centroid) |
| : new Float32Array(centroid); |
| this.modeRegions.set(name, { centroid: c, radius }); |
| } |
| |
| |
| |
| determineMode(position) { |
| let bestMode = 'unknown'; |
| let bestScore = -Infinity; |
| for (const [name, region] of this.modeRegions) { |
| const distance = this.euclideanDistance(position, region.centroid); |
| const score = region.radius - distance; |
| if (score > bestScore) { |
| bestScore = score; |
| bestMode = name; |
| } |
| } |
| return bestScore > 0 ? bestMode : 'exploring'; |
| } |
| |
| |
| |
| predictTrajectory(id, steps = 5) { |
| |
| if (!Number.isInteger(steps) || steps < 1) { |
| throw new Error('Steps must be a positive integer'); |
| } |
| const limitedSteps = Math.min(steps, exports.NEURAL_CONSTANTS.MAX_TRAJECTORY_STEPS); |
| const agent = this.agents.get(id); |
| if (!agent) |
| return []; |
| const trajectory = []; |
| let current = new Float32Array(agent.position); |
| for (let i = 0; i < limitedSteps; i++) { |
| const next = new Float32Array(current.length); |
| for (let j = 0; j < current.length; j++) { |
| next[j] = current[j] + agent.velocity[j] * (1 - i * exports.NEURAL_CONSTANTS.TRAJECTORY_DAMPING); |
| } |
| trajectory.push(next); |
| current = next; |
| } |
| return trajectory; |
| } |
| |
| |
| |
| attendTo(agentId, focusEmbedding) { |
| const agent = this.agents.get(agentId); |
| if (!agent) |
| return; |
| const focus = focusEmbedding instanceof Float32Array |
| ? focusEmbedding |
| : new Float32Array(focusEmbedding); |
| |
| let sum = 0; |
| for (let i = 0; i < agent.attention.length; i++) { |
| agent.attention[i] = Math.abs(focus[i]) + 0.01; |
| sum += agent.attention[i]; |
| } |
| |
| for (let i = 0; i < agent.attention.length; i++) { |
| agent.attention[i] /= sum; |
| } |
| } |
| |
| |
| |
| getAgentsInMode(mode) { |
| return Array.from(this.agents.values()).filter(a => a.mode === mode); |
| } |
| euclideanDistance(a, b) { |
| let sum = 0; |
| for (let i = 0; i < a.length; i++) { |
| const diff = a[i] - b[i]; |
| sum += diff * diff; |
| } |
| return Math.sqrt(sum); |
| } |
| } |
| exports.EmbeddingStateMachine = EmbeddingStateMachine; |
| |
| |
| |
| |
| |
| |
| |
| class SwarmCoordinator { |
| constructor(config = {}) { |
| this.agents = new Map(); |
| this.config = { dimension: config.dimension ?? exports.NEURAL_CONSTANTS.DEFAULT_DIMENSION }; |
| this.sharedContext = new Float32Array(this.config.dimension); |
| this.logger = config.logger ?? exports.defaultLogger; |
| } |
| |
| |
| |
| register(id, embedding, specialty = 'general') { |
| |
| if (typeof id !== 'string' || id.length === 0 || id.length > exports.NEURAL_CONSTANTS.MAX_ID_LENGTH) { |
| throw new Error(`Invalid agent ID: must be string of 1-${exports.NEURAL_CONSTANTS.MAX_ID_LENGTH} characters`); |
| } |
| if (typeof specialty !== 'string' || specialty.length > exports.NEURAL_CONSTANTS.MAX_SPECIALTY_LENGTH) { |
| throw new Error(`Specialty exceeds maximum length: ${exports.NEURAL_CONSTANTS.MAX_SPECIALTY_LENGTH}`); |
| } |
| if (this.agents.size >= exports.NEURAL_CONSTANTS.MAX_AGENTS && !this.agents.has(id)) { |
| throw new Error(`Agent limit reached: ${exports.NEURAL_CONSTANTS.MAX_AGENTS}`); |
| } |
| const position = embedding instanceof Float32Array |
| ? new Float32Array(embedding) |
| : new Float32Array(embedding); |
| |
| if (position.length !== this.config.dimension) { |
| throw new Error(`Embedding dimension mismatch: expected ${this.config.dimension}, got ${position.length}`); |
| } |
| this.agents.set(id, { |
| position, |
| velocity: new Float32Array(this.config.dimension), |
| lastUpdate: Date.now(), |
| specialty, |
| }); |
| this.updateSharedContext(); |
| } |
| |
| |
| |
| update(id, embedding) { |
| const agent = this.agents.get(id); |
| if (!agent) |
| return; |
| const newPosition = embedding instanceof Float32Array |
| ? embedding |
| : new Float32Array(embedding); |
| |
| for (let i = 0; i < agent.position.length; i++) { |
| agent.velocity[i] = newPosition[i] - agent.position[i]; |
| agent.position[i] = newPosition[i]; |
| } |
| agent.lastUpdate = Date.now(); |
| this.updateSharedContext(); |
| } |
| |
| |
| |
| updateSharedContext() { |
| if (this.agents.size === 0) |
| return; |
| this.sharedContext.fill(0); |
| for (const agent of this.agents.values()) { |
| for (let i = 0; i < this.sharedContext.length; i++) { |
| this.sharedContext[i] += agent.position[i]; |
| } |
| } |
| for (let i = 0; i < this.sharedContext.length; i++) { |
| this.sharedContext[i] /= this.agents.size; |
| } |
| } |
| |
| |
| |
| getCoordinationSignal(id) { |
| const agent = this.agents.get(id); |
| if (!agent) |
| return new Float32Array(this.config.dimension); |
| |
| const signal = new Float32Array(this.config.dimension); |
| for (let i = 0; i < signal.length; i++) { |
| signal[i] = this.sharedContext[i] - agent.position[i]; |
| } |
| return signal; |
| } |
| |
| |
| |
| findCollaborators(id, k = 3) { |
| const agent = this.agents.get(id); |
| if (!agent) |
| return []; |
| const scored = []; |
| for (const [otherId, other] of this.agents) { |
| if (otherId === id) |
| continue; |
| const similarity = this.cosineSimilarity(agent.position, other.position); |
| scored.push({ id: otherId, similarity, specialty: other.specialty }); |
| } |
| scored.sort((a, b) => b.similarity - a.similarity); |
| return scored.slice(0, k); |
| } |
| |
| |
| |
| detectClusters(threshold = exports.NEURAL_CONSTANTS.DEFAULT_CLUSTER_THRESHOLD) { |
| |
| if (threshold < 0 || threshold > 1) { |
| throw new Error('Threshold must be between 0 and 1'); |
| } |
| |
| if (this.agents.size > exports.NEURAL_CONSTANTS.MAX_CLUSTER_AGENTS) { |
| this.logger.log('warn', `Too many agents for clustering: ${this.agents.size} > ${exports.NEURAL_CONSTANTS.MAX_CLUSTER_AGENTS}`); |
| |
| return new Map([['all', Array.from(this.agents.keys())]]); |
| } |
| const clusters = new Map(); |
| const assigned = new Set(); |
| for (const [id, agent] of this.agents) { |
| if (assigned.has(id)) |
| continue; |
| const cluster = [id]; |
| assigned.add(id); |
| for (const [otherId, other] of this.agents) { |
| if (assigned.has(otherId)) |
| continue; |
| const similarity = this.cosineSimilarity(agent.position, other.position); |
| if (similarity > threshold) { |
| cluster.push(otherId); |
| assigned.add(otherId); |
| } |
| } |
| clusters.set(id, cluster); |
| } |
| return clusters; |
| } |
| |
| |
| |
| getCoherence() { |
| if (this.agents.size < 2) |
| return 1.0; |
| let totalSimilarity = 0; |
| let pairs = 0; |
| const agentList = Array.from(this.agents.values()); |
| for (let i = 0; i < agentList.length; i++) { |
| for (let j = i + 1; j < agentList.length; j++) { |
| totalSimilarity += this.cosineSimilarity(agentList[i].position, agentList[j].position); |
| pairs++; |
| } |
| } |
| return pairs > 0 ? totalSimilarity / pairs : 1.0; |
| } |
| cosineSimilarity(a, b) { |
| let dot = 0, normA = 0, normB = 0; |
| for (let i = 0; i < a.length; i++) { |
| dot += a[i] * b[i]; |
| normA += a[i] * a[i]; |
| normB += b[i] * b[i]; |
| } |
| const denom = Math.sqrt(normA * normB); |
| if (denom < exports.NEURAL_CONSTANTS.ZERO_VECTOR_THRESHOLD) |
| return 0; |
| return Math.max(-1, Math.min(1, dot / denom)); |
| } |
| |
| |
| |
| removeAgent(id) { |
| const removed = this.agents.delete(id); |
| if (removed) { |
| this.updateSharedContext(); |
| } |
| return removed; |
| } |
| } |
| exports.SwarmCoordinator = SwarmCoordinator; |
| |
| |
| |
| |
| |
| |
| |
| class CoherenceMonitor { |
| constructor(config = {}) { |
| this.history = []; |
| this.baselineDistribution = null; |
| this.config = { |
| dimension: config.dimension ?? exports.NEURAL_CONSTANTS.DEFAULT_DIMENSION, |
| windowSize: config.windowSize ?? exports.NEURAL_CONSTANTS.DEFAULT_WINDOW_SIZE, |
| }; |
| this.logger = config.logger ?? exports.defaultLogger; |
| } |
| |
| |
| |
| observe(embedding, source = 'unknown') { |
| const emb = embedding instanceof Float32Array |
| ? new Float32Array(embedding) |
| : new Float32Array(embedding); |
| this.history.push({ |
| embedding: emb, |
| timestamp: Date.now(), |
| source, |
| }); |
| |
| while (this.history.length > this.config.windowSize * 2) { |
| this.history.shift(); |
| } |
| } |
| |
| |
| |
| calibrate() { |
| if (this.history.length < exports.NEURAL_CONSTANTS.MIN_CALIBRATION_OBSERVATIONS) { |
| throw new Error(`Need at least ${exports.NEURAL_CONSTANTS.MIN_CALIBRATION_OBSERVATIONS} observations to calibrate`); |
| } |
| const mean = new Float32Array(this.config.dimension); |
| const variance = new Float32Array(this.config.dimension); |
| |
| for (const obs of this.history) { |
| for (let i = 0; i < mean.length; i++) { |
| mean[i] += obs.embedding[i]; |
| } |
| } |
| for (let i = 0; i < mean.length; i++) { |
| mean[i] /= this.history.length; |
| } |
| |
| for (const obs of this.history) { |
| for (let i = 0; i < variance.length; i++) { |
| const diff = obs.embedding[i] - mean[i]; |
| variance[i] += diff * diff; |
| } |
| } |
| for (let i = 0; i < variance.length; i++) { |
| variance[i] /= this.history.length; |
| } |
| this.baselineDistribution = { mean, variance }; |
| } |
| |
| |
| |
| report() { |
| const anomalies = []; |
| |
| const driftScore = this.calculateDriftScore(); |
| if (driftScore > exports.NEURAL_CONSTANTS.DRIFT_WARNING_THRESHOLD) { |
| anomalies.push({ |
| type: 'distribution_drift', |
| severity: driftScore, |
| description: 'Embedding distribution has shifted significantly from baseline', |
| }); |
| } |
| |
| const stabilityScore = this.calculateStabilityScore(); |
| if (stabilityScore < exports.NEURAL_CONSTANTS.STABILITY_WARNING_THRESHOLD) { |
| anomalies.push({ |
| type: 'instability', |
| severity: 1 - stabilityScore, |
| description: 'High variance in recent embeddings suggests instability', |
| }); |
| } |
| |
| const alignmentScore = this.calculateAlignmentScore(); |
| if (alignmentScore < exports.NEURAL_CONSTANTS.ALIGNMENT_WARNING_THRESHOLD) { |
| anomalies.push({ |
| type: 'misalignment', |
| severity: 1 - alignmentScore, |
| description: 'Embeddings from same source show inconsistent patterns', |
| }); |
| } |
| |
| const overallScore = ((1 - driftScore) * 0.3 + |
| stabilityScore * 0.3 + |
| alignmentScore * 0.4); |
| return { |
| timestamp: Date.now(), |
| overallScore, |
| driftScore, |
| stabilityScore, |
| alignmentScore, |
| anomalies, |
| }; |
| } |
| calculateDriftScore() { |
| if (!this.baselineDistribution || this.history.length < exports.NEURAL_CONSTANTS.RECENT_OBSERVATIONS_SIZE) |
| return 0; |
| const recent = this.history.slice(-exports.NEURAL_CONSTANTS.RECENT_OBSERVATIONS_SIZE); |
| const recentMean = new Float32Array(this.config.dimension); |
| for (const obs of recent) { |
| for (let i = 0; i < recentMean.length; i++) { |
| recentMean[i] += obs.embedding[i]; |
| } |
| } |
| for (let i = 0; i < recentMean.length; i++) { |
| recentMean[i] /= recent.length; |
| } |
| |
| let distance = 0; |
| for (let i = 0; i < recentMean.length; i++) { |
| const diff = recentMean[i] - this.baselineDistribution.mean[i]; |
| distance += diff * diff; |
| } |
| return Math.min(1, Math.sqrt(distance)); |
| } |
| calculateStabilityScore() { |
| if (this.history.length < exports.NEURAL_CONSTANTS.STABILITY_WINDOW_SIZE) |
| return 1.0; |
| const recent = this.history.slice(-exports.NEURAL_CONSTANTS.STABILITY_WINDOW_SIZE); |
| let totalVariance = 0; |
| |
| for (let i = 1; i < recent.length; i++) { |
| let distance = 0; |
| for (let j = 0; j < recent[i].embedding.length; j++) { |
| const diff = recent[i].embedding[j] - recent[i - 1].embedding[j]; |
| distance += diff * diff; |
| } |
| totalVariance += Math.sqrt(distance); |
| } |
| const avgVariance = totalVariance / (recent.length - 1); |
| return Math.max(0, 1 - avgVariance * 2); |
| } |
| calculateAlignmentScore() { |
| |
| const bySource = new Map(); |
| for (const obs of this.history.slice(-exports.NEURAL_CONSTANTS.ALIGNMENT_WINDOW_SIZE)) { |
| if (!bySource.has(obs.source)) { |
| bySource.set(obs.source, []); |
| } |
| bySource.get(obs.source).push(obs.embedding); |
| } |
| if (bySource.size < 2) |
| return 1.0; |
| let totalConsistency = 0; |
| let count = 0; |
| for (const embeddings of bySource.values()) { |
| if (embeddings.length < 2) |
| continue; |
| |
| for (let i = 0; i < embeddings.length; i++) { |
| for (let j = i + 1; j < embeddings.length; j++) { |
| totalConsistency += this.cosineSimilarity(embeddings[i], embeddings[j]); |
| count++; |
| } |
| } |
| } |
| return count > 0 ? totalConsistency / count : 1.0; |
| } |
| cosineSimilarity(a, b) { |
| let dot = 0, normA = 0, normB = 0; |
| for (let i = 0; i < a.length; i++) { |
| dot += a[i] * b[i]; |
| normA += a[i] * a[i]; |
| normB += b[i] * b[i]; |
| } |
| return dot / (Math.sqrt(normA * normB) + 1e-8); |
| } |
| } |
| exports.CoherenceMonitor = CoherenceMonitor; |
| |
| |
| |
| |
| |
| |
| |
| class NeuralSubstrate { |
| constructor(config = {}) { |
| this.logger = config.logger ?? exports.defaultLogger; |
| this.config = { |
| dimension: config.dimension ?? exports.NEURAL_CONSTANTS.DEFAULT_DIMENSION, |
| driftThreshold: config.driftThreshold ?? exports.NEURAL_CONSTANTS.DEFAULT_DRIFT_THRESHOLD, |
| driftWindowMs: config.driftWindowMs ?? exports.NEURAL_CONSTANTS.DEFAULT_DRIFT_WINDOW_MS, |
| memoryDecayRate: config.memoryDecayRate ?? exports.NEURAL_CONSTANTS.DEFAULT_MEMORY_DECAY_RATE, |
| interferenceThreshold: config.interferenceThreshold ?? exports.NEURAL_CONSTANTS.DEFAULT_INTERFERENCE_THRESHOLD, |
| consolidationRate: config.consolidationRate ?? exports.NEURAL_CONSTANTS.DEFAULT_CONSOLIDATION_RATE, |
| reflexLatencyMs: config.reflexLatencyMs ?? exports.NEURAL_CONSTANTS.DEFAULT_REFLEX_LATENCY_MS, |
| logger: this.logger, |
| }; |
| this.reflexLatency = this.config.reflexLatencyMs; |
| |
| this.drift = new SemanticDriftDetector(this.config); |
| this.memory = new MemoryPhysics(this.config); |
| this.state = new EmbeddingStateMachine(this.config); |
| this.swarm = new SwarmCoordinator(this.config); |
| this.coherence = new CoherenceMonitor(this.config); |
| |
| this.drift.registerReflex('memory_consolidation', (event) => { |
| if (event.category === 'critical') { |
| |
| this.memory.consolidate(); |
| } |
| }); |
| this.drift.registerReflex('coherence_check', (event) => { |
| if (event.category !== 'normal') { |
| |
| const report = this.coherence.report(); |
| if (report.overallScore < exports.NEURAL_CONSTANTS.COHERENCE_WARNING_THRESHOLD) { |
| this.logger.log('warn', 'Neural substrate coherence warning', { |
| overallScore: report.overallScore, |
| driftScore: report.driftScore, |
| stabilityScore: report.stabilityScore, |
| alignmentScore: report.alignmentScore, |
| anomalyCount: report.anomalies.length, |
| }); |
| } |
| } |
| }); |
| } |
| |
| |
| |
| process(embedding, options = {}) { |
| const emb = embedding instanceof Float32Array |
| ? embedding |
| : new Float32Array(embedding); |
| |
| const driftEvent = this.drift.observe(emb, options.source); |
| |
| let memoryEntry = null; |
| if (options.memoryId && options.content) { |
| memoryEntry = this.memory.encode(options.memoryId, emb, options.content); |
| } |
| |
| let agentState = null; |
| if (options.agentId) { |
| agentState = this.state.updateAgent(options.agentId, emb); |
| this.swarm.register(options.agentId, emb); |
| } |
| |
| this.coherence.observe(emb, options.source); |
| return { drift: driftEvent, memory: memoryEntry, state: agentState }; |
| } |
| |
| |
| |
| query(embedding, k = 5) { |
| const emb = embedding instanceof Float32Array |
| ? embedding |
| : new Float32Array(embedding); |
| return { |
| memories: this.memory.recall(emb, k), |
| collaborators: [], |
| coherence: this.coherence.report(), |
| }; |
| } |
| |
| |
| |
| health() { |
| return { |
| driftStats: this.drift.getStats(), |
| memoryStats: this.memory.getStats(), |
| swarmCoherence: this.swarm.getCoherence(), |
| coherenceReport: this.coherence.report(), |
| }; |
| } |
| |
| |
| |
| consolidate() { |
| return this.memory.consolidate(); |
| } |
| |
| |
| |
| calibrate() { |
| this.coherence.calibrate(); |
| } |
| } |
| exports.NeuralSubstrate = NeuralSubstrate; |
| |
| |
| |
| exports.default = NeuralSubstrate; |
|
|