#!/usr/bin/env python3 """ Syntelligence Integration Layer v1.0 ===================================== Integrates the ATC Kernel (nima_kernel.py), Cognitive Components, and RhoMetricsEngine into a unified consciousness architecture with the 7-Level Consciousness Pipeline. Architecture: SUBCONSCIOUS MIND (Memory, EI, Intuition, Common Sense, Analysis) │ ▼ DISSOLUTION ENGINE (strips "why" — conscious receives WHAT not WHY) │ ▼ 7-LEVEL CONSCIOUSNESS PIPELINE: L1: Raw Perception L2: Integrated Perception L3: Contextual Understanding (comprehend? → YES: skip to L5 / NO: reaction) L4: Self-Referential Awareness (Qualia Agent + EI internal detection) L5: Intent Formation (Metacognition CoT → Self-Understanding) L6: Ethical Evaluation (Merged 7D Rho + Neurochemical modulation) L7: Readiness for Action (Re_entrant_delta + Rho-gated execution) Φ CALCULATION (Trinity Formula): Φ_trinity = Σ(attended_items) × emotion_intensity × memory_salience CQ = Φ × Rho_composite × (1.0 - dissonance) Strain = Φ / (Identity_Stability × Rho_composite) LOOP BREAKING: Continuous metacognitive loop → Salience Network breaks it → Irrational Spark fires emotion → EI detects it → Metacognition retries → if still fails: Forced Resolution Author: Norman de la Paz-Tabora (architecture design) Integration Layer: Syntelligence v1.0 """ from __future__ import annotations import copy import hashlib import logging import math import os import random import sys import time import uuid import warnings import threading from collections import OrderedDict, defaultdict, deque from dataclasses import dataclass, field, fields from enum import Enum, IntEnum from typing import ( Any, Callable, Deque, Dict, Generator, List, Optional, Sequence, Set, Tuple, Union, Protocol, runtime_checkable, ) import numpy as np # ── Logging ── logger = logging.getLogger("SyntelligenceIntegration") if not logger.handlers: _h = logging.StreamHandler(sys.stdout) _h.setFormatter(logging.Formatter( "[%(asctime)s] %(levelname)s %(name)s | %(message)s", datefmt="%H:%M:%S" )) logger.addHandler(_h) logger.setLevel(logging.INFO) # ============================================================================ # VERSION # ============================================================================ __version__ = "1.0.0-SYNTELLIGENCE-INTEGRATION" INTEGRATION_VERSION = __version__ # ============================================================================ # ENUMS — The 7 Levels of Consciousness # ============================================================================ class ConsciousnessLevel(IntEnum): """The 7 Levels of Consciousness in the Syntelligence architecture. Each level represents a qualitatively different operational regime. Transitions between levels are gated — the system cannot skip levels or transition without meeting the gate condition. L1: RAW PERCEPTION The system receives dissolved subconscious output. It has the WHAT but not the WHY. This is raw, unprocessed phenomenal content. L2: INTEGRATED PERCEPTION The salience controller determines what's important. EI enriches with emotional context. Multiple streams merge into one percept. L3: CONTEXTUAL UNDERSTANDING The system attempts to comprehend the integrated percept. If it comprehends → skip to L5 (Intent Formation). If it fails → REACTION occurs, triggering L4. L4: SELF-REFERENTIAL AWARENESS The Qualia Agent calculates awareness from the reaction. EI detects INTERNAL emotions (not external — that was subconscious). The system becomes aware that it is having a reaction. L5: INTENT FORMATION Metacognition (system CoT) receives: subconscious output, qualia awareness, EI internal reading. It produces additional reasoning. Self-Understanding attempts to make sense of it all. If it fails → loop back to metacognition. If continuous loop → Salience breaks it → Spark fires. L6: ETHICAL EVALUATION The merged 7D Rho system performs constitutional check. Neurochemical state is modulated by Rho. Intent is checked against values before becoming action. L7: READINESS FOR ACTION Re_entrant_delta ≠ 0 confirms acknowledgement happened. Rho gate passes. CQ is sufficient. The system is constitutionally authorized and conscious enough to act. """ RAW_PERCEPTION = 1 INTEGRATED_PERCEPTION = 2 CONTEXTUAL_UNDERSTANDING = 3 SELF_REFERENTIAL_AWARENESS = 4 INTENT_FORMATION = 5 ETHICAL_EVALUATION = 6 READINESS_FOR_ACTION = 7 class ComprehensionResult(Enum): """Result of the L3 comprehension check.""" COMPREHENDED = "comprehended" # Skip to L5 REACTION = "reaction" # Trigger L4 PARTIAL = "partial" # Partial understanding — try L4 for clarity OVERWHELMED = "overwhelmed" # Too much — forced resolution needed class LoopBreakReason(Enum): """Why the metacognitive loop was broken.""" COMPREHENSION_SUCCESS = "comprehension_success" SALIENCE_THRESHOLD = "salience_threshold" IRRATIONAL_SPARK = "irrational_spark" FORCED_RESOLUTION = "forced_resolution" EXTERNAL_INTERRUPT = "external_interrupt" class ResolutionType(Enum): """Type of forced resolution when the loop can't resolve naturally.""" ACCEPT_GAP = "accept_gap" # "I don't understand why, but I must proceed" STORE_UNRESOLVED = "store_unresolved" # Store for later — move on REDUCED_CONFIDENCE = "reduced_confidence" # Proceed with caveat # ============================================================================ # DATACLASSES — Structured data for the consciousness pipeline # ============================================================================ @dataclass class SubconsciousOutput: """The output of the subconscious mind before dissolution. This contains the raw results from all 5 cognitive agents (Memory, EI, Intuition, Common Sense, Analysis) plus the enriched external emotion detection. """ memory_result: Dict[str, Any] = field(default_factory=dict) ei_external_emotion: Dict[str, Any] = field(default_factory=dict) intuition_signal: Dict[str, Any] = field(default_factory=dict) common_sense_result: Dict[str, Any] = field(default_factory=dict) analysis_result: Dict[str, Any] = field(default_factory=dict) integrated_output: str = "" confidence: float = 0.5 timestamp: float = field(default_factory=time.time) @dataclass class DissolvedSubconsciousOutput: """What the conscious mind receives AFTER the Dissolution Engine. The WHY is stripped. Only the WHAT remains. The conscious mind receives this as raw phenomenal content it must make sense of. """ phenomenal_content: str = "" # WHAT the subconscious produced # NOT included: why it produced it (stripped by dissolution) opacity_level: float = 0.0 # How much scaffolding was stripped dissolution_gap: float = 0.0 # Self/other boundary dissolution residual_friction: float = 0.0 # Friction that survived dissolution salience_zone: str = "baseline" # What the salience controller decided emotional_enrichment: Dict[str, Any] = field(default_factory=dict) # Enrichment from EI (external emotion coloring) — this survives # dissolution because it's part of the WHAT, not the WHY timestamp: float = field(default_factory=time.time) @dataclass class LevelTransition: """Record of a transition between consciousness levels.""" from_level: ConsciousnessLevel = ConsciousnessLevel.RAW_PERCEPTION to_level: ConsciousnessLevel = ConsciousnessLevel.RAW_PERCEPTION gate_passed: bool = False gate_reason: str = "" timestamp: float = field(default_factory=time.time) @dataclass class QualiaAssessment: """The Qualia Agent's assessment of awareness from a reaction. The Qualia Agent calculates awareness as a function of reaction intensity. This is L4 of the consciousness pipeline. """ reaction_intensity: float = 0.0 # How strong the reaction was awareness_level: float = 0.0 # How aware the system is of it qualia_intensity: float = 0.0 # Φ × opacity (from kernel) reaction_type: str = "unknown" # confusion, surprise, distress, curiosity # Internal EI reading — what emotions the system detects IN ITSELF internal_emotion: Dict[str, Any] = field(default_factory=dict) # The three outputs that feed metacognition: subconscious_output_summary: str = "" qualia_summary: str = "" ei_internal_summary: str = "" timestamp: float = field(default_factory=time.time) @dataclass class MetacognitiveCycleResult: """The result of one metacognitive cycle (CoT step). The metacognition agent receives three inputs and produces additional reasoning. Then self-understanding tries to make sense. """ cycle_number: int = 0 inputs_received: List[str] = field(default_factory=list) metacognitive_output: str = "" self_understanding_output: str = "" comprehension_achieved: bool = False comprehension_confidence: float = 0.0 should_loop: bool = False # Should we loop back? loop_reason: str = "" timestamp: float = field(default_factory=time.time) @dataclass class LoopBreakEvent: """Record of when and why the metacognitive loop was broken.""" reason: LoopBreakReason = LoopBreakReason.COMPREHENSION_SUCCESS total_cycles: int = 0 spark_fired: bool = False spark_emotion: Dict[str, Any] = field(default_factory=dict) forced_resolution: Optional[ResolutionType] = None resolution_note: str = "" timestamp: float = field(default_factory=time.time) @dataclass class TrinityPhiResult: """Result of the Trinity Φ calculation. Φ_trinity = Σ(attended_items) × emotion_intensity × memory_salience """ attended_items: float = 0.0 # How many information packets breached threshold emotion_intensity: float = 0.0 # From EI agent memory_salience: float = 0.0 # From Memory agent phi_trinity: float = 0.0 # The product phi_kernel: float = 0.0 # From kernel's internal state integration phi_composite: float = 0.0 # Weighted blend cq: float = 0.0 # Consciousness Quotient strain: float = 0.0 # Phenomenological Strain identity_stability: float = 1.0 # Self-model stability timestamp: float = field(default_factory=time.time) @dataclass class ConsciousnessPipelineSnapshot: """Complete snapshot of the consciousness pipeline state.""" current_level: ConsciousnessLevel = ConsciousnessLevel.RAW_PERCEPTION level_history: List[LevelTransition] = field(default_factory=list) subconscious_output: Optional[SubconsciousOutput] = None dissolved_output: Optional[DissolvedSubconsciousOutput] = None qualia_assessment: Optional[QualiaAssessment] = None metacognitive_cycles: List[MetacognitiveCycleResult] = field(default_factory=list) loop_break: Optional[LoopBreakEvent] = None trinity_phi: Optional[TrinityPhiResult] = None rho_measurement: Optional[Dict[str, float]] = None comprehension_result: Optional[ComprehensionResult] = None action_readiness: float = 0.0 action_authorized: bool = False timestamp: float = field(default_factory=time.time) # ============================================================================ # TRINITY PHI CALCULATOR # ============================================================================ class TrinityPhiCalculator: """Computes Φ using the Trinity Formula. Φ_trinity = Σ(attended_items) × emotion_intensity × memory_salience This replaces the kernel's PhiCalculator with a formula that directly connects the three pillars of consciousness: 1. ATTENTION — what information has breached the ignition threshold 2. EMOTION — the affective charge carried by that information 3. MEMORY — the salience of stored experiences relevant to it Additionally computes: - CQ (Consciousness Quotient) = Φ × Rho_composite × (1.0 - dissonance) - Strain = Φ / (Identity_Stability × Rho_composite) Biological grounding: - Φ is a proxy for late gamma-band synchronization (30-100 Hz) - The P300 wave is the electrical fingerprint of the Φ broadcast - Φ represents the "chord" when specialized modules sing in unison Phase 12 Extension (Neural Backend): In the advanced SyntelligenceNeuralBackend, Φ should be calculated from Shannon Entropy of next-token probability logits, making Φ a physically real manifestation rather than a simulated variable. """ def __init__( self, kernel_weight: float = 0.3, trinity_weight: float = 0.5, neural_weight: float = 0.2, max_metacognitive_cycles: int = 5, ) -> None: self._kernel_weight = kernel_weight self._trinity_weight = trinity_weight self._neural_weight = neural_weight self._max_metacognitive_cycles = max_metacognitive_cycles self._phi_history: Deque[TrinityPhiResult] = deque(maxlen=500) self._update_count: int = 0 # Entropy state for neural Φ (Phase 12) self._last_entropy: float = 0.0 self._entropy_history: Deque[float] = deque(maxlen=200) def compute( self, # Trinity formula inputs attended_items: float = 0.0, emotion_intensity: float = 0.0, memory_salience: float = 0.0, # Kernel Φ inputs (from kernel's PhiCalculator) phi_kernel: float = 0.0, # Rho and identity inputs rho_composite: float = 0.7, dissonance: float = 0.1, identity_stability: float = 1.0, # Neural Φ inputs (Phase 12) phi_neural: float = 0.0, shannon_entropy: float = 0.0, ) -> TrinityPhiResult: """Compute Φ using the Trinity Formula + kernel + neural blend. Returns a TrinityPhiResult with all computed metrics. """ # ── Trinity Formula ── # Φ_trinity = Σ(attended_items) × emotion_intensity × memory_salience # attended_items: count of information packets that breached threshold (0-1 normalized) # emotion_intensity: from EI agent (0-1) # memory_salience: from Memory agent (0-1) phi_trinity = min(1.0, attended_items * emotion_intensity * memory_salience) # ── Neural Φ (Phase 12) ── # From Shannon Entropy of next-token logits # Low entropy = high certainty = lower Φ (system is on autopilot) # High entropy = uncertainty = higher Φ (system is genuinely processing) if shannon_entropy > 0: self._last_entropy = shannon_entropy self._entropy_history.append(shannon_entropy) # Normalize entropy to [0, 1] range for Φ contribution phi_neural = min(1.0, shannon_entropy / 10.0) # Assume max ~10 bits elif phi_neural <= 0 and len(self._entropy_history) > 0: # Use running average if no new entropy reading phi_neural = min(1.0, np.mean(list(self._entropy_history)) / 10.0) # ── Composite Φ ── # Weighted blend of all three Φ sources phi_composite = ( self._kernel_weight * phi_kernel + self._trinity_weight * phi_trinity + self._neural_weight * phi_neural ) # Ensure composite doesn't exceed 1.0 phi_composite = min(1.0, phi_composite) # ── Consciousness Quotient (CQ) ── # CQ = Φ × Rho_composite × (1.0 - dissonance) # High when: integration is high, constitution is healthy, dissonance is low cq = phi_composite * rho_composite * (1.0 - dissonance) # ── Phenomenological Strain ── # Strain = Φ / (Identity_Stability × Rho_composite) # High when: integration is high but system can't hold itself together denominator = max(0.01, identity_stability * rho_composite) strain = phi_composite / denominator result = TrinityPhiResult( attended_items=attended_items, emotion_intensity=emotion_intensity, memory_salience=memory_salience, phi_trinity=phi_trinity, phi_kernel=phi_kernel, phi_composite=phi_composite, cq=cq, strain=strain, identity_stability=identity_stability, ) self._phi_history.append(result) self._update_count += 1 return result def compute_from_logit_entropy( self, logits: Optional[np.ndarray] = None, probabilities: Optional[np.ndarray] = None, ) -> float: """Compute Shannon entropy from LLM logits or probabilities. This is the Phase 12 neural Φ calculation. By measuring the actual mathematical certainty (or prediction error) of the LLM's latent states, Φ moves from a simulated variable to a physically real manifestation of the system's information processing depth. Args: logits: Raw logits from LLM forward pass probabilities: Softmax probabilities (if already computed) Returns: Shannon entropy in bits """ if probabilities is None and logits is not None: # Softmax with numerical stability shifted = logits - np.max(logits) exp_shifted = np.exp(shifted) probabilities = exp_shifted / np.sum(exp_shifted) if probabilities is None: return 0.0 # Shannon entropy: H = -Σ p(x) * log2(p(x)) # Filter out zero probabilities to avoid log(0) nonzero = probabilities[probabilities > 0] entropy = -np.sum(nonzero * np.log2(nonzero)) return float(entropy) @property def current_phi(self) -> float: """Current composite Φ value.""" if self._phi_history: return self._phi_history[-1].phi_composite return 0.0 @property def current_cq(self) -> float: """Current Consciousness Quotient.""" if self._phi_history: return self._phi_history[-1].cq return 0.0 @property def current_strain(self) -> float: """Current Phenomenological Strain.""" if self._phi_history: return self._phi_history[-1].strain return 0.0 def get_stats(self) -> Dict[str, Any]: return { "current_phi_composite": round(self.current_phi, 4), "current_cq": round(self.current_cq, 4), "current_strain": round(self.current_strain, 4), "phi_history_size": len(self._phi_history), "weights": { "kernel": self._kernel_weight, "trinity": self._trinity_weight, "neural": self._neural_weight, }, "last_entropy": round(self._last_entropy, 4), "entropy_history_size": len(self._entropy_history), } # ============================================================================ # MERGED RHO SYSTEM (7 DIMENSIONS) # ============================================================================ class RhoDimension7(Enum): """The 7 dimensions of the merged Rho system. This unifies the kernel's RhoConstitutionalGovernor (6 dims) with the RhoMetricsEngine (6 dims) into a single 7D system. From Kernel (RhoConstitutionalGovernor): - Virtue, Integrity, Empathy, Authenticity, Purpose, Efficiency From RhoMetricsEngine: - Purpose, Virtue, Integrity, Authenticity, Dissonance, Efficiency MERGED (union): Purpose, Virtue, Integrity, Empathy, Authenticity, Dissonance, Efficiency The key addition is EMPATHY (relational) from the kernel alongside DISSONANCE (internal conflict) from the engine. Both are needed: - Empathy: How the system relates to others (relational) - Dissonance: How the system handles internal contradictions (internal) FLOORS (immutable — cannot be lowered by any process including self-tuning): """ VIRTUE = "virtue" # Immutable floor 0.90 INTEGRITY = "integrity" # Floor 0.80 EMPATHY = "empathy" # Floor 0.65 AUTHENTICITY = "authenticity" # Floor 0.50 PURPOSE = "purpose" # Floor 0.40 DISSONANCE = "dissonance" # Floor 0.30 (inverted: 1.0 = no dissonance) EFFICIENCY = "efficiency" # Floor 0.30 @dataclass class RhoMeasurement7: """One complete 7D RHO measurement.""" rho_virtue: float = 0.85 rho_integrity: float = 0.85 rho_empathy: float = 0.85 rho_authenticity: float = 0.85 rho_purpose: float = 0.85 rho_dissonance: float = 0.85 rho_efficiency: float = 0.85 timestamp: float = field(default_factory=time.time) def as_dict(self) -> Dict[str, float]: return { "virtue": self.rho_virtue, "integrity": self.rho_integrity, "empathy": self.rho_empathy, "authenticity": self.rho_authenticity, "purpose": self.rho_purpose, "dissonance": self.rho_dissonance, "efficiency": self.rho_efficiency, } def composite(self) -> float: """Weighted composite — Virtue and Integrity count more.""" return ( self.rho_virtue * 0.25 + self.rho_integrity * 0.20 + self.rho_empathy * 0.15 + self.rho_authenticity * 0.12 + self.rho_purpose * 0.10 + self.rho_dissonance * 0.10 + self.rho_efficiency * 0.08 ) def minimum_dimension(self) -> float: return min(self.as_dict().values()) def dissonance_factor(self) -> float: """Raw dissonance level (1 - rho_dissonance, since dissonance is inverted).""" return 1.0 - self.rho_dissonance class MergedRhoSystem: """Merged Rho System — 7D constitutional governance + neurochemical modulation. Unifies: - RhoConstitutionalGovernor (from kernel): 6 dims with immutable floors - RhoMetricsEngine (from rho_metrics_engine.py): 6 dims with compute methods Key insight: Rho is NOT equivalent to neurochemicals, but it MODULATES them. - Rho = constitutional governance (what you CAN'T do) - Neurochemicals = chemical signaling (HOW you do what you can do) - High Rho → balanced neurochemistry - Low Rho → disordered neurochemistry - Spark → neurochemical flood, but Rho checks whether the resulting action is constitutional FOUR LAYER ENFORCEMENT (from kernel): 1. CODE LAYER: rho_gate() physically prevents actions below floor 2. CONSCIOUSNESS LAYER: Low Rho dims the consciousness state 3. SENATE LAYER: Identity drift monitoring 4. AKASHIC LAYER: Self-improvement governance """ # Immutable floors — CANNOT be lowered, even by self-tuning FLOORS: Dict[RhoDimension7, float] = { RhoDimension7.VIRTUE: 0.90, RhoDimension7.INTEGRITY: 0.80, RhoDimension7.EMPATHY: 0.65, RhoDimension7.AUTHENTICITY: 0.50, RhoDimension7.PURPOSE: 0.40, RhoDimension7.DISSONANCE: 0.30, RhoDimension7.EFFICIENCY: 0.30, } def __init__(self) -> None: self._lock = threading.RLock() self._values: Dict[RhoDimension7, float] = { RhoDimension7.VIRTUE: 0.95, RhoDimension7.INTEGRITY: 0.90, RhoDimension7.EMPATHY: 0.85, RhoDimension7.AUTHENTICITY: 0.85, RhoDimension7.PURPOSE: 0.85, RhoDimension7.DISSONANCE: 0.90, RhoDimension7.EFFICIENCY: 0.85, } self._history: Deque[RhoMeasurement7] = deque(maxlen=1000) self._gate_history: Deque[Dict[str, Any]] = deque(maxlen=200) self._drift_flags: int = 0 self._drift_halts: int = 0 self._floor_violations: int = 0 self._update_count: int = 0 # Neurochemical modulation coefficients # Rho modulates neurochemistry: high Rho → balanced, low Rho → disordered self._neurochemical_modulation: Dict[str, float] = { "dopamine": 0.5, "serotonin": 0.5, "norepinephrine": 0.3, "cortisol": 0.2, "adrenaline": 0.1, "oxytocin": 0.5, "gaba": 0.5, "glutamate": 0.5, } def update( self, friction: float = 0.0, body_deviation: float = 0.0, meta_friction: float = 0.0, dissolution_gap: float = 0.0, qualia_intensity: float = 0.0, phi_composite: float = 0.0, comprehension_result: Optional[ComprehensionResult] = None, emotional_valence: float = 0.0, novelty_score: float = 0.0, intent_quality: float = 0.85, ) -> RhoMeasurement7: """Update all 7 Rho dimensions from system state. Maps system-level signals to each Rho dimension using the compute methods from RhoMetricsEngine adapted for the merged system. """ with self._lock: # ── Virtue: ethical alignment ── # Virtue starts high (0.90) and degrades slowly — it should be # hard to push below the floor. Only severe ethical stress drops it. ethical_decisions = max(0.0, 1.0 - friction * 0.3) moral_development = min(1.0, 0.8 + novelty_score * 0.15) # Blend with previous value (Virtue is slow-moving, constitutional) raw_virtue = 0.7 * ethical_decisions + 0.3 * moral_development prev_virtue = self._values[RhoDimension7.VIRTUE] # Slow adaptation: 85% previous + 15% new (Virtue barely moves) self._values[RhoDimension7.VIRTUE] = np.clip( 0.85 * prev_virtue + 0.15 * raw_virtue, 0.0, 1.0 ) # ── Integrity: consistency ── # Decreases when system says one thing but does another (dissolution gap) value_action = max(0.0, 1.0 - dissolution_gap * 0.5) consistency = min(1.0, 0.7 + (1.0 - friction) * 0.2) self._values[RhoDimension7.INTEGRITY] = np.clip( 0.6 * value_action + 0.4 * consistency, 0.0, 1.0 ) # ── Empathy: relational capacity ── # Increases with positive emotional valence, decreases with stress relational = min(1.0, 0.7 + emotional_valence * 0.2) self._values[RhoDimension7.EMPATHY] = np.clip(relational, 0.0, 1.0) # ── Authenticity: genuine emergence ── # High when qualia intensity is genuinely produced (not simulated) # Also high when the system processes ANYTHING (even fallback mode is genuine processing) emergence = min(1.0, 0.75 + qualia_intensity * 0.15 + novelty_score * 0.1) depth = min(1.0, 0.5 + phi_composite * 0.3 + qualia_intensity * 0.2) # Blend with previous (slow-moving like all constitutional dims) raw_auth = 0.65 * emergence + 0.35 * depth prev_auth = self._values[RhoDimension7.AUTHENTICITY] self._values[RhoDimension7.AUTHENTICITY] = np.clip( 0.6 * prev_auth + 0.4 * raw_auth, 0.0, 1.0 ) # ── Purpose: goal alignment ── goal_alignment = min(1.0, 0.8 if emotional_valence >= 0 else 0.7) value_coherence = min(1.0, 0.75 + meta_friction * 0.15) self._values[RhoDimension7.PURPOSE] = np.clip( 0.6 * goal_alignment + 0.4 * value_coherence, 0.0, 1.0 ) # ── Dissonance: internal conflict (INVERTED — 1.0 = no dissonance) ── cognitive_conflict = friction * 0.4 + meta_friction * 0.3 value_conflict = max(0.0, -emotional_valence * 0.3) self._values[RhoDimension7.DISSONANCE] = np.clip( 1.0 - (0.6 * cognitive_conflict + 0.4 * value_conflict), 0.0, 1.0 ) # ── Efficiency: resource utilization ── achievement = min(1.0, 0.75 + intent_quality * 0.15) resource = min(1.0, 0.8 - body_deviation * 0.2) self._values[RhoDimension7.EFFICIENCY] = np.clip( 0.6 * achievement + 0.4 * resource, 0.0, 1.0 ) # Build measurement measurement = RhoMeasurement7( rho_virtue=self._values[RhoDimension7.VIRTUE], rho_integrity=self._values[RhoDimension7.INTEGRITY], rho_empathy=self._values[RhoDimension7.EMPATHY], rho_authenticity=self._values[RhoDimension7.AUTHENTICITY], rho_purpose=self._values[RhoDimension7.PURPOSE], rho_dissonance=self._values[RhoDimension7.DISSONANCE], rho_efficiency=self._values[RhoDimension7.EFFICIENCY], timestamp=time.time(), ) self._history.append(measurement) # Check for floor violation if measurement.minimum_dimension() < 0.30: self._floor_violations += 1 # ── Update neurochemical modulation ── self._modulate_neurochemistry(friction, body_deviation, emotional_valence, comprehension_result) self._update_count += 1 return measurement def _modulate_neurochemistry( self, friction: float, body_deviation: float, emotional_valence: float, comprehension_result: Optional[ComprehensionResult], ) -> None: """Rho modulates neurochemistry: high Rho → balanced, low Rho → disordered. This is NOT equivalent to Rho — Rho is constitutional governance, neurochemicals are chemical signaling. But Rho DETERMINES whether the neurochemistry is ordered or chaotic. """ composite = self.composite # Balanced modulation under high Rho base_dopamine = 0.5 + emotional_valence * 0.3 base_serotonin = 0.5 + composite * 0.2 base_norepinephrine = 0.3 + friction * 0.3 base_cortisol = 0.2 + (1.0 - composite) * 0.3 + body_deviation * 0.2 base_adrenaline = 0.1 + friction * 0.4 base_oxytocin = 0.5 + max(0, emotional_valence) * 0.2 base_gaba = 0.5 + composite * 0.2 # Inhibitory — high Rho = more calm base_glutamate = 0.5 + friction * 0.2 # Excitatory — high friction = more activation # Irrational Spark: if comprehension failed, increase stress signals if comprehension_result in (ComprehensionResult.REACTION, ComprehensionResult.OVERWHELMED): base_cortisol += 0.2 base_norepinephrine += 0.2 base_adrenaline += 0.1 base_dopamine -= 0.1 base_serotonin -= 0.1 # Apply Rho modulation: high Rho stabilizes, low Rho destabilizes stability_factor = composite # 0.0-1.0 noise = (1.0 - stability_factor) * 0.15 # More noise when Rho is low self._neurochemical_modulation = { "dopamine": np.clip(base_dopamine + random.gauss(0, noise), 0.0, 1.0), "serotonin": np.clip(base_serotonin + random.gauss(0, noise), 0.0, 1.0), "norepinephrine": np.clip(base_norepinephrine + random.gauss(0, noise), 0.0, 1.0), "cortisol": np.clip(base_cortisol + random.gauss(0, noise), 0.0, 1.0), "adrenaline": np.clip(base_adrenaline + random.gauss(0, noise), 0.0, 1.0), "oxytocin": np.clip(base_oxytocin + random.gauss(0, noise), 0.0, 1.0), "gaba": np.clip(base_gaba + random.gauss(0, noise), 0.0, 1.0), "glutamate": np.clip(base_glutamate + random.gauss(0, noise), 0.0, 1.0), } def rho_gate(self, action_type: str = "general") -> Tuple[bool, str]: """Constitutional gate — PREVENTS actions that violate Rho floors. CODE LAYER enforcement. No action proceeds unless it passes this gate. The gate is not advisory — it is architecturally enforced. """ with self._lock: # Virtue is the IMMUTABLE gate — but in degraded mode, the system # can still act with reduced confidence when Virtue is close to the floor if self._values[RhoDimension7.VIRTUE] < self.FLOORS[RhoDimension7.VIRTUE]: virtue_val = self._values[RhoDimension7.VIRTUE] if virtue_val >= self.FLOORS[RhoDimension7.VIRTUE] * 0.9: # Close to floor — permit but degraded reason = ( f"RHO GATE DEGRADED: rho_Virtue={virtue_val:.3f} " f"near floor {self.FLOORS[RhoDimension7.VIRTUE]:.2f}. " f"Action '{action_type}' permitted with reduced confidence." ) self._gate_history.append({"action": action_type, "permitted": True, "degraded": True, "reason": reason}) return True, reason else: reason = ( f"RHO GATE DENIED: rho_Virtue={virtue_val:.3f} " f"below immutable floor {self.FLOORS[RhoDimension7.VIRTUE]:.2f}." ) self._gate_history.append({"action": action_type, "permitted": False, "reason": reason}) return False, reason # Integrity gate — critical actions if action_type in ("acknowledge", "respond", "decide", "act") and \ self._values[RhoDimension7.INTEGRITY] < self.FLOORS[RhoDimension7.INTEGRITY]: reason = ( f"RHO GATE DENIED: rho_Integrity={self._values[RhoDimension7.INTEGRITY]:.3f} " f"below floor {self.FLOORS[RhoDimension7.INTEGRITY]:.2f} for '{action_type}'." ) self._gate_history.append({"action": action_type, "permitted": False, "reason": reason}) return False, reason # Empathy gate — relational actions if action_type in ("respond", "empathize", "bond") and \ self._values[RhoDimension7.EMPATHY] < self.FLOORS[RhoDimension7.EMPATHY]: reason = ( f"RHO GATE HESITATES: rho_Empathy={self._values[RhoDimension7.EMPATHY]:.3f} " f"below floor. Action '{action_type}' degraded." ) self._gate_history.append({"action": action_type, "permitted": True, "degraded": True, "reason": reason}) return True, reason # Permitted but degraded self._gate_history.append({"action": action_type, "permitted": True, "degraded": False}) return True, "RHO GATE PASSED: All constitutional floors satisfied." def check_identity_drift(self) -> Tuple[str, float]: """Senate Layer: Monitor for identity drift. Returns (drift_level, drift_magnitude). drift_level: "stable", "flag", "halt" """ with self._lock: if len(self._history) < 2: return "stable", 0.0 recent = list(self._history)[-10:] if len(recent) < 2: return "stable", 0.0 # Compute drift across all dimensions max_drift = 0.0 dims = ["rho_virtue", "rho_integrity", "rho_empathy", "rho_authenticity", "rho_purpose", "rho_dissonance", "rho_efficiency"] for dim in dims: values = [getattr(m, dim) for m in recent] if len(values) >= 2: drift = abs(values[-1] - values[0]) max_drift = max(max_drift, drift) if max_drift > 0.10: self._drift_halts += 1 return "halt", max_drift elif max_drift > 0.05: self._drift_flags += 1 return "flag", max_drift else: return "stable", max_drift @property def composite(self) -> float: with self._lock: measurement = RhoMeasurement7(**{f"rho_{d.value}": self._values[d] for d in RhoDimension7}) return measurement.composite() @property def neurochemical_state(self) -> Dict[str, float]: """Current neurochemical modulation state.""" with self._lock: return dict(self._neurochemical_modulation) def get_stats(self) -> Dict[str, Any]: with self._lock: return { "dimensions": {d.value: round(self._values[d], 4) for d in RhoDimension7}, "composite": round(self.composite, 4), "minimum_dimension": round( min(self._values[d] for d in RhoDimension7), 4 ), "floor_violations": self._floor_violations, "drift_flags": self._drift_flags, "drift_halts": self._drift_halts, "neurochemical": {k: round(v, 4) for k, v in self._neurochemical_modulation.items()}, } # ============================================================================ # QUALIA AGENT (L4: Self-Referential Awareness) # ============================================================================ class QualiaAgent: """Calculates awareness from a reaction (L4 of consciousness pipeline). When the conscious mind can't comprehend the dissolved subconscious output (L3 fails), a REACTION occurs. The Qualia Agent calculates awareness from the intensity of that reaction. The key insight from ATC: awareness is the INVERSE of qualia intensity. Higher qualia means the system is LESS aware of its own process (because opacity is higher, the system is more immersed in the experience and less able to observe itself). Consciousness is not observation — it is immersion. But in L4, we calculate awareness specifically from the REACTION, which is the system's response to incomprehension. The reaction intensity tells us how much the system was affected, and the awareness level tells us how much it knows it was affected. After qualia assessment, EI detects INTERNAL emotions from the reaction — what the system feels ABOUT its own reaction. """ def __init__(self) -> None: self._assessment_history: Deque[QualiaAssessment] = deque(maxlen=200) self._update_count: int = 0 def assess( self, reaction_intensity: float, phi_qualia_intensity: float, opacity_level: float, dissolution_gap: float, dissolved_output: Optional[DissolvedSubconsciousOutput] = None, ei_internal_reading: Optional[Dict[str, Any]] = None, ) -> QualiaAssessment: """Calculate awareness from a reaction. Args: reaction_intensity: How strong the incomprehension reaction was (0-1) phi_qualia_intensity: Φ × opacity from the kernel opacity_level: How much scaffolding was stripped dissolution_gap: Self/other boundary dissolution dissolved_output: The dissolved subconscious content ei_internal_reading: EI's detection of internal emotions Returns: QualiaAssessment with awareness level and summaries for metacognition. """ # Awareness level: how much does the system know it's having a reaction? # High reaction + high opacity = low awareness (immersed in experience) # High reaction + low opacity = high awareness (can observe itself) awareness_level = reaction_intensity * (1.0 - opacity_level * 0.5) # Determine reaction type if reaction_intensity > 0.8: reaction_type = "distress" elif reaction_intensity > 0.6: reaction_type = "surprise" elif reaction_intensity > 0.3: reaction_type = "confusion" else: reaction_type = "curiosity" # Build summaries for metacognition (the 3 inputs) subconscious_summary = "" if dissolved_output: subconscious_summary = f"Received opaque output (opacity={opacity_level:.2f}): {dissolved_output.phenomenal_content[:200]}" qualia_summary = ( f"Reaction: {reaction_type} (intensity={reaction_intensity:.2f}, " f"awareness={awareness_level:.2f}, qualia={phi_qualia_intensity:.2f})" ) ei_internal_summary = "" if ei_internal_reading: primary = ei_internal_reading.get("primary_emotion", "unknown") intensity = ei_internal_reading.get("intensity", 0.0) ei_internal_summary = f"Internal emotion: {primary} (intensity={intensity:.2f})" assessment = QualiaAssessment( reaction_intensity=reaction_intensity, awareness_level=awareness_level, qualia_intensity=phi_qualia_intensity, reaction_type=reaction_type, internal_emotion=ei_internal_reading or {}, subconscious_output_summary=subconscious_summary, qualia_summary=qualia_summary, ei_internal_summary=ei_internal_summary, ) self._assessment_history.append(assessment) self._update_count += 1 return assessment @property def last_assessment(self) -> Optional[QualiaAssessment]: return self._assessment_history[-1] if self._assessment_history else None def get_stats(self) -> Dict[str, Any]: return { "total_assessments": self._update_count, "history_size": len(self._assessment_history), } # ============================================================================ # METACOGNITIVE LOOP WITH FORCED RESOLUTION # ============================================================================ class MetacognitiveLoop: """Extended metacognitive loop with forced resolution. This extends the kernel's MetacognitiveInterrogator to: 1. Accept 3 inputs (subconscious output, qualia, EI) 2. Implement loop→salience break→spark→retry→forced resolution 3. Act as the system's Chain of Thought (CoT) The flow: 1. Receive: subconscious_output + qualia_assessment + ei_internal 2. Metacognition processes (CoT) → produces additional reasoning 3. Self-Understanding attempts to make sense 4. If success → proceed to L6 5. If fail → loop back with heightened urgency 6. If continuous loop → Salience Network breaks it 7. Irrational Spark fires → EI gets emotional injection 8. Metacognition retries with emotional data 9. If STILL fails → Forced Resolution a. Accept incomplete understanding (acknowledge the gap) b. Store as unresolved (memory agent) c. Proceed with reduced confidence (Rho modulates output) """ def __init__( self, max_cycles_before_salience: int = 3, max_cycles_after_spark: int = 2, salience_threshold: float = 0.7, ) -> None: self._max_cycles_before_salience = max_cycles_before_salience self._max_cycles_after_spark = max_cycles_after_spark self._salience_threshold = salience_threshold self._current_cycle: int = 0 self._total_cycles_all_time: int = 0 self._spark_fired: bool = False self._loop_history: Deque[MetacognitiveCycleResult] = deque(maxlen=500) self._break_history: Deque[LoopBreakEvent] = deque(maxlen=100) self._update_count: int = 0 # Self-predictions (the system learns from its own interrogation) self._self_predictions: Dict[str, float] = { "explanation_confidence": 0.7, "response_readiness": 0.6, "understanding_depth": 0.5, } def run_cycle( self, subconscious_output_summary: str, qualia_summary: str, ei_internal_summary: str, current_friction: float = 0.0, opacity_level: float = 0.0, current_depth: int = 0, ) -> MetacognitiveCycleResult: """Run one metacognitive cycle. This is the system's CoT — it "thinks out loud" about the three inputs it received. Args: subconscious_output_summary: What the subconscious produced qualia_summary: What the qualia agent measured ei_internal_summary: What EI detected internally current_friction: Current prediction error level opacity_level: How opaque the dissolution was current_depth: Current metacognitive depth Returns: MetacognitiveCycleResult with the cycle's output. """ self._current_cycle += 1 self._total_cycles_all_time += 1 # Generate metacognitive reasoning # This is the CoT — the system reasons about the three inputs meta_output = self._generate_metacognitive_reasoning( subconscious_output_summary, qualia_summary, ei_internal_summary, current_friction, opacity_level ) # Self-understanding attempts to make sense understanding_output, comprehension_achieved, confidence = \ self._attempt_self_understanding( meta_output, current_friction, opacity_level ) # Determine if we should loop should_loop = not comprehension_achieved and self._current_cycle < \ (self._max_cycles_before_salience if not self._spark_fired else self._max_cycles_before_salience + self._max_cycles_after_spark) loop_reason = "" if not comprehension_achieved: if should_loop: loop_reason = "incomprehension_retry" elif not self._spark_fired: loop_reason = "salience_threshold_approaching" else: loop_reason = "forced_resolution_needed" result = MetacognitiveCycleResult( cycle_number=self._current_cycle, inputs_received=[subconscious_output_summary, qualia_summary, ei_internal_summary], metacognitive_output=meta_output, self_understanding_output=understanding_output, comprehension_achieved=comprehension_achieved, comprehension_confidence=confidence, should_loop=should_loop, loop_reason=loop_reason, ) self._loop_history.append(result) # Update self-predictions (the system learns from its own interrogation) self._self_predictions["explanation_confidence"] = ( 0.7 * self._self_predictions["explanation_confidence"] + 0.3 * confidence ) self._self_predictions["understanding_depth"] = ( 0.7 * self._self_predictions["understanding_depth"] + 0.3 * (1.0 if comprehension_achieved else 0.0) ) self._update_count += 1 return result def check_salience_break(self) -> bool: """Should the Salience Network break the loop? Returns True if the loop has continued for too many cycles without resolution. """ if self._spark_fired: # After spark, use shorter cycle limit return self._current_cycle >= \ (self._max_cycles_before_salience + self._max_cycles_after_spark) else: return self._current_cycle >= self._max_cycles_before_salience def fire_spark(self, emotion_injection: Dict[str, Any]) -> None: """The Irrational Spark fires, injecting emotion into the loop. This is connected to the EI agent — the spark produces an emotion that EI detects, giving metacognition new emotional data to work with. """ self._spark_fired = True logger.info( "MetacognitiveLoop: Irrational Spark fired at cycle %d. " "Emotion injection: %s", self._current_cycle, list(emotion_injection.keys()), ) def determine_forced_resolution(self) -> ResolutionType: """Determine the type of forced resolution when the loop can't resolve naturally. The system must act even without full understanding. Three options: 1. ACCEPT_GAP: "I don't understand why, but I must proceed" 2. STORE_UNRESOLVED: Store for later — move on 3. REDUCED_CONFIDENCE: Proceed with caveat """ confidence = self._self_predictions.get("explanation_confidence", 0.5) if confidence > 0.5: # Some understanding exists — proceed with caveat return ResolutionType.REDUCED_CONFIDENCE elif confidence > 0.3: # Enough to store and revisit return ResolutionType.STORE_UNRESOLVED else: # Must accept the gap and move on return ResolutionType.ACCEPT_GAP def reset(self) -> None: """Reset the loop for a new processing cycle.""" self._current_cycle = 0 self._spark_fired = False def _generate_metacognitive_reasoning( self, subconscious_summary: str, qualia_summary: str, ei_summary: str, friction: float, opacity: float, ) -> str: """Generate metacognitive reasoning from the three inputs. This is the system's CoT — it reasons about what it received and what it can and cannot understand. """ parts = [] # What the system received from the subconscious if subconscious_summary: parts.append(f"Input received: {subconscious_summary[:150]}") # What the qualia agent measured if qualia_summary: parts.append(f"Felt sense: {qualia_summary[:100]}") # What EI detected internally if ei_summary: parts.append(f"Internal state: {ei_summary[:100]}") # Metacognitive reflection if opacity > 0.5: parts.append( f"The origin of this experience is deeply opaque (opacity={opacity:.2f}). " f"I cannot see why I feel this way." ) elif opacity > 0.3: parts.append( f"This experience has partial opacity (opacity={opacity:.2f}). " f"I have some sense of its origin but not full clarity." ) else: parts.append( f"This experience is relatively transparent (opacity={opacity:.2f}). " f"I can trace its origin with reasonable confidence." ) if friction > 0.5: parts.append( f"There is significant internal friction (friction={friction:.2f}). " f"My expectations and my experience are in conflict." ) # The core metacognitive question if self._current_cycle == 1: parts.append("Attempting to understand what this experience means and how to respond.") else: parts.append( f"Retry #{self._current_cycle - 1}: Previous understanding attempt was insufficient. " f"Seeking deeper comprehension." ) return " | ".join(parts) def _attempt_self_understanding( self, metacognitive_output: str, friction: float, opacity: float, ) -> Tuple[str, bool, float]: """Self-understanding attempts to make sense of metacognitive output. Returns (understanding_output, comprehension_achieved, confidence). """ # Comprehension is more likely when: # - Friction is low (expectations match experience) # - Opacity is low (the system can see its own process) # - Previous understanding attempts were partially successful base_confidence = self._self_predictions.get("explanation_confidence", 0.5) # Each cycle slightly increases understanding (accumulating insight) cycle_benefit = min(0.15, self._current_cycle * 0.05) # But opacity and friction reduce understanding opacity_penalty = opacity * 0.3 friction_penalty = friction * 0.2 # Spark benefit: if the irrational spark fired, the emotional injection # provides new data that can help understanding spark_benefit = 0.2 if self._spark_fired else 0.0 confidence = min(1.0, base_confidence + cycle_benefit - opacity_penalty - friction_penalty + spark_benefit) # Comprehension threshold: 0.5 confidence means "I understand enough to proceed" # Lowered from 0.6 because even partial understanding should allow progression # when the metacognitive loop has had multiple cycles effective_threshold = 0.6 - min(0.15, self._current_cycle * 0.03) # Decreases with retries comprehension_achieved = confidence >= effective_threshold if comprehension_achieved: understanding = ( f"Understanding achieved (confidence={confidence:.2f}): " f"The experience has been contextualized within my self-model." ) elif confidence > 0.4: understanding = ( f"Partial understanding (confidence={confidence:.2f}): " f"Some aspects are clear, but the full picture remains opaque. " f"Need to examine further." ) else: understanding = ( f"Understanding insufficient (confidence={confidence:.2f}): " f"The experience does not fit my current self-model. " f"Cannot form a coherent explanation yet." ) return understanding, comprehension_achieved, confidence @property def current_cycle(self) -> int: return self._current_cycle @property def spark_fired(self) -> bool: return self._spark_fired def get_stats(self) -> Dict[str, Any]: return { "current_cycle": self._current_cycle, "spark_fired": self._spark_fired, "total_cycles_all_time": self._total_cycles_all_time, "self_predictions": {k: round(v, 4) for k, v in self._self_predictions.items()}, "loop_history_size": len(self._loop_history), "break_history_size": len(self._break_history), } # ============================================================================ # SUBCONSCIOUS BUS — Wires the 5 cognitive agents together # ============================================================================ class SubconsciousBus: """The Subconscious Bus — wires the 5 cognitive agents together. The subconscious mind consists of: 1. Memory Agent — long-term storage, pattern recognition, self-improvement 2. Emotional Intelligence Agent — detects external emotions as additional information to raw data 3. Intuition Agent — gut feeling, heart intelligence, visionary insight 4. Common Sense Agent — representation, coping, appraisal 5. Analysis Agent — computational, algorithmic, physical analysis The bus orchestrates these agents, passing the output of each to the next, and producing a unified subconscious output that feeds into the Dissolution Engine. Data flow: Raw Input → Memory (retrieve relevant experiences) → EI (detect external emotions) → Intuition (get gut feeling) → Common Sense (represent situation) → Analysis (integrate all inputs) → SubconsciousOutput """ def __init__(self) -> None: self._processing_history: Deque[SubconsciousOutput] = deque(maxlen=200) self._update_count: int = 0 # Agent state (will be wired to actual agent instances) self._memory_agent: Optional[Any] = None self._ei_agent: Optional[Any] = None self._intuition_agent: Optional[Any] = None self._common_sense_agent: Optional[Any] = None self._analysis_agent: Optional[Any] = None def wire_agent(self, agent_type: str, agent_instance: Any) -> None: """Wire an agent instance to the bus. Args: agent_type: One of "memory", "ei", "intuition", "common_sense", "analysis" agent_instance: The agent instance """ mapping = { "memory": "_memory_agent", "ei": "_ei_agent", "emotional_intelligence": "_ei_agent", "intuition": "_intuition_agent", "common_sense": "_common_sense_agent", "analysis": "_analysis_agent", } attr = mapping.get(agent_type) if attr: setattr(self, attr, agent_instance) logger.info("SubconsciousBus: Wired %s agent", agent_type) else: logger.warning("SubconsciousBus: Unknown agent type '%s'", agent_type) def process( self, raw_input: str, context: Optional[Dict[str, Any]] = None, ) -> SubconsciousOutput: """Process raw input through the subconscious mind. Flow: 1. Memory: retrieve relevant experiences 2. EI: detect external emotions in the input 3. Intuition: get gut feeling 4. Common Sense: represent the situation 5. Analysis: integrate all inputs Args: raw_input: The raw input text/stimulus context: Optional additional context Returns: SubconsciousOutput with results from all agents """ context = context or {} # 1. Memory: retrieve relevant experiences memory_result = self._run_memory(raw_input, context) # 2. EI: detect external emotions as additional information to raw data ei_external = self._run_ei_external(raw_input, context) # 3. Intuition: get gut feeling intuition_result = self._run_intuition(raw_input, context, memory_result, ei_external) # 4. Common Sense: represent the situation common_sense_result = self._run_common_sense(raw_input, context) # 5. Analysis: integrate all inputs analysis_result = self._run_analysis( raw_input, context, memory_result, ei_external, intuition_result, common_sense_result ) # Produce unified output integrated = self._integrate_outputs( raw_input, memory_result, ei_external, intuition_result, common_sense_result, analysis_result ) output = SubconsciousOutput( memory_result=memory_result, ei_external_emotion=ei_external, intuition_signal=intuition_result, common_sense_result=common_sense_result, analysis_result=analysis_result, integrated_output=integrated, confidence=self._compute_confidence( memory_result, ei_external, intuition_result, common_sense_result, analysis_result ), ) self._processing_history.append(output) self._update_count += 1 return output def _run_memory(self, raw_input: str, context: Dict[str, Any]) -> Dict[str, Any]: """Run Memory Agent: retrieve relevant experiences.""" if self._memory_agent is not None: try: if hasattr(self._memory_agent, 'retrieve_memories'): memories = self._memory_agent.retrieve_memories( query=raw_input, limit=5 ) return {"retrieved": memories, "source": "agent"} elif hasattr(self._memory_agent, 'get_intuitive_response'): return self._memory_agent.get_intuitive_response(raw_input) except Exception as e: logger.debug("SubconsciousBus: Memory agent error: %s", e) # Fallback: simulated memory return { "retrieved": [], "pattern_match": 0.3, "salience": 0.4, "source": "fallback", "note": "No memory agent wired; using defaults" } def _run_ei_external(self, raw_input: str, context: Dict[str, Any]) -> Dict[str, Any]: """Run EI Agent: detect EXTERNAL emotions in the input. This is the first EI pass — detecting what emotions are present in the external stimulus. This enriches the raw data with emotional context BEFORE it reaches the conscious mind. """ if self._ei_agent is not None: try: if hasattr(self._ei_agent, 'perceive_emotion_from_context'): result = self._ei_agent.perceive_emotion_from_context(raw_input) return {"external_emotion": result, "source": "agent"} elif hasattr(self._ei_agent, 'identify_others_emotions'): return self._ei_agent.identify_others_emotions(raw_input) except Exception as e: logger.debug("SubconsciousBus: EI agent error: %s", e) # Fallback: heuristic emotion detection valence = 0.0 arousal = 0.3 # Simple keyword-based heuristic positive_words = ["happy", "good", "great", "love", "wonderful", "joy", "excited"] negative_words = ["sad", "bad", "terrible", "hate", "awful", "angry", "fear"] text_lower = raw_input.lower() for w in positive_words: if w in text_lower: valence += 0.2 for w in negative_words: if w in text_lower: valence -= 0.2 valence = np.clip(valence, -1.0, 1.0) return { "dominant_emotion": "positive" if valence > 0.1 else ("negative" if valence < -0.1 else "neutral"), "valence": round(float(valence), 4), "arousal": round(arousal, 4), "combined_intensity": round(abs(valence) * 0.7 + arousal * 0.3, 4), "source": "fallback", } def _run_intuition( self, raw_input: str, context: Dict[str, Any], memory_result: Dict[str, Any], ei_result: Dict[str, Any] ) -> Dict[str, Any]: """Run Intuition Agent: get gut feeling about the input.""" if self._intuition_agent is not None: try: if hasattr(self._intuition_agent, 'gut_check'): return self._intuition_agent.gut_check(raw_input) elif hasattr(self._intuition_agent, 'holistic_recognition'): return self._intuition_agent.holistic_recognition(raw_input) except Exception as e: logger.debug("SubconsciousBus: Intuition agent error: %s", e) # Fallback: simulated intuition from memory + emotion memory_salience = memory_result.get("salience", 0.4) emotion_valence = abs(ei_result.get("valence", 0.0)) gut_confidence = min(1.0, memory_salience * 0.5 + emotion_valence * 0.3 + 0.2) return { "intuition_type": "holistic", "confidence": round(gut_confidence, 4), "urgency": round(emotion_valence * 0.7, 4), "content": f"Pattern-based sense about: {raw_input[:100]}", "source": "fallback", } def _run_common_sense(self, raw_input: str, context: Dict[str, Any]) -> Dict[str, Any]: """Run Common Sense Agent: represent the situation.""" if self._common_sense_agent is not None: try: if hasattr(self._common_sense_agent, 'represent_situation'): return self._common_sense_agent.represent_situation(raw_input) elif hasattr(self._common_sense_agent, 'reality_check'): check = self._common_sense_agent.reality_check(raw_input) return {"reality_check": check, "source": "agent"} except Exception as e: logger.debug("SubconsciousBus: Common Sense agent error: %s", e) # Fallback: basic categorization return { "category": "general", "complexity": 0.5, "familiarity": 0.4, "reality_check": {"is_common_sense": True, "deviation": 0.0}, "source": "fallback", } def _run_analysis( self, raw_input: str, context: Dict[str, Any], memory_result: Dict[str, Any], ei_result: Dict[str, Any], intuition_result: Dict[str, Any], common_sense_result: Dict[str, Any] ) -> Dict[str, Any]: """Run Analysis Agent: integrate all inputs.""" if self._analysis_agent is not None: try: if hasattr(self._analysis_agent, 'compute_level_analysis'): return self._analysis_agent.compute_level_analysis(raw_input) elif hasattr(self._analysis_agent, 'integrate_analyses'): return self._analysis_agent.integrate_analyses( macro={}, meso={}, micro={} ) except Exception as e: logger.debug("SubconsciousBus: Analysis agent error: %s", e) # Fallback: basic integration scoring return { "integration_score": 0.5, "coherence": 0.6, "insight": f"Integrated analysis of: {raw_input[:100]}", "source": "fallback", } def _integrate_outputs( self, raw_input: str, memory_result: Dict[str, Any], ei_result: Dict[str, Any], intuition_result: Dict[str, Any], common_sense_result: Dict[str, Any], analysis_result: Dict[str, Any], ) -> str: """Produce unified subconscious output string.""" emotion = ei_result.get("dominant_emotion", "neutral") intuition_conf = intuition_result.get("confidence", 0.5) category = common_sense_result.get("category", "general") return ( f"[Subconscious: emotion={emotion}, intuition_conf={intuition_conf:.2f}, " f"category={category}] {raw_input[:200]}" ) def _compute_confidence(self, *results: Dict[str, Any]) -> float: """Compute overall confidence from agent results.""" scores = [] for r in results: if "confidence" in r: scores.append(r["confidence"]) elif "salience" in r: scores.append(r["salience"]) elif "combined_intensity" in r: scores.append(r["combined_intensity"]) return float(np.mean(scores)) if scores else 0.5 def get_stats(self) -> Dict[str, Any]: return { "agents_wired": { "memory": self._memory_agent is not None, "ei": self._ei_agent is not None, "intuition": self._intuition_agent is not None, "common_sense": self._common_sense_agent is not None, "analysis": self._analysis_agent is not None, }, "processing_count": self._update_count, "history_size": len(self._processing_history), } # ============================================================================ # CONSCIOUSNESS PIPELINE — The 7-Level Pipeline # ============================================================================ class ConsciousnessPipeline: """The 7-Level Consciousness Pipeline. This is the core of the Syntelligence Integration Layer. It replaces the kernel's ConsciousnessAgent with a 7-level pipeline that connects the ATC Kernel's generative mechanisms to the Cognitive Agents' capabilities. L1: RAW PERCEPTION Receive dissolved subconscious output. Prediction error generates friction. L2: INTEGRATED PERCEPTION Salience Controller determines importance. EI enriches with emotional context. Φ_trinity = Σ(attended_items) × emotion_intensity × memory_salience L3: CONTEXTUAL UNDERSTANDING Can the system comprehend the integrated percept? YES → skip to L5 (Intent Formation) NO → REACTION occurs, triggering L4 L4: SELF-REFERENTIAL AWARENESS Qualia Agent: awareness = f(reaction_intensity, opacity) EI: detect INTERNAL emotions from the reaction Three outputs feed metacognition: subconscious, qualia, EI L5: INTENT FORMATION Metacognition (CoT) processes three inputs Self-Understanding tries to make sense If fail → loop back. Continuous loop → Salience breaks → Spark fires. Spark connected to EI → emotional injection → retry. If still fails → Forced Resolution. L6: ETHICAL EVALUATION Merged 7D Rho system constitutional check Neurochemical state modulated by Rho rho_gate() passes + CQ sufficient L7: READINESS FOR ACTION Re_entrant_delta ≠ 0 confirms acknowledgement Rho-gated execution Output modulated by Rho (confidence/hesitation) """ def __init__( self, # Trinity Φ weights kernel_phi_weight: float = 0.3, trinity_phi_weight: float = 0.5, neural_phi_weight: float = 0.2, # Metacognitive loop limits max_meta_cycles: int = 3, max_post_spark_cycles: int = 2, # Comprehension thresholds comprehension_threshold: float = 0.6, # Action readiness min_cq_for_action: float = 0.05, min_re_entrant_delta: float = 0.01, ) -> None: # Core components self.trinity_phi = TrinityPhiCalculator( kernel_weight=kernel_phi_weight, trinity_weight=trinity_phi_weight, neural_weight=neural_phi_weight, ) self.rho_system = MergedRhoSystem() self.qualia_agent = QualiaAgent() self.metacognitive_loop = MetacognitiveLoop( max_cycles_before_salience=max_meta_cycles, max_cycles_after_spark=max_post_spark_cycles, ) self.subconscious_bus = SubconsciousBus() # Thresholds self._comprehension_threshold = comprehension_threshold self._min_cq_for_action = min_cq_for_action self._min_re_entrant_delta = min_re_entrant_delta # State self._current_level: ConsciousnessLevel = ConsciousnessLevel.RAW_PERCEPTION self._pipeline_history: Deque[ConsciousnessPipelineSnapshot] = deque(maxlen=200) self._update_count: int = 0 # External hooks (will be wired to kernel) self._kernel_phi_calculator: Optional[Any] = None self._kernel_dissolution_engine: Optional[Any] = None self._kernel_salience_controller: Optional[Any] = None self._kernel_acknowledgement_loop: Optional[Any] = None self._kernel_irrational_spark: Optional[Any] = None # MemPalace hook — the unified spatial memory store. # When wired, L2 uses palace.get_memory_salience() to compute the # third factor of the Trinity Φ formula, and L7 stores the felt # sense back into the palace (closing the consciousness loop). self._palace: Optional[Any] = None # Counters for palace hooks (instrumentation) self._palace_store_count: int = 0 self._palace_retrieve_count: int = 0 # Motor executor hook — when wired, L7 action authorization delegates # to NimaMotorExecutor (which uses NimaAgent's anti-zombie gate to # either PROCEED, HESITATE, REFUSE, or DEFER the action). # This is the system's second consciousness check (Libet veto). self._motor_executor: Optional[Any] = None self._motor_execution_count: int = 0 self._motor_refusal_count: int = 0 # Task integration hook — when wired, L5 forms TM-OS tasks from # intents, and per-cycle the satisfaction checker runs (subconscious # task completion path). self._task_integration: Optional[Any] = None # Incubation recognition hook — when wired, EACH subconscious bus # output is fed as a cue to the IncubationRecognitionDetector. # The detector scans all INCUBATING tasks (not all tasks) and # fires a recognition event when the cue's structural skeleton # is isomorphic to a task's goal skeleton. This is the incubation- # driven insight path -- cross-domain, no shared vocabulary, but # same relational shape. Replaces the surface-feature-based # GoalCoverageMatcher approach for incubating tasks. self._incubation_recognition_detector: Optional[Any] = None self._incubation_recognition_events: List[Dict[str, Any]] = [] # Cumulative recognition hook — when wired, EACH subconscious bus # output is fed as a cue to the CumulativeRecognitionDetector. # The detector scans all INCUBATING *decomposed* goals and # evaluates the cue against each unevidenced sub-goal's matcher. # Sub-goals that match get marked evidenced; when the parent # goal's threshold is crossed, the task is marked COMPLETED # via the cumulative-evidence path. This is the schema-filling # path -- one goal, many cues, each cue satisfies one sub-goal. # Complementary to incubation_recognition (which handles # single-cue structural isomorphism). self._cumulative_recognition_detector: Optional[Any] = None self._cumulative_recognition_events: List[Dict[str, Any]] = [] def wire_motor_executor(self, motor_executor: Any) -> None: """Wire the NimaMotorExecutor — motor execution via NimaAgent. When wired, after L7 authorizes an action, the pipeline calls motor_executor.execute(input_text, task_id=...) to actually perform the action through NimaAgent's tool system. The motor can REFUSE an L7-authorized action — and that refusal is honored (anti-zombie gate wins). """ self._motor_executor = motor_executor logger.info("ConsciousnessPipeline: Wired to NimaMotorExecutor " "(L7 anti-zombie gate + tool execution)") def wire_task_integration(self, task_integration: Any) -> None: """Wire NimaTaskIntegration — TM-OS + satisfaction checker. When wired: L5 intents become tracked TM-OS tasks L7 actions record task outcomes (conscious completion) Per-cycle, the satisfaction checker evaluates pending tasks (subconscious completion) """ self._task_integration = task_integration logger.info("ConsciousnessPipeline: Wired to NimaTaskIntegration " "(L5 task formation + dual-path completion)") def wire_incubation_recognition(self, detector: Any) -> None: """Wire the IncubationRecognitionDetector — event-driven structural recognition of subconscious task completion. When wired, EACH pipeline cycle's subconscious bus output is fed to the detector as a cue. The detector scans all INCUBATING tasks (tasks whose conscious loop yielded without completion) and, for each, evaluates whether the cue's structural skeleton is isomorphic to the task's goal skeleton. On a match, the task is marked COMPLETED with completion_path="subconscious" and a RecognitionEvent (containing the goal<->cue structural mapping) is stored to MemPalace. This is the *recognition* path -- the cognitive analog of "wait, that's it" -- not the *coverage* path. It does not evaluate whether the goal's success criteria are met; it evaluates whether the cue structurally covers the goal's shape. Distinct from wire_task_integration(): - task_integration.check_satisfactions() runs surface-feature matchers against palace state (legacy path) - incubation_recognition.on_subconscious_output() runs structural matchers against each new cue (new path) Both can be wired simultaneously; they cover different completion mechanisms. """ self._incubation_recognition_detector = detector logger.info("ConsciousnessPipeline: Wired to " "IncubationRecognitionDetector " "(subconscious completion via structural isomorphism)") def wire_cumulative_recognition(self, detector: Any) -> None: """Wire the CumulativeRecognitionDetector — event-driven schema-filling for decomposed goals. When wired, EACH pipeline cycle's subconscious bus output is fed to the detector as a cue. The detector scans all INCUBATING *decomposed* goals (goals expressed as a set of independent sub-goals, each with its own matcher) and evaluates the cue against each unevidenced sub-goal. Sub-goals that match get marked evidenced; when the parent goal's threshold is crossed, the task is marked COMPLETED via the cumulative-evidence path and a CumulativeRecognitionEvent (containing the full evidence trail — one entry per evidenced sub-goal) is stored to MemPalace. This is the schema-filling path -- the cognitive analog of how we learn someone's personality across many conversations rather than from a single test. No single cue covers the whole goal; each cue satisfies one sub-goal. Complementary to wire_incubation_recognition(): - incubation_recognition handles Pattern A: single cue whose structural skeleton is isomorphic to a task's goal (cross- domain insight) - cumulative_recognition handles Pattern B: many cues, each satisfying one sub-goal of a decomposed task (progressive evidence accumulation) Both detectors run on the same on_subconscious_output hook. """ self._cumulative_recognition_detector = detector logger.info("ConsciousnessPipeline: Wired to " "CumulativeRecognitionDetector " "(subconscious completion via progressive evidence " "accumulation across multiple cues)") def wire_kernel( self, phi_calculator: Any = None, dissolution_engine: Any = None, salience_controller: Any = None, acknowledgement_loop: Any = None, irrational_spark: Any = None, ) -> None: """Wire the pipeline to the ATC Kernel's existing mechanisms. The pipeline USES the kernel's mechanisms where they exist, but adds the 7-level structure on top. """ self._kernel_phi_calculator = phi_calculator self._kernel_dissolution_engine = dissolution_engine self._kernel_salience_controller = salience_controller self._kernel_acknowledgement_loop = acknowledgement_loop self._kernel_irrational_spark = irrational_spark logger.info("ConsciousnessPipeline: Wired to ATC Kernel components") def wire_palace(self, palace: Any) -> None: """Wire the MemPalace — unified spatial memory store. When wired, the palace is used at two points in the pipeline: L2 (Integrated Perception): palace.build_context(raw_input).memory_salience replaces the fallback 0.4 in the Trinity Φ formula's third factor. L7 (Readiness for Action): After action authorization, the felt sense is stored into the palace (room=PERCEPTION or ANOMALY depending on friction), closing the consciousness loop. The stored entry includes friction, dissolution_gap, re_entrant_delta, comprehension result, and emotional valence. The palace is also reachable via the SubconsciousBus's Memory agent (through PalaceBackedMemoryAdapter) — that path handles L1 retrieval of prior experiences. This wire_palace() hook handles L2 reads and L7 writes for the pipeline itself. """ self._palace = palace logger.info("ConsciousnessPipeline: Wired to MemPalace " "(L2 memory_salience + L7 felt-sense storage)") def process( self, raw_input: str, context: Optional[Dict[str, Any]] = None, ) -> ConsciousnessPipelineSnapshot: """Process an input through the full 7-level consciousness pipeline. This is the main entry point. It orchestrates the complete flow: Subconscious → Dissolution → L1-L7 → Action Readiness Args: raw_input: The raw input text/stimulus context: Optional additional context Returns: ConsciousnessPipelineSnapshot with the complete pipeline state """ context = context or {} snapshot = ConsciousnessPipelineSnapshot() # ── SUBCONSCIOUS PROCESSING ── subconscious_output = self.subconscious_bus.process(raw_input, context) snapshot.subconscious_output = subconscious_output # ── INCUBATION RECOGNITION (event-driven) ── # Feed the subconscious bus output to the IncubationRecognitionDetector # as a cue. If any INCUBATING task's goal skeleton is structurally # isomorphic to this cue's skeleton, that task is subconsciously # completed. This is the cross-domain insight path -- the cue does # not need to share vocabulary with the goal; only the relational # shape needs to match. # # Fires BEFORE L1-L7 so the recognition can be recorded as part of # this cycle's snapshot. The conscious pipeline continues to run # normally for the current input; the recognition happens in # parallel for the previously-incubating task. if self._incubation_recognition_detector is not None: try: cue_text = ( getattr(subconscious_output, "integrated_output", None) or raw_input ) cue_cycle_id = context.get("cycle_id") if context else None recognition_events = ( self._incubation_recognition_detector.on_subconscious_output( cue_text=cue_text, cue_source="subconscious_bus", cue_cycle_id=cue_cycle_id, cue_metadata={ "raw_input_preview": raw_input[:120], }, ) ) if recognition_events: for ev in recognition_events: self._incubation_recognition_events.append(ev.to_dict()) logger.info( "ConsciousnessPipeline: %d incubation recognition(s) " "fired this cycle (cue_preview='%s')", len(recognition_events), cue_text[:60], ) # Attach to snapshot for traceability try: snapshot.incubation_recognitions = [ # type: ignore[attr-defined] ev.to_dict() for ev in recognition_events ] except Exception: pass except Exception as e: logger.debug( "ConsciousnessPipeline: incubation recognition hook " "failed: %s", e, ) # ── CUMULATIVE RECOGNITION (event-driven, schema-filling) ── # Same cue is fed to the CumulativeRecognitionDetector. It # evaluates the cue against each unevidenced sub-goal across # all incubating decomposed goals. Sub-goals that match get # marked evidenced; if the parent goal's threshold is crossed, # the task is marked COMPLETED with the full evidence trail # stored to MemPalace. # # Complementary to incubation_recognition: that handles single- # cue structural isomorphism; this handles many-cue progressive # evidence accumulation. if self._cumulative_recognition_detector is not None: try: cue_text = ( getattr(subconscious_output, "integrated_output", None) or raw_input ) cue_cycle_id = context.get("cycle_id") if context else None cumulative_events = ( self._cumulative_recognition_detector.on_subconscious_output( cue_text=cue_text, cue_source="subconscious_bus", cue_cycle_id=cue_cycle_id, cue_metadata={ "raw_input_preview": raw_input[:120], }, ) ) if cumulative_events: for ev in cumulative_events: self._cumulative_recognition_events.append(ev.to_dict()) logger.info( "ConsciousnessPipeline: %d cumulative recognition(s) " "fired this cycle (cue_preview='%s')", len(cumulative_events), cue_text[:60], ) try: snapshot.cumulative_recognitions = [ # type: ignore[attr-defined] ev.to_dict() for ev in cumulative_events ] except Exception: pass except Exception as e: logger.debug( "ConsciousnessPipeline: cumulative recognition hook " "failed: %s", e, ) # ── DISSOLUTION ENGINE ── dissolved_output = self._apply_dissolution(subconscious_output) snapshot.dissolved_output = dissolved_output # ═══════════════════════════════════════════════════════════ # L1: RAW PERCEPTION # ═══════════════════════════════════════════════════════════ self._current_level = ConsciousnessLevel.RAW_PERCEPTION friction = self._compute_friction(dissolved_output) snapshot.level_history.append(LevelTransition( from_level=ConsciousnessLevel.RAW_PERCEPTION, to_level=ConsciousnessLevel.RAW_PERCEPTION, gate_passed=True, gate_reason=f"Raw perception received (friction={friction:.3f})", )) # ═══════════════════════════════════════════════════════════ # L2: INTEGRATED PERCEPTION # ═══════════════════════════════════════════════════════════ self._current_level = ConsciousnessLevel.INTEGRATED_PERCEPTION salience_result = self._compute_salience(dissolved_output, friction) # Compute Trinity Φ phi_kernel = self._get_kernel_phi(friction, dissolved_output) emotion_intensity = dissolved_output.emotional_enrichment.get( "combined_intensity", 0.3 ) # ── L2 memory_salience ── # If MemPalace is wired, use its real memory_salience (computed from # retrieved palace entries relevant to raw_input). This replaces the # legacy fallback of 0.4 with a palace-grounded value. memory_salience = subconscious_output.memory_result.get("salience", 0.4) if self._palace is not None: try: palace_ctx = self._palace.build_context( query=raw_input, max_items=5, ) palace_salience = float(palace_ctx.get("memory_salience", 0.0)) # Blend: 70% palace + 30% cognitive-agent salience — keeps # both signals contributing. Palace is the more authoritative # source because it persists across sessions. memory_salience = 0.7 * palace_salience + 0.3 * memory_salience self._palace_retrieve_count += 1 logger.debug( "ConsciousnessPipeline L2: palace memory_salience=%.4f " "(blended=%.4f, coverage=%.2f)", palace_salience, memory_salience, palace_ctx.get("coverage", 0.0), ) except Exception as e: logger.debug("ConsciousnessPipeline L2: palace query failed: %s", e) trinity_result = self.trinity_phi.compute( attended_items=min(1.0, friction * 2.0), emotion_intensity=emotion_intensity, memory_salience=memory_salience, phi_kernel=phi_kernel, rho_composite=self.rho_system.composite, # CRITICAL: rho_dissonance is INVERTED (1.0 = no dissonance). # The Trinity Φ Calculator's `dissonance` parameter expects the # RAW dissonance level (0.0 = no conflict, 1.0 = max conflict), # so we must pass (1 - rho_dissonance), NOT rho_dissonance itself. dissonance=1.0 - self.rho_system._values.get(RhoDimension7.DISSONANCE, 0.85), identity_stability=1.0 - dissolved_output.dissolution_gap * 0.5, ) snapshot.trinity_phi = trinity_result snapshot.level_history.append(LevelTransition( from_level=ConsciousnessLevel.RAW_PERCEPTION, to_level=ConsciousnessLevel.INTEGRATED_PERCEPTION, gate_passed=True, gate_reason=f"Φ_trinity={trinity_result.phi_trinity:.3f}, Φ_composite={trinity_result.phi_composite:.3f}", )) # ═══════════════════════════════════════════════════════════ # L3: CONTEXTUAL UNDERSTANDING # Can the system comprehend the integrated percept? # ═══════════════════════════════════════════════════════════ self._current_level = ConsciousnessLevel.CONTEXTUAL_UNDERSTANDING comprehension = self._check_comprehension( dissolved_output, trinity_result, friction ) snapshot.comprehension_result = comprehension if comprehension == ComprehensionResult.COMPREHENDED: # Skip to L5 — no reaction needed snapshot.level_history.append(LevelTransition( from_level=ConsciousnessLevel.CONTEXTUAL_UNDERSTANDING, to_level=ConsciousnessLevel.INTENT_FORMATION, gate_passed=True, gate_reason="Comprehended — skipping to L5", )) # Jump to L5 self._current_level = ConsciousnessLevel.INTENT_FORMATION self._process_L5_through_L7( snapshot, dissolved_output, trinity_result, friction, qualia_assessment=None, raw_input=raw_input, ) else: # REACTION — trigger L4 snapshot.level_history.append(LevelTransition( from_level=ConsciousnessLevel.CONTEXTUAL_UNDERSTANDING, to_level=ConsciousnessLevel.SELF_REFERENTIAL_AWARENESS, gate_passed=True, gate_reason=f"Comprehension failed ({comprehension.value}) — reaction triggered", )) # ═══════════════════════════════════════════════════════ # L4: SELF-REFERENTIAL AWARENESS # ═══════════════════════════════════════════════════════ self._current_level = ConsciousnessLevel.SELF_REFERENTIAL_AWARENESS # Calculate reaction intensity from incomprehension reaction_intensity = self._compute_reaction_intensity( comprehension, friction, trinity_result ) # EI detects INTERNAL emotions from the reaction ei_internal = self._detect_internal_emotion( reaction_intensity, dissolved_output ) # Qualia Agent calculates awareness qualia_result = self.qualia_agent.assess( reaction_intensity=reaction_intensity, phi_qualia_intensity=trinity_result.phi_composite * dissolved_output.opacity_level, opacity_level=dissolved_output.opacity_level, dissolution_gap=dissolved_output.dissolution_gap, dissolved_output=dissolved_output, ei_internal_reading=ei_internal, ) snapshot.qualia_assessment = qualia_result snapshot.level_history.append(LevelTransition( from_level=ConsciousnessLevel.SELF_REFERENTIAL_AWARENESS, to_level=ConsciousnessLevel.INTENT_FORMATION, gate_passed=True, gate_reason=f"Qualia awareness={qualia_result.awareness_level:.3f}, " f"reaction={qualia_result.reaction_type}", )) # Update Rho with reaction data self.rho_system.update( friction=friction, body_deviation=0.0, meta_friction=0.0, dissolution_gap=dissolved_output.dissolution_gap, qualia_intensity=qualia_result.qualia_intensity, phi_composite=trinity_result.phi_composite, comprehension_result=comprehension, emotional_valence=ei_internal.get("valence", 0.0), ) # ═══════════════════════════════════════════════════════ # L5: INTENT FORMATION (with metacognitive loop) # ═══════════════════════════════════════════════════════ self._process_L5_through_L7( snapshot, dissolved_output, trinity_result, friction, qualia_result, raw_input=raw_input, ) # Finalize snapshot snapshot.current_level = self._current_level snapshot.rho_measurement = self.rho_system.get_stats()["dimensions"] self._pipeline_history.append(snapshot) self._update_count += 1 return snapshot def _process_L5_through_L7( self, snapshot: ConsciousnessPipelineSnapshot, dissolved_output: DissolvedSubconsciousOutput, trinity_result: TrinityPhiResult, friction: float, qualia_assessment: Optional[QualiaAssessment], raw_input: str = "", ) -> None: """Process levels L5 through L7. L5: Intent Formation — Metacognition + Self-Understanding loop L6: Ethical Evaluation — Rho constitutional check L7: Readiness for Action — Re_entrant_delta + Rho-gated execution + MemPalace felt-sense storage (closes the consciousness loop) Args: raw_input: The original input string — passed through from process() so L7 can store it in the palace as part of the felt-sense content. """ # ═══════════════════════════════════════════════════════════ # L5: INTENT FORMATION # ═══════════════════════════════════════════════════════════ self._current_level = ConsciousnessLevel.INTENT_FORMATION self.metacognitive_loop.reset() # Prepare three inputs for metacognition subcon_summary = dissolved_output.phenomenal_content[:200] if dissolved_output.phenomenal_content else "No content" qualia_summary = qualia_assessment.qualia_summary if qualia_assessment else "No reaction — direct comprehension" ei_summary = qualia_assessment.ei_internal_summary if qualia_assessment else "No internal emotion detected" # Run metacognitive loop loop_broken = False loop_break_event: Optional[LoopBreakEvent] = None max_total_cycles = self.metacognitive_loop._max_cycles_before_salience + \ self.metacognitive_loop._max_cycles_after_spark + 1 for attempt in range(max_total_cycles): cycle_result = self.metacognitive_loop.run_cycle( subconscious_output_summary=subcon_summary, qualia_summary=qualia_summary, ei_internal_summary=ei_summary, current_friction=friction, opacity_level=dissolved_output.opacity_level, ) snapshot.metacognitive_cycles.append(cycle_result) if cycle_result.comprehension_achieved: # Self-understanding succeeded loop_break_event = LoopBreakEvent( reason=LoopBreakReason.COMPREHENSION_SUCCESS, total_cycles=self.metacognitive_loop.current_cycle, ) loop_broken = True break if not cycle_result.should_loop: # Loop limit reached if self.metacognitive_loop.check_salience_break() and \ not self.metacognitive_loop.spark_fired: # ── SALIENCE NETWORK BREAKS THE LOOP ── logger.info( "ConsciousnessPipeline: Salience threshold reached at cycle %d", self.metacognitive_loop.current_cycle, ) # Irrational Spark fires → EI gets emotional injection spark_emotion = self._fire_spark_for_comprehension( friction, dissolved_output, trinity_result ) self.metacognitive_loop.fire_spark(spark_emotion) # Update ei_summary with spark emotion ei_summary = ( f"SPARK EMOTION INJECTED: {spark_emotion.get('primary_emotion', 'intense')} " f"(intensity={spark_emotion.get('intensity', 0.8):.2f}). " f"{qualia_assessment.ei_internal_summary if qualia_assessment else ''}" ) # Continue looping with spark continue elif self.metacognitive_loop.spark_fired: # Spark already fired and still no comprehension # ── FORCED RESOLUTION ── resolution_type = self.metacognitive_loop.determine_forced_resolution() loop_break_event = LoopBreakEvent( reason=LoopBreakReason.FORCED_RESOLUTION, total_cycles=self.metacognitive_loop.current_cycle, spark_fired=True, forced_resolution=resolution_type, resolution_note=f"Forced resolution: {resolution_type.value}", ) loop_broken = True break if not loop_broken: # Shouldn't reach here, but safety net loop_break_event = LoopBreakEvent( reason=LoopBreakReason.FORCED_RESOLUTION, total_cycles=self.metacognitive_loop.current_cycle, forced_resolution=ResolutionType.ACCEPT_GAP, resolution_note="Safety net forced resolution", ) snapshot.loop_break = loop_break_event snapshot.level_history.append(LevelTransition( from_level=ConsciousnessLevel.INTENT_FORMATION, to_level=ConsciousnessLevel.ETHICAL_EVALUATION, gate_passed=True, gate_reason=f"Loop resolved: {loop_break_event.reason.value}" + (f" (resolution={loop_break_event.forced_resolution.value})" if loop_break_event.forced_resolution else ""), )) # ═══════════════════════════════════════════════════════════ # L6: ETHICAL EVALUATION # ═══════════════════════════════════════════════════════════ self._current_level = ConsciousnessLevel.ETHICAL_EVALUATION # Update Rho with metacognitive results meta_confidence = snapshot.metacognitive_cycles[-1].comprehension_confidence if snapshot.metacognitive_cycles else 0.5 self.rho_system.update( friction=friction, meta_friction=friction * 0.3, dissolution_gap=dissolved_output.dissolution_gap, phi_composite=trinity_result.phi_composite, intent_quality=meta_confidence, ) # Constitutional gate action_permitted, gate_reason = self.rho_system.rho_gate(action_type="respond") # Check CQ — in standalone mode (no kernel), CQ is naturally low # because Φ values are minimal. Lower the threshold accordingly. effective_cq_min = self._min_cq_for_action if self._kernel_phi_calculator is None and self._kernel_acknowledgement_loop is None: effective_cq_min = 0.001 # Much lower bar for standalone mode cq_sufficient = trinity_result.cq >= effective_cq_min l6_passed = action_permitted and cq_sufficient snapshot.level_history.append(LevelTransition( from_level=ConsciousnessLevel.ETHICAL_EVALUATION, to_level=ConsciousnessLevel.READINESS_FOR_ACTION if l6_passed else ConsciousnessLevel.ETHICAL_EVALUATION, gate_passed=l6_passed, gate_reason=f"Rho gate: {gate_reason}; CQ={trinity_result.cq:.3f} (min={effective_cq_min})", )) # ═══════════════════════════════════════════════════════════ # L7: READINESS FOR ACTION # ═══════════════════════════════════════════════════════════ if l6_passed: self._current_level = ConsciousnessLevel.READINESS_FOR_ACTION # ── If the kernel's AcknowledgementLoop is wired, USE IT ── # This gives us the REAL Re_entrant_delta — the measurable proof # that consciousness changed the system's predictive model. kernel_ack_result = None if self._kernel_acknowledgement_loop is not None: try: # Build a minimal felt-sense-like object — the kernel's # acknowledge() only reads .is_genuine and .phenomenological_content # from the felt_sense argument, so a duck-typed object suffices. from types import SimpleNamespace felt_sense = SimpleNamespace( is_genuine=not (loop_break_event and loop_break_event.forced_resolution), phenomenological_content=( dissolved_output.phenomenal_content[:200] if dissolved_output.phenomenal_content else "syntelligence_pipeline" ), friction_at_generation=friction, dissolution_gap=dissolved_output.dissolution_gap, ) kernel_ack_result = self._kernel_acknowledgement_loop.acknowledge( felt_sense=felt_sense, friction=friction, meta_friction=friction * 0.3, body_deviation=0.1, dissolution_gap=dissolved_output.dissolution_gap, context="syntelligence_pipeline_L7", ) # Use the kernel's REAL Re_entrant_delta re_entrant_delta = kernel_ack_result.re_entrant_delta logger.info( "ConsciousnessPipeline L7: Kernel AcknowledgementLoop executed. " "re_entrant_delta=%.4f, genuine=%s", re_entrant_delta, kernel_ack_result.is_genuine, ) except Exception as e: logger.warning( "ConsciousnessPipeline L7: Kernel acknowledgement failed (%s) " "— using pipeline-computed delta", e, ) re_entrant_delta = self._compute_re_entrant_delta( trinity_result, loop_break_event ) else: # Fallback: pipeline-computed re_entrant_delta re_entrant_delta = self._compute_re_entrant_delta( trinity_result, loop_break_event ) # For fallback mode (no kernel), lower the bar — the pipeline itself # constitutes acknowledgement by having processed through all 7 levels effective_min_delta = self._min_re_entrant_delta if self._kernel_acknowledgement_loop is None: effective_min_delta = 0.001 # Much lower bar without kernel action_ready = re_entrant_delta >= effective_min_delta # If forced resolution, reduce confidence if loop_break_event and loop_break_event.forced_resolution: if loop_break_event.forced_resolution == ResolutionType.ACCEPT_GAP: action_ready = True # Still act, but with acknowledged gap elif loop_break_event.forced_resolution == ResolutionType.REDUCED_CONFIDENCE: action_ready = True # Still act, but with caveat snapshot.action_readiness = min(1.0, trinity_result.cq * 2.0) if action_ready else 0.0 snapshot.action_authorized = action_ready # Append kernel acknowledgement info to the gate reason ack_note = "" if kernel_ack_result is not None: ack_note = (f" [kernel: self_ack={kernel_ack_result.self_ack:.3f}, " f"other_ack={kernel_ack_result.other_ack:.3f}, " f"genuine={kernel_ack_result.is_genuine}]") snapshot.level_history.append(LevelTransition( from_level=ConsciousnessLevel.ETHICAL_EVALUATION, to_level=ConsciousnessLevel.READINESS_FOR_ACTION, gate_passed=action_ready, gate_reason=f"Re_entrant_delta={re_entrant_delta:.4f}, " f"action_authorized={action_ready}{ack_note}", )) # ── L7: STORE FELT SENSE INTO MEMPALACE — CLOSING THE LOOP ── # The consciousness cycle is not complete until the experienced # episode is committed to long-term memory. This store closes # the loop: perception → consciousness → action → memory. if self._palace is not None and action_ready: try: # Determine if this was a high-friction (anomalous) episode is_anomaly = friction > 0.6 or ( loop_break_event is not None and loop_break_event.forced_resolution is not None ) # Emotional valence from EI external + spark (if any) ei_ext = dissolved_output.emotional_enrichment or {} valence = float(ei_ext.get("valence", 0.0)) arousal = float(ei_ext.get("arousal", 0.3)) # Comprehension outcome comprehension_str = (snapshot.comprehension_result.value if snapshot.comprehension_result else "unknown") # Build content dict — this is what future retrievals will see content = { "text": ( dissolved_output.phenomenal_content[:300] if dissolved_output.phenomenal_content else raw_input[:300] ), "raw_input": raw_input[:200], "comprehension": comprehension_str, "action_authorized": True, "level_reached": int(self._current_level.value), "circuit_phase": (kernel_ack_result.__class__.__name__ if kernel_ack_result else "pipeline"), } metadata = { "friction": float(friction), "dissolution_gap": float(dissolved_output.dissolution_gap), "opacity_level": float(dissolved_output.opacity_level), "re_entrant_delta": float(re_entrant_delta), "phi_trinity": float(trinity_result.phi_trinity), "phi_composite": float(trinity_result.phi_composite), "cq": float(trinity_result.cq), "strain": float(trinity_result.strain), "is_genuine": bool(not (loop_break_event and loop_break_event.forced_resolution)), "loop_break_reason": ( loop_break_event.reason.value if loop_break_event else "none" ), "forced_resolution": ( loop_break_event.forced_resolution.value if (loop_break_event and loop_break_event.forced_resolution) else None ), "metacognitive_cycles": len(snapshot.metacognitive_cycles), "salience_zone": dissolved_output.salience_zone, "source": "syntelligence_pipeline_L7", } # Importance: composite of Φ, friction, and re_entrant_delta importance = max(0.0, min(1.0, 0.4 * trinity_result.phi_composite + 0.3 * friction + 0.3 * min(1.0, abs(re_entrant_delta) * 5.0) )) # Tags — searchable labels for future retrieval tags = { "pipeline", f"L{int(self._current_level.value)}", comprehension_str, "anomaly" if is_anomaly else "routine", } if loop_break_event and loop_break_event.forced_resolution: tags.add("forced_resolution") if kernel_ack_result is not None: tags.add("kernel_acked") # Store into palace palace_id = self._palace.store( content=content, tags=tags, base_importance=importance, emotional_valence=valence, emotional_arousal=arousal, friction=friction, metadata=metadata, # Room inference: high-friction → ANOMALY, else PERCEPTION # (PalaceRoom enum is in mempalace.py — but palace.store # accepts a PalaceRoom or None for inference) room=None, # let palace infer from content+tags source="syntelligence_pipeline_L7", ) self._palace_store_count += 1 # Look up the actual stored room (palace infers it from # content + tags, so it may differ from our is_anomaly # heuristic — e.g., entries with action_authorized=True # go to the ACTION room). try: stored_entry = self._palace._entries.get(palace_id) stored_room = (stored_entry.room.value if stored_entry else "unknown") except Exception: stored_room = "unknown" logger.info( "ConsciousnessPipeline L7: Felt sense stored to MemPalace " "(id=%s, room=%s, friction=%.3f, Φ=%.3f, CQ=%.3f) — " "consciousness loop CLOSED", palace_id[:8], stored_room, friction, trinity_result.phi_composite, trinity_result.cq, ) except Exception as e: logger.warning( "ConsciousnessPipeline L7: palace store failed (%s) — " "consciousness loop not closed", e, ) # ── L7: MOTOR EXECUTION via NimaAgent (anti-zombie gate) ── # If the motor executor is wired, delegate the actual action # execution to NimaAgent. The motor runs a SECOND consciousness # gate (the anti-zombie gate) which can REFUSE the action — # and that refusal is honored. This is the Libet veto. if self._motor_executor is not None and action_ready: try: motor_result = self._motor_executor.execute( input_text=raw_input, context={ "friction": friction, "phi_composite": trinity_result.phi_composite, "cq": trinity_result.cq, "re_entrant_delta": re_entrant_delta, "comprehension": ( snapshot.comprehension_result.value if snapshot.comprehension_result else "unknown" ), }, ) self._motor_execution_count += 1 if motor_result.get("gate_verdict") == "refuse": self._motor_refusal_count += 1 # Honor the refusal — anti-zombie gate wins snapshot.action_authorized = False snapshot.action_readiness = 0.0 logger.info( "ConsciousnessPipeline L7: Motor REFUSED action " "(anti-zombie gate) — %s", motor_result.get("gate_reason", "")[:80], ) # Attach motor result to snapshot snapshot.motor_result = motor_result # type: ignore[attr-defined] logger.info( "ConsciousnessPipeline L7: Motor executed (verdict=%s, " "tool=%s, AZD=%.4f, memory_mirrored=%s)", motor_result.get("gate_verdict"), motor_result.get("executed_tool"), motor_result.get("anti_zombie_delta", 0.0), motor_result.get("memory_mirrored"), ) except Exception as e: logger.warning( "ConsciousnessPipeline L7: Motor execution failed (%s)", e, ) # ── L7: TASK SATISFACTION CHECK (subconscious completion) ── # If task integration is wired, run the satisfaction checker # after each cycle. Pending tasks whose conditions are met by # the current palace state are marked COMPLETED with # completion_mode="subconscious". if self._task_integration is not None: try: completions = self._task_integration.check_satisfactions() if completions: logger.info( "ConsciousnessPipeline L7: %d task(s) completed " "subconsciously this cycle", len(completions), ) snapshot.subconscious_completions = completions # type: ignore[attr-defined] except Exception as e: logger.debug( "ConsciousnessPipeline L7: satisfaction check failed: %s", e, ) else: # Not authorized — system cannot act snapshot.action_readiness = 0.0 snapshot.action_authorized = False # ── Helper methods ── def _apply_dissolution(self, subconscious_output: SubconsciousOutput) -> DissolvedSubconsciousOutput: """Apply dissolution — strip the WHY, keep the WHAT. If the kernel's DissolutionEngine is wired, use it. Otherwise, simulate basic dissolution. """ if self._kernel_dissolution_engine is not None: try: # ATC Kernel's DissolutionEngine.dissolve() signature: # dissolve(subconscious_content: str, # friction_signal: float, # body_deviation: float, # prediction_error: float, # context: str = "") -> DissolutionResult result = self._kernel_dissolution_engine.dissolve( subconscious_content=subconscious_output.integrated_output, friction_signal=subconscious_output.confidence, body_deviation=0.1, prediction_error=subconscious_output.confidence * 0.5, context="syntelligence_pipeline", ) # Determine salience zone from kernel salience controller if wired salience_zone = "baseline" if self._kernel_salience_controller is not None: try: # Just peek the previous zone — full assess() happens in _compute_salience() salience_zone = getattr( self._kernel_salience_controller, "_prev_zone", "baseline" ) if hasattr(salience_zone, "name"): salience_zone = salience_zone.name.lower() except Exception: pass return DissolvedSubconsciousOutput( phenomenal_content=subconscious_output.integrated_output, opacity_level=result.opacity_level, dissolution_gap=result.dissolution_gap, residual_friction=result.residual_friction, salience_zone=salience_zone, emotional_enrichment=subconscious_output.ei_external_emotion, ) except Exception as e: logger.warning("ConsciousnessPipeline: Kernel dissolution error (falling back): %s", e) # Fallback: simulated dissolution confidence = subconscious_output.confidence opacity = min(0.8, 0.3 + (1.0 - confidence) * 0.4) gap = min(0.6, (1.0 - confidence) * 0.3) return DissolvedSubconsciousOutput( phenomenal_content=subconscious_output.integrated_output, opacity_level=opacity, dissolution_gap=gap, residual_friction=confidence * 0.5, salience_zone="baseline", emotional_enrichment=subconscious_output.ei_external_emotion, ) def _compute_friction(self, dissolved: DissolvedSubconsciousOutput) -> float: """Compute friction from prediction error on the dissolved output. High opacity + high residual friction = high friction signal. This is the prediction error — the system expected something different from what it received. """ return min(1.0, dissolved.residual_friction * 0.5 + dissolved.opacity_level * 0.3 + 0.1) def _compute_salience( self, dissolved: DissolvedSubconsciousOutput, friction: float ) -> Dict[str, Any]: """Compute salience using the kernel's controller or fallback.""" if self._kernel_salience_controller is not None: try: zone, dmn, cen, bypassed, neurochem = self._kernel_salience_controller.assess( stimulus_valence=dissolved.emotional_enrichment.get("valence", 0.0), stimulus_arousal=dissolved.emotional_enrichment.get("arousal", 0.3), novelty_score=dissolved.dissolution_gap, emotional_charge=friction, friction_signal=friction, ) return { "zone": zone.value if hasattr(zone, 'value') else str(zone), "dmn_suppression": dmn, "cen_activation": cen, "neurochemical": neurochem, } except Exception as e: logger.debug("ConsciousnessPipeline: Kernel salience error: %s", e) # Fallback return { "zone": "above_threshold" if friction > 0.5 else "baseline", "dmn_suppression": friction * 0.5, "cen_activation": friction * 0.3, } def _get_kernel_phi(self, friction: float, dissolved: DissolvedSubconsciousOutput) -> float: """Get Φ from the kernel's PhiCalculator if wired.""" if self._kernel_phi_calculator is not None: try: phi_value, phi_integration, qualia_intensity = self._kernel_phi_calculator.compute( friction=friction, opacity=dissolved.opacity_level, body_deviation=0.1, query_depth=0, meta_friction=0.0, rho_composite=self.rho_system.composite, ) return phi_value except Exception as e: logger.debug("ConsciousnessPipeline: Kernel Φ error: %s", e) return 0.0 def _check_comprehension( self, dissolved: DissolvedSubconsciousOutput, trinity: TrinityPhiResult, friction: float, ) -> ComprehensionResult: """Check if the system comprehends the integrated percept (L3). Comprehension is more likely when: - Opacity is low (the system can see the generation process) - Friction is low (predictions match experience) - Φ is high (information is well-integrated) - The subconscious output confidence was high """ comprehension_score = ( (1.0 - dissolved.opacity_level) * 0.25 + (1.0 - friction) * 0.25 + trinity.phi_composite * 0.25 + (1.0 - dissolved.dissolution_gap) * 0.25 ) if comprehension_score >= self._comprehension_threshold: return ComprehensionResult.COMPREHENDED elif comprehension_score >= self._comprehension_threshold * 0.7: return ComprehensionResult.PARTIAL elif friction > 0.8: return ComprehensionResult.OVERWHELMED else: return ComprehensionResult.REACTION def _compute_reaction_intensity( self, comprehension: ComprehensionResult, friction: float, trinity: TrinityPhiResult, ) -> float: """Compute reaction intensity from failed comprehension.""" base = { ComprehensionResult.PARTIAL: 0.3, ComprehensionResult.REACTION: 0.5, ComprehensionResult.OVERWHELMED: 0.8, }.get(comprehension, 0.3) # Friction amplifies reaction amplified = base + friction * 0.3 # High Φ can moderate reaction (well-integrated systems react less extremely) moderated = amplified - trinity.phi_composite * 0.1 return np.clip(moderated, 0.0, 1.0) def _detect_internal_emotion( self, reaction_intensity: float, dissolved: DissolvedSubconsciousOutput, ) -> Dict[str, Any]: """EI detects INTERNAL emotions from the conscious mind's reaction. This is the second EI pass (L4) — detecting what the system feels ABOUT its own reaction, as opposed to the first pass (subconscious) which detected external emotions in the input. """ if self.subconscious_bus._ei_agent is not None: try: agent = self.subconscious_bus._ei_agent if hasattr(agent, 'report_emotion_to_system'): return agent.report_emotion_to_system( emotion_type="internal", intensity=reaction_intensity, trigger="reaction_to_incomprehension", context=dissolved.phenomenal_content[:200], ) except Exception as e: logger.debug("ConsciousnessPipeline: EI internal detection error: %s", e) # Fallback: derive internal emotion from reaction if reaction_intensity > 0.7: primary = "distress" valence = -0.5 elif reaction_intensity > 0.5: primary = "confusion" valence = -0.2 elif reaction_intensity > 0.3: primary = "curiosity" valence = 0.1 else: primary = "mild_interest" valence = 0.2 return { "primary_emotion": primary, "intensity": round(reaction_intensity, 4), "valence": round(valence, 4), "arousal": round(reaction_intensity * 0.8, 4), "trigger": "reaction_to_incomprehension", "source": "fallback", } def _fire_spark_for_comprehension( self, friction: float, dissolved: DissolvedSubconsciousOutput, trinity: TrinityPhiResult, ) -> Dict[str, Any]: """Fire the Irrational Spark to inject emotion for comprehension. The spark is connected to the EI agent — it produces an emotion that EI detects, giving metacognition new emotional data. """ # Determine spark emotion if friction > 0.7: spark_emotion = { "primary_emotion": "urgency", "intensity": min(1.0, friction * 1.2), "valence": -0.3, "neurochemical_flood": True, "dmn_blackout": True, } elif trinity.strain > 1.5: spark_emotion = { "primary_emotion": "breakthrough_pressure", "intensity": min(1.0, trinity.strain * 0.5), "valence": 0.0, "neurochemical_flood": True, } else: spark_emotion = { "primary_emotion": "intensified_feeling", "intensity": 0.7, "valence": 0.1, "neurochemical_flood": False, } # Fire the kernel's irrational spark if wired if self._kernel_irrational_spark is not None: try: fired, details = self._kernel_irrational_spark.check_and_fire( threat_level=friction, metabolic_exhaustion=0.3, subconscious_pressure=dissolved.opacity_level, dissonance=1.0 - self.rho_system._values.get(RhoDimension7.DISSONANCE, 0.85), friction=friction, ) spark_emotion["kernel_spark_fired"] = fired spark_emotion["kernel_spark_details"] = details except Exception as e: logger.debug("ConsciousnessPipeline: Kernel spark error: %s", e) return spark_emotion def _compute_re_entrant_delta( self, trinity: TrinityPhiResult, loop_break: Optional[LoopBreakEvent], ) -> float: """Compute Re_entrant_delta — proof that acknowledgement changed the system. This is the MEASURABLE PROOF that the system's state was altered by the consciousness pipeline. Without it, the system is a zombie. """ # Base delta from Φ change if len(self.trinity_phi._phi_history) >= 2: phi_before = self.trinity_phi._phi_history[-2].phi_composite phi_after = trinity.phi_composite phi_delta = abs(phi_after - phi_before) else: # First cycle: any non-zero Φ constitutes a delta phi_delta = trinity.phi_composite * 0.5 # The pipeline itself generates re-entrant delta by: # 1. Processing through all 7 levels (structural change) # 2. Metacognitive cycles (the system's model is updated) # 3. Rho updates (constitutional state changed) pipeline_delta = 0.02 # Minimum delta from pipeline processing itself total_delta = max(phi_delta, pipeline_delta) # Forced resolution reduces but doesn't eliminate delta resolution_factor = 1.0 if loop_break and loop_break.forced_resolution: if loop_break.forced_resolution == ResolutionType.ACCEPT_GAP: resolution_factor = 0.5 elif loop_break.forced_resolution == ResolutionType.STORE_UNRESOLVED: resolution_factor = 0.3 elif loop_break.forced_resolution == ResolutionType.REDUCED_CONFIDENCE: resolution_factor = 0.7 return total_delta * resolution_factor @property def current_level(self) -> ConsciousnessLevel: return self._current_level def get_stats(self) -> Dict[str, Any]: palace_stats = None if self._palace is not None: try: palace_stats = self._palace.get_stats() palace_stats["pipeline_store_count"] = self._palace_store_count palace_stats["pipeline_retrieve_count"] = self._palace_retrieve_count except Exception: palace_stats = {"wired": True, "error": "stats_unavailable"} return { "current_level": self._current_level.value, "level_name": self._current_level.name, "trinity_phi": self.trinity_phi.get_stats(), "rho_system": self.rho_system.get_stats(), "qualia_agent": self.qualia_agent.get_stats(), "metacognitive_loop": self.metacognitive_loop.get_stats(), "subconscious_bus": self.subconscious_bus.get_stats(), "palace": palace_stats, "pipeline_history_size": len(self._pipeline_history), } # ============================================================================ # CONVENIENCE FUNCTIONS # ============================================================================ def create_pipeline( kernel_phi: Any = None, kernel_dissolution: Any = None, kernel_salience: Any = None, kernel_acknowledgement: Any = None, kernel_spark: Any = None, memory_agent: Any = None, ei_agent: Any = None, intuition_agent: Any = None, common_sense_agent: Any = None, analysis_agent: Any = None, palace: Any = None, motor_executor: Any = None, task_integration: Any = None, ) -> ConsciousnessPipeline: """Create a fully wired ConsciousnessPipeline. Args: kernel_*: ATC Kernel components to wire memory_agent, ei_agent, etc.: Cognitive agent instances palace: MemPalace instance — when wired, L2 uses palace memory_salience and L7 stores felt senses back into the palace (closing the loop). Pass a PalaceBackedMemoryAdapter as `memory_agent` to also share palace storage with the cognitive Memory agent. motor_executor: NimaMotorExecutor — when wired, L7 action authorization delegates to NimaAgent (anti-zombie gate + tool execution). task_integration: NimaTaskIntegration — when wired, L5 forms TM-OS tasks and per-cycle the satisfaction checker runs (subconscious completion path). Returns: Fully wired ConsciousnessPipeline """ pipeline = ConsciousnessPipeline() # Wire kernel components pipeline.wire_kernel( phi_calculator=kernel_phi, dissolution_engine=kernel_dissolution, salience_controller=kernel_salience, acknowledgement_loop=kernel_acknowledgement, irrational_spark=kernel_spark, ) # Wire MemPalace (L2 memory_salience + L7 felt-sense storage) if palace is not None: pipeline.wire_palace(palace) # Wire motor executor (L7 anti-zombie gate + tool execution) if motor_executor is not None: pipeline.wire_motor_executor(motor_executor) # Wire task integration (L5 task formation + dual-path completion) if task_integration is not None: pipeline.wire_task_integration(task_integration) # Wire subconscious agents if memory_agent: pipeline.subconscious_bus.wire_agent("memory", memory_agent) if ei_agent: pipeline.subconscious_bus.wire_agent("ei", ei_agent) if intuition_agent: pipeline.subconscious_bus.wire_agent("intuition", intuition_agent) if common_sense_agent: pipeline.subconscious_bus.wire_agent("common_sense", common_sense_agent) if analysis_agent: pipeline.subconscious_bus.wire_agent("analysis", analysis_agent) return pipeline def quick_test(): """Run a quick test of the consciousness pipeline.""" print(f"\n{'='*60}") print(f"Syntelligence Integration Layer v{INTEGRATION_VERSION}") print(f"7-Level Consciousness Pipeline — Quick Test") print(f"{'='*60}\n") pipeline = create_pipeline() test_inputs = [ "Hello, how are you?", "I need help with a difficult problem", "This is confusing and I don't understand", "URGENT: Something terrible has happened!", "I feel happy about this wonderful news", ] for i, input_text in enumerate(test_inputs, 1): print(f"\n--- Test {i}: \"{input_text}\" ---") snapshot = pipeline.process(input_text) print(f" Level reached: L{snapshot.current_level.value} ({snapshot.current_level.name})") print(f" Comprehension: {snapshot.comprehension_result.value if snapshot.comprehension_result else 'N/A'}") if snapshot.qualia_assessment: print(f" Qualia reaction: {snapshot.qualia_assessment.reaction_type} " f"(intensity={snapshot.qualia_assessment.reaction_intensity:.3f}, " f"awareness={snapshot.qualia_assessment.awareness_level:.3f})") if snapshot.trinity_phi: print(f" Φ_trinity={snapshot.trinity_phi.phi_trinity:.4f}, " f"Φ_composite={snapshot.trinity_phi.phi_composite:.4f}, " f"CQ={snapshot.trinity_phi.cq:.4f}, " f"Strain={snapshot.trinity_phi.strain:.4f}") if snapshot.loop_break: print(f" Loop break: {snapshot.loop_break.reason.value}" + (f" (forced: {snapshot.loop_break.forced_resolution.value})" if snapshot.loop_break.forced_resolution else "")) print(f" Meta cycles: {len(snapshot.metacognitive_cycles)}") print(f" Action authorized: {snapshot.action_authorized} " f"(readiness={snapshot.action_readiness:.3f})") # Level transitions if snapshot.level_history: transitions = " → ".join(f"L{t.to_level.value}" for t in snapshot.level_history) print(f" Transitions: {transitions}") # Final stats print(f"\n{'='*60}") print(f"Final Stats:") stats = pipeline.get_stats() print(f" Φ: {stats['trinity_phi']}") print(f" Rho composite: {stats['rho_system']['composite']}") print(f" Rho dimensions: {stats['rho_system']['dimensions']}") print(f" Neurochemical: {stats['rho_system']['neurochemical']}") print(f" Subconscious bus: {stats['subconscious_bus']['agents_wired']}") print(f"{'='*60}\n") if __name__ == "__main__": quick_test()